muhtasham commited on
Commit
020bd94
·
1 Parent(s): 0844bdd
Files changed (2) hide show
  1. app.py +138 -2
  2. requirements.txt +2 -1
app.py CHANGED
@@ -3,9 +3,15 @@ import subprocess
3
  import datetime
4
  import tempfile
5
  import requests
 
 
6
  from loguru import logger
7
 
8
- API_URL = "https://skdpcqcdd929o4k3.us-east-1.aws.endpoints.huggingface.cloud"
 
 
 
 
9
  headers = {
10
  "Accept": "application/json",
11
  "Content-Type": "audio/flac"
@@ -109,6 +115,114 @@ def check_ffmpeg():
109
  # Initialize ffmpeg check
110
  check_ffmpeg()
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  def transcribe(inputs, return_timestamps, generate_subs):
113
  """Transcribe audio input using Whisper model via Hugging Face Inference API.
114
 
@@ -194,6 +308,25 @@ def transcribe(inputs, return_timestamps, generate_subs):
194
  demo = gr.Blocks(theme=gr.themes.Ocean())
195
 
196
  # Define interfaces first
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  mf_transcribe = gr.Interface(
198
  fn=transcribe,
199
  inputs=[
@@ -234,7 +367,10 @@ file_transcribe = gr.Interface(
234
 
235
  # Then set up the demo with the interfaces
236
  with demo:
237
- gr.TabbedInterface([file_transcribe, mf_transcribe], ["Audio file", "Microphone"])
 
 
 
238
 
239
  logger.info("Starting Gradio interface")
240
  demo.queue().launch(ssr_mode=False)
 
3
  import datetime
4
  import tempfile
5
  import requests
6
+ import os
7
+ import time
8
  from loguru import logger
9
 
10
+ # Load API keys from environment variables
11
+ API_URL = os.getenv("API_URL")
12
+ SIEVE_API_KEY = os.getenv("SIEVE_API_KEY")
13
+ SIEVE_API_URL = "https://mango.sievedata.com/v2"
14
+
15
  headers = {
16
  "Accept": "application/json",
17
  "Content-Type": "audio/flac"
 
115
  # Initialize ffmpeg check
116
  check_ffmpeg()
117
 
118
+ def download_youtube_audio(url):
119
+ """Download audio from YouTube using Sieve API.
120
+
121
+ Args:
122
+ url (str): YouTube video URL
123
+
124
+ Returns:
125
+ str: Path to downloaded audio file
126
+
127
+ Raises:
128
+ gr.Error: If download fails or API key is not set
129
+ """
130
+ if not SIEVE_API_KEY:
131
+ raise gr.Error("SIEVE_API_KEY environment variable is not set")
132
+
133
+ try:
134
+ # Create a temporary file for the audio
135
+ temp_file = tempfile.NamedTemporaryFile(suffix='.mp3', delete=False)
136
+ temp_file.close()
137
+ output_path = temp_file.name
138
+
139
+ # Prepare the request to Sieve API
140
+ payload = {
141
+ "function": "sieve/youtube-downloader",
142
+ "inputs": {
143
+ "url": url,
144
+ "download_type": "audio",
145
+ "audio_format": "mp3",
146
+ "include_metadata": False,
147
+ "include_subtitles": False
148
+ }
149
+ }
150
+
151
+ # Send request to Sieve API
152
+ response = requests.post(
153
+ f"{SIEVE_API_URL}/push",
154
+ headers={"X-API-Key": SIEVE_API_KEY, "Content-Type": "application/json"},
155
+ json=payload
156
+ )
157
+ response.raise_for_status()
158
+ job_id = response.json().get("id")
159
+
160
+ if not job_id:
161
+ raise gr.Error("Failed to get job ID from Sieve API")
162
+
163
+ # Poll for job completion
164
+ while True:
165
+ job_response = requests.get(
166
+ f"{SIEVE_API_URL}/jobs/{job_id}",
167
+ headers={"X-API-Key": SIEVE_API_KEY}
168
+ )
169
+ job_response.raise_for_status()
170
+ job_data = job_response.json()
171
+
172
+ if job_data.get("status") == "completed":
173
+ # Download the audio file
174
+ audio_url = job_data.get("output_0", {}).get("url")
175
+ if not audio_url:
176
+ raise gr.Error("No audio URL in job response")
177
+
178
+ audio_response = requests.get(audio_url)
179
+ audio_response.raise_for_status()
180
+
181
+ with open(output_path, "wb") as f:
182
+ f.write(audio_response.content)
183
+
184
+ return output_path
185
+
186
+ elif job_data.get("status") == "failed":
187
+ raise gr.Error(f"Job failed: {job_data.get('error', 'Unknown error')}")
188
+
189
+ # Wait before polling again
190
+ time.sleep(2)
191
+
192
+ except Exception as e:
193
+ logger.exception(f"Error downloading YouTube audio: {str(e)}")
194
+ raise gr.Error(f"Failed to download YouTube audio: {str(e)}")
195
+
196
+ def transcribe_youtube(url, return_timestamps, generate_subs):
197
+ """Transcribe audio from YouTube video.
198
+
199
+ Args:
200
+ url (str): YouTube video URL
201
+ return_timestamps (bool): Whether to include timestamps in output
202
+ generate_subs (bool): Whether to generate SRT subtitles
203
+
204
+ Returns:
205
+ tuple: (formatted_result, srt_file, correction_text)
206
+ """
207
+ try:
208
+ # Download audio from YouTube
209
+ audio_path = download_youtube_audio(url)
210
+
211
+ # Transcribe the downloaded audio
212
+ result = transcribe(audio_path, return_timestamps, generate_subs)
213
+
214
+ # Clean up the temporary file
215
+ try:
216
+ os.unlink(audio_path)
217
+ except Exception as e:
218
+ logger.warning(f"Failed to delete temporary file: {str(e)}")
219
+
220
+ return result
221
+
222
+ except Exception as e:
223
+ logger.exception(f"Error in YouTube transcription: {str(e)}")
224
+ raise gr.Error(f"Failed to transcribe YouTube video: {str(e)}")
225
+
226
  def transcribe(inputs, return_timestamps, generate_subs):
227
  """Transcribe audio input using Whisper model via Hugging Face Inference API.
228
 
 
308
  demo = gr.Blocks(theme=gr.themes.Ocean())
309
 
310
  # Define interfaces first
311
+ youtube_transcribe = gr.Interface(
312
+ fn=transcribe_youtube,
313
+ inputs=[
314
+ gr.Textbox(label="YouTube URL", placeholder="https://www.youtube.com/watch?v=..."),
315
+ gr.Checkbox(label="Include timestamps", value=True),
316
+ gr.Checkbox(label="Generate subtitles", value=True),
317
+ ],
318
+ outputs=[
319
+ gr.JSON(label="Transcription", open=True),
320
+ gr.File(label="Subtitles (SRT)", visible=True),
321
+ ],
322
+ title="Tajik Speech Transcription",
323
+ description=(
324
+ "Transcribe Tajik language audio from YouTube videos. "
325
+ "Paste a YouTube URL and get accurate transcription with optional timestamps "
326
+ "and subtitles."
327
+ )
328
+ )
329
+
330
  mf_transcribe = gr.Interface(
331
  fn=transcribe,
332
  inputs=[
 
367
 
368
  # Then set up the demo with the interfaces
369
  with demo:
370
+ gr.TabbedInterface(
371
+ [youtube_transcribe, file_transcribe, mf_transcribe],
372
+ ["YouTube", "Audio file", "Microphone"]
373
+ )
374
 
375
  logger.info("Starting Gradio interface")
376
  demo.queue().launch(ssr_mode=False)
requirements.txt CHANGED
@@ -1,2 +1,3 @@
1
  loguru
2
- gradio
 
 
1
  loguru
2
+ gradio
3
+ requests