Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add feature to add YouTube videos with AI-generated quizzes #3794

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

deepan190703
Copy link

@deepan190703 deepan190703 commented Mar 3, 2025

User description

Fixes #3769

Add feature to allow users to add educational YouTube videos with AI-generated quizzes.

  • Add YouTubeVideoForm in website/forms.py to handle YouTube link input and description.
  • Add add_youtube_video view function in website/views/education.py to handle form submission, validate YouTube link, process video transcript using OpenAI, generate quiz, and save lecture.
  • Update website/templates/education/education.html to include a form for inputting YouTube video link and description.
  • Add new modal for adding YouTube videos in website/templates/education/includes/add_lecture_modal.html with fields for YouTube link and description.

PR Type

Enhancement, Tests


Description

  • Added functionality to upload YouTube videos with AI-generated quizzes.

  • Introduced YouTubeVideoForm for handling YouTube video input and description.

  • Updated templates to support YouTube video addition and modal integration.

  • Implemented backend logic for video validation, transcript processing, and quiz generation.


Changes walkthrough 📝

Relevant files
Enhancement
education.html
Add YouTube video upload form to education page                   

website/templates/education/education.html

  • Added a form for uploading YouTube videos.
  • Included fields for video URL and description.
  • Enhanced UI with a submission button for video addition.
  • +17/-0   
    add_lecture_modal.html
    Extend lecture modal to support YouTube videos                     

    website/templates/education/includes/add_lecture_modal.html

  • Added a new option for YouTube videos in lecture modal.
  • Included fields for YouTube URL in modal form.
  • Updated JavaScript to handle YouTube video-specific fields.
  • +12/-0   
    forms.py
    Add YouTube video form for input validation                           

    website/forms.py

  • Created YouTubeVideoForm for handling YouTube video input.
  • Added fields for video URL and optional description.
  • Included validation for URL format.
  • +23/-0   
    education.py
    Implement backend logic for YouTube video uploads               

    website/views/education.py

  • Added add_youtube_video view for handling video uploads.
  • Implemented YouTube URL validation and video ID extraction.
  • Integrated OpenAI for transcript processing and quiz generation.
  • Saved lecture details with generated quiz content.
  • +70/-1   

    Need help?
  • Type /help how to ... in the comments thread for any questions about PR-Agent usage.
  • Check out the documentation for more information.
  • Fixes OWASP-BLT#3769
    
    Add feature to allow users to add educational YouTube videos with AI-generated quizzes.
    
    * Add `YouTubeVideoForm` in `website/forms.py` to handle YouTube link input and description.
    * Add `add_youtube_video` view function in `website/views/education.py` to handle form submission, validate YouTube link, process video transcript using OpenAI, generate quiz, and save lecture.
    * Update `website/templates/education/education.html` to include a form for inputting YouTube video link and description.
    * Add new modal for adding YouTube videos in `website/templates/education/includes/add_lecture_modal.html` with fields for YouTube link and description.
    Copy link
    Contributor

    github-actions bot commented Mar 3, 2025

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    🎫 Ticket compliance analysis 🔶

    3769 - Partially compliant

    Compliant requirements:

    • Allow users to add educational YouTube videos by providing a link.
    • Use AI to check the transcript and label the video appropriately.
    • Generate an AI-based mini quiz after users watch the video.

    Non-compliant requirements:

    []

    Requires further human verification:

    []

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Possible Issue

    The add_youtube_video function does not handle cases where the client.transcriptions.create or client.quizzes.create methods return unexpected data types or structures, which could lead to runtime errors.

    @login_required(login_url="/accounts/login")
    def add_youtube_video(request):
        if request.method == "POST":
            form = YouTubeVideoForm(request.POST)
            if form.is_valid():
                youtube_url = form.cleaned_data["youtube_url"]
                description = form.cleaned_data["description"]
    
                # Validate YouTube URL
                youtube_regex = (
                    r"^(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+$"
                )
                if not re.match(youtube_regex, youtube_url):
                    messages.error(request, "Invalid YouTube URL")
                    return redirect("education_home")
    
                # Extract video ID from URL
                video_id = None
                if "youtu.be" in youtube_url:
                    video_id = youtube_url.split("/")[-1]
                else:
                    query = urlparse(youtube_url).query
                    params = parse_qs(query)
                    video_id = params.get("v", [None])[0]
    
                if not video_id:
                    messages.error(request, "Unable to extract video ID from URL")
                    return redirect("education_home")
    
                # Use OpenAI to process the video transcript and generate quiz
                try:
                    transcript = client.transcriptions.create(video_id=video_id)
                    if not transcript:
                        messages.error(request, "Unable to retrieve video transcript")
                        return redirect("education_home")
    
                    # Generate quiz from transcript
                    quiz = client.quizzes.create(transcript=transcript)
                    if not quiz:
                        messages.error(request, "Unable to generate quiz from transcript")
                        return redirect("education_home")
    
                    # Save the lecture with the generated quiz
                    user_profile = request.user.userprofile
                    lecture = Lecture.objects.create(
                        title=f"YouTube Video: {video_id}",
                        instructor=user_profile,
                        content_type="VIDEO",
                        video_url=youtube_url,
                        description=description,
                        content=json.dumps(quiz),
                    )
    
                    messages.success(request, "YouTube video added successfully with AI-generated quiz")
                    return redirect("education_home")
    
                except Exception as e:
                    messages.error(request, f"Error processing video: {str(e)}")
                    return redirect("education_home")
    
        else:
            form = YouTubeVideoForm()
    
        return render(request, "education/add_youtube_video.html", {"form": form})
    Error Handling

    The error handling in the add_youtube_video function is generic and does not provide detailed feedback for debugging. Consider logging the exceptions with more context.

    @login_required(login_url="/accounts/login")
    def add_youtube_video(request):
        if request.method == "POST":
            form = YouTubeVideoForm(request.POST)
            if form.is_valid():
                youtube_url = form.cleaned_data["youtube_url"]
                description = form.cleaned_data["description"]
    
                # Validate YouTube URL
                youtube_regex = (
                    r"^(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+$"
                )
                if not re.match(youtube_regex, youtube_url):
                    messages.error(request, "Invalid YouTube URL")
                    return redirect("education_home")
    
                # Extract video ID from URL
                video_id = None
                if "youtu.be" in youtube_url:
                    video_id = youtube_url.split("/")[-1]
                else:
                    query = urlparse(youtube_url).query
                    params = parse_qs(query)
                    video_id = params.get("v", [None])[0]
    
                if not video_id:
                    messages.error(request, "Unable to extract video ID from URL")
                    return redirect("education_home")
    
                # Use OpenAI to process the video transcript and generate quiz
                try:
                    transcript = client.transcriptions.create(video_id=video_id)
                    if not transcript:
                        messages.error(request, "Unable to retrieve video transcript")
                        return redirect("education_home")
    
                    # Generate quiz from transcript
                    quiz = client.quizzes.create(transcript=transcript)
                    if not quiz:
                        messages.error(request, "Unable to generate quiz from transcript")
                        return redirect("education_home")
    
                    # Save the lecture with the generated quiz
                    user_profile = request.user.userprofile
                    lecture = Lecture.objects.create(
                        title=f"YouTube Video: {video_id}",
                        instructor=user_profile,
                        content_type="VIDEO",
                        video_url=youtube_url,
                        description=description,
                        content=json.dumps(quiz),
                    )
    
                    messages.success(request, "YouTube video added successfully with AI-generated quiz")
                    return redirect("education_home")
    
                except Exception as e:
                    messages.error(request, f"Error processing video: {str(e)}")
                    return redirect("education_home")
    
        else:
            form = YouTubeVideoForm()
    
        return render(request, "education/add_youtube_video.html", {"form": form})

    Copy link
    Contributor

    github-actions bot commented Mar 3, 2025

    PR Code Suggestions ✨

    Copy link
    Collaborator

    @DonnieBLT DonnieBLT left a comment

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    So the idea is to let anyone even if they’re not logged in to post an educational YouTube video so I was thinking of having some verification on the YouTube video and will detect if it’s really an educational video and not spam so maybe we can only accept videos that have more than 100 views and we will run the transcript through open AI to detect if there is educational value as well as generate the quiz I would also like to see a new model for the quiz unless we have one already, but I don’t think we do.

    <input type="url" id="youtube_url" name="youtube_url" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500" required>
    </div>
    <div class="mb-4">
    <label for="description" class="block text-sm font-medium text-gray-700">Description</label>
    Copy link
    Collaborator

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Please remove anything other than URL so remove the description here

    @@ -25,6 +25,7 @@ <h5 class="text-xl font-semibold text-gray-800">Add New Lecture</h5>
    <option value="VIDEO" selected>Video Lecture</option>
    <option value="LIVE">Live Session</option>
    <option value="DOCUMENT">Document</option>
    <option value="YOUTUBE">YouTube Video</option>
    Copy link
    Collaborator

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    No need to make any changes on this page

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    Add a feature to /education that lets people add educational videos from YouTube just from a link
    2 participants