Sayiqa commited on
Commit
a66d421
Β·
verified Β·
1 Parent(s): 3d4840a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +289 -293
app.py CHANGED
@@ -49,314 +49,310 @@ def install_missing_packages():
49
 
50
  }
51
 
52
- # #"genai":None,
53
- # #"google-generativeai": None,
54
- # #"google-cloud-aiplatform":"==1.34.0"
55
- # for package, version in required_packages.items():
56
- # try:
57
- # __import__(package)
58
- # except ImportError:
59
- # package_name = f"{package}{version}" if version else package
60
- # subprocess.check_call(["pip", "install", package_name])
61
-
62
- # install_missing_packages()
63
- # # Configuration
64
- # USER_CREDENTIALS = {
65
- # "admin": "password123",
66
- # "teacher": "teach2024",
67
- # "student": "learn2024"
68
- # }
69
-
70
- # hf_token = os.getenv("HF_TOKEN")
71
- # if hf_token:
72
- # login(hf_token)
73
- # else:
74
- # raise ValueError("HF_TOKEN environment variable not set.")
75
 
76
- # # GOOGLE_API_KEY = "AIzaSyAURQb9jueh3dBQ4SITgKoR0L2_33en3yU"
77
- # # YOUTUBE_API_KEY = "AIzaSyB7X-RYjZmUuDSMTQsvCfyzURw5bhqOto4"
78
- # # genai.configure(api_key=GOOGLE_API_KEY)
79
- # # GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
80
- # # genai.configure(api_key=GOOGLE_API_KEY)
81
- # YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
82
- # #print("GOOGLE_API_KEY:", os.getenv("GOOGLE_API_KEY"))
83
- # print("YOUTUBE_API_KEY:", os.getenv("YOUTUBE_API_KEY"))
84
-
85
- # # Database
86
- # students_data = [
87
- # (1, "Alice", "A", "Computer Science"),
88
- # (2, "Aliaa", "B", "Mathematics"),
89
- # (3, "Charlie", "A", "Machine Learning"),
90
- # (4, "Daan", "A", "Physics"),
91
- # (5, "Jhon", "C", "Math"),
92
- # (6, "Emma", "A+", "Computer Science")
93
- # ]
94
-
95
- # teachers_data = [
96
- # (1, "Dr. Smith", "Math", "MS Mathematics"),
97
- # (2, "Ms. Johnson", "Science", "MSc Physics"),
98
- # (3, "Ms. Jack", "Artificial Intelligence Engineer", "MSc AI"),
99
- # (4, "Ms. Evelyn", "Computer Science", "MSc Computer Science"),
100
- # ]
101
-
102
- # courses_data = [
103
- # (1, "Algebra", "Dr. Smith", "Advanced"),
104
- # (2, "Biology", "Ms. Mia", "Intermediate"),
105
- # (3, "Machine Learning", "Ms. Jack", "Intermediate"),
106
- # (4, "Computer Science", "Ms. Evelyn", "Intermediate"),
107
- # (5, "Mathematics", "Ms. Smith", "Intermediate")
108
- # ]
109
-
110
- # def sanitize_text(text):
111
- # """Remove invalid Unicode characters."""
112
- # return text.encode("utf-8", "replace").decode("utf-8")
113
-
114
- # def extract_video_id(url):
115
- # if not url:
116
- # return None
117
- # patterns = [
118
- # r'(?:v=|\/videos\/|embed\/|youtu.be\/|\/v\/|\/e\/|watch\?v=|\/watch\?v=)([^#\&\?]*)'
119
- # ]
120
- # for pattern in patterns:
121
- # match = re.search(pattern, url)
122
- # if match:
123
- # return match.group(1)
124
- # return None
125
- # from youtube_transcript_api import YouTubeTranscriptApi
126
- # from transformers import T5ForConditionalGeneration, T5Tokenizer
127
- # from nltk.sentiment.vader import SentimentIntensityAnalyzer
128
- # import nltk
129
- # import sys
130
-
131
- # # Download NLTK VADER data
132
- # nltk.download('vader_lexicon')
133
-
134
- # def get_youtube_transcript(video_url):
135
- # """Extract transcript from a YouTube video."""
136
- # video_id = video_url.split("v=")[-1]
137
- # transcript = YouTubeTranscriptApi.get_transcript(video_id)
138
- # full_text = " ".join([entry['text'] for entry in transcript])
139
- # return full_text
140
-
141
- # def summarize_text(text, model_name="t5-small", max_length=150, min_length=40):
142
- # """Summarize text using T5 model."""
143
- # tokenizer = T5Tokenizer.from_pretrained(model_name)
144
- # model = T5ForConditionalGeneration.from_pretrained(model_name)
145
-
146
- # input_text = "summarize: " + text
147
- # inputs = tokenizer.encode(input_text, return_tensors="pt", max_length=512, truncation=True)
148
-
149
- # summary_ids = model.generate(inputs, max_length=max_length, min_length=min_length, length_penalty=2.0, num_beams=4, early_stopping=True)
150
- # summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
151
- # return summary
152
-
153
- # def analyze_sentiment(text):
154
- # """Perform sentiment analysis on text using VADER."""
155
- # sid = SentimentIntensityAnalyzer()
156
- # sentiment_scores = sid.polarity_scores(text)
157
- # return sentiment_scores
158
-
159
- # def main():
160
- # # Check if a URL is passed as a command-line argument
161
- # if len(sys.argv) > 1:
162
- # video_url = sys.argv[1]
163
- # else:
164
- # # Use a hardcoded URL for testing if no input is provided
165
- # video_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" # Replace with a valid URL
166
-
167
- # print("Fetching transcript...")
168
-
169
- # try:
170
- # transcript = get_youtube_transcript(video_url)
171
- # print("Transcript fetched successfully.")
172
-
173
- # print("Summarizing transcript...")
174
- # summary = summarize_text(transcript)
175
- # print("Summary:\n", summary)
176
-
177
- # print("Analyzing sentiment...")
178
- # sentiment = analyze_sentiment(transcript)
179
- # print("Sentiment Analysis:\n", sentiment)
180
-
181
- # except Exception as e:
182
- # print("An error occurred:", str(e))
183
-
184
-
185
-
186
- # def get_recommendations(keywords, max_results=5):
187
- # if not keywords:
188
- # return "Please provide search keywords"
189
- # try:
190
- # response = requests.get(
191
- # "https://www.googleapis.com/youtube/v3/search",
192
- # params={
193
- # "part": "snippet",
194
- # "q": f"educational {keywords}",
195
- # "type": "video",
196
- # "maxResults": max_results,
197
- # "relevanceLanguage": "en",
198
- # "key": YOUTUBE_API_KEY
199
- # }
200
- # ).json()
201
 
