Sayiqa commited on
Commit
bc2763c
·
verified ·
1 Parent(s): 925e76d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -99
app.py CHANGED
@@ -67,12 +67,9 @@ 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
@@ -111,36 +108,6 @@ courses_data = [
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
-
136
-
137
- from textblob import TextBlob
138
- from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
139
- import re
140
- from collections import Counter
141
- from googleapiclient.discovery import build
142
-
143
-
144
  def extract_video_id(url):
145
  match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11})", url)
146
  return match.group(1) if match else None
@@ -165,17 +132,6 @@ def get_video_metadata(video_id):
165
  def clean_text_for_analysis(text):
166
  return " ".join(text.split())
167
 
168
- def extract_subtitle_info(text):
169
- try:
170
- sentences = text.split(". ")
171
- words = text.split()
172
- common_words = Counter(words).most_common(10)
173
- key_topics = ", ".join([word for word, count in common_words])
174
- info = f"Key topics discussed: {key_topics}. \nNumber of sentences: {len(sentences)}. \nTotal words: {len(words)}."
175
- return info
176
- except Exception as e:
177
- return f"Error extracting subtitle information: {str(e)}"
178
-
179
  def get_recommendations(keywords, max_results=5):
180
  if not keywords:
181
  return "Please provide search keywords"
@@ -203,16 +159,15 @@ def get_recommendations(keywords, max_results=5):
203
  except Exception as e:
204
  return f"Error: {str(e)}"
205
 
206
- def process_youtube_video(url, keywords):
207
  try:
208
  thumbnail = None
209
  summary = "No transcript available"
210
  sentiment_label = "N/A"
211
- recommendations = ""
212
 
213
  video_id = extract_video_id(url)
214
  if not video_id:
215
- return None, "Invalid YouTube URL", "N/A", "", ""
216
 
217
  thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"
218
 
@@ -240,41 +195,10 @@ def process_youtube_video(url, keywords):
240
  summary = metadata.get("description", "No subtitles available")
241
  sentiment_label = "N/A"
242
 
243
- if keywords.strip():
244
- recommendations = get_recommendations(keywords)
245
-
246
- return thumbnail, summary, sentiment_label, recommendations
247
 
248
  except Exception as e:
249
- return None, f"Error: {str(e)}", "N/A", ""
250
-
251
-
252
- # def get_recommendations(keywords, max_results=5):
253
- # if not keywords:
254
- # return "Please provide search keywords"
255
- # try:
256
- # response = requests.get(
257
- # "https://www.googleapis.com/youtube/v3/search",
258
- # params={
259
- # "part": "snippet",
260
- # "q": f"educational {keywords}",
261
- # "type": "video",
262
- # "maxResults": max_results,
263
- # "relevanceLanguage": "en",
264
- # "key": YOUTUBE_API_KEY
265
- # }
266
- # ).json()
267
-
268
- # results = []
269
- # for item in response.get("items", []):
270
- # title = item["snippet"]["title"]
271
- # channel = item["snippet"]["channelTitle"]
272
- # video_id = item["id"]["videoId"]
273
- # results.append(f"📺 {title}\n👤 {channel}\n🔗 https://youtube.com/watch?v={video_id}\n")
274
-
275
- # return "\n".join(results) if results else "No recommendations found"
276
- # except Exception as e:
277
- # return f"Error: {str(e)}"
278
 
279
  # Gradio Interface
280
  with gr.Blocks(theme=gr.themes.Soft()) as app:
@@ -285,7 +209,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
285
  password = gr.Textbox(label="Password", type="password")
286
  login_btn = gr.Button("Login", variant="primary")
287
  login_msg = gr.Markdown()
288
-
289
  # Main Interface
290
  with gr.Group(visible=False) as main_page:
291
  with gr.Row():
@@ -297,7 +221,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
297
  nav_courses = gr.Button("📚 Courses")
298
  nav_youtube = gr.Button("🎥 YouTube Tool")
299
  logout_btn = gr.Button("🚪 Logout", variant="stop")
300
-
301
  with gr.Column(scale=3):
302
  # Dashboard Content
303
  dashboard_page = gr.Group()
@@ -308,13 +232,12 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
308
  - 👥 Total Students: {len(students_data)}
