Sayiqa7 commited on
Commit
2f645cd
Β·
verified Β·
1 Parent(s): ba09a01

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -55
app.py CHANGED
@@ -353,7 +353,7 @@
353
  # app.launch()
354
 
355
 
356
-
357
  import subprocess
358
  subprocess.check_call(["pip", "install", "transformers==4.34.0"])
359
  subprocess.check_call(["pip", "install", "torch>=1.7.1"])
@@ -463,6 +463,8 @@ courses_data = [
463
  (4, "Computer Science", "Ms. Evelyn", "Intermediate"),
464
  (5, "Mathematics", "Ms. Smith", "Intermediate")
465
  ]
 
 
466
 
467
  def extract_video_id(url):
468
  match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11})", url)
@@ -488,15 +490,52 @@ def get_video_metadata(video_id):
488
  def clean_text_for_analysis(text):
489
  return " ".join(text.split())
490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491
  def process_youtube_video(url):
492
  try:
 
 
 
 
493
  video_id = extract_video_id(url)
494
  if not video_id:
495
  return None, "Invalid YouTube URL", "N/A"
496
 
497
  thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"
498
- summary = "No transcript available"
499
- sentiment_label = "N/A"
500
 
501
  try:
502
  transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
@@ -511,53 +550,26 @@ def process_youtube_video(url):
511
  raise ValueError("Transcript is empty")
512
 
513
  cleaned_text = clean_text_for_analysis(text)
 
514
 
515
  sentiment = TextBlob(cleaned_text).sentiment
516
  sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"
517
 
518
- summary = f"Summary of Content: {cleaned_text[:400]}..."
519
-
520
  except (TranscriptsDisabled, NoTranscriptFound):
521
  metadata = get_video_metadata(video_id)
522
- summary = metadata.get("description", "No subtitles available")
 
523
 
524
- return thumbnail, summary, sentiment_label
525
 
526
  except Exception as e:
527
  return None, f"Error: {str(e)}", "N/A"
528
 
529
- def get_recommendations(keywords, max_results=5):
530
- if not keywords:
531
- return "Please provide search keywords"
532
- try:
533
- response = requests.get(
534
- "https://www.googleapis.com/youtube/v3/search",
535
- params={
536
- "part": "snippet",
537
- "q": f"educational {keywords}",
538
- "type": "video",
539
- "maxResults": max_results,
540
- "relevanceLanguage": "en",
541
- "key": YOUTUBE_API_KEY
542
- }
543
- ).json()
544
-
545
- results = []
546
- for item in response.get("items", []):
547
- title = item["snippet"]["title"]
548
- channel = item["snippet"]["channelTitle"]
549
- video_id = item["id"]["videoId"]
550
- results.append(f"\ud83d\udcfa {title}\n\ud83d\udc64 {channel}\n\ud83d\udd17 https://youtube.com/watch?v={video_id}\n")
551
-
552
- return "\n".join(results) if results else "No recommendations found"
553
- except Exception as e:
554
- return f"Error: {str(e)}"
555
-
556
  # Gradio Interface
557
  with gr.Blocks(theme=gr.themes.Soft()) as app:
558
  # Login Page
559
  with gr.Group() as login_page:
560
- gr.Markdown("# \ud83c\udf93 Educational Learning Management System")
561
  username = gr.Textbox(label="Username")
562
  password = gr.Textbox(label="Password", type="password")
563
  login_btn = gr.Button("Login", variant="primary")
@@ -567,24 +579,24 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
567
  with gr.Group(visible=False) as main_page:
568
  with gr.Row():
569
  with gr.Column(scale=1):
570
- gr.Markdown("### \ud83d\udccb Navigation")
571
- nav_dashboard = gr.Button("\ud83d\udcca Dashboard", variant="primary")
572
- nav_students = gr.Button("\ud83d\udc65 Students")
573
- nav_teachers = gr.Button("\ud83d\udc69\u200d\ud83c\udf93 Teachers")
574
- nav_courses = gr.Button("\ud83d\udcda Courses")
575
- nav_youtube = gr.Button("\ud83c\udfa5 YouTube Tool")
576
- logout_btn = gr.Button("\ud83d\udeaa Logout", variant="stop")
577
 
578
  with gr.Column(scale=3):
579
  # Dashboard Content
580
  dashboard_page = gr.Group()
581
  with dashboard_page:
582
- gr.Markdown("## \ud83d\udcca Dashboard")
583
  gr.Markdown(f"""
584
  ### System Overview
585
- - \ud83d\udc65 Total Students: {len(students_data)}
586
- - \ud83d\udc69\u200d\ud83c\udf93 Total Teachers: {len(teachers_data)}
587
- - \ud83d\udcda Total Courses: {len(courses_data)}
588
  ### Quick Actions
589
  - View student performance
590
  - Access course materials
@@ -594,7 +606,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
594
  # Students Content
595
  students_page = gr.Group(visible=False)
596
  with students_page:
597
- gr.Markdown("## \ud83d\udc65 Students")
598
  gr.DataFrame(
599
  value=students_data,
600
  headers=["ID", "Name", "Grade", "Program"]
@@ -603,7 +615,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
603
  # Teachers Content
604
  teachers_page = gr.Group(visible=False)
605
  with teachers_page:
606
- gr.Markdown("## \ud83d\udc69\u200d\ud83c\udf93 Teachers")
607
  gr.DataFrame(
608
  value=teachers_data,
609
  headers=["ID", "Name", "Subject", "Qualification"]
@@ -612,7 +624,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
612
  # Courses Content
613
  courses_page = gr.Group(visible=False)
614
  with courses_page:
615
- gr.Markdown("## \ud83d\udcda Courses")
616
  gr.DataFrame(
617
  value=courses_data,
618
  headers=["ID", "Name", "Instructor", "Level"]
@@ -632,18 +644,18 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
632
  label="Keywords for Recommendations",
633
  placeholder="e.g., python programming, machine learning"
634
  )
635
- analyze_btn = gr.Button("\ud83d\udd0d Analyze Video", variant="primary")
636
- recommend_btn = gr.Button("\ud83d\udd0e Get Recommendations", variant="primary")
637
 
638
  with gr.Column(scale=1):
639
  video_thumbnail = gr.Image(label="Video Preview")
640
 
641
  with gr.Row():
642
  with gr.Column():
643
- summary = gr.Textbox(label="\ud83d\uddcb Summary", lines=8)
644
- sentiment = gr.Textbox(label="\ud83d\ude0a Content Sentiment")
645
  with gr.Column():
646
- recommendations = gr.Textbox(label="\ud83c\udf1f Related Videos", lines=10)
647
 
648
  def login_check(user, pwd):
649
  if USER_CREDENTIALS.get(user) == pwd:
@@ -655,7 +667,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
655
  return {
656
  login_page: gr.update(visible=True),
657
  main_page: gr.update(visible=False),
658
- login_msg: "\u274c Invalid credentials"
659
  }
660
 
661
  def show_page(page_name):
@@ -704,3 +716,4 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
704
 
705
  if __name__ == "__main__":
706
  app.launch()
 
 
353
  # app.launch()
354
 
355
 
356
+ ##############################
357
  import subprocess
358
  subprocess.check_call(["pip", "install", "transformers==4.34.0"])
359
  subprocess.check_call(["pip", "install", "torch>=1.7.1"])
 
463
  (4, "Computer Science", "Ms. Evelyn", "Intermediate"),
464
  (5, "Mathematics", "Ms. Smith", "Intermediate")
465
  ]
466
+ # Load Hugging Face summarization pipeline
467
+ summarizer = pipeline("summarization", model="t5-small", tokenizer="t5-small")
468
 
469
  def extract_video_id(url):
470
  match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11})", url)
 
490
  def clean_text_for_analysis(text):
491
  return " ".join(text.split())
492
 
493
+ def get_recommendations(keywords, max_results=5):
494
+ if not keywords:
495
+ return "Please provide search keywords"
496
+ try:
497
+ response = requests.get(
498
+ "https://www.googleapis.com/youtube/v3/search",
499
+ params={
500
+ "part": "snippet",
501
+ "q": f"educational {keywords}",
502
+ "type": "video",
503
+ "maxResults": max_results,
504
+ "relevanceLanguage": "en",
505
+ "key": YOUTUBE_API_KEY
506
+ }
507
+ ).json()
508
+
509
+ results = []
510
+ for item in response.get("items", []):
511
+ title = item["snippet"]["title"]
512
+ channel = item["snippet"]["channelTitle"]
513
+ video_id = item["id"]["videoId"]
514
+ results.append(f"\ud83d\udcfa {title}\n\ud83d\udc64 {channel}\n\ud83d\udd17 https://youtube.com/watch?v={video_id}\n")
515
+
516
+ return "\n".join(results) if results else "No recommendations found"
517
+ except Exception as e:
518
+ return f"Error: {str(e)}"
519
+
520
+ def summarize_text(text):
521
+ try:
522
+ chunks = [text[i:i+1000] for i in range(0, len(text), 1000)] # Summarize in chunks
523
+ summaries = summarizer(chunks, max_length=150, min_length=50, do_sample=False)
524
+ return " ".join([summary['summary_text'] for summary in summaries])
525
+ except Exception as e:
526
+ return f"Error during summarization: {str(e)}"
527
+
528
  def process_youtube_video(url):
529
  try:
530
+ thumbnail = None
531
+ detailed_summary = "No transcript available"
532
+ sentiment_label = "N/A"
533
+
534
  video_id = extract_video_id(url)
535
  if not video_id:
536
  return None, "Invalid YouTube URL", "N/A"
537
 
538
  thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"
 
 
539
 
540
  try:
541
  transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
 
550
  raise ValueError("Transcript is empty")
551
 
552
  cleaned_text = clean_text_for_analysis(text)
553
+ detailed_summary = summarize_text(cleaned_text)
554
 
555
  sentiment = TextBlob(cleaned_text).sentiment
556
  sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"
557
 
 
 
558
  except (TranscriptsDisabled, NoTranscriptFound):
559
  metadata = get_video_metadata(video_id)
560
+ detailed_summary = metadata.get("description", "No subtitles available")
561
+ sentiment_label = "N/A"
562
 
563
+ return thumbnail, detailed_summary, sentiment_label
564
 
565
  except Exception as e:
566
  return None, f"Error: {str(e)}", "N/A"
567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
568
  # Gradio Interface
569
  with gr.Blocks(theme=gr.themes.Soft()) as app:
570
  # Login Page
571
  with gr.Group() as login_page:
572
+ gr.Markdown("# πŸŽ“ Educational Learning Management System")
573
  username = gr.Textbox(label="Username")
574
  password = gr.Textbox(label="Password", type="password")
575
  login_btn = gr.Button("Login", variant="primary")
 
579
  with gr.Group(visible=False) as main_page:
580
  with gr.Row():
581
  with gr.Column(scale=1):
582
+ gr.Markdown("### πŸ“‹ Navigation")
583
+ nav_dashboard = gr.Button("πŸ“Š Dashboard", variant="primary")
584
+ nav_students = gr.Button("πŸ‘₯ Students")
585
+ nav_teachers = gr.Button("πŸ‘¨β€πŸ« Teachers")
586
+ nav_courses = gr.Button("πŸ“š Courses")
587
+ nav_youtube = gr.Button("πŸŽ₯ YouTube Tool")
588
+ logout_btn = gr.Button("πŸšͺ Logout", variant="stop")
589
 
590
  with gr.Column(scale=3):
591
  # Dashboard Content
592
  dashboard_page = gr.Group()
593
  with dashboard_page:
594
+ gr.Markdown("## πŸ“Š Dashboard")
595
  gr.Markdown(f"""
596
  ### System Overview
597
+ - πŸ‘₯ Total Students: {len(students_data)}
598
+ - πŸ‘¨β€πŸ« Total Teachers: {len(teachers_data)}
599
+ - πŸ“š Total Courses: {len(courses_data)}
600
  ### Quick Actions
601
  - View student performance
602
  - Access course materials
 
606
  # Students Content
607
  students_page = gr.Group(visible=False)
608
  with students_page:
609
+ gr.Markdown("## πŸ‘₯ Students")
610
  gr.DataFrame(
611
  value=students_data,
612
  headers=["ID", "Name", "Grade", "Program"]
 
615
  # Teachers Content
616
  teachers_page = gr.Group(visible=False)
617
  with teachers_page:
618
+ gr.Markdown("## πŸ‘¨β€πŸ« Teachers")
619
  gr.DataFrame(
620
  value=teachers_data,
621
  headers=["ID", "Name", "Subject", "Qualification"]
 
624
  # Courses Content
625
  courses_page = gr.Group(visible=False)
626
  with courses_page:
627
+ gr.Markdown("## πŸ“š Courses")
628
  gr.DataFrame(
629
  value=courses_data,
630
  headers=["ID", "Name", "Instructor", "Level"]
 
644
  label="Keywords for Recommendations",
645
  placeholder="e.g., python programming, machine learning"
646
  )
647
+ analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
648
+ recommend_btn = gr.Button("πŸ”Ž Get Recommendations", variant="primary")
649
 
650
  with gr.Column(scale=1):
651
  video_thumbnail = gr.Image(label="Video Preview")
652
 
653
  with gr.Row():
654
  with gr.Column():
655
+ summary = gr.Textbox(label="πŸ“ Summary", lines=8)
656
+ sentiment = gr.Textbox(label="😊 Content Sentiment")
657
  with gr.Column():
658
+ recommendations = gr.Textbox(label="🎯 Related Videos", lines=10)
659
 
660
  def login_check(user, pwd):
661
  if USER_CREDENTIALS.get(user) == pwd:
 
667
  return {
668
  login_page: gr.update(visible=True),
669
  main_page: gr.update(visible=False),
670
+ login_msg: "❌ Invalid credentials"
671
  }
672
 
673
  def show_page(page_name):
 
716
 
717
  if __name__ == "__main__":
718
  app.launch()
719
+