Sayiqa7 commited on
Commit
dbac2c6
·
verified ·
1 Parent(s): fc7aa4a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -0
app.py CHANGED
@@ -110,6 +110,78 @@ courses_data = [
110
  ]
111
 
112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  def get_recommendations(keywords, max_results=5):
114
  if not keywords:
115
  return "Please provide search keywords"
@@ -136,6 +208,55 @@ def get_recommendations(keywords, max_results=5):
136
  except Exception as e:
137
  return f"Error: {str(e)}"
138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
  # Gradio Interface
141
  with gr.Blocks(theme=gr.themes.Soft()) as app:
 
110
  ]
111
 
112
 
113
+
114
+ def extract_video_id(url):
115
+ # Improved regex to handle various YouTube URL formats
116
+ match = re.search(r"(?:v=|\/|be\/|embed\/|watch\?v=)([0-9A-Za-z_-]{11})", url)
117
+ return match.group(1) if match else None
118
+
119
+ def get_video_metadata(video_id):
120
+ try:
121
+ youtube = build("youtube", "v3", developerKey=YOUTUBE_API_KEY)
122
+ request = youtube.videos().list(part="snippet,contentDetails", id=video_id)
123
+ response = request.execute()
124
+
125
+ if "items" in response and len(response["items"]) > 0:
126
+ snippet = response["items"][0]["snippet"]
127
+ return {
128
+ "title": snippet.get("title", "No title available"),
129
+ "description": snippet.get("description", "No description available"),
130
+ "publishedAt": snippet.get("publishedAt", "Unknown"),
131
+ "channelTitle": snippet.get("channelTitle", "Unknown"),
132
+ }
133
+ return {}
134
+
135
+ except Exception as e:
136
+ return {"title": "Error fetching metadata", "description": str(e)}
137
+
138
+ def clean_text_for_analysis(text):
139
+ return " ".join(text.split())
140
+
141
+ def segment_transcript(transcript):
142
+ # Segment the transcript into introduction, key points, main body, and conclusion
143
+ intro, key_points, main_body, conclusion = [], [], [], []
144
+ total_segments = len(transcript)
145
+
146
+ for idx, segment in enumerate(transcript):
147
+ start_time = segment['start']
148
+ text = segment['text']
149
+
150
+ # Use rough heuristics to segment transcript
151
+ if idx < total_segments * 0.1: # First 10% as introduction
152
+ intro.append(text)
153
+ elif idx < total_segments * 0.5: # Next 40% as key points
154
+ key_points.append(text)
155
+ elif idx < total_segments * 0.9: # Next 40% as main body
156
+ main_body.append(text)
157
+ else: # Last 10% as conclusion
158
+ conclusion.append(text)
159
+
160
+ return {
161
+ "introduction": " ".join(intro),
162
+ "key_points": " ".join(key_points),
163
+ "main_body": " ".join(main_body),
164
+ "conclusion": " ".join(conclusion),
165
+ }
166
+
167
+ def generate_summary(segments):
168
+ # Generate a formatted summary
169
+ return (
170
+ "**Introduction:**\n" + segments["introduction"][:400] + "...\n\n" +
171
+ "**Key Points:**\n" + segments["key_points"][:400] + "...\n\n" +
172
+ "**Main Body:**\n" + segments["main_body"][:400] + "...\n\n" +
173
+ "**Conclusion:**\n" + segments["conclusion"][:400] + "...\n"
174
+ )
175
+
176
+ def analyze_sentiment(text):
177
+ sentiment = TextBlob(text).sentiment
178
+ sentiment_label = (
179
+ "Positive" if sentiment.polarity > 0 else
180
+ "Negative" if sentiment.polarity < 0 else
181
+ "Neutral"
182
+ )
183
+ return f"{sentiment_label} ({sentiment.polarity:.2f})"
184
+
185
  def get_recommendations(keywords, max_results=5):
186
  if not keywords:
187
  return "Please provide search keywords"
 
208
  except Exception as e:
209
  return f"Error: {str(e)}"
210
 
211
+ def process_youtube_video(url):
212
+ try:
213
+ video_id = extract_video_id(url)
214
+ if not video_id:
215
+ return None, "Invalid YouTube URL", "N/A"
216
+
217
+ metadata = get_video_metadata(video_id)
218
+ title = metadata.get("title", "No title")
219
+ description = metadata.get("description", "No description available")
220
+
221
+ thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"
222
+ summary = ""
223
+ sentiment_label = "N/A"
224
+
225
+ try:
226
+ transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
227
+ transcript = None
228
+ try:
229
+ transcript = transcript_list.find_transcript(['en'])
230
+ except:
231
+ transcript = transcript_list.find_generated_transcript(['en'])
232
+
233
+ text_segments = transcript.fetch()
234
+ transcript_text = " ".join([segment['text'] for segment in text_segments])
235
+ cleaned_text = clean_text_for_analysis(transcript_text)
236
+ segmented = segment_transcript(text_segments)
237
+ summary = generate_summary(segmented)
238
+ sentiment_label = analyze_sentiment(cleaned_text)
239
+
240
+ except (TranscriptsDisabled, NoTranscriptFound):
241
+ summary = "No transcript available."
242
+
243
+ return thumbnail, title, description, summary, sentiment_label
244
+
245
+ except Exception as e:
246
+ return None, f"Error: {str(e)}", "N/A", "N/A", "N/A"
247
+
248
+ url = "https://www.youtube.com/watch?v=q1XFm21I-VQ"
249
+ thumbnail, title, description, summary, sentiment = process_youtube_video(url)
250
+
251
+ print(f"Thumbnail: {thumbnail}\n")
252
+ print(f"Title: {title}\n")
253
+ print(f"Description:\n{description}\n")
254
+ print(f"Summary:\n{summary}\n")
255
+ print(f"Sentiment: {sentiment}")
256
+
257
+
258
+
259
+
260
 
261
  # Gradio Interface
262
  with gr.Blocks(theme=gr.themes.Soft()) as app: