File size: 37,514 Bytes
6a69603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1e6180
 
 
 
 
 
 
 
 
 
 
 
1258843
d1e6180
 
 
 
 
 
 
 
 
 
 
 
 
 
1258843
d1e6180
 
 
 
1258843
d1e6180
 
 
 
 
 
 
 
 
 
 
 
 
 
1258843
 
d1e6180
edf026f
a66d421
d1e6180
 
 
 
 
 
a66d421
d1e6180
 
edf026f
d1e6180
 
 
 
 
edf026f
5be560d
6a69603
 
 
e9d3c73
d1e6180
 
edf026f
d1e6180
 
 
3dbaa5e
d1e6180
 
3dbaa5e
d1e6180
3dbaa5e
d1e6180
 
 
 
 
 
 
 
 
3dbaa5e
d1e6180
 
 
 
 
 
3dbaa5e
d1e6180
 
 
 
 
 
 
3dbaa5e
00e4be8
 
7d41522
54e44e6
2906dc3
7d41522
2906dc3
7d41522
2906dc3
 
 
7d41522
2906dc3
 
 
 
 
 
 
7d41522
2906dc3
 
7d41522
2906dc3
 
 
00e4be8
d1e6180
00e4be8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2906dc3
00e4be8
 
 
 
 
 
 
 
2906dc3
d1e6180
00e4be8
1258843
4fbdbe4
849266a
2906dc3
 
4fbdbe4
849266a
2906dc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fbdbe4
2906dc3
 
4fbdbe4
2906dc3
 
4fbdbe4
849266a
c171c6f
d1e6180
 
 
 
00e4be8
d1e6180
 
 
 
6a69603
d1e6180
 
 
 
00e4be8
 
 
 
6a69603
d1e6180
 
 
00e4be8
6a69603
d1e6180
 
 
 
 
 
 
 
 
00e4be8
 
6a69603
d1e6180
 
6a69603
d1e6180
 
00e4be8
 
d1e6180
c171c6f
d1e6180
 
 
 
 
 
 
 
 
 
00e4be8
d1e6180
6a69603
d1e6180
 
 
 
 
 
 
6a69603
d1e6180
 
 
 
 
6a69603
d1e6180
 
6a69603
d1e6180
 
6a69603
4fbdbe4
d1e6180
6a69603
4fbdbe4
 
 
 
 
 
d1e6180
 
 
 
 
 
 
a66d421
d1e6180
6a69603
4fbdbe4
 
 
00e4be8
 
 
 
 
4fbdbe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
# import subprocess
# subprocess.check_call(["pip", "install", "transformers==4.34.0"])
# subprocess.check_call(["pip", "install", "torch>=1.7.1"])
# subprocess.check_call(["pip", "install", "youtube_transcript_api>=0.6.3"])
# subprocess.check_call(["pip", "install", "pytube"])
# subprocess.check_call(["pip", "install", "huggingface_hub>=0.19.0"])
# subprocess.check_call(["pip", "install", "PyPDF2>=3.0.1"])
# subprocess.check_call(["pip", "install", "google-generativeai"])
# subprocess.check_call(["pip", "install", "textblob>=0.17.1"])
# subprocess.check_call(["pip", "install", "python-dotenv>=1.0.0"])
# subprocess.check_call(["pip", "install", "genai"])
# subprocess.check_call(["pip", "install", "google-cloud-aiplatform==1.34.0"])
# subprocess.check_call(["pip", "install", "google-api-python-client>=2.0.0"])
# import transformers
# import torch
# import os 
# import youtube_transcript_api
# import pytube
# import gradio
# import PyPDF2
# import pathlib
# import pandas
# import numpy
# import textblob
# import gradio as gr
# from youtube_transcript_api import YouTubeTranscriptApi
# import google.generativeai as genai
# from googleapiclient.discovery import build
# import requests
# from textblob import TextBlob
# import re
# #from google.cloud import generativeai
# from googleapiclient.discovery import build
# from huggingface_hub import login
# from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
# def install_missing_packages():
#     required_packages = {
#          "torch":">=1.11.0",
#         "transformers":">=4.34.0",
#         "youtube_transcript_api" :">=0.6.3" ,
#         "pytube":None,
#         "huggingface_hub": ">=0.19.0",
#         "PyPDF2": ">=3.0.1",
#         "textblob":">=0.17.1",
#         "python-dotenv":">=1.0.0",
#         "genai":None,
#         "google-generativeai": None,
#         "google-cloud-aiplatform":"==1.34.0",
#         "google-api-python-client": ">=2.0.0"
#     }


