Sayiqa commited on
Commit
00e4be8
Β·
verified Β·
1 Parent(s): 4fbdbe4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -80
app.py CHANGED
@@ -524,8 +524,9 @@ courses_data = [
524
  (5, "Mathematics", "Ms. Smith", "Intermediate")
525
  ]
526
 
 
 
527
  def extract_video_id(url):
528
- # Improved regex to handle various YouTube URL formats
529
  match = re.search(r"(?:v=|\/|be\/|embed\/|watch\?v=)([0-9A-Za-z_-]{11})", url)
530
  return match.group(1) if match else None
531
 
@@ -549,44 +550,45 @@ def get_video_metadata(video_id):
549
  def clean_text_for_analysis(text):
550
  return " ".join(text.split())
551
 
552
- def get_recommendations(keywords, max_results=5):
553
- if not keywords:
554
- return "Please provide search keywords"
555
  try:
556
- response = requests.get(
557
- "https://www.googleapis.com/youtube/v3/search",
558
- params={
559
- "part": "snippet",
560
- "q": f"educational {keywords}",
561
- "type": "video",
562
- "maxResults": max_results,
563
- "relevanceLanguage": "en",
564
- "key": YOUTUBE_API_KEY
565
- }
566
- ).json()
 
 
 
 
 
 
567
 
568
- results = []
569
- for item in response.get("items", []):
570
- title = item["snippet"]["title"]
571
- channel = item["snippet"]["channelTitle"]
572
- video_id = item["id"]["videoId"]
573
- results.append(f"\ud83d\udcfa {title}\n\ud83d\udc64 {channel}\n\ud83d\udd17 https://youtube.com/watch?v={video_id}\n")
 
 
574
 
575
- return "\n".join(results) if results else "No recommendations found"
576
  except Exception as e:
577
- return f"Error: {str(e)}"
578
 
579
  def analyze_sentiment(url):
580
- from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
581
- from textblob import TextBlob
582
-
583
  try:
584
  video_id = extract_video_id(url)
585
  if not video_id:
586
  return "Invalid YouTube URL", "N/A"
587
 
588
  try:
589
- # Fetch transcript
590
  transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
591
  transcript = None
592
  try:
@@ -594,12 +596,10 @@ def analyze_sentiment(url):
594
  except:
595
  transcript = transcript_list.find_generated_transcript(['en'])
596
 
597
- # Combine transcript into text
598
  text = " ".join([t['text'] for t in transcript.fetch()])
599
  if not text.strip():
600
  raise ValueError("Transcript is empty")
601
 
602
- # Clean and analyze text
603
  cleaned_text = clean_text_for_analysis(text)
604
  sentiment = TextBlob(cleaned_text).sentiment
605
  sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"
@@ -616,7 +616,7 @@ def analyze_sentiment(url):
616
  with gr.Blocks(theme=gr.themes.Soft()) as app:
617
  # Login Page
618
  with gr.Group() as login_page:
619
- gr.Markdown("# \ud83c\udf93 Educational Learning Management System")
620
  username = gr.Textbox(label="Username")
621
  password = gr.Textbox(label="Password", type="password")
622
  login_btn = gr.Button("Login", variant="primary")
@@ -626,36 +626,16 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
626
  with gr.Group(visible=False) as main_page:
627
  with gr.Row():
628
  with gr.Column(scale=1):
629
- gr.Markdown("### \ud83d\uddcb Navigation")
630
- nav_dashboard = gr.Button("\ud83d\udcca Dashboard", variant="primary")
631
- nav_students = gr.Button("\ud83d\udc65 Students")
632
- nav_teachers = gr.Button("\ud83d\udc68\u200d\ud83c\udf93 Teachers")
633
- nav_courses = gr.Button("\ud83d\udcda Courses")
634
- nav_youtube = gr.Button("\ud83c\udfa5 YouTube Tool")
635
- logout_btn = gr.Button("\ud83d\udeaa Logout", variant="stop")
636
 
637
  with gr.Column(scale=3):
638
- # Dashboard Content
639
  dashboard_page = gr.Group()
640
  with dashboard_page:
641
- gr.Markdown("## \ud83d\udcca Dashboard")
642
 
643
- # Students Content
644
- students_page = gr.Group(visible=False)
645
- with students_page:
646
- gr.Markdown("## \ud83d\udc65 Students")
647
-
648
- # Teachers Content
649
- teachers_page = gr.Group(visible=False)
650
- with teachers_page:
651
- gr.Markdown("## \ud83d\udc68\u200d\ud83c\udf93 Teachers")
652
-
653
- # Courses Content
654
- courses_page = gr.Group(visible=False)
655
- with courses_page:
656
- gr.Markdown("## \ud83d\udcda Courses")
657
-
658
- # YouTube Tool Content
659
  youtube_page = gr.Group(visible=False)
660
  with youtube_page:
661
  gr.Markdown("## Agent for YouTube Content Exploration")
@@ -665,23 +645,16 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
665
  label="YouTube URL",
666
  placeholder="https://youtube.com/watch?v=..."
667
  )
668
- keywords = gr.Textbox(
669
- label="Keywords for Recommendations",
670
- placeholder="e.g., python programming, machine learning"
671
- )
672
- analyze_btn = gr.Button("\ud83d\udd0d Analyze Video", variant="primary")
673
- recommend_btn = gr.Button("\ud83d\udd0e Get Recommendations", variant="primary")
674
- sentiment_btn = gr.Button("\ud83d\ude0a Analyze Sentiment", variant="primary")
675
 
676
  with gr.Column(scale=1):
677
  video_thumbnail = gr.Image(label="Video Preview")
678
 
679
  with gr.Row():
680
  with gr.Column():
681
- summary = gr.Textbox(label="\ud83d\udd8b\ufe0f Summary", lines=8)
682
- sentiment = gr.Textbox(label="\ud83d\ude0a Content Sentiment")
683
- with gr.Column():
684
- recommendations = gr.Textbox(label="\ud83c\udfaf Related Videos", lines=10)
685
 
686
  def login_check(user, pwd):
687
  if USER_CREDENTIALS.get(user) == pwd:
@@ -693,21 +666,17 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
693
  return {
694
  login_page: gr.update(visible=True),
695
  main_page: gr.update(visible=False),
696
- login_msg: "\u274c Invalid credentials"
697
  }
698
 
699
  def show_page(page_name):
700
  updates = {
701
  dashboard_page: gr.update(visible=False),
702
- students_page: gr.update(visible=False),
703
- teachers_page: gr.update(visible=False),
704
- courses_page: gr.update(visible=False),
705
  youtube_page: gr.update(visible=False)
706
  }
707
  updates[page_name] = gr.update(visible=True)
708
  return updates
709
 
710
- # Event Handlers
711
  login_btn.click(
712
  login_check,
713
  inputs=[username, password],
@@ -715,9 +684,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
715
  )
716
 
717
  nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
718
- nav_students.click(lambda: show_page(students_page), outputs=list(show_page(students_page).keys()))
719
- nav_teachers.click(lambda: show_page(teachers_page), outputs=list(show_page(teachers_page).keys()))
720
- nav_courses.click(lambda: show_page(courses_page), outputs=list(show_page(courses_page).keys()))
721
  nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
722
 
723
  analyze_btn.click(
@@ -726,12 +692,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
726
  outputs=[video_thumbnail, summary]
727
  )
728
 
729
- recommend_btn.click(
730
- get_recommendations,
731
- inputs=[keywords],
732
- outputs=[recommendations]
733
- )
734
-
735
  sentiment_btn.click(
736
  analyze_sentiment,
737
  inputs=[video_url],
@@ -751,6 +711,11 @@ if __name__ == "__main__":
751
 
752
 
753
 
 
 
 
 
 
754
  # def extract_video_id(url):
755
  # # Improved regex to handle various YouTube URL formats
756
  # match = re.search(r"(?:v=|\/|be\/|embed\/|watch\?v=)([0-9A-Za-z_-]{11})", url)
 
524
  (5, "Mathematics", "Ms. Smith", "Intermediate")
525
  ]
526
 
527
+
528
+
529
  def extract_video_id(url):
 
530
  match = re.search(r"(?:v=|\/|be\/|embed\/|watch\?v=)([0-9A-Za-z_-]{11})", url)
531
  return match.group(1) if match else None
532
 
 
550
  def clean_text_for_analysis(text):
551
  return " ".join(text.split())
552
 
553
+ def process_youtube_video(url):
 
 
554
  try:
555
+ video_id = extract_video_id(url)
556
+ if not video_id:
557
+ return None, "Invalid YouTube URL"
558
+
559
+ thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"
560
+
561
+ try:
562
+ transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
563
+ transcript = None
564
+ try:
565
+ transcript = transcript_list.find_transcript(['en'])
566
+ except:
567
+ transcript = transcript_list.find_generated_transcript(['en'])
568
+
569
+ text = " ".join([t['text'] for t in transcript.fetch()])
570
+ if not text.strip():
571
+ raise ValueError("Transcript is empty")
572
 