309
  - 👨‍🏫 Total Teachers: {len(teachers_data)}
310
  - 📚 Total Courses: {len(courses_data)}
311
-
312
  ### Quick Actions
313
  - View student performance
314
  - Access course materials
315
  - Generate learning insights
316
  """)
317
-
318
  # Students Content
319
  students_page = gr.Group(visible=False)
320
  with students_page:
@@ -323,7 +246,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
323
  value=students_data,
324
  headers=["ID", "Name", "Grade", "Program"]
325
  )
326
-
327
  # Teachers Content
328
  teachers_page = gr.Group(visible=False)
329
  with teachers_page:
@@ -332,7 +255,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
332
  value=teachers_data,
333
  headers=["ID", "Name", "Subject", "Qualification"]
334
  )
335
-
336
  # Courses Content
337
  courses_page = gr.Group(visible=False)
338
  with courses_page:
@@ -341,7 +264,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
341
  value=courses_data,
342
  headers=["ID", "Name", "Instructor", "Level"]
343
  )
344
-
345
  # YouTube Tool Content
346
  youtube_page = gr.Group(visible=False)
347
  with youtube_page:
@@ -357,10 +280,11 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
357
  placeholder="e.g., python programming, machine learning"
358
  )
359
  analyze_btn = gr.Button("🔍 Analyze Video", variant="primary")
360
-
 
361
  with gr.Column(scale=1):
362
  video_thumbnail = gr.Image(label="Video Preview")
363
-
364
  with gr.Row():
365
  with gr.Column():
366
  summary = gr.Textbox(label="📝 Summary", lines=8)
@@ -380,7 +304,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
380
  main_page: gr.update(visible=False),
381
  login_msg: "❌ Invalid credentials"
382
  }
383
-
384
  def show_page(page_name):
385
  updates = {
386
  dashboard_page: gr.update(visible=False),
@@ -391,26 +315,32 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
391
  }
392
  updates[page_name] = gr.update(visible=True)
393
  return updates
394
-
395
  # Event Handlers
396
  login_btn.click(
397
  login_check,
398
  inputs=[username, password],
399
  outputs=[login_page, main_page, login_msg]
400
  )
401
-
402
  nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
403
  nav_students.click(lambda: show_page(students_page), outputs=list(show_page(students_page).keys()))
404
  nav_teachers.click(lambda: show_page(teachers_page), outputs=list(show_page(teachers_page).keys()))
405
  nav_courses.click(lambda: show_page(courses_page), outputs=list(show_page(courses_page).keys()))
406
  nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
407
-
408
  analyze_btn.click(
409
  process_youtube_video,
410
- inputs=[video_url, keywords],
411
- outputs=[video_thumbnail, summary, sentiment, recommendations]
 
 
 
 
 
 
412
  )
413
-
414
  logout_btn.click(
415
  lambda: {
416
  login_page: gr.update(visible=True),
 
67
  raise ValueError("HF_TOKEN environment variable not set.")
68
 
69
 
70
+ YOUTUBE_API_KEY = "AIzaSyD_SDF4lC3vpHVAMnBOcN2ZCTz7dRjUc98" # Replace with your YouTube API Key
71
+
72
+ USER_CREDENTIALS = {"admin": "password"} # Example user credentials
 
 
 
73
 
74
  import os
75
  from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
 
108
  (5, "Mathematics", "Ms. Smith", "Intermediate")
109
  ]
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  def extract_video_id(url):
112
  match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11})", url)
113
  return match.group(1) if match else None
 
132
  def clean_text_for_analysis(text):
133
  return " ".join(text.split())
134
 
 
 
 
 
 
 
 
 
 
 
 
135
  def get_recommendations(keywords, max_results=5):
136
  if not keywords:
137
  return "Please provide search keywords"
 
159
  except Exception as e:
160
  return f"Error: {str(e)}"
161
 
162
+ def process_youtube_video(url):
163
  try:
164
  thumbnail = None
165
  summary = "No transcript available"
166
  sentiment_label = "N/A"
 
167
 
168
  video_id = extract_video_id(url)
169
  if not video_id:
170
+ return None, "Invalid YouTube URL", "N/A"
171
 
172
  thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"
173
 
 
195
  summary = metadata.get("description", "No subtitles available")
196
  sentiment_label = "N/A"
197
 
198
+ return thumbnail, summary, sentiment_label
 
 
 
199
 
200
  except Exception as e:
201
+ return None, f"Error: {str(e)}", "N/A"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
  # Gradio Interface
204
  with gr.Blocks(theme=gr.themes.Soft()) as app:
 
209
  password = gr.Textbox(label="Password", type="password")
210
  login_btn = gr.Button("Login", variant="primary")
211
  login_msg = gr.Markdown()
212
+
213
  # Main Interface
214
  with gr.Group(visible=False) as main_page:
215
  with gr.Row():
 
221
  nav_courses = gr.Button("📚 Courses")
222
  nav_youtube = gr.Button("🎥 YouTube Tool")
223
  logout_btn = gr.Button("🚪 Logout", variant="stop")
224
+
225
  with gr.Column(scale=3):
226
  # Dashboard Content
227
  dashboard_page = gr.Group()
 
232
  - 👥 Total Students: {len(students_data)}
233
  - 👨‍🏫 Total Teachers: {len(teachers_data)}
234
  - 📚 Total Courses: {len(courses_data)}
 
235
  ### Quick Actions
236
  - View student performance
237
  - Access course materials
238
  - Generate learning insights
239
  """)