#     for package, version in required_packages.items():
#         try:
#             __import__(package)
#         except ImportError:
#             package_name = f"{package}{version}" if version else package
#             subprocess.check_call(["pip", "install", package_name])

# install_missing_packages()
# # Configuration

# hf_token = os.getenv("HF_TOKEN")
# if hf_token:
#     login(hf_token)
# else:
#     raise ValueError("HF_TOKEN environment variable not set.")


# # Configuration
# USER_CREDENTIALS = {
#     "admin": "password123",
#     "teacher": "teach2024",
#     "student": "learn2024"
# }

# import os
# from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound

# # Use environment variables
# GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
# YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")

# if not GOOGLE_API_KEY or not YOUTUBE_API_KEY:
#     raise ValueError("Please set GOOGLE_API_KEY and YOUTUBE_API_KEY environment variables")

# genai.configure(api_key=GOOGLE_API_KEY)

# # Database
# students_data = [
#     (1, "Alice", "A", "Computer Science"),
#     (2, "Aliaa", "B", "Mathematics"),
#     (3, "Charlie", "A", "Machine Learning"),
#     (4, "Daan", "A", "Physics"),
#     (5, "Jhon", "C", "Math"),
#     (6, "Emma", "A+", "Computer Science")
# ]

# teachers_data = [
#     (1, "Dr. Smith", "Math", "MS Mathematics"),
#     (2, "Ms. Johnson", "Science", "MSc Physics"),
#     (3, "Ms. Jack", "Artificial Intelligence Engineer", "MSc AI"),
#     (4, "Ms. Evelyn", "Computer Science", "MSc Computer Science"),
# ]

# courses_data = [
#     (1, "Algebra", "Dr. Smith", "Advanced"),
#     (2, "Biology", "Ms. Mia", "Intermediate"),
#     (3, "Machine Learning", "Ms. Jack", "Intermediate"),
#     (4, "Computer Science", "Ms. Evelyn", "Intermediate"),
#     (5, "Mathematics", "Ms. Smith", "Intermediate")
# ]

# def sanitize_text(text):
#     """Remove invalid Unicode characters."""
#     return text.encode("utf-8", "replace").decode("utf-8")

# def extract_video_id(url):
#     if not url:
#         return None
#     patterns = [
#         r'(?:v=|\/videos\/|embed\/|youtu.be\/|\/v\/|\/e\/|watch\?v=|\/watch\?v=)([^#\&\?]*)'
#     ]
#     for pattern in patterns:
#         match = re.search(pattern, url)
#         if match:
#             return match.group(1)
#     return None

# from textblob import TextBlob
# from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
# import re
# from collections import Counter
# from googleapiclient.discovery import build


# def extract_video_id(url):
#     match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11})", url)
#     return match.group(1) if match else None

# def get_video_metadata(video_id):
#     try:
#         youtube = build("youtube", "v3", developerKey=YOUTUBE_API_KEY)
#         request = youtube.videos().list(part="snippet", id=video_id)
#         response = request.execute()

#         if "items" in response and len(response["items"]) > 0:
#             snippet = response["items"][0]["snippet"]
#             return {
#                 "title": snippet.get("title", "No title available"),
#                 "description": snippet.get("description", "No description available"),
#             }
#         return {}

#     except Exception as e:
#         return {"title": "Error fetching metadata", "description": str(e)}

# def clean_text_for_analysis(text):
#     return " ".join(text.split())

# def extract_subtitle_info(text):
#     try:
#         sentences = text.split(". ")
#         words = text.split()
#         common_words = Counter(words).most_common(10)
#         key_topics = ", ".join([word for word, count in common_words])
#         info = f"Key topics discussed: {key_topics}. \nNumber of sentences: {len(sentences)}. \nTotal words: {len(words)}."
#         return info
#     except Exception as e:
#         return f"Error extracting subtitle information: {str(e)}"

# def get_recommendations(keywords, max_results=5):
#     if not keywords:
#         return "Please provide search keywords"
#     try:
#         response = requests.get(
#             "https://www.googleapis.com/youtube/v3/search",
#             params={
#                 "part": "snippet",
#                 "q": f"educational {keywords}",
#                 "type": "video",
#                 "maxResults": max_results,
#                 "relevanceLanguage": "en",
#                 "key": YOUTUBE_API_KEY
#             }
#         ).json()