202
- # results = []
203
- # for item in response.get("items", []):
204
- # title = item["snippet"]["title"]
205
- # channel = item["snippet"]["channelTitle"]
206
- # video_id = item["id"]["videoId"]
207
- # results.append(f"πŸ“Ί {title}\nπŸ‘€ {channel}\nπŸ”— https://youtube.com/watch?v={video_id}\n")
208
 
209
- # return "\n".join(results) if results else "No recommendations found"
210
- # except Exception as e:
211
- # return f"Error: {str(e)}"
212
-
213
- # # Gradio Interface
214
- # with gr.Blocks(theme=gr.themes.Soft()) as app:
215
- # # Login Page
216
- # with gr.Group() as login_page:
217
- # gr.Markdown("# πŸŽ“ Educational Learning Management System")
218
- # username = gr.Textbox(label="Username")
219
- # password = gr.Textbox(label="Password", type="password")
220
- # login_btn = gr.Button("Login", variant="primary")
221
- # login_msg = gr.Markdown()
222
 
223
- # # Main Interface
224
- # with gr.Group(visible=False) as main_page:
225
- # with gr.Row():
226
- # with gr.Column(scale=1):
227
- # gr.Markdown("### πŸ“‹ Navigation")
228
- # nav_dashboard = gr.Button("πŸ“Š Dashboard", variant="primary")
229
- # nav_students = gr.Button("πŸ‘₯ Students")
230
- # nav_teachers = gr.Button("πŸ‘¨β€πŸ« Teachers")
231
- # nav_courses = gr.Button("πŸ“š Courses")
232
- # nav_youtube = gr.Button("πŸŽ₯ YouTube Tool")
233
- # logout_btn = gr.Button("πŸšͺ Logout", variant="stop")
234
 
235
- # with gr.Column(scale=3):
236
- # # Dashboard Content
237
- # dashboard_page = gr.Group()
238
- # with dashboard_page:
239
- # gr.Markdown("## πŸ“Š Dashboard")
240
- # gr.Markdown(f"""
241
- # ### System Overview
242
- # - πŸ‘₯ Total Students: {len(students_data)}
243
- # - πŸ‘¨β€πŸ« Total Teachers: {len(teachers_data)}
244
- # - πŸ“š Total Courses: {len(courses_data)}
245
 
