Sayiqa commited on
Commit
8fea716
Β·
verified Β·
1 Parent(s): 9122b5c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -336
app.py CHANGED
@@ -444,338 +444,6 @@ from googleapiclient.discovery import build
444
 
445
 
446
  #############################
447
- # def process_youtube_video(url="", keywords=""):
448
- # try:
449
- # # Initialize variables
450
- # thumbnail = None
451
- # summary = "No transcript available"
452
- # sentiment_label = "N/A"
453
- # recommendations = ""
454
- # subtitle_info = "No additional information available"
455
-
456
- # # If URL is provided, process the YouTube video
457
- # if url.strip():
458
- # video_id = extract_video_id(url)
459
- # if not video_id:
460
- # return None, "Invalid YouTube URL", "N/A", "", ""
461
-
462
- # thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"
463
-
464
- # try:
465
- # # Fetch transcript
466
- # transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
467
- # transcript = None
468
- # try:
469
- # transcript = transcript_list.find_transcript(['en'])
470
- # except:
471
- # transcript = transcript_list.find_generated_transcript(['en'])
472
-
473
- # text = " ".join([t['text'] for t in transcript.fetch()])
474
- # if not text.strip():
475
- # raise ValueError("Transcript is empty")
476
-
477
- # # Clean up the text for sentiment analysis
478
- # cleaned_text = clean_text_for_analysis(text)
479
-
480
- # # Sentiment analysis
481
- # sentiment = TextBlob(cleaned_text).sentiment # Use cleaned text for sentiment analysis
482
- # sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"
483
-
484
- # # Generate summary
485
- # model = genai.GenerativeModel("gemini-pro")
486
- # summary = model.generate_content(f"Summarize this: {cleaned_text[:4000]}").text
487
-
488
- # # Extract subtitle information
489
- # subtitle_info = extract_subtitle_info(cleaned_text)
490
-
491
- # except TranscriptsDisabled:
492
- # metadata = get_video_metadata(video_id)
493
- # summary = metadata.get("description", "⚠️ This video has disabled subtitles.")
494
- # sentiment_label = "N/A"
495
- # subtitle_info = "No subtitles available for analysis."
496
- # except NoTranscriptFound:
497
- # metadata = get_video_metadata(video_id)
498
- # summary = metadata.get("description", "⚠️ No English transcript available.")
499
- # sentiment_label = "N/A"
500
- # subtitle_info = "No subtitles available for analysis."
501
- # except Exception as e:
502
- # return thumbnail, f"⚠️ Error processing transcript: {str(e)}", "N/A", "", ""
503
-
504
- # # If keywords are provided, get recommendations
505
- # if keywords.strip():
506
- # recommendations = get_recommendations(keywords)
507
-
508
- # return thumbnail, summary, sentiment_label, subtitle_info, recommendations
509
-
510
- # except Exception as e:
511
- # return None, f"Error: {str(e)}", "N/A", "", ""
512
-
513
- # def get_recommendations(keywords, max_results=5):
514
- # """
515
- # Fetches related video recommendations based on the provided keywords.
516
- # """
517
- # YOUTUBE_API_KEY = "AIzaSyD_SDF4lC3vpHVAMnBOcN2ZCTz7dRjUc98" # Replace with your YouTube Data API key
518
- # if not keywords.strip():
519
- # return "Please provide search keywords"
520
- # try:
521
- # response = requests.get(
522
- # "https://www.googleapis.com/youtube/v3/search",
523
- # params={
524
- # "part": "snippet",
525
- # "q": f"educational {keywords}",
526
- # "type": "video",
527
- # "maxResults": max_results,
528
- # "relevanceLanguage": "en",
529
- # "key": YOUTUBE_API_KEY
530
- # }
531
- # ).json()
532
-
533
- # results = []
534
- # for item in response.get("items", []):
535
- # title = item["snippet"]["title"]
536
- # channel = item["snippet"]["channelTitle"]
537
- # video_id = item["id"]["videoId"]
538
- # results.append(f"πŸ“Ί {title}\nπŸ‘€ {channel}\nπŸ”— https://youtube.com/watch?v={video_id}\n")
539
-
540
- # return "\n".join(results) if results else "No recommendations found"
541
- # except Exception as e:
542
- # return f"Error: {str(e)}"
543
-
544
-
545
-
546
-
547
- # # Gradio Interface
548
- # with gr.Blocks(theme=gr.themes.Soft()) as app:
549
- # # Login Page
550
- # with gr.Group() as login_page:
551
- # gr.Markdown("# πŸŽ“ Educational Learning Management System")
552
- # username = gr.Textbox(label="Username")
553
- # password = gr.Textbox(label="Password", type="password")
554
- # login_btn = gr.Button("Login", variant="primary")
555
- # login_msg = gr.Markdown()
556
-
557
- # # Main Interface
558
- # with gr.Group(visible=False) as main_page:
559
- # with gr.Row():
560
- # with gr.Column(scale=1):
561
- # gr.Markdown("### πŸ“‹ Navigation")
562
- # nav_dashboard = gr.Button("πŸ“Š Dashboard", variant="primary")
563
- # nav_students = gr.Button("πŸ‘₯ Students")
564
- # nav_teachers = gr.Button("πŸ‘¨β€πŸ« Teachers")
565
- # nav_courses = gr.Button("πŸ“š Courses")
566
- # nav_youtube = gr.Button("πŸŽ₯ YouTube Tool")
567
- # logout_btn = gr.Button("πŸšͺ Logout", variant="stop")
568
-
569
- # with gr.Column(scale=3):
570
- # # Dashboard Content
571
- # dashboard_page = gr.Group()
572
- # with dashboard_page:
573
- # gr.Markdown("## πŸ“Š Dashboard")
574
- # gr.Markdown(f"""
575
- # ### System Overview
576
- # - πŸ‘₯ Total Students: {len(students_data)}
577
- # - πŸ‘¨β€πŸ« Total Teachers: {len(teachers_data)}
578
- # - πŸ“š Total Courses: {len(courses_data)}
579
-
580
- # ### Quick Actions
581
- # - View student performance
582
- # - Access course materials
583
- # - Generate learning insights
584
- # """)
585
-
586
- # # Students Content
587
- # students_page = gr.Group(visible=False)
588
- # with students_page:
589
- # gr.Markdown("## πŸ‘₯ Students")
590
- # gr.DataFrame(
591
- # value=students_data,
592
- # headers=["ID", "Name", "Grade", "Program"]
593
- # )
594
-
595
- # # Teachers Content
596
- # teachers_page = gr.Group(visible=False)
597
- # with teachers_page:
598
- # gr.Markdown("## πŸ‘¨β€πŸ« Teachers")
599
- # gr.DataFrame(
600
- # value=teachers_data,
601
- # headers=["ID", "Name", "Subject", "Qualification"]
602
- # )
603
-
604
- # # Courses Content
605
- # courses_page = gr.Group(visible=False)
606
- # with courses_page:
607
- # gr.Markdown("## πŸ“š Courses")
608
- # gr.DataFrame(
609
- # value=courses_data,
610
- # headers=["ID", "Name", "Instructor", "Level"]
611
- # )
612
-
613
- # # YouTube Tool Content
614
- # youtube_page = gr.Group(visible=False)
615
- # with youtube_page:
616
- # gr.Markdown("## Agent for YouTube Content Exploration")
617
- # with gr.Row():
618
- # with gr.Column(scale=2):
619
- # video_url = gr.Textbox(
620
- # label="YouTube URL",
621
- # placeholder="https://youtube.com/watch?v=..."
622
- # )
623
- # keywords = gr.Textbox(
624
- # label="Keywords for Recommendations",
625
- # placeholder="e.g., python programming, machine learning"
626
- # )
627
- # analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
628
-
629
- # with gr.Column(scale=1):
630
- # video_thumbnail = gr.Image(label="Video Preview")
631
-
632
- # with gr.Row():
633
- # with gr.Column():
634
- # summary = gr.Textbox(label="πŸ“ Summary", lines=8)
635
- # sentiment = gr.Textbox(label="😊 Content Sentiment")
636
- # with gr.Column():
637
- # recommendations = gr.Textbox(label="🎯 Related Videos", lines=10)
638
-
639
- # def login_check(user, pwd):
640
- # if USER_CREDENTIALS.get(user) == pwd:
641
- # return {
642
- # login_page: gr.update(visible=False),
643
- # main_page: gr.update(visible=True),
644
- # login_msg: ""
645
- # }
646
- # return {
647
- # login_page: gr.update(visible=True),
648
- # main_page: gr.update(visible=False),
649
- # login_msg: "❌ Invalid credentials"
650
- # }
651
-
652
- # def show_page(page_name):
653
- # updates = {
654
- # dashboard_page: gr.update(visible=False),
655
- # students_page: gr.update(visible=False),
656
- # teachers_page: gr.update(visible=False),
657
- # courses_page: gr.update(visible=False),
658
- # youtube_page: gr.update(visible=False)
659
- # }
660
- # updates[page_name] = gr.update(visible=True)
661
- # return updates
662
-
663
- # # Event Handlers
664
- # login_btn.click(
665
- # login_check,
666
- # inputs=[username, password],
667
- # outputs=[login_page, main_page, login_msg]
668
- # )
669
-
670
- # nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
671
- # nav_students.click(lambda: show_page(students_page), outputs=list(show_page(students_page).keys()))
672
- # nav_teachers.click(lambda: show_page(teachers_page), outputs=list(show_page(teachers_page).keys()))
673
- # nav_courses.click(lambda: show_page(courses_page), outputs=list(show_page(courses_page).keys()))
674
- # nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
675
-
676
- # analyze_btn.click(
677
- # process_youtube_video,
678
- # inputs=[video_url, keywords],
679
- # outputs=[video_thumbnail, summary, sentiment, recommendations]
680
- # )
681
-
682
- # logout_btn.click(
683
- # lambda: {
684
- # login_page: gr.update(visible=True),
685
- # main_page: gr.update(visible=False)
686
- # },
687
- # outputs=[login_page, main_page]
688
- # )
689
-
690
- # if __name__ == "__main__":
691
- # app.launch()
692
-
693
- import requests
694
- from textblob import TextBlob
695
- from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
696
- import gradio as gr
697
-
698
- # Helper Functions
699
- def extract_video_id(url):
700
- """
701
- Extract the video ID from a YouTube URL.
702
- """
703
- import re
704
- match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11})", url)
705
- return match.group(1) if match else None
706
-
707
- def clean_text_for_analysis(text):
708
- """
709
- Clean text for sentiment analysis.
710
- """
711
- import re
712
- return re.sub(r"[^a-zA-Z0-9\s]", "", text)
713
-
714
- def extract_subtitle_info(cleaned_text):
715
- """
716
- Extract additional information from subtitles (e.g., keywords, summary).
717
- """
718
- from collections import Counter
719
- words = cleaned_text.split()
720
- common_words = Counter(words).most_common(5)
721
- return f"Most common words: {', '.join([word for word, _ in common_words])}"
722
-
723
- def get_video_metadata(video_id):
724
- """
725
- Fetch metadata for a YouTube video using the YouTube Data API.
726
- """
727
- YOUTUBE_API_KEY = "AIzaSyD_SDF4lC3vpHVAMnBOcN2ZCTz7dRjUc98" # Replace with your YouTube Data API key
728
- try:
729
- response = requests.get(
730
- f"https://www.googleapis.com/youtube/v3/videos",
731
- params={
732
- "part": "snippet",
733
- "id": video_id,
734
- "key": YOUTUBE_API_KEY
735
- }
736
- ).json()
737
- if "items" in response and response["items"]:
738
- snippet = response["items"][0]["snippet"]
739
- return {
740
- "title": snippet.get("title", "N/A"),
741
- "description": snippet.get("description", "N/A"),
742
- "channelTitle": snippet.get("channelTitle", "N/A")
743
- }
744
- return {}
745
- except Exception as e:
746
- return {"error": str(e)}
747
-
748
- def get_recommendations(keywords, max_results=5):
749
- """
750
- Fetches related video recommendations based on the provided keywords.
751
- """
752
- YOUTUBE_API_KEY = "AIzaSyD_SDF4lC3vpHVAMnBOcN2ZCTz7dRjUc98" # Replace with your YouTube Data API key
753
- if not keywords.strip():
754
- return "Please provide search keywords"
755
- try:
756
- response = requests.get(
757
- "https://www.googleapis.com/youtube/v3/search",
758
- params={
759
- "part": "snippet",
760
- "q": f"educational {keywords}",
761
- "type": "video",
762
- "maxResults": max_results,
763
- "relevanceLanguage": "en",
764
- "key": YOUTUBE_API_KEY
765
- }
766
- ).json()
767
-
768
- results = []
769
- for item in response.get("items", []):
770
- title = item["snippet"]["title"]
771
- channel = item["snippet"]["channelTitle"]
772
- video_id = item["id"]["videoId"]
773
- results.append(f"πŸ“Ί {title}\nπŸ‘€ {channel}\nπŸ”— https://youtube.com/watch?v={video_id}\n")
774
-
775
- return "\n".join(results) if results else "No recommendations found"
776
- except Exception as e:
777
- return f"Error: {str(e)}"
778
-
779
  def process_youtube_video(url="", keywords=""):
