Sayiqa commited on
Commit
9cb19c8
·
verified ·
1 Parent(s): 3857103

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +368 -257
app.py CHANGED
@@ -67,71 +67,71 @@ else:
67
  raise ValueError("HF_TOKEN environment variable not set.")
68
 
69
 
70
- # # Configuration
71
- # USER_CREDENTIALS = {
72
- # "admin": "password123",
73
- # "teacher": "teach2024",
74
- # "student": "learn2024"
75
- # }
76
 
77
- # import os
78
- # from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
79
 
80
- # # Use environment variables
81
- # GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
82
- # YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
83
 
84
- # if not GOOGLE_API_KEY or not YOUTUBE_API_KEY:
85
- # raise ValueError("Please set GOOGLE_API_KEY and YOUTUBE_API_KEY environment variables")
86
 
87
- # genai.configure(api_key=GOOGLE_API_KEY)
88
-
89
- # # Database
90
- # students_data = [
91
- # (1, "Alice", "A", "Computer Science"),
92
- # (2, "Aliaa", "B", "Mathematics"),
93
- # (3, "Charlie", "A", "Machine Learning"),
94
- # (4, "Daan", "A", "Physics"),
95
- # (5, "Jhon", "C", "Math"),
96
- # (6, "Emma", "A+", "Computer Science")
97
- # ]
98
-
99
- # teachers_data = [
100
- # (1, "Dr. Smith", "Math", "MS Mathematics"),
101
- # (2, "Ms. Johnson", "Science", "MSc Physics"),
102
- # (3, "Ms. Jack", "Artificial Intelligence Engineer", "MSc AI"),
103
- # (4, "Ms. Evelyn", "Computer Science", "MSc Computer Science"),
104
- # ]
105
-
106
- # courses_data = [
107
- # (1, "Algebra", "Dr. Smith", "Advanced"),
108
- # (2, "Biology", "Ms. Mia", "Intermediate"),
109
- # (3, "Machine Learning", "Ms. Jack", "Intermediate"),
110
- # (4, "Computer Science", "Ms. Evelyn", "Intermediate"),
111
- # (5, "Mathematics", "Ms. Smith", "Intermediate")
112
- # ]
113
-
114
- # def sanitize_text(text):
115
- # """Remove invalid Unicode characters."""
116
- # return text.encode("utf-8", "replace").decode("utf-8")
117
 
118
- # def extract_video_id(url):
119
- # if not url:
120
- # return None
121
- # patterns = [
122
- # r'(?:v=|\/videos\/|embed\/|youtu.be\/|\/v\/|\/e\/|watch\?v=|\/watch\?v=)([^#\&\?]*)'
123
- # ]
124
- # for pattern in patterns:
125
- # match = re.search(pattern, url)
126
- # if match:
127
- # return match.group(1)
128
- # return None
129
-
130
- # from textblob import TextBlob
131
- # from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
132
- # import re
133
- # from collections import Counter
134
- # from googleapiclient.discovery import build
135
  # def process_youtube_video(url="", keywords=""):
136
  # try:
137
  # # Initialize variables
@@ -269,189 +269,6 @@ else:
269
  # # Placeholder for fetching recommendations based on keywords
270
  # return f"Recommendations for: {keywords}" # Dummy return for now
271
 
272
-
273
-
274
- # def get_recommendations(keywords, max_results=5):
275
- # if not keywords:
276
- # return "Please provide search keywords"
277
- # try:
278
- # response = requests.get(
279
- # "https://www.googleapis.com/youtube/v3/search",
280
- # params={
281
- # "part": "snippet",
282
- # "q": f"educational {keywords}",
283
- # "type": "video",
284
- # "maxResults": max_results,
285
- # "relevanceLanguage": "en",
286
- # "key": YOUTUBE_API_KEY
287
- # }
288
- # ).json()
289
-
290
- # results = []
291
- # for item in response.get("items", []):
292
- # title = item["snippet"]["title"]
293
- # channel = item["snippet"]["channelTitle"]
294
- # video_id = item["id"]["videoId"]
295
- # results.append(f"📺 {title}\n👤 {channel}\n🔗 https://youtube.com/watch?v={video_id}\n")
296
-
297
- # return "\n".join(results) if results else "No recommendations found"
298
- # except Exception as e:
299
- # return f"Error: {str(e)}"
300
-
301
- # # Gradio Interface
302
- # with gr.Blocks(theme=gr.themes.Soft()) as app:
303
- # # Login Page
304
- # with gr.Group() as login_page:
305
- # gr.Markdown("# 🎓 Educational Learning Management System")
306
- # username = gr.Textbox(label="Username")
307
- # password = gr.Textbox(label="Password", type="password")
308
- # login_btn = gr.Button("Login", variant="primary")
309
- # login_msg = gr.Markdown()
310
-
311
- # # Main Interface
312
- # with gr.Group(visible=False) as main_page:
313
- # with gr.Row():
314
- # with gr.Column(scale=1):
315
- # gr.Markdown("### 📋 Navigation")
316
- # nav_dashboard = gr.Button("📊 Dashboard", variant="primary")
317
- # nav_students = gr.Button("👥 Students")
318
- # nav_teachers = gr.Button("👨‍🏫 Teachers")
319
- # nav_courses = gr.Button("📚 Courses")
320
- # nav_youtube = gr.Button("🎥 YouTube Tool")
321
- # logout_btn = gr.Button("🚪 Logout", variant="stop")
322
-
323
- # with gr.Column(scale=3):
324
- # # Dashboard Content
325
- # dashboard_page = gr.Group()
326
- # with dashboard_page:
327
- # gr.Markdown("## 📊 Dashboard")
328
- # gr.Markdown(f"""
329
- # ### System Overview
330
- # - 👥 Total Students: {len(students_data)}
331
- # - 👨‍🏫 Total Teachers: {len(teachers_data)}
332
- # - 📚 Total Courses: {len(courses_data)}
333
-
334
- # ### Quick Actions
335
- # - View student performance
336
- # - Access course materials
337
- # - Generate learning insights
338
- # """)
339
-
340
- # # Students Content
341
- # students_page = gr.Group(visible=False)
342
- # with students_page:
343
- # gr.Markdown("## 👥 Students")
344
- # gr.DataFrame(
345
- # value=students_data,
346
- # headers=["ID", "Name", "Grade", "Program"]
347
- # )
348
-
349
- # # Teachers Content
350
- # teachers_page = gr.Group(visible=False)
351
- # with teachers_page:
352
- # gr.Markdown("## 👨‍🏫 Teachers")
353
- # gr.DataFrame(
354
- # value=teachers_data,
355
- # headers=["ID", "Name", "Subject", "Qualification"]
356
- # )
357
-
358
- # # Courses Content
359
- # courses_page = gr.Group(visible=False)
360
- # with courses_page:
361
- # gr.Markdown("## 📚 Courses")
362
- # gr.DataFrame(
363
- # value=courses_data,
364
- # headers=["ID", "Name", "Instructor", "Level"]
365
- # )
366
-
367
- # # YouTube Tool Content
368
- # youtube_page = gr.Group(visible=False)
369
- # with youtube_page:
370
- # gr.Markdown("## Agent for YouTube Content Exploration")
371
- # with gr.Row():
372
- # with gr.Column(scale=2):
373
- # video_url = gr.Textbox(
374
- # label="YouTube URL",
375
- # placeholder="https://youtube.com/watch?v=..."
376
- # )
377
- # keywords = gr.Textbox(
378
- # label="Keywords for Recommendations",
379
- # placeholder="e.g., python programming, machine learning"
380
- # )
381
- # analyze_btn = gr.Button("🔍 Analyze Video", variant="primary")
382
-
383
- # with gr.Column(scale=1):
384
- # video_thumbnail = gr.Image(label="Video Preview")
385
-
386
- # with gr.Row():
387
- # with gr.Column():
388
- # summary = gr.Textbox(label="📝 Summary", lines=8)
389
- # sentiment = gr.Textbox(label="😊 Content Sentiment")
390
- # with gr.Column():
391
- # recommendations = gr.Textbox(label="🎯 Related Videos", lines=10)
392
-
393
- # def login_check(user, pwd):
394
- # if USER_CREDENTIALS.get(user) == pwd:
395
- # return {
396
- # login_page: gr.update(visible=False),
397
- # main_page: gr.update(visible=True),
398
- # login_msg: ""
399
- # }
400
- # return {
401
- # login_page: gr.update(visible=True),
402
- # main_page: gr.update(visible=False),
403
- # login_msg: "❌ Invalid credentials"
404
- # }
405
-
406
- # def show_page(page_name):
407
- # updates = {
408
- # dashboard_page: gr.update(visible=False),
409
- # students_page: gr.update(visible=False),
410
- # teachers_page: gr.update(visible=False),
411
- # courses_page: gr.update(visible=False),
412
- # youtube_page: gr.update(visible=False)
413
- # }
414
- # updates[page_name] = gr.update(visible=True)
415
- # return updates
416
-
417
- # # Event Handlers
418
- # login_btn.click(
419
- # login_check,
420
- # inputs=[username, password],
421
- # outputs=[login_page, main_page, login_msg]
422
- # )
423
-
424
- # nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
425
- # nav_students.click(lambda: show_page(students_page), outputs=list(show_page(students_page).keys()))
426
- # nav_teachers.click(lambda: show_page(teachers_page), outputs=list(show_page(teachers_page).keys()))
427
- # nav_courses.click(lambda: show_page(courses_page), outputs=list(show_page(courses_page).keys()))
428
- # nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
429
-
430
- # analyze_btn.click(
431
- # process_youtube_video,
432
- # inputs=[video_url, keywords],
433
- # outputs=[video_thumbnail, summary, sentiment, recommendations]
434
- # )
435
-
436
- # logout_btn.click(
437
- # lambda: {
438
- # login_page: gr.update(visible=True),
439
- # main_page: gr.update(visible=False)
440
- # },
441
- # outputs=[login_page, main_page]
442
- # )
443
-
444
- # if __name__ == "__main__":
445
- # app.launch()
446
-
447
-
448
- # Configuration
449
- GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
450
- YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
451
-
452
- if not GOOGLE_API_KEY or not YOUTUBE_API_KEY:
453
- raise ValueError("Please set GOOGLE_API_KEY and YOUTUBE_API_KEY environment variables")
454
-
455
  def extract_video_id(url):