246
- # ### Quick Actions
247
- # - View student performance
248
- # - Access course materials
249
- # - Generate learning insights
250
- # """)
251
 
252
- # # Students Content
253
- # students_page = gr.Group(visible=False)
254
- # with students_page:
255
- # gr.Markdown("## πŸ‘₯ Students")
256
- # gr.DataFrame(
257
- # value=students_data,
258
- # headers=["ID", "Name", "Grade", "Program"]
259
- # )
260
 
261
- # # Teachers Content
262
- # teachers_page = gr.Group(visible=False)
263
- # with teachers_page:
264
- # gr.Markdown("## πŸ‘¨β€πŸ« Teachers")
265
- # gr.DataFrame(
266
- # value=teachers_data,
267
- # headers=["ID", "Name", "Subject", "Qualification"]
268
- # )
269
 
270
- # # Courses Content
271
- # courses_page = gr.Group(visible=False)
272
- # with courses_page:
273
- # gr.Markdown("## πŸ“š Courses")
274
- # gr.DataFrame(
275
- # value=courses_data,
276
- # headers=["ID", "Name", "Instructor", "Level"]
277
- # )
278
 
279
- # # YouTube Tool Content
280
- # youtube_page = gr.Group(visible=False)
281
- # with youtube_page:
282
- # gr.Markdown("## Agent for YouTube Content Exploration")
283
- # with gr.Row():
284
- # with gr.Column(scale=2):
285
- # video_url = gr.Textbox(
286
- # label="YouTube URL",
287
- # placeholder="https://youtube.com/watch?v=..."
288
- # )
289
- # keywords = gr.Textbox(
290
- # label="Keywords for Recommendations",
291
- # placeholder="e.g., python programming, machine learning"
292
- # )
293
- # analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
294
 
295
- # with gr.Column(scale=1):
296
- # video_thumbnail = gr.Image(label="Video Preview")
297
 
298
- # with gr.Row():
299
- # with gr.Column():
300
- # summary = gr.Textbox(label="πŸ“ Summary", lines=8)
301
- # sentiment = gr.Textbox(label="😊 Content Sentiment")
302
- # with gr.Column():
303
- # recommendations = gr.Textbox(label="🎯 Related Videos", lines=10)
304
-
305
- # def login_check(user, pwd):
306
- # if USER_CREDENTIALS.get(user) == pwd:
307
- # return {
308
- # login_page: gr.update(visible=False),
309
- # main_page: gr.update(visible=True),
310
- # login_msg: ""
311
- # }
312
- # return {
313
- # login_page: gr.update(visible=True),
314
- # main_page: gr.update(visible=False),
315
- # login_msg: "❌ Invalid credentials"
316
- # }
317
 
318
- # def show_page(page_name):
319
- # updates = {
320
- # dashboard_page: gr.update(visible=False),
321
- # students_page: gr.update(visible=False),
322
- # teachers_page: gr.update(visible=False),
323
- # courses_page: gr.update(visible=False),
324
- # youtube_page: gr.update(visible=False)
325
- # }
326
- # updates[page_name] = gr.update(visible=True)
327
- # return updates
328
 
329
- # # Event Handlers
330
- # login_btn.click(
331
- # login_check,
332
- # inputs=[username, password],
333
- # outputs=[login_page, main_page, login_msg]
334
- # )
335
 
336
- # nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
337
- # nav_students.click(lambda: show_page(students_page), outputs=list(show_page(students_page).keys()))
338
- # nav_teachers.click(lambda: show_page(teachers_page), outputs=list(show_page(teachers_page).keys()))
339
- # nav_courses.click(lambda: show_page(courses_page), outputs=list(show_page(courses_page).keys()))
340
- # nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
341
 
342
- # analyze_btn.click(
343
- # process_youtube_video,
344
- # inputs=[video_url, keywords],
345
- # outputs=[video_thumbnail, summary, sentiment, recommendations]
346
- # )
347
 
348
- # logout_btn.click(
349
- # lambda: {
350
- # login_page: gr.update(visible=True),
351
- # main_page: gr.update(visible=False)
352
- # },
353
- # outputs=[login_page, main_page]
354
- # )
355
-
356
- # if __name__ == "__main__":
357
- # app.launch()
358
-
359
-
360
-
361
-
362
 
 
49
 
