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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -77
app.py CHANGED
@@ -444,6 +444,34 @@ from googleapiclient.discovery import build
444
 
445
 
446
  #############################
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
  def process_youtube_video(url="", keywords=""):
448
  try:
449
  # Initialize variables
@@ -457,7 +485,7 @@ def process_youtube_video(url="", keywords=""):
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
 
@@ -478,15 +506,14 @@ def process_youtube_video(url="", keywords=""):
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)
@@ -499,7 +526,7 @@ def process_youtube_video(url="", keywords=""):
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():
@@ -508,7 +535,7 @@ def process_youtube_video(url="", keywords=""):
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
  """
@@ -529,21 +556,18 @@ def get_recommendations(keywords, max_results=5):
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
@@ -571,72 +595,35 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
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),
@@ -652,9 +639,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
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)
@@ -668,14 +652,17 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
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
 
@@ -691,3 +678,4 @@ if __name__ == "__main__":
691
  app.launch()
692
 
693
 
 
 
444
 
445
 
446
  #############################
447
+ import gradio as gr
448
+ from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
449
+ from textblob import TextBlob
450
+ import requests
451
+ import re
452
+
453
+ # Helper Functions
454
+ def extract_video_id(url):
455
+ """
456
+ Extracts the video ID from a YouTube URL.
457
+ """
458
+ pattern = r"(?:v=|\/)([0-9A-Za-z_-]{11}).*"
459
+ match = re.search(pattern, url)
460
+ return match.group(1) if match else None
461
+
462
+ def clean_text_for_analysis(text):
463
+ """
464
+ Cleans text for sentiment analysis.
465
+ """
466
+ return re.sub(r"[^a-zA-Z0-9 .,!?']", "", text)
467
+
468
+ def get_video_metadata(video_id):
469
+ """
470
+ Fetches video metadata using YouTube Data API.
471
+ """
472
+ # Dummy implementation for metadata fetching.
473
+ return {"description": "No metadata available."}
474
+
475
  def process_youtube_video(url="", keywords=""):
476
  try:
477
  # Initialize variables
 
485
  if url.strip():
486
  video_id = extract_video_id(url)
487
  if not video_id:
488
+ return None, "Invalid YouTube URL", "N/A", ""
489
 
490
  thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"
491
 
 
506
  cleaned_text = clean_text_for_analysis(text)
507
 
508
  # Sentiment analysis
509
+ sentiment = TextBlob(cleaned_text).sentiment
510
  sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"
511
 
512
+ # Generate summary (Dummy implementation)
513
+ summary = f"Summary: {cleaned_text[:200]}..."
 
514
 
515
+ # Extract subtitle information (Dummy implementation)
516
+ subtitle_info = "Subtitle processed successfully."
517
 
518
  except TranscriptsDisabled:
519
  metadata = get_video_metadata(video_id)
 
526
  sentiment_label = "N/A"
527
  subtitle_info = "No subtitles available for analysis."
528
  except Exception as e:
529
+ return thumbnail, f"⚠️ Error processing transcript: {str(e)}", "N/A", ""
530
 
531
  # If keywords are provided, get recommendations
532
  if keywords.strip():
 
535
  return thumbnail, summary, sentiment_label, subtitle_info, recommendations
536
 
537
  except Exception as e:
538
+ return None, f"Error: {str(e)}", "N/A", ""
539
 
540
  def get_recommendations(keywords, max_results=5):
541
  """
 
556
  "key": YOUTUBE_API_KEY
557
  }
558
  ).json()
559
+
560
  results = []
561
  for item in response.get("items", []):
562
  title = item["snippet"]["title"]
563
  channel = item["snippet"]["channelTitle"]
564
  video_id = item["id"]["videoId"]
565
  results.append(f"πŸ“Ί {title}\nπŸ‘€ {channel}\nπŸ”— https://youtube.com/watch?v={video_id}\n")
566
+
567
  return "\n".join(results) if results else "No recommendations found"
568
  except Exception as e:
569
  return f"Error: {str(e)}"
570
 
 
 
 
571
  # Gradio Interface
572
  with gr.Blocks(theme=gr.themes.Soft()) as app:
573
  # Login Page
 
595
  dashboard_page = gr.Group()
596
  with dashboard_page:
597
  gr.Markdown("## πŸ“Š Dashboard")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
598
 
599
  # YouTube Tool Content
600
  youtube_page = gr.Group(visible=False)
601
  with youtube_page:
602
  gr.Markdown("## Agent for YouTube Content Exploration")
603
  with gr.Row():
604
+ video_url = gr.Textbox(
605
+ label="YouTube URL",
606
+ placeholder="https://youtube.com/watch?v=..."
607
+ )
608
+ analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
 
 
 
 
 
 
 
 
609
 
610
  with gr.Row():
611
+ keywords = gr.Textbox(
612
+ label="Keywords for Recommendations",
613
+ placeholder="e.g., python programming, machine learning"
614
+ )
615
+ recommend_btn = gr.Button("πŸ” Get Recommendations", variant="primary")
616
+
617
+ with gr.Row():
618
+ video_thumbnail = gr.Image(label="Video Preview")
619
+
620
+ with gr.Row():
621
+ summary = gr.Textbox(label="πŸ“ Summary", lines=8)
622
+ sentiment = gr.Textbox(label="😊 Content Sentiment")
623
+ recommendations = gr.Textbox(label="🎯 Related Videos", lines=10)
624
 
625
  def login_check(user, pwd):
626
+ USER_CREDENTIALS = {"admin": "admin"}
627
  if USER_CREDENTIALS.get(user) == pwd:
628
  return {
629
  login_page: gr.update(visible=False),
 
639
  def show_page(page_name):
640
  updates = {
641
  dashboard_page: gr.update(visible=False),
 
 
 
642
  youtube_page: gr.update(visible=False)
643
  }
644
  updates[page_name] = gr.update(visible=True)
 
652
  )
653
 
654
  nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
 
 
 
655
  nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
656
 
657
  analyze_btn.click(
658
  process_youtube_video,
659
+ inputs=[video_url, gr.Textbox(label="")], # Empty input for keywords
660
+ outputs=[video_thumbnail, summary, sentiment, recommendations]
661
+ )
662
+
663
+ recommend_btn.click(
664
+ lambda keywords: (None, "", "", get_recommendations(keywords)),
665
+ inputs=[keywords],
666
  outputs=[video_thumbnail, summary, sentiment, recommendations]
667
  )
668
 
 
678
  app.launch()
679
 
680
 
681
+