#         results = []
#         for item in response.get("items", []):
#             title = item["snippet"]["title"]
#             channel = item["snippet"]["channelTitle"]
#             video_id = item["id"]["videoId"]
#             results.append(f"πŸ“Ί {title}\nπŸ‘€ {channel}\nπŸ”— https://youtube.com/watch?v={video_id}\n")

#         return "\n".join(results) if results else "No recommendations found"
#     except Exception as e:
#         return f"Error: {str(e)}"

# def process_youtube_video(url, keywords):
#     try:
#         thumbnail = None
#         summary = "No transcript available"
#         sentiment_label = "N/A"
#         recommendations = ""

#         video_id = extract_video_id(url)
#         if not video_id:
#             return None, "Invalid YouTube URL", "N/A", "", ""

#         thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"

#         try:
#             transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
#             transcript = None
#             try:
#                 transcript = transcript_list.find_transcript(['en'])
#             except:
#                 transcript = transcript_list.find_generated_transcript(['en'])

#             text = " ".join([t['text'] for t in transcript.fetch()])
#             if not text.strip():
#                 raise ValueError("Transcript is empty")

#             cleaned_text = clean_text_for_analysis(text)

#             sentiment = TextBlob(cleaned_text).sentiment
#             sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"

#             summary = f"Summary: {cleaned_text[:400]}..."

#         except (TranscriptsDisabled, NoTranscriptFound):
#             metadata = get_video_metadata(video_id)
#             summary = metadata.get("description", "No subtitles available")
#             sentiment_label = "N/A"

#         if keywords.strip():
#             recommendations = get_recommendations(keywords)

#         return thumbnail, summary, sentiment_label, recommendations

#     except Exception as e:
#         return None, f"Error: {str(e)}", "N/A", ""


# # def get_recommendations(keywords, max_results=5):
# #     if not keywords:
# #         return "Please provide search keywords"
# #     try:
# #         response = requests.get(
# #             "https://www.googleapis.com/youtube/v3/search",
# #             params={
# #                 "part": "snippet",
# #                 "q": f"educational {keywords}",
# #                 "type": "video",
# #                 "maxResults": max_results,
# #                 "relevanceLanguage": "en",
# #                 "key": YOUTUBE_API_KEY
# #             }
# #         ).json()
        
# #         results = []
# #         for item in response.get("items", []):
# #             title = item["snippet"]["title"]
# #             channel = item["snippet"]["channelTitle"]
# #             video_id = item["id"]["videoId"]
# #             results.append(f"πŸ“Ί {title}\nπŸ‘€ {channel}\nπŸ”— https://youtube.com/watch?v={video_id}\n")
        
# #         return "\n".join(results) if results else "No recommendations found"
# #     except Exception as e:
# #         return f"Error: {str(e)}"

# # Gradio Interface
# with gr.Blocks(theme=gr.themes.Soft()) as app:
#     # Login Page
#     with gr.Group() as login_page:
#         gr.Markdown("# πŸŽ“ Educational Learning Management System")
#         username = gr.Textbox(label="Username")
#         password = gr.Textbox(label="Password", type="password")
#         login_btn = gr.Button("Login", variant="primary")
#         login_msg = gr.Markdown()
    
#     # Main Interface
#     with gr.Group(visible=False) as main_page:
#         with gr.Row():
#             with gr.Column(scale=1):
#                 gr.Markdown("### πŸ“‹ Navigation")
#                 nav_dashboard = gr.Button("πŸ“Š Dashboard", variant="primary")
#                 nav_students = gr.Button("πŸ‘₯ Students")
#                 nav_teachers = gr.Button("πŸ‘¨β€πŸ« Teachers")
#                 nav_courses = gr.Button("πŸ“š Courses")
#                 nav_youtube = gr.Button("πŸŽ₯ YouTube Tool")
#                 logout_btn = gr.Button("πŸšͺ Logout", variant="stop")
            
#             with gr.Column(scale=3):
#                 # Dashboard Content
#                 dashboard_page = gr.Group()
#                 with dashboard_page:
#                     gr.Markdown("## πŸ“Š Dashboard")
#                     gr.Markdown(f"""
#                     ### System Overview
#                     - πŸ‘₯ Total Students: {len(students_data)}
#                     - πŸ‘¨β€πŸ« Total Teachers: {len(teachers_data)}
#                     - πŸ“š Total Courses: {len(courses_data)}
                    
#                     ### Quick Actions
#                     - View student performance
#                     - Access course materials
#                     - Generate learning insights
#                     """)
                