780
  try:
781
  # Initialize variables
@@ -814,7 +482,8 @@ def process_youtube_video(url="", keywords=""):
814
  sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"
815
 
816
  # Generate summary
817
- summary = f"Summary: {cleaned_text[:400]}..."
 
818
 
819
  # Extract subtitle information
820
  subtitle_info = extract_subtitle_info(cleaned_text)
@@ -841,6 +510,40 @@ def process_youtube_video(url="", keywords=""):
841
  except Exception as e:
842
  return None, f"Error: {str(e)}", "N/A", "", ""
843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
844
  # Gradio Interface
845
  with gr.Blocks(theme=gr.themes.Soft()) as app:
846
  # Login Page
@@ -857,11 +560,58 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
857
  with gr.Column(scale=1):
858
  gr.Markdown("### πŸ“‹ Navigation")
859
  nav_dashboard = gr.Button("πŸ“Š Dashboard", variant="primary")
 
 
 
860
  nav_youtube = gr.Button("πŸŽ₯ YouTube Tool")
861
  logout_btn = gr.Button("πŸšͺ Logout", variant="stop")
862
 
863
  with gr.Column(scale=3):
864
- youtube_page = gr.Group()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
865
  with youtube_page:
866
  gr.Markdown("## Agent for YouTube Content Exploration")