456
  match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11})", url)
457
  return match.group(1) if match else None
@@ -559,29 +376,323 @@ def process_youtube_video(url, keywords):
559
  except Exception as e:
560
  return None, f"Error: {str(e)}", "N/A", ""
561
 
562
- # Gradio Interface
563
- with gr.Blocks() as app:
564
- with gr.Row():
565
- gr.Markdown("# YouTube Content Analysis Tool")
566
 
567
- with gr.Row():
568
- video_url = gr.Textbox(label="YouTube URL", placeholder="https://youtube.com/watch?v=...")
569
- keywords = gr.Textbox(label="Keywords for Recommendations", placeholder="e.g., Python programming")
570
- analyze_btn = gr.Button("Analyze")
571
 
572
- with gr.Row():
573
- video_thumbnail = gr.Image(label="Thumbnail")
574
- summary = gr.Textbox(label="Summary", lines=5)
575
 
576
- with gr.Row():
577
- sentiment = gr.Textbox(label="Sentiment")
578
- recommendations = gr.Textbox(label="Related Videos", lines=5)
579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580
  analyze_btn.click(
581
  process_youtube_video,
582
  inputs=[video_url, keywords],
583
  outputs=[video_thumbnail, summary, sentiment, recommendations]
584
  )
 
 
 
 
 
 
 
 
585
 
586
  if __name__ == "__main__":
587
  app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  raise ValueError("HF_TOKEN environment variable not set.")
68
 
69
 