#                 # Students Content
#                 students_page = gr.Group(visible=False)
#                 with students_page:
#                     gr.Markdown("## πŸ‘₯ Students")
#                     gr.DataFrame(
#                         value=students_data,
#                         headers=["ID", "Name", "Grade", "Program"]
#                     )
                
#                 # Teachers Content
#                 teachers_page = gr.Group(visible=False)
#                 with teachers_page:
#                     gr.Markdown("## πŸ‘¨β€πŸ« Teachers")
#                     gr.DataFrame(
#                         value=teachers_data,
#                         headers=["ID", "Name", "Subject", "Qualification"]
#                     )
                
#                 # Courses Content
#                 courses_page = gr.Group(visible=False)
#                 with courses_page:
#                     gr.Markdown("## πŸ“š Courses")
#                     gr.DataFrame(
#                         value=courses_data,
#                         headers=["ID", "Name", "Instructor", "Level"]
#                     )
                
#                 # YouTube Tool Content
#                 youtube_page = gr.Group(visible=False)
#                 with youtube_page:
#                     gr.Markdown("## Agent for YouTube Content Exploration")
#                     with gr.Row():
#                         with gr.Column(scale=2):
#                             video_url = gr.Textbox(
#                                 label="YouTube URL",
#                                 placeholder="https://youtube.com/watch?v=..."
#                             )
#                             keywords = gr.Textbox(
#                                 label="Keywords for Recommendations",
#                                 placeholder="e.g., python programming, machine learning"
#                             )
#                             analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
                        
#                         with gr.Column(scale=1):
#                             video_thumbnail = gr.Image(label="Video Preview")
                    
#                     with gr.Row():
#                         with gr.Column():
#                             summary = gr.Textbox(label="πŸ“ Summary", lines=8)
#                             sentiment = gr.Textbox(label="😊 Content Sentiment")
#                         with gr.Column():
#                             recommendations = gr.Textbox(label="🎯 Related Videos", lines=10)

#     def login_check(user, pwd):
#         if USER_CREDENTIALS.get(user) == pwd:
#             return {
#                 login_page: gr.update(visible=False),
#                 main_page: gr.update(visible=True),
#                 login_msg: ""
#             }
#         return {
#             login_page: gr.update(visible=True),
#             main_page: gr.update(visible=False),
#             login_msg: "❌ Invalid credentials"
#         }
    
#     def show_page(page_name):
#         updates = {
#             dashboard_page: gr.update(visible=False),
#             students_page: gr.update(visible=False),
#             teachers_page: gr.update(visible=False),
#             courses_page: gr.update(visible=False),
#             youtube_page: gr.update(visible=False)
#         }
#         updates[page_name] = gr.update(visible=True)
#         return updates
    
#     # Event Handlers
#     login_btn.click(
#         login_check,
#         inputs=[username, password],
#         outputs=[login_page, main_page, login_msg]
#     )
    
#     nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
#     nav_students.click(lambda: show_page(students_page), outputs=list(show_page(students_page).keys()))
#     nav_teachers.click(lambda: show_page(teachers_page), outputs=list(show_page(teachers_page).keys()))
#     nav_courses.click(lambda: show_page(courses_page), outputs=list(show_page(courses_page).keys()))
#     nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
    
#     analyze_btn.click(
#         process_youtube_video,
#         inputs=[video_url, keywords],
#         outputs=[video_thumbnail, summary, sentiment, recommendations]
#     )
    
#     logout_btn.click(
#         lambda: {
#             login_page: gr.update(visible=True),
#             main_page: gr.update(visible=False)
#         },
#         outputs=[login_page, main_page]
#     )