867
  with gr.Row():
@@ -887,7 +637,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
887
  recommendations = gr.Textbox(label="🎯 Related Videos", lines=10)
888
 
889
  def login_check(user, pwd):
890
- if user == "admin" and pwd == "admin": # Replace with secure authentication
891
  return {
892
  login_page: gr.update(visible=False),
893
  main_page: gr.update(visible=True),
@@ -900,7 +650,13 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
900
  }
901
 
902
  def show_page(page_name):
903
- updates = {youtube_page: gr.update(visible=False)}
 
 
 
 
 
 
904
  updates[page_name] = gr.update(visible=True)
905
  return updates
906
 
@@ -911,6 +667,10 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
911
  outputs=[login_page, main_page, login_msg]
912
  )
913
 
 
 
 
 
914
  nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
915
 
916
  analyze_btn.click(
@@ -929,3 +689,5 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
929
 
930
  if __name__ == "__main__":
931
  app.launch()
 
 
 
444
 
445
 
446
  #############################
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
  def process_youtube_video(url="", keywords=""):
448
  try:
449
  # Initialize variables
 
482
  sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"
483
 
484
  # Generate summary
485
+ model = genai.GenerativeModel("gemini-pro")
486
+ summary = model.generate_content(f"Summarize this: {cleaned_text[:4000]}").text
487
 
488
  # Extract subtitle information
489
  subtitle_info = extract_subtitle_info(cleaned_text)
 
510
  except Exception as e:
511
  return None, f"Error: {str(e)}", "N/A", "", ""
512
 
513
+ def get_recommendations(keywords, max_results=5):
514
+ """
515
+ Fetches related video recommendations based on the provided keywords.
516
+ """
517
+ YOUTUBE_API_KEY = "AIzaSyD_SDF4lC3vpHVAMnBOcN2ZCTz7dRjUc98" # Replace with your YouTube Data API key
518
+ if not keywords.strip():
519
+ return "Please provide search keywords"
520
+ try:
521
+ response = requests.get(
522
+ "https://www.googleapis.com/youtube/v3/search",
523
+ params={
524
+ "part": "snippet",
525
+ "q": f"educational {keywords}",
526
+ "type": "video",
527
+ "maxResults": max_results,
528
+ "relevanceLanguage": "en",
529
+ "key": YOUTUBE_API_KEY
530
+ }
531
+ ).json()
532
+
533
+ results = []
534
+ for item in response.get("items", []):
535
+ title = item["snippet"]["title"]
536
+ channel = item["snippet"]["channelTitle"]
537
+ video_id = item["id"]["videoId"]
538
+ results.append(f"πŸ“Ί {title}\nπŸ‘€ {channel}\nπŸ”— https://youtube.com/watch?v={video_id}\n")
539
+
540
+ return "\n".join(results) if results else "No recommendations found"
541
+ except Exception as e:
542
+ return f"Error: {str(e)}"
543
+
544
+
545
+
546
+
547
  # Gradio Interface
548
  with gr.Blocks(theme=gr.themes.Soft()) as app:
549
  # Login Page
 
560
  with gr.Column(scale=1):
561
  gr.Markdown("### πŸ“‹ Navigation")
562
  nav_dashboard = gr.Button("πŸ“Š Dashboard", variant="primary")
563
+ nav_students = gr.Button("πŸ‘₯ Students")
564
+ nav_teachers = gr.Button("πŸ‘¨β€πŸ« Teachers")
565
+ nav_courses = gr.Button("πŸ“š Courses")
566
  nav_youtube = gr.Button("πŸŽ₯ YouTube Tool")
567
  logout_btn = gr.Button("πŸšͺ Logout", variant="stop")
568
 
569
  with gr.Column(scale=3):
570
+ # Dashboard Content
571
+ dashboard_page = gr.Group()
572
+ with dashboard_page:
573
+ gr.Markdown("## πŸ“Š Dashboard")
574
+ gr.Markdown(f"""
575
+ ### System Overview
576
+ - πŸ‘₯ Total Students: {len(students_data)}
577
+ - πŸ‘¨β€πŸ« Total Teachers: {len(teachers_data)}
578
+ - πŸ“š Total Courses: {len(courses_data)}
579
+
580
+ ### Quick Actions
581
+ - View student performance
582
+ - Access course materials
583
+ - Generate learning insights
584
+ """)
585
+
586
+ # Students Content
587
+ students_page = gr.Group(visible=False)
588
+ with students_page:
589
+ gr.Markdown("## πŸ‘₯ Students")
590
+ gr.DataFrame(
591
+ value=students_data,
592
+ headers=["ID", "Name", "Grade", "Program"]
593
+ )
594
+
595
+ # Teachers Content
596
+ teachers_page = gr.Group(visible=False)
597
+ with teachers_page:
598
+ gr.Markdown("## πŸ‘¨β€πŸ« Teachers")
599
+ gr.DataFrame(
600
+ value=teachers_data,
601
+ headers=["ID", "Name", "Subject", "Qualification"]
602
+ )
603
+
604
+ # Courses Content
605
+ courses_page = gr.Group(visible=False)
606
+ with courses_page:
607
+ gr.Markdown("## πŸ“š Courses")
608
+ gr.DataFrame(
609
+ value=courses_data,
610
+ headers=["ID", "Name", "Instructor", "Level"]
611
+ )
612
+
613
+ # YouTube Tool Content
614
+ youtube_page = gr.Group(visible=False)
615
  with youtube_page:
616
  gr.Markdown("## Agent for YouTube Content Exploration")
617
  with gr.Row():
 
637
  recommendations = gr.Textbox(label="🎯 Related Videos", lines=10)
638
 
639
  def login_check(user, pwd):
640
+ if USER_CREDENTIALS.get(user) == pwd:
641
  return {
642
  login_page: gr.update(visible=False),
643
  main_page: gr.update(visible=True),
 
650
  }
651
 
652
  def show_page(page_name):
653
+ updates = {
654
+ dashboard_page: gr.update(visible=False),
655
+ students_page: gr.update(visible=False),
656
+ teachers_page: gr.update(visible=False),
657
+ courses_page: gr.update(visible=False),
658
+ youtube_page: gr.update(visible=False)
659
+ }
660
  updates[page_name] = gr.update(visible=True)
661
  return updates
662
 
 
667
  outputs=[login_page, main_page, login_msg]
668
  )
669
 
670
+ nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
671
+ nav_students.click(lambda: show_page(students_page), outputs=list(show_page(students_page).keys()))
672
+ nav_teachers.click(lambda: show_page(teachers_page), outputs=list(show_page(teachers_page).keys()))
673
+ nav_courses.click(lambda: show_page(courses_page), outputs=list(show_page(courses_page).keys()))
674
  nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
675
 
676
  analyze_btn.click(
 
689
 
690
  if __name__ == "__main__":
691
  app.launch()
692
+
693
+