70
+ # Configuration
71
+ USER_CREDENTIALS = {
72
+ "admin": "password123",
73
+ "teacher": "teach2024",
74
+ "student": "learn2024"
75
+ }
76
 
77
+ import os
78
+ from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
79
 
80
+ # Use environment variables
81
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
82
+ YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
83
 
84
+ if not GOOGLE_API_KEY or not YOUTUBE_API_KEY:
85
+ raise ValueError("Please set GOOGLE_API_KEY and YOUTUBE_API_KEY environment variables")
86
 
87
+ genai.configure(api_key=GOOGLE_API_KEY)
88
+
89
+ # Database
90
+ students_data = [
91
+ (1, "Alice", "A", "Computer Science"),
92
+ (2, "Aliaa", "B", "Mathematics"),
93
+ (3, "Charlie", "A", "Machine Learning"),
94
+ (4, "Daan", "A", "Physics"),
95
+ (5, "Jhon", "C", "Math"),
96
+ (6, "Emma", "A+", "Computer Science")
97
+ ]
98
+
99
+ teachers_data = [
100
+ (1, "Dr. Smith", "Math", "MS Mathematics"),
101
+ (2, "Ms. Johnson", "Science", "MSc Physics"),
102
+ (3, "Ms. Jack", "Artificial Intelligence Engineer", "MSc AI"),
103
+ (4, "Ms. Evelyn", "Computer Science", "MSc Computer Science"),
104
+ ]
105
+
106
+ courses_data = [
107
+ (1, "Algebra", "Dr. Smith", "Advanced"),
108
+ (2, "Biology", "Ms. Mia", "Intermediate"),
109
+ (3, "Machine Learning", "Ms. Jack", "Intermediate"),
110
+ (4, "Computer Science", "Ms. Evelyn", "Intermediate"),
111
+ (5, "Mathematics", "Ms. Smith", "Intermediate")
112
+ ]
113
+
114
+ def sanitize_text(text):
115
+ """Remove invalid Unicode characters."""
116
+ return text.encode("utf-8", "replace").decode("utf-8")
117
 
118
+ def extract_video_id(url):
119
+ if not url:
120
+ return None
121
+ patterns = [
122
+ r'(?:v=|\/videos\/|embed\/|youtu.be\/|\/v\/|\/e\/|watch\?v=|\/watch\?v=)([^#\&\?]*)'
123
+ ]
124
+ for pattern in patterns:
125
+ match = re.search(pattern, url)
126
+ if match:
127
+ return match.group(1)
128
+ return None
129
+
130
+ from textblob import TextBlob
131
+ from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
132
+ import re
133
+ from collections import Counter
134
+ from googleapiclient.discovery import build
135
  # def process_youtube_video(url="", keywords=""):
136
  # try:
137
  # # Initialize variables
 
269
  # # Placeholder for fetching recommendations based on keywords
270
  # return f"Recommendations for: {keywords}" # Dummy return for now
271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  def extract_video_id(url):
273
  match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11})", url)
274
  return match.group(1) if match else None
 
376
  except Exception as e:
377
  return None, f"Error: {str(e)}", "N/A", ""
378
 
 
 
 
 
379
 
 
 
 
 
380
 
 
 
 
381
 
 
 
 
382
 
