tdurzynski commited on
Commit
60616ea
·
verified ·
1 Parent(s): 1e56bb0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -0
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import os
3
+ import requests
4
+ import subprocess
5
+ import tempfile
6
+
7
+ from selenium import webdriver
8
+ from selenium.webdriver.chrome.options import Options
9
+ from webdriver_manager.chrome import ChromeDriverManager
10
+
11
+ import whisper
12
+ import openai
13
+ import gradio as gr
14
+
15
+ def get_video_url(page_url):
16
+ """
17
+ Uses Selenium in headless mode to load the page and extract the video URL from a <video> element.
18
+ Adjust the element-finding logic if the video is embedded differently.
19
+ """
20
+ # Set Chrome options for headless operation.
21
+ chrome_options = Options()
22
+ chrome_options.add_argument("--headless")
23
+ chrome_options.add_argument("--disable-gpu")
24
+ chrome_options.add_argument("--no-sandbox")
25
+
26
+ # Initialize Chrome driver using webdriver-manager.
27
+ driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
28
+ driver.get(page_url)
29
+
30
+ # Wait for JavaScript to render video element.
31
+ time.sleep(5)
32
+
33
+ try:
34
+ video_element = driver.find_element("tag name", "video")
35
+ video_url = video_element.get_attribute("src")
36
+ except Exception as e:
37
+ driver.quit()
38
+ raise Exception("Could not locate a <video> element. The page structure may differ: " + str(e))
39
+
40
+ driver.quit()
41
+ return video_url
42
+
43
+ def download_video(video_url, output_path):
44
+ """
45
+ Downloads the video from the extracted URL to a local file.
46
+ """
47
+ response = requests.get(video_url, stream=True)
48
+ if response.status_code != 200:
49
+ raise Exception("Failed to download video; status code: " + str(response.status_code))
50
+
51
+ with open(output_path, "wb") as f:
52
+ for chunk in response.iter_content(chunk_size=8192):
53
+ if chunk:
54
+ f.write(chunk)
55
+ return output_path
56
+
57
+ def extract_audio(video_file, audio_file):
58
+ """
59
+ Uses FFmpeg (which must be installed on your system) to extract the audio track from the video.
60
+ """
61
+ command = [
62
+ "ffmpeg",
63
+ "-i", video_file, # Input video file
64
+ "-vn", # Disable video recording
65
+ "-acodec", "pcm_s16le", # Audio codec for WAV
66
+ "-ar", "44100", # Set audio sample rate
67
+ "-ac", "2", # Set number of audio channels
68
+ audio_file
69
+ ]
70
+ try:
71
+ subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
72
+ except subprocess.CalledProcessError as e:
73
+ raise Exception("FFmpeg failed to extract audio: " + str(e))
74
+ return audio_file
75
+
76
+ def transcribe_audio(audio_file):
77
+ """
78
+ Loads the Whisper model and transcribes the provided audio file.
79
+ """
80
+ model = whisper.load_model("base")
81
+ result = model.transcribe(audio_file)
82
+ transcription = result["text"]
83
+ return transcription
84
+
85
+ def summarize_text(transcription, openai_api_key, model_name="text-davinci-003"):
86
+ """
87
+ Uses the OpenAI API to summarize the transcription.
88
+ """
89
+ openai.api_key = openai_api_key
90
+ prompt = (
91
+ "Please summarize the following transcription of a video lecture concisely:\n\n"
92
+ f"{transcription}\n\nSummary:"
93
+ )
94
+
95
+ response = openai.Completion.create(
96
+ engine=model_name,
97
+ prompt=prompt,
98
+ max_tokens=150,
99
+ temperature=0.5
100
+ )
101
+ summary = response.choices[0].text.strip()
102
+ return summary
103
+
104
+ def process_page(page_url, openai_api_key):
105
+ """
106
+ Processes the given course page URL:
107
+ 1. Scrapes the page to find the embedded video URL.
108
+ 2. Downloads the video.
109
+ 3. Extracts the audio using FFmpeg.
110
+ 4. Transcribes the audio with Whisper.
111
+ 5. Summarizes the transcription via OpenAI.
112
+
113
+ Returns the extracted video URL, full transcription, and summary.
114
+ """
115
+ try:
116
+ # 1. Get the video URL from the course page.
117
+ video_url = get_video_url(page_url)
118
+
119
+ # 2. Create a temporary file for the video.
120
+ video_temp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
121
+ video_file = video_temp.name
122
+ video_temp.close()
123
+
124
+ # Download the video.
125
+ download_video(video_url, video_file)
126
+
127
+ # 3. Create a temporary file for the audio.
128
+ audio_temp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
129
+ audio_file = audio_temp.name
130
+ audio_temp.close()
131
+
132
+ # Extract audio from the video.
133
+ extract_audio(video_file, audio_file)
134
+
135
+ # 4. Transcribe the audio.
136
+ transcription = transcribe_audio(audio_file)
137
+
138
+ # 5. Summarize the transcription.
139
+ summary = summarize_text(transcription, openai_api_key)
140
+
141
+ # Clean up temporary files.
142
+ os.remove(video_file)
143
+ os.remove(audio_file)
144
+
145
+ return video_url, transcription, summary
146
+ except Exception as e:
147
+ return "Error: " + str(e), "", ""
148
+
149
+ # Create a Gradio interface for the HF Spaces app.
150
+ interface = gr.Interface(
151
+ fn=process_page,
152
+ inputs=[
153
+ gr.Textbox(label="Course Page URL", placeholder="Enter the deeplearning.ai course page URL here..."),
154
+ gr.Textbox(label="OpenAI API Key", type="password", placeholder="Enter your OpenAI API key")
155
+ ],
156
+ outputs=[
157
+ gr.Textbox(label="Extracted Video URL"),
158
+ gr.Textbox(label="Transcription"),
159
+ gr.Textbox(label="Summary")
160
+ ],
161
+ title="Deeplearning.ai Video Analyzer",
162
+ description=(
163
+ "Enter a deeplearning.ai course page URL and your OpenAI API key. "
164
+ "The app will scrape the page to find the embedded video, download it, "
165
+ "extract the audio, transcribe the speech using Whisper, and summarize the content using GPT."
166
+ "\n\nNote: Ensure FFmpeg is installed on your system."
167
+ )
168
+ )
169
+
170
+ if __name__ == "__main__":
171
+ interface.launch()