# if __name__ == "__main__":
#     app.launch()
import subprocess
subprocess.check_call(["pip", "install", "transformers==4.34.0"])
subprocess.check_call(["pip", "install", "torch>=1.7.1"])
subprocess.check_call(["pip", "install", "youtube_transcript_api>=0.6.3"])
subprocess.check_call(["pip", "install", "pytube"])
subprocess.check_call(["pip", "install", "huggingface_hub>=0.19.0"])
subprocess.check_call(["pip", "install", "PyPDF2>=3.0.1"])
subprocess.check_call(["pip", "install", "google-generativeai"])
subprocess.check_call(["pip", "install", "textblob>=0.17.1"])
subprocess.check_call(["pip", "install", "python-dotenv>=1.0.0"])
subprocess.check_call(["pip", "install", "genai"])
subprocess.check_call(["pip", "install", "google-cloud-aiplatform==1.34.0"])
subprocess.check_call(["pip", "install", "google-api-python-client>=2.0.0"])
import transformers
import torch
import os 
import youtube_transcript_api
import pytube
import gradio
import PyPDF2
import pathlib
import pandas
import numpy
import textblob
import gradio as gr
from youtube_transcript_api import YouTubeTranscriptApi
import google.generativeai as genai
from googleapiclient.discovery import build
import requests
from textblob import TextBlob
import re
#from google.cloud import generativeai
from googleapiclient.discovery import build
from huggingface_hub import login
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
def install_missing_packages():
    required_packages = {
         "torch":">=1.11.0",
        "transformers":">=4.34.0",
        "youtube_transcript_api" :">=0.6.3" ,
        "pytube":None,
        "huggingface_hub": ">=0.19.0",
        "PyPDF2": ">=3.0.1",
        "textblob":">=0.17.1",
        "python-dotenv":">=1.0.0",
        "genai":None,
        "google-generativeai": None,
        "google-cloud-aiplatform":"==1.34.0",
        "google-api-python-client": ">=2.0.0"
    }


    for package, version in required_packages.items():
        try:
            __import__(package)
        except ImportError:
            package_name = f"{package}{version}" if version else package
            subprocess.check_call(["pip", "install", package_name])

install_missing_packages()
# Configuration

hf_token = os.getenv("HF_TOKEN")
if hf_token:
    login(hf_token)
else:
    raise ValueError("HF_TOKEN environment variable not set.")


YOUTUBE_API_KEY = "AIzaSyD_SDF4lC3vpHVAMnBOcN2ZCTz7dRjUc98"  # Replace with your YouTube API Key

USER_CREDENTIALS = {"admin": "password"}  # Example user credentials

import os
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound

# Use environment variables
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")

if not GOOGLE_API_KEY or not YOUTUBE_API_KEY:
    raise ValueError("Please set GOOGLE_API_KEY and YOUTUBE_API_KEY environment variables")

genai.configure(api_key=GOOGLE_API_KEY)

# Database
students_data = [
    (1, "Alice", "A", "Computer Science"),
    (2, "Aliaa", "B", "Mathematics"),
    (3, "Charlie", "A", "Machine Learning"),
    (4, "Daan", "A", "Physics"),
    (5, "Jhon", "C", "Math"),
    (6, "Emma", "A+", "Computer Science")
]

teachers_data = [
    (1, "Dr. Smith", "Math", "MS Mathematics"),
    (2, "Ms. Johnson", "Science", "MSc Physics"),
    (3, "Ms. Jack", "Artificial Intelligence Engineer", "MSc AI"),
    (4, "Ms. Evelyn", "Computer Science", "MSc Computer Science"),
]

courses_data = [
    (1, "Algebra", "Dr. Smith", "Advanced"),
    (2, "Biology", "Ms. Mia", "Intermediate"),
    (3, "Machine Learning", "Ms. Jack", "Intermediate"),
    (4, "Computer Science", "Ms. Evelyn", "Intermediate"),
    (5, "Mathematics", "Ms. Smith", "Intermediate")
]



def extract_video_id(url):
    match = re.search(r"(?:v=|\/|be\/|embed\/|watch\?v=)([0-9A-Za-z_-]{11})", url)
    return match.group(1) if match else None

def get_video_metadata(video_id):
    try:
        youtube = build("youtube", "v3", developerKey=YOUTUBE_API_KEY)
        request = youtube.videos().list(part="snippet", id=video_id)
        response = request.execute()

        if "items" in response and len(response["items"]) > 0:
            snippet = response["items"][0]["snippet"]
            return {
                "title": snippet.get("title", "No title available"),
                "description": snippet.get("description", "No description available"),
            }
        return {}

    except Exception as e:
        return {"title": "Error fetching metadata", "description": str(e)}

def clean_text_for_analysis(text):
    return " ".join(text.split())

def process_youtube_video(url):
    try:
        video_id = extract_video_id(url)
        if not video_id:
            return None, "Invalid YouTube URL"

        thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"

        try:
            transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
            transcript = None
            try:
                transcript = transcript_list.find_transcript(['en'])
            except:
                transcript = transcript_list.find_generated_transcript(['en'])

            text = " ".join([t['text'] for t in transcript.fetch()])
            if not text.strip():
                raise ValueError("Transcript is empty")

            cleaned_text = clean_text_for_analysis(text)
            summary = f"Summary: {cleaned_text[:400]}..."
            return thumbnail, summary

        except (TranscriptsDisabled, NoTranscriptFound):
            metadata = get_video_metadata(video_id)
            summary = metadata.get("description", "No subtitles available")
            return thumbnail, summary

    except Exception as e:
        return None, f"Error: {str(e)}"