383
+
384
+
385
+ # def get_recommendations(keywords, max_results=5):
386
+ # if not keywords:
387
+ # return "Please provide search keywords"
388
+ # try:
389
+ # response = requests.get(
390
+ # "https://www.googleapis.com/youtube/v3/search",
391
+ # params={
392
+ # "part": "snippet",
393
+ # "q": f"educational {keywords}",
394
+ # "type": "video",
395
+ # "maxResults": max_results,
396
+ # "relevanceLanguage": "en",
397
+ # "key": YOUTUBE_API_KEY
398
+ # }
399
+ # ).json()
400
+
401
+ # results = []
402
+ # for item in response.get("items", []):
403
+ # title = item["snippet"]["title"]
404
+ # channel = item["snippet"]["channelTitle"]
405
+ # video_id = item["id"]["videoId"]
406
+ # results.append(f"📺 {title}\n👤 {channel}\n🔗 https://youtube.com/watch?v={video_id}\n")
407
+
408
+ # return "\n".join(results) if results else "No recommendations found"
409
+ # except Exception as e:
410
+ # return f"Error: {str(e)}"
411
+
412
+ # Gradio Interface
413
+ with gr.Blocks(theme=gr.themes.Soft()) as app:
414
+ # Login Page
415
+ with gr.Group() as login_page:
416
+ gr.Markdown("# 🎓 Educational Learning Management System")
417
+ username = gr.Textbox(label="Username")
418
+ password = gr.Textbox(label="Password", type="password")
419
+ login_btn = gr.Button("Login", variant="primary")
420
+ login_msg = gr.Markdown()
421
+
422
+ # Main Interface
423
+ with gr.Group(visible=False) as main_page:
424
+ with gr.Row():
425
+ with gr.Column(scale=1):
426
+ gr.Markdown("### 📋 Navigation")
427
+ nav_dashboard = gr.Button("📊 Dashboard", variant="primary")
428
+ nav_students = gr.Button("👥 Students")
429
+ nav_teachers = gr.Button("👨‍🏫 Teachers")
430
+ nav_courses = gr.Button("📚 Courses")
431
+ nav_youtube = gr.Button("🎥 YouTube Tool")
432
+ logout_btn = gr.Button("🚪 Logout", variant="stop")
433
+
434
+ with gr.Column(scale=3):
435
+ # Dashboard Content
436
+ dashboard_page = gr.Group()
437
+ with dashboard_page:
438
+ gr.Markdown("## 📊 Dashboard")
439
+ gr.Markdown(f"""
440
+ ### System Overview
441
+ - 👥 Total Students: {len(students_data)}
442
+ - 👨‍🏫 Total Teachers: {len(teachers_data)}
443
+ - 📚 Total Courses: {len(courses_data)}
444
+
445
+ ### Quick Actions
446
+ - View student performance
447
+ - Access course materials
448
+ - Generate learning insights
449
+ """)
450
+
451
+ # Students Content
452
+ students_page = gr.Group(visible=False)
453
+ with students_page:
454
+ gr.Markdown("## 👥 Students")
455
+ gr.DataFrame(
456
+ value=students_data,
457
+ headers=["ID", "Name", "Grade", "Program"]
458
+ )
459
+
460
+ # Teachers Content
461
+ teachers_page = gr.Group(visible=False)
462
+ with teachers_page:
463
+ gr.Markdown("## 👨‍🏫 Teachers")
464
+ gr.DataFrame(
465
+ value=teachers_data,
466
+ headers=["ID", "Name", "Subject", "Qualification"]
467
+ )
468
+
469
+ # Courses Content
470
+ courses_page = gr.Group(visible=False)
471
+ with courses_page:
472
+ gr.Markdown("## 📚 Courses")
473
+ gr.DataFrame(
474
+ value=courses_data,
475
+ headers=["ID", "Name", "Instructor", "Level"]
476
+ )
477
+
478
+ # YouTube Tool Content
479
+ youtube_page = gr.Group(visible=False)
480
+ with youtube_page:
481
+ gr.Markdown("## Agent for YouTube Content Exploration")
482
+ with gr.Row():
483
+ with gr.Column(scale=2):
484
+ video_url = gr.Textbox(
485
+ label="YouTube URL",
486
+ placeholder="https://youtube.com/watch?v=..."
487
+ )
488
+ keywords = gr.Textbox(
489
+ label="Keywords for Recommendations",
490
+ placeholder="e.g., python programming, machine learning"
491
+ )
492
+ analyze_btn = gr.Button("🔍 Analyze Video", variant="primary")
493
+
494
+ with gr.Column(scale=1):
495
+ video_thumbnail = gr.Image(label="Video Preview")
496
+
497
+ with gr.Row():
498
+ with gr.Column():
499
+ summary = gr.Textbox(label="📝 Summary", lines=8)
500
+ sentiment = gr.Textbox(label="😊 Content Sentiment")
501
+ with gr.Column():
502
+ recommendations = gr.Textbox(label="🎯 Related Videos", lines=10)
503
+
504
+ def login_check(user, pwd):
505
+ if USER_CREDENTIALS.get(user) == pwd:
506
+ return {
507
+ login_page: gr.update(visible=False),
508
+ main_page: gr.update(visible=True),
509
+ login_msg: ""
510
+ }
511
+ return {
512
+ login_page: gr.update(visible=True),
513
+ main_page: gr.update(visible=False),
514
+ login_msg: "❌ Invalid credentials"
515
+ }
516
+
517
+ def show_page(page_name):
518
+ updates = {
519
+ dashboard_page: gr.update(visible=False),
520
+ students_page: gr.update(visible=False),
521
+ teachers_page: gr.update(visible=False),
522
+ courses_page: gr.update(visible=False),
523
+ youtube_page: gr.update(visible=False)
524
+ }
525
+ updates[page_name] = gr.update(visible=True)
526
+ return updates
527
+
528
+ # Event Handlers
529
+ login_btn.click(
530
+ login_check,
531
+ inputs=[username, password],
532
+ outputs=[login_page, main_page, login_msg]
533
+ )
534
+
535
+ nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
536
+ nav_students.click(lambda: show_page(students_page), outputs=list(show_page(students_page).keys()))
537
+ nav_teachers.click(lambda: show_page(teachers_page), outputs=list(show_page(teachers_page).keys()))
538
+ nav_courses.click(lambda: show_page(courses_page), outputs=list(show_page(courses_page).keys()))
539
+ nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
540
+
541
  analyze_btn.click(
542
  process_youtube_video,
543
  inputs=[video_url, keywords],
544
  outputs=[video_thumbnail, summary, sentiment, recommendations]
545
  )
546
+
547
+ logout_btn.click(
548
+ lambda: {
549
+ login_page: gr.update(visible=True),
550
+ main_page: gr.update(visible=False)
551
+ },
552
+ outputs=[login_page, main_page]
553
+ )
554
 
555
  if __name__ == "__main__":
556
  app.launch()
557
+
558
+ ################################################
559
+ # Configuration
560
+ # GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
561
+ # YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
562
+
563
+ # if not GOOGLE_API_KEY or not YOUTUBE_API_KEY:
564
+ # raise ValueError("Please set GOOGLE_API_KEY and YOUTUBE_API_KEY environment variables")
565
+
566
+ # def extract_video_id(url):
567
+ # match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11})", url)
568
+ # return match.group(1) if match else None
569
+
570
+ # def get_video_metadata(video_id):
571
+ # try:
572
+ # youtube = build("youtube", "v3", developerKey=YOUTUBE_API_KEY)
573
+ # request = youtube.videos().list(part="snippet", id=video_id)
574
+ # response = request.execute()
575
+
576
+ # if "items" in response and len(response["items"]) > 0:
577
+ # snippet = response["items"][0]["snippet"]
578
+ # return {
579
+ # "title": snippet.get("title", "No title available"),
580
+ # "description": snippet.get("description", "No description available"),
581
+ # }
582
+ # return {}
583
+
584
+ # except Exception as e:
585
+ # return {"title": "Error fetching metadata", "description": str(e)}
586
+
587
+ # def clean_text_for_analysis(text):
588
+ # return " ".join(text.split())
589
+
590
+ # def extract_subtitle_info(text):
591
+ # try:
592
+ # sentences = text.split(". ")
593
+ # words = text.split()
594
+ # common_words = Counter(words).most_common(10)
595
+ # key_topics = ", ".join([word for word, count in common_words])
596
+ # info = f"Key topics discussed: {key_topics}. \nNumber of sentences: {len(sentences)}. \nTotal words: {len(words)}."
597
+ # return info
598
+ # except Exception as e:
599
+ # return f"Error extracting subtitle information: {str(e)}"
600
+
601
+ # def get_recommendations(keywords, max_results=5):
602
+ # if not keywords:
603
+ # return "Please provide search keywords"
604
+ # try:
605
+ # response = requests.get(
606
+ # "https://www.googleapis.com/youtube/v3/search",
607
+ # params={
608
+ # "part": "snippet",
609
+ # "q": f"educational {keywords}",
610
+ # "type": "video",
611
+ # "maxResults": max_results,
612
+ # "relevanceLanguage": "en",
613
+ # "key": YOUTUBE_API_KEY
614
+ # }
615
+ # ).json()
616
+
617
+ # results = []
618
+ # for item in response.get("items", []):
619
+ # title = item["snippet"]["title"]
620
+ # channel = item["snippet"]["channelTitle"]
621
+ # video_id = item["id"]["videoId"]
622
+ # results.append(f"📺 {title}\n👤 {channel}\n🔗 https://youtube.com/watch?v={video_id}\n")
623
+
624
+ # return "\n".join(results) if results else "No recommendations found"
625
+ # except Exception as e:
626
+ # return f"Error: {str(e)}"
627
+
628
+ # def process_youtube_video(url, keywords):
629
+ # try:
630
+ # thumbnail = None
631
+ # summary = "No transcript available"
632
+ # sentiment_label = "N/A"
633
+ # recommendations = ""
634
+
635
+ # video_id = extract_video_id(url)
636
+ # if not video_id:
637
+ # return None, "Invalid YouTube URL", "N/A", "", ""
638
+
639
+ # thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"
640
+
641
+ # try:
642
+ # transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
643
+ # transcript = None
644
+ # try:
645
+ # transcript = transcript_list.find_transcript(['en'])
646
+ # except:
647
+ # transcript = transcript_list.find_generated_transcript(['en'])
648
+
649
+ # text = " ".join([t['text'] for t in transcript.fetch()])
650
+ # if not text.strip():
651
+ # raise ValueError("Transcript is empty")
652
+
653
+ # cleaned_text = clean_text_for_analysis(text)
654
+
655
+ # sentiment = TextBlob(cleaned_text).sentiment
656
+ # sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"
657
+
658
+ # summary = f"Summary: {cleaned_text[:400]}..."
659
+
660
+ # except (TranscriptsDisabled, NoTranscriptFound):
661
+ # metadata = get_video_metadata(video_id)
662
+ # summary = metadata.get("description", "No subtitles available")
663
+ # sentiment_label = "N/A"
664
+
665
+ # if keywords.strip():
666
+ # recommendations = get_recommendations(keywords)
667
+
668
+ # return thumbnail, summary, sentiment_label, recommendations
669
+
670
+ # except Exception as e:
671
+ # return None, f"Error: {str(e)}", "N/A", ""
672
+
673
+ # # Gradio Interface
674
+ # with gr.Blocks() as app:
675
+ # with gr.Row():
676
+ # gr.Markdown("# YouTube Content Analysis Tool")
677
+
678
+ # with gr.Row():
679
+ # video_url = gr.Textbox(label="YouTube URL", placeholder="https://youtube.com/watch?v=...")
680
+ # keywords = gr.Textbox(label="Keywords for Recommendations", placeholder="e.g., Python programming")
681
+ # analyze_btn = gr.Button("Analyze")
682
+
683
+ # with gr.Row():
684
+ # video_thumbnail = gr.Image(label="Thumbnail")
685
+ # summary = gr.Textbox(label="Summary", lines=5)
686
+
687
+ # with gr.Row():
688
+ # sentiment = gr.Textbox(label="Sentiment")
689
+ # recommendations = gr.Textbox(label="Related Videos", lines=5)
690
+
691
+ # analyze_btn.click(
692
+ # process_youtube_video,
693
+ # inputs=[video_url, keywords],
694
+ # outputs=[video_thumbnail, summary, sentiment, recommendations]
695
+ # )
696
+
697
+ # if __name__ == "__main__":
698
+ # app.launch()