50
  }
51
 
52
+ #"genai":None,
53
+ #"google-generativeai": None,
54
+ #"google-cloud-aiplatform":"==1.34.0"
55
+ for package, version in required_packages.items():
56
+ try:
57
+ __import__(package)
58
+ except ImportError:
59
+ package_name = f"{package}{version}" if version else package
60
+ subprocess.check_call(["pip", "install", package_name])
61
+
62
+ install_missing_packages()
63
+ # Configuration
64
+ USER_CREDENTIALS = {
65
+ "admin": "password123",
66
+ "teacher": "teach2024",
67
+ "student": "learn2024"
68
+ }
69
+
70
+ hf_token = os.getenv("HF_TOKEN")
71
+ if hf_token:
72
+ login(hf_token)
73
+ else:
74
+ raise ValueError("HF_TOKEN environment variable not set.")
75
 
76
+ # GOOGLE_API_KEY = "AIzaSyAURQb9jueh3dBQ4SITgKoR0L2_33en3yU"
77
+ # YOUTUBE_API_KEY = "AIzaSyB7X-RYjZmUuDSMTQsvCfyzURw5bhqOto4"
78
+ # genai.configure(api_key=GOOGLE_API_KEY)
79
+ # GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
80
+ # genai.configure(api_key=GOOGLE_API_KEY)
81
+ YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
82
+ #print("GOOGLE_API_KEY:", os.getenv("GOOGLE_API_KEY"))
83
+ print("YOUTUBE_API_KEY:", os.getenv("YOUTUBE_API_KEY"))
84
+
85
+ # Database
86
+ students_data = [
87
+ (1, "Alice", "A", "Computer Science"),
88
+ (2, "Aliaa", "B", "Mathematics"),
89
+ (3, "Charlie", "A", "Machine Learning"),
90
+ (4, "Daan", "A", "Physics"),
91
+ (5, "Jhon", "C", "Math"),
92
+ (6, "Emma", "A+", "Computer Science")
93
+ ]
94
+
95
+ teachers_data = [
96
+ (1, "Dr. Smith", "Math", "MS Mathematics"),
97
+ (2, "Ms. Johnson", "Science", "MSc Physics"),
98
+ (3, "Ms. Jack", "Artificial Intelligence Engineer", "MSc AI"),
99
+ (4, "Ms. Evelyn", "Computer Science", "MSc Computer Science"),
100
+ ]
101
+
102
+ courses_data = [
103
+ (1, "Algebra", "Dr. Smith", "Advanced"),
104
+ (2, "Biology", "Ms. Mia", "Intermediate"),
105
+ (3, "Machine Learning", "Ms. Jack", "Intermediate"),
106
+ (4, "Computer Science", "Ms. Evelyn", "Intermediate"),
107
+ (5, "Mathematics", "Ms. Smith", "Intermediate")
108
+ ]
109
+
110
+ def sanitize_text(text):
111
+ """Remove invalid Unicode characters."""
112
+ return text.encode("utf-8", "replace").decode("utf-8")
113
+
114
+ def extract_video_id(url):
115
+ if not url:
116
+ return None
117
+ patterns = [
118
+ r'(?:v=|\/videos\/|embed\/|youtu.be\/|\/v\/|\/e\/|watch\?v=|\/watch\?v=)([^#\&\?]*)'
119
+ ]
120
+ for pattern in patterns:
121
+ match = re.search(pattern, url)
122
+ if match:
123
+ return match.group(1)
124
+ return None
125
+ from youtube_transcript_api import YouTubeTranscriptApi
126
+ from transformers import T5ForConditionalGeneration, T5Tokenizer
127
+ from nltk.sentiment.vader import SentimentIntensityAnalyzer
128
+ import nltk
129
+ import sys
130
+
131
+ # Download NLTK VADER data
132
+ nltk.download('vader_lexicon')
133
+
134
+ def get_youtube_transcript(video_url):
135
+ """Extract transcript from a YouTube video."""
136
+ video_id = video_url.split("v=")[-1]
137
+ transcript = YouTubeTranscriptApi.get_transcript(video_id)
138
+ full_text = " ".join([entry['text'] for entry in transcript])
139
+ return full_text
140
+
141
+ def summarize_text(text, model_name="t5-small", max_length=150, min_length=40):
142
+ """Summarize text using T5 model."""
143
+ tokenizer = T5Tokenizer.from_pretrained(model_name)
144
+ model = T5ForConditionalGeneration.from_pretrained(model_name)
145
+
146
+ input_text = "summarize: " + text
147
+ inputs = tokenizer.encode(input_text, return_tensors="pt", max_length=512, truncation=True)
148
+
149
+ summary_ids = model.generate(inputs, max_length=max_length, min_length=min_length, length_penalty=2.0, num_beams=4, early_stopping=True)
150
+ summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
151
+ return summary
152
+
153
+ def analyze_sentiment(text):
154
+ """Perform sentiment analysis on text using VADER."""
155
+ sid = SentimentIntensityAnalyzer()
156
+ sentiment_scores = sid.polarity_scores(text)
157
+ return sentiment_scores
158
+
159
+ def main():
160
+ # Check if a URL is passed as a command-line argument
161
+ if len(sys.argv) > 1:
162
+ video_url = sys.argv[1]
163
+ else:
164
+ # Use a hardcoded URL for testing if no input is provided
165
+ video_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" # Replace with a valid URL
166
+
167
+ print("Fetching transcript...")
168
+
169
+ try:
170
+ transcript = get_youtube_transcript(video_url)
171
+ print("Transcript fetched successfully.")
172
+
173
+ print("Summarizing transcript...")
174
+ summary = summarize_text(transcript)
175
+ print("Summary:\n", summary)
176
+
177
+ print("Analyzing sentiment...")
178
+ sentiment = analyze_sentiment(transcript)
179
+ print("Sentiment Analysis:\n", sentiment)
180
+
181
+ except Exception as e:
182
+ print("An error occurred:", str(e))
183
+
184
+
185
+
186
+ def get_recommendations(keywords, max_results=5):
187
+ if not keywords:
188
+ return "Please provide search keywords"
189
+ try:
190
+ response = requests.get(
191
+ "https://www.googleapis.com/youtube/v3/search",
192
+ params={
193
+ "part": "snippet",
194
+ "q": f"educational {keywords}",
195
+ "type": "video",
196
+ "maxResults": max_results,
197
+ "relevanceLanguage": "en",
198
+ "key": YOUTUBE_API_KEY
199
+ }
200
+ ).json()
201
 