def analyze_sentiment(url):
    try:
        video_id = extract_video_id(url)
        if not video_id:
            return "Invalid YouTube URL", "N/A"

        try:
            transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
            transcript = None
            try:
                transcript = transcript_list.find_transcript(['en'])
            except:
                transcript = transcript_list.find_generated_transcript(['en'])

            text = " ".join([t['text'] for t in transcript.fetch()])
            if not text.strip():
                raise ValueError("Transcript is empty")

            cleaned_text = clean_text_for_analysis(text)
            sentiment = TextBlob(cleaned_text).sentiment
            sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"

            return "Sentiment Analysis Completed", sentiment_label

        except (TranscriptsDisabled, NoTranscriptFound):
            return "No transcript available", "N/A"

    except Exception as e:
        return f"Error: {str(e)}", "N/A"

# Gradio Interface
# Gradio Interface
with gr.Blocks(theme=gr.themes.Soft()) as app:
    # Login Page
    with gr.Group() as login_page:
        gr.Markdown("# πŸŽ“ Educational Learning Management System")
        username = gr.Textbox(label="Username")
        password = gr.Textbox(label="Password", type="password")
        login_btn = gr.Button("Login", variant="primary")
        login_msg = gr.Markdown()

    # Main Interface
    with gr.Group(visible=False) as main_page:
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("### πŸ“‹ Navigation")
                nav_dashboard = gr.Button("πŸ“Š Dashboard", variant="primary")
                nav_youtube = gr.Button("πŸŽ₯ YouTube Tool")
                logout_btn = gr.Button("πŸšͺ Logout", variant="stop")

            with gr.Column(scale=3):
                dashboard_page = gr.Group()
                with dashboard_page:
                    gr.Markdown("## πŸ“Š Dashboard")

                youtube_page = gr.Group(visible=False)
                with youtube_page:
                    gr.Markdown("## Agent for YouTube Content Exploration")
                    with gr.Row():
                        with gr.Column(scale=2):
                            video_url = gr.Textbox(
                                label="YouTube URL",
                                placeholder="https://youtube.com/watch?v=..."
                            )
                            analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
                            sentiment_btn = gr.Button("😊 Analyze Sentiment", variant="primary")

                        with gr.Column(scale=1):
                            video_thumbnail = gr.Image(label="Video Preview")

                    with gr.Row():
                        with gr.Column():
                            summary = gr.Textbox(label="πŸ“ Summary", lines=8)
                            sentiment = gr.Textbox(label="😊 Content Sentiment")


    def login_check(user, pwd):
        if USER_CREDENTIALS.get(user) == pwd:
            return {
                login_page: gr.update(visible=False),
                main_page: gr.update(visible=True),
                login_msg: ""
            }
        return {
            login_page: gr.update(visible=True),
            main_page: gr.update(visible=False),
            login_msg: "❌ Invalid credentials"
        }

    def show_page(page_name):
        updates = {
            dashboard_page: gr.update(visible=False),
            youtube_page: gr.update(visible=False)
        }
        updates[page_name] = gr.update(visible=True)
        return updates

    login_btn.click(
        login_check,
        inputs=[username, password],
        outputs=[login_page, main_page, login_msg]
    )

    nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
    nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))

    analyze_btn.click(
        process_youtube_video,
        inputs=[video_url],
        outputs=[video_thumbnail, summary]
    )

    sentiment_btn.click(
        analyze_sentiment,
        inputs=[video_url],
        outputs=[summary, sentiment]
    )

    logout_btn.click(
        lambda: {
            login_page: gr.update(visible=True),
            main_page: gr.update(visible=False)
        },
        outputs=[login_page, main_page]
    )

if __name__ == "__main__":
    app.launch()








# def extract_video_id(url):
#     # Improved regex to handle various YouTube URL formats
#     match = re.search(r"(?:v=|\/|be\/|embed\/|watch\?v=)([0-9A-Za-z_-]{11})", url)
#     return match.group(1) if match else None

# def get_video_metadata(video_id):
#     try:
#         youtube = build("youtube", "v3", developerKey=YOUTUBE_API_KEY)
#         request = youtube.videos().list(part="snippet", id=video_id)
#         response = request.execute()

#         if "items" in response and len(response["items"]) > 0:
#             snippet = response["items"][0]["snippet"]
#             return {
#                 "title": snippet.get("title", "No title available"),
#                 "description": snippet.get("description", "No description available"),
#             }
#         return {}

#     except Exception as e:
#         return {"title": "Error fetching metadata", "description": str(e)}

# def clean_text_for_analysis(text):
#     return " ".join(text.split())

# def get_recommendations(keywords, max_results=5):
#     if not keywords:
#         return "Please provide search keywords"
#     try:
#         response = requests.get(
#             "https://www.googleapis.com/youtube/v3/search",
#             params={
#                 "part": "snippet",
#                 "q": f"educational {keywords}",
#                 "type": "video",
#                 "maxResults": max_results,
#                 "relevanceLanguage": "en",
#                 "key": YOUTUBE_API_KEY
#             }
#         ).json()

#         results = []
#         for item in response.get("items", []):
#             title = item["snippet"]["title"]
#             channel = item["snippet"]["channelTitle"]
#             video_id = item["id"]["videoId"]
#             results.append(f"πŸ“Ί {title}\nπŸ‘€ {channel}\nπŸ”— https://youtube.com/watch?v={video_id}\n")

#         return "\n".join(results) if results else "No recommendations found"
#     except Exception as e:
#         return f"Error: {str(e)}"

# def process_youtube_video(url):
#     import re
#     from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
#     from textblob import TextBlob

#     try:
#         # Extract video ID
#         video_id = extract_video_id(url)
#         if not video_id:
#             return None, "Invalid YouTube URL", "N/A"

#         # Generate thumbnail URL
#         thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"

#         # Initialize default values
#         summary = "No transcript available"
#         sentiment_label = "N/A"

#         try:
#             # Fetch transcript
#             print(f"Fetching transcript for video ID: {video_id}")
#             transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
#             transcript = None
#             try:
#                 transcript = transcript_list.find_transcript(['en'])
#             except:
#                 transcript = transcript_list.find_generated_transcript(['en'])

#             # Combine transcript into text
#             text = " ".join([t['text'] for t in transcript.fetch()])
#             if not text.strip():
#                 raise ValueError("Transcript is empty")

#             # Clean and analyze text
#             print(f"Transcript fetched successfully. Length: {len(text)} characters")
#             cleaned_text = clean_text_for_analysis(text)
#             sentiment = TextBlob(cleaned_text).sentiment
#             sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"

#             # Summarize text
#             summary = f"Summary: {cleaned_text[:400]}..."
#             print(f"Sentiment analysis completed: {sentiment_label}")

#         except (TranscriptsDisabled, NoTranscriptFound):
#             # Fall back to metadata if no transcript
#             print(f"No transcript found for video ID: {video_id}")
#             metadata = get_video_metadata(video_id)
#             summary = metadata.get("description", "No subtitles available")
#             sentiment_label = "N/A"

#         return thumbnail, summary, sentiment_label

#     except Exception as e:
#         print(f"Error processing video: {e}")
#         return None, f"Error: {str(e)}", "N/A"

# # Test the function
# url = "https://www.youtube.com/watch?v=q1XFm21I-VQ"
# thumbnail, summary, sentiment = process_youtube_video(url)
# print(f"Thumbnail: {thumbnail}\n")
# print(f"Summary:\n{summary}\n")
# print(f"Sentiment: {sentiment}")


# # Gradio Interface
# with gr.Blocks(theme=gr.themes.Soft()) as app:
#     # Login Page
#     with gr.Group() as login_page:
#         gr.Markdown("# πŸŽ“ Educational Learning Management System")
#         username = gr.Textbox(label="Username")
#         password = gr.Textbox(label="Password", type="password")
#         login_btn = gr.Button("Login", variant="primary")
#         login_msg = gr.Markdown()

#     # Main Interface
#     with gr.Group(visible=False) as main_page:
#         with gr.Row():
#             with gr.Column(scale=1):
#                 gr.Markdown("### πŸ“‹ Navigation")
#                 nav_dashboard = gr.Button("πŸ“Š Dashboard", variant="primary")
#                 nav_students = gr.Button("πŸ‘₯ Students")
#                 nav_teachers = gr.Button("πŸ‘¨β€πŸ« Teachers")
#                 nav_courses = gr.Button("πŸ“š Courses")
#                 nav_youtube = gr.Button("πŸŽ₯ YouTube Tool")
#                 logout_btn = gr.Button("πŸšͺ Logout", variant="stop")

#             with gr.Column(scale=3):
#                 # Dashboard Content
#                 dashboard_page = gr.Group()
#                 with dashboard_page:
#                     gr.Markdown("## πŸ“Š Dashboard")
#                     gr.Markdown(f"""
#                     ### System Overview
#                     - πŸ‘₯ Total Students: {len(students_data)}
#                     - πŸ‘¨β€πŸ« Total Teachers: {len(teachers_data)}
#                     - πŸ“š Total Courses: {len(courses_data)}

#                     ### Quick Actions
#                     - View student performance
#                     - Access course materials
#                     - Generate learning insights
#                     """)

#                 # Students Content
#                 students_page = gr.Group(visible=False)
#                 with students_page:
#                     gr.Markdown("## πŸ‘₯ Students")
#                     gr.DataFrame(
#                         value=students_data,
#                         headers=["ID", "Name", "Grade", "Program"]
#                     )

#                 # Teachers Content
#                 teachers_page = gr.Group(visible=False)
#                 with teachers_page:
#                     gr.Markdown("## πŸ‘¨β€πŸ« Teachers")
#                     gr.DataFrame(
#                         value=teachers_data,
#                         headers=["ID", "Name", "Subject", "Qualification"]
#                     )

#                 # Courses Content
#                 courses_page = gr.Group(visible=False)
#                 with courses_page:
#                     gr.Markdown("## πŸ“š Courses")
#                     gr.DataFrame(
#                         value=courses_data,
#                         headers=["ID", "Name", "Instructor", "Level"]
#                     )

#                 # YouTube Tool Content
#                 youtube_page = gr.Group(visible=False)
#                 with youtube_page:
#                     gr.Markdown("## Agent for YouTube Content Exploration")
#                     with gr.Row():
#                         with gr.Column(scale=2):
#                             video_url = gr.Textbox(
#                                 label="YouTube URL",
#                                 placeholder="https://youtube.com/watch?v=..."
#                             )
#                             keywords = gr.Textbox(
#                                 label="Keywords for Recommendations",
#                                 placeholder="e.g., python programming, machine learning"
#                             )
#                             analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
#                             recommend_btn = gr.Button("πŸ”Ž Get Recommendations", variant="primary")

#                         with gr.Column(scale=1):
#                             video_thumbnail = gr.Image(label="Video Preview")

#                     with gr.Row():
#                         with gr.Column():
#                             summary = gr.Textbox(label="πŸ“ Summary", lines=8)
#                             sentiment = gr.Textbox(label="😊 Content Sentiment")
#                         with gr.Column():
#                             recommendations = gr.Textbox(label="🎯 Related Videos", lines=10)

#     def login_check(user, pwd):
#         if USER_CREDENTIALS.get(user) == pwd:
#             return {
#                 login_page: gr.update(visible=False),
#                 main_page: gr.update(visible=True),
#                 login_msg: ""
#             }
#         return {
#             login_page: gr.update(visible=True),
#             main_page: gr.update(visible=False),
#             login_msg: "❌ Invalid credentials"
#         }

#     def show_page(page_name):
#         updates = {
#             dashboard_page: gr.update(visible=False),
#             students_page: gr.update(visible=False),
#             teachers_page: gr.update(visible=False),
#             courses_page: gr.update(visible=False),
#             youtube_page: gr.update(visible=False)
#         }
#         updates[page_name] = gr.update(visible=True)
#         return updates

#     # Event Handlers
#     login_btn.click(
#         login_check,
#         inputs=[username, password],
#         outputs=[login_page, main_page, login_msg]
#     )

#     nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
#     nav_students.click(lambda: show_page(students_page), outputs=list(show_page(students_page).keys()))
#     nav_teachers.click(lambda: show_page(teachers_page), outputs=list(show_page(teachers_page).keys()))
#     nav_courses.click(lambda: show_page(courses_page), outputs=list(show_page(courses_page).keys()))
#     nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))

#     analyze_btn.click(
#         process_youtube_video,
#         inputs=[video_url],
#         outputs=[video_thumbnail, summary, sentiment]
#     )

#     recommend_btn.click(
#         get_recommendations,
#         inputs=[keywords],
#         outputs=[recommendations]
#     )

#     logout_btn.click(
#         lambda: {
#             login_page: gr.update(visible=True),
#             main_page: gr.update(visible=False)
#         },
#         outputs=[login_page, main_page]
#     )

# if __name__ == "__main__":
#     app.launch()