240
+
241
  # Students Content
242
  students_page = gr.Group(visible=False)
243
  with students_page:
 
246
  value=students_data,
247
  headers=["ID", "Name", "Grade", "Program"]
248
  )
249
+
250
  # Teachers Content
251
  teachers_page = gr.Group(visible=False)
252
  with teachers_page:
 
255
  value=teachers_data,
256
  headers=["ID", "Name", "Subject", "Qualification"]
257
  )
258
+
259
  # Courses Content
260
  courses_page = gr.Group(visible=False)
261
  with courses_page:
 
264
  value=courses_data,
265
  headers=["ID", "Name", "Instructor", "Level"]
266
  )
267
+
268
  # YouTube Tool Content
269
  youtube_page = gr.Group(visible=False)
270
  with youtube_page:
 
280
  placeholder="e.g., python programming, machine learning"
281
  )
282
  analyze_btn = gr.Button("🔍 Analyze Video", variant="primary")
283
+ recommend_btn = gr.Button("🔎 Get Recommendations", variant="primary")
284
+
285
  with gr.Column(scale=1):
286
  video_thumbnail = gr.Image(label="Video Preview")
287
+
288
  with gr.Row():
289
  with gr.Column():
290
  summary = gr.Textbox(label="📝 Summary", lines=8)
 
304
  main_page: gr.update(visible=False),
305
  login_msg: "❌ Invalid credentials"
306
  }
307
+
308
  def show_page(page_name):
309
  updates = {
310
  dashboard_page: gr.update(visible=False),
 
315
  }
316
  updates[page_name] = gr.update(visible=True)
317
  return updates
318
+
319
  # Event Handlers
320
  login_btn.click(
321
  login_check,
322
  inputs=[username, password],
323
  outputs=[login_page, main_page, login_msg]
324
  )
325
+
326
  nav_dashboard.click(lambda: show_page(dashboard_page), outputs=list(show_page(dashboard_page).keys()))
327
  nav_students.click(lambda: show_page(students_page), outputs=list(show_page(students_page).keys()))
328
  nav_teachers.click(lambda: show_page(teachers_page), outputs=list(show_page(teachers_page).keys()))
329
  nav_courses.click(lambda: show_page(courses_page), outputs=list(show_page(courses_page).keys()))
330
  nav_youtube.click(lambda: show_page(youtube_page), outputs=list(show_page(youtube_page).keys()))
331
+
332
  analyze_btn.click(
333
  process_youtube_video,
334
+ inputs=[video_url],
335
+ outputs=[video_thumbnail, summary, sentiment]
336
+ )
337
+
338
+ recommend_btn.click(
339
+ get_recommendations,
340
+ inputs=[keywords],
341
+ outputs=[recommendations]
342
  )
343
+
344
  logout_btn.click(
345
  lambda: {
346
  login_page: gr.update(visible=True),