202
+ results = []
203
+ for item in response.get("items", []):
204
+ title = item["snippet"]["title"]
205
+ channel = item["snippet"]["channelTitle"]
206
+ video_id = item["id"]["videoId"]
207
+ results.append(f"πŸ“Ί {title}\nπŸ‘€ {channel}\nπŸ”— https://youtube.com/watch?v={video_id}\n")
208
 
209
+ return "\n".join(results) if results else "No recommendations found"
210
+ except Exception as e:
211
+ return f"Error: {str(e)}"
212
+
213
+ # Gradio Interface
214
+ with gr.Blocks(theme=gr.themes.Soft()) as app:
215
+ # Login Page
216
+ with gr.Group() as login_page:
217
+ gr.Markdown("# πŸŽ“ Educational Learning Management System")
218
+ username = gr.Textbox(label="Username")
219
+ password = gr.Textbox(label="Password", type="password")
220
+ login_btn = gr.Button("Login", variant="primary")
221
+ login_msg = gr.Markdown()
222
 
223
+ # Main Interface
224
+ with gr.Group(visible=False) as main_page:
225
+ with gr.Row():
226
+ with gr.Column(scale=1):
227
+ gr.Markdown("### πŸ“‹ Navigation")
228
+ nav_dashboard = gr.Button("πŸ“Š Dashboard", variant="primary")
229
+ nav_students = gr.Button("πŸ‘₯ Students")
230
+ nav_teachers = gr.Button("πŸ‘¨β€πŸ« Teachers")
231
+ nav_courses = gr.Button("πŸ“š Courses")
232
+ nav_youtube = gr.Button("πŸŽ₯ YouTube Tool")
233
+ logout_btn = gr.Button("πŸšͺ Logout", variant="stop")
234
 
235
+ with gr.Column(scale=3):
236
+ # Dashboard Content
237
+ dashboard_page = gr.Group()
238
+ with dashboard_page:
239
+ gr.Markdown("## πŸ“Š Dashboard")
240
+ gr.Markdown(f"""
241
+ ### System Overview
242
+ - πŸ‘₯ Total Students: {len(students_data)}
243
+ - πŸ‘¨β€πŸ« Total Teachers: {len(teachers_data)}
244
+ - πŸ“š Total Courses: {len(courses_data)}
245
 
246
+ ### Quick Actions
247
+ - View student performance
248
+ - Access course materials
249
+ - Generate learning insights
250
+ """)
251
 
252
+ # Students Content
253
+ students_page = gr.Group(visible=False)
254
+ with students_page:
255
+ gr.Markdown("## πŸ‘₯ Students")
256
+ gr.DataFrame(
257
+ value=students_data,
258
+ headers=["ID", "Name", "Grade", "Program"]
259
+ )
260
 
261
+ # Teachers Content
262
+ teachers_page = gr.Group(visible=False)
263
+ with teachers_page:
264
+ gr.Markdown("## πŸ‘¨β€πŸ« Teachers")
265
+ gr.DataFrame(
266
+ value=teachers_data,
267
+ headers=["ID", "Name", "Subject", "Qualification"]
268
+ )
269
 
270
+ # Courses Content
271
+ courses_page = gr.Group(visible=False)
272
+ with courses_page:
273
+ gr.Markdown("## πŸ“š Courses")
274
+ gr.DataFrame(
275
+ value=courses_data,
276
+ headers=["ID", "Name", "Instructor", "Level"]
277
+ )
278
 
279
+ # YouTube Tool Content
280
+ youtube_page = gr.Group(visible=False)
281
+ with youtube_page:
282
+ gr.Markdown("## Agent for YouTube Content Exploration")
283
+ with gr.Row():
284
+ with gr.Column(scale=2):
285
+ video_url = gr.Textbox(
286
+ label="YouTube URL",
287
+ placeholder="https://youtube.com/watch?v=..."
288
+ )
289
+ keywords = gr.Textbox(
290
+ label="Keywords for Recommendations",
291
+ placeholder="e.g., python programming, machine learning"
292
+ )
293
+ analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
294
 
295
+ with gr.Column(scale=1):
296
+ video_thumbnail = gr.Image(label="Video Preview")
297
 
298
+ with gr.Row():
299
+ with gr.Column():
300
+ summary = gr.Textbox(label="πŸ“ Summary", lines=8)
301
+ sentiment = gr.Textbox(label="😊 Content Sentiment")
302
+ with gr.Column():
303
+ recommendations = gr.Textbox(label="🎯 Related Videos", lines=10)
304
+
305
+ def login_check(user, pwd):
306
+ if USER_CREDENTIALS.get(user) == pwd:
307
+ return {
308
+ login_page: gr.update(visible=False),
309
+ main_page: gr.update(visible=True),
310
+ login_msg: ""
311
+ }
312
+ return {
313
+ login_page: gr.update(visible=True),
314
+ main_page: gr.update(visible=False),
315
+ login_msg: "❌ Invalid credentials"
316
+ }
317
 
318
+ def show_page(page_name):
319
+ updates = {
320
+ dashboard_page: gr.update(visible=False),
321
+ students_page: gr.update(visible=False),
322
+ teachers_page: gr.update(visible=False),
323
+ courses_page: gr.update(visible=False),
324
+ youtube_page: gr.update(visible=False)
325
+ }
326
+ updates[page_name] = gr.update(visible=True)
327
+ return updates
328
 
329
+ # Event Handlers
330
+ login_btn.click(
331
+ login_check,
332
+ inputs=[username, password],
333
+ outputs=[login_page, main_page, login_msg]
334
+ )
335
 
336
+ nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
337
+ nav_students.click(lambda: show_page(students_page), outputs=list(show_page(students_page).keys()))
338
+ nav_teachers.click(lambda: show_page(teachers_page), outputs=list(show_page(teachers_page).keys()))
339
+ nav_courses.click(lambda: show_page(courses_page), outputs=list(show_page(courses_page).keys()))
340
+ nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
341
 
342
+ analyze_btn.click(
343
+ process_youtube_video,
344
+ inputs=[video_url, keywords],
345
+ outputs=[video_thumbnail, summary, sentiment, recommendations]
346
+ )
347
 
348
+ logout_btn.click(
349
+ lambda: {
350
+ login_page: gr.update(visible=True),
351
+ main_page: gr.update(visible=False)
352
+ },
353
+ outputs=[login_page, main_page]
354
+ )
355
+
356
+ if __name__ == "__main__":
357
+ app.launch()
 
 
 
 
358