573
+ cleaned_text = clean_text_for_analysis(text)
574
+ summary = f"Summary: {cleaned_text[:400]}..."
575
+ return thumbnail, summary
576
+
577
+ except (TranscriptsDisabled, NoTranscriptFound):
578
+ metadata = get_video_metadata(video_id)
579
+ summary = metadata.get("description", "No subtitles available")
580
+ return thumbnail, summary
581
 
 
582
  except Exception as e:
583
+ return None, f"Error: {str(e)}"
584
 
585
  def analyze_sentiment(url):
 
 
 
586
  try:
587
  video_id = extract_video_id(url)
588
  if not video_id:
589
  return "Invalid YouTube URL", "N/A"
590
 
591
  try:
 
592
  transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
593
  transcript = None
594
  try:
 
596
  except:
597
  transcript = transcript_list.find_generated_transcript(['en'])
598
 
 
599
  text = " ".join([t['text'] for t in transcript.fetch()])
600
  if not text.strip():
601
  raise ValueError("Transcript is empty")
602
 
 
603
  cleaned_text = clean_text_for_analysis(text)
604
  sentiment = TextBlob(cleaned_text).sentiment
605
  sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"
 
616
  with gr.Blocks(theme=gr.themes.Soft()) as app:
617
  # Login Page
618
  with gr.Group() as login_page:
619
+ gr.Markdown("# πŸŽ“ Educational Learning Management System")
620
  username = gr.Textbox(label="Username")
621
  password = gr.Textbox(label="Password", type="password")
622
  login_btn = gr.Button("Login", variant="primary")
 
626
  with gr.Group(visible=False) as main_page:
627
  with gr.Row():
628
  with gr.Column(scale=1):
629
+ gr.Markdown("### πŸ“‹ Navigation")
630
+ nav_dashboard = gr.Button("πŸ“Š Dashboard", variant="primary")
631
+ nav_youtube = gr.Button("πŸŽ₯ YouTube Tool")
632
+ logout_btn = gr.Button("πŸšͺ Logout", variant="stop")
 
 
 
633
 
634
  with gr.Column(scale=3):
 
635
  dashboard_page = gr.Group()
636
  with dashboard_page:
637
+ gr.Markdown("## πŸ“Š Dashboard")
638
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
639
  youtube_page = gr.Group(visible=False)
640
  with youtube_page:
641
  gr.Markdown("## Agent for YouTube Content Exploration")
 
645
  label="YouTube URL",
646
  placeholder="https://youtube.com/watch?v=..."
647
  )
648
+ analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
649
+ sentiment_btn = gr.Button("😊 Analyze Sentiment", variant="primary")
 
 
 
 
 
650
 
651
  with gr.Column(scale=1):
652
  video_thumbnail = gr.Image(label="Video Preview")
653
 
654
  with gr.Row():
655
  with gr.Column():
656
+ summary = gr.Textbox(label="πŸ“ Summary", lines=8)
657
+ sentiment = gr.Textbox(label="😊 Content Sentiment")
 
 
658
 
659
  def login_check(user, pwd):
660
  if USER_CREDENTIALS.get(user) == pwd:
 
666
  return {
667
  login_page: gr.update(visible=True),
668
  main_page: gr.update(visible=False),
669
+ login_msg: "❌ Invalid credentials"
670
  }
671
 
672
  def show_page(page_name):
673
  updates = {
674
  dashboard_page: gr.update(visible=False),
 
 
 
675
  youtube_page: gr.update(visible=False)
676
  }
677
  updates[page_name] = gr.update(visible=True)
678
  return updates
679
 
 
680
  login_btn.click(
681
  login_check,
682
  inputs=[username, password],
 
684
  )
685
 
686
  nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
 
 
 
687
  nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
688
 
689
  analyze_btn.click(
 
692
  outputs=[video_thumbnail, summary]
693
  )
694
 
 
 
 
 
 
 
695
  sentiment_btn.click(
696
  analyze_sentiment,
697
  inputs=[video_url],
 
711
 
712
 
713
 
714
+
715
+
716
+
717
+
718
+
719
  # def extract_video_id(url):
720
  # # Improved regex to handle various YouTube URL formats
721
  # match = re.search(r"(?:v=|\/|be\/|embed\/|watch\?v=)([0-9A-Za-z_-]{11})", url)