Spaces:
Sleeping

RillSvai commited on
Commit
896993c
·
1 Parent(s): f9291ee
Files changed (1) hide show
  1. app.py +153 -63
app.py CHANGED
@@ -2,13 +2,21 @@ import os
2
  import time
3
  import requests
4
  import gradio as gr
5
- import torch
 
 
 
6
  from huggingface_hub import login
7
  from pyannote.audio import Pipeline
8
  from transformers import pipeline
9
  from pydub import AudioSegment
10
  from io import BytesIO
 
11
 
 
 
 
 
12
 
13
  HUGGINGFACE_HUB_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
14
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
@@ -16,25 +24,59 @@ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
16
  if not HUGGINGFACE_HUB_TOKEN:
17
  raise EnvironmentError("HUGGINGFACE_HUB_TOKEN not found in environment variables.")
18
 
19
- # Authenticate with Hugging Face
20
- login(token=HUGGINGFACE_HUB_TOKEN)
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  # === Initialize Pipelines ===
23
- print("Initializing speaker diarization pipeline...")
24
- diarization_pipeline = Pipeline.from_pretrained(
25
- "pyannote/speaker-diarization-3.1",
26
- use_auth_token=HUGGINGFACE_HUB_TOKEN
27
- )
28
- print("Diarization pipeline loaded successfully.")
 
 
 
 
29
 
30
- print("Initializing transcription pipeline (Whisper)...")
31
- transcription_pipeline = pipeline(
32
- "automatic-speech-recognition",
33
- model="openai/whisper-large-v3",
34
- device=0 if torch.cuda.is_available() else -1
35
- )
36
- print("Transcription pipeline loaded successfully.")
 
 
 
 
 
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  def extract_audio_segment(audio_path, start_time, end_time):
40
  """
@@ -48,12 +90,17 @@ def extract_audio_segment(audio_path, start_time, end_time):
48
  Returns:
49
  - BytesIO object containing the audio segment in WAV format.
50
  """
51
- audio = AudioSegment.from_file(audio_path)
52
- segment = audio[start_time * 1000 : end_time * 1000]
53
- buffer = BytesIO()
54
- segment.export(buffer, format="wav")
55
- buffer.seek(0)
56
- return buffer
 
 
 
 
 
57
 
58
  def transcribe_segment(audio_segment, method='gradio'):
59
  """
@@ -66,39 +113,55 @@ def transcribe_segment(audio_segment, method='gradio'):
66
  Returns:
67
  - Transcribed text as a string.
68
  """
69
- if method == 'gradio':
70
- result = transcription_pipeline(audio_segment, return_timestamps=False)
71
- return result.get("text", "No transcription available.")
72
- elif method == 'openai':
73
- headers = {
74
- "Authorization": f"Bearer {OPENAI_API_KEY}"
75
- }
76
- files = {
77
- "file": ("segment.wav", audio_segment, "audio/wav")
78
- }
79
- data = {
80
- "model": "whisper-1"
81
- }
82
- response = requests.post(
83
- "https://api.openai.com/v1/audio/transcriptions",
84
- headers=headers,
85
- files=files,
86
- data=data
87
- )
88
- if response.status_code == 200:
89
- return response.json().get("text", "No transcription available.")
 
 
 
 
 
 
 
 
 
 
 
90
  else:
91
- return f"Transcription failed: {response.text}"
92
- else:
93
- return "Invalid transcription method."
 
 
 
94
 
95
- def process_audio(audio_file, resourceId, webhookUrl, transcription_method='gradio'):
 
 
96
  """
97
  Processes the audio file by performing speaker diarization and transcription.
98
  Sends the results to the specified webhook URL along with the resourceId.
99
 
100
  Parameters:
101
- - audio_file: Uploaded audio file.
102
  - resourceId: Identifier for the resource.
103
  - webhookUrl: URL to send the processed results.
104
  - transcription_method: Method to use for transcription ('gradio' or 'openai')
@@ -107,16 +170,28 @@ def process_audio(audio_file, resourceId, webhookUrl, transcription_method='grad
107
  - Confirmation message indicating the status of the operation.
108
  """
109
  start_time_total = time.time()
 
 
 
110
 
111
  try:
112
- audio_path = "temp_audio"
113
- with open(audio_path, "wb") as f:
114
- f.write(audio_file.read())
 
 
 
 
 
 
115
 
 
116
  diarization_start = time.time()
117
- diarization_result = diarization_pipeline(audio_path)
118
  diarization_time = time.time() - diarization_start
 
119
 
 
120
  speaker_segments = []
121
  for turn, _, speaker in diarization_result.itertracks(yield_label=True):
122
  speaker_segments.append({
@@ -124,56 +199,70 @@ def process_audio(audio_file, resourceId, webhookUrl, transcription_method='grad
124
  "start": turn.start,
125
  "end": turn.end
126
  })
 
127
 
 
128
  transcription_start = time.time()
129
  transcribed_text = ""
130
  for segment in speaker_segments:
131
  segment_audio = extract_audio_segment(
132
- audio_path, segment["start"], segment["end"]
133
  )
134
  transcription = transcribe_segment(segment_audio, method=transcription_method)
135
  transcribed_text += f"Speaker {segment['speaker']} [{segment['start']:.2f}s - {segment['end']:.2f}s]: {transcription}\n"
136
  transcription_time = time.time() - transcription_start
 
137
 
 
138
  total_execution_time = time.time() - start_time_total
 
139
 
 
140
  metrics = {
141
  "total_execution_time_sec": total_execution_time,
142
- "audio_conversion_time_sec": 0.1,
143
  "diarization_time_sec": diarization_time,
144
  "transcription_time_sec": transcription_time
145
  }
 
146
 
 
147
  result_payload = {
148
  "resourceId": resourceId,
149
  "transcribed_text": transcribed_text.strip(),
150
  "speaker_labels": list({f"Speaker {seg['speaker']}" for seg in speaker_segments}),
151
  "metrics": metrics
152
  }
 
153
 
 
154
  headers = {"Content-Type": "application/json"}
155
  response = requests.post(webhookUrl, json=result_payload, headers=headers)
156
- response.raise_for_status()
 
157
 
158
- return transcribed_text.strip()
159
 
160
  except requests.exceptions.RequestException as req_err:
161
  error_message = f"Failed to send data to webhook: {req_err}"
162
- print(error_message)
163
  return error_message
164
  except Exception as e:
165
  error_message = f"An error occurred during processing: {e}"
166
- print(error_message)
167
  return error_message
168
  finally:
169
- if os.path.exists(audio_path):
170
- os.remove(audio_path)
 
 
171
 
 
172
 
173
  interface = gr.Interface(
174
  fn=process_audio,
175
  inputs=[
176
- gr.Audio(type="file", label="Upload Audio File"),
177
  gr.Textbox(label="Resource ID", placeholder="Enter Resource ID"),
178
  gr.Textbox(label="Webhook URL", placeholder="https://your-webhook-url.com/endpoint"),
179
  gr.Radio(
@@ -193,19 +282,20 @@ interface = gr.Interface(
193
  [
194
  "path/to/audio1.wav",
195
  "resource_123",
196
- "https://webhook.site/your-webhook-url",
197
  "gradio"
198
  ],
199
  [
200
  "path/to/audio2.mp3",
201
  "resource_456",
202
- "https://webhook.site/your-webhook-url",
203
  "openai"
204
  ]
205
  ],
206
  allow_flagging="never"
207
  )
208
 
 
209
 
210
  if __name__ == "__main__":
211
  interface.launch(share=True)
 
2
  import time
3
  import requests
4
  import gradio as gr
5
+ import torch # Ensure torch is imported
6
+ import logging
7
+ import uuid
8
+ import shutil # Import shutil for file operations
9
  from huggingface_hub import login
10
  from pyannote.audio import Pipeline
11
  from transformers import pipeline
12
  from pydub import AudioSegment
13
  from io import BytesIO
14
+ from urllib.parse import urlparse
15
 
16
+ # === Configuration ===
17
+ # Ensure that you have set the following environment variables:
18
+ # - HUGGINGFACE_HUB_TOKEN: Your Hugging Face token
19
+ # - OPENAI_API_KEY: Your OpenAI API key (if using OpenAI for transcription)
20
 
21
  HUGGINGFACE_HUB_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
22
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
 
24
  if not HUGGINGFACE_HUB_TOKEN:
25
  raise EnvironmentError("HUGGINGFACE_HUB_TOKEN not found in environment variables.")
26
 
27
+ # === Logging Configuration ===
28
+ logging.basicConfig(
29
+ level=logging.INFO, # Change to DEBUG for more verbosity
30
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
31
+ )
32
+ logger = logging.getLogger(__name__)
33
+
34
+ # === Authenticate with Hugging Face ===
35
+ try:
36
+ login(token=HUGGINGFACE_HUB_TOKEN)
37
+ logger.info("Authenticated with Hugging Face.")
38
+ except Exception as e:
39
+ logger.error(f"Failed to authenticate with Hugging Face: {e}", exc_info=True)
40
+ raise e
41
 
42
  # === Initialize Pipelines ===
43
+ try:
44
+ logger.info("Initializing speaker diarization pipeline...")
45
+ diarization_pipeline = Pipeline.from_pretrained(
46
+ "pyannote/speaker-diarization-3.1",
47
+ use_auth_token=HUGGINGFACE_HUB_TOKEN
48
+ )
49
+ logger.info("Diarization pipeline loaded successfully.")
50
+ except Exception as e:
51
+ logger.error(f"Failed to initialize diarization pipeline: {e}", exc_info=True)
52
+ raise e
53
 
54
+ try:
55
+ logger.info("Initializing transcription pipeline (Whisper)...")
56
+ transcription_pipeline = pipeline(
57
+ "automatic-speech-recognition",
58
+ model="openai/whisper-large-v3",
59
+ device=0 if torch.cuda.is_available() else -1 # Use GPU if available
60
+ )
61
+ logger.info("Transcription pipeline loaded successfully.")
62
+ except Exception as e:
63
+ logger.error(f"Failed to initialize transcription pipeline: {e}", exc_info=True)
64
+ raise e
65
+
66
+ # === Helper Functions ===
67
 
68
+ def is_valid_url(url):
69
+ """
70
+ Validates the given URL.
71
+
72
+ Parameters:
73
+ - url: The URL string to validate.
74
+
75
+ Returns:
76
+ - True if the URL is valid, False otherwise.
77
+ """
78
+ parsed = urlparse(url)
79
+ return all([parsed.scheme, parsed.netloc])
80
 
81
  def extract_audio_segment(audio_path, start_time, end_time):
82
  """
 
90
  Returns:
91
  - BytesIO object containing the audio segment in WAV format.
92
  """
93
+ try:
94
+ audio = AudioSegment.from_file(audio_path)
95
+ segment = audio[start_time * 1000 : end_time * 1000] # pydub works in milliseconds
96
+ buffer = BytesIO()
97
+ segment.export(buffer, format="wav")
98
+ buffer.seek(0)
99
+ logger.debug(f"Extracted audio segment: {start_time}s to {end_time}s.")
100
+ return buffer
101
+ except Exception as e:
102
+ logger.error(f"Failed to extract audio segment: {e}", exc_info=True)
103
+ raise e
104
 
105
  def transcribe_segment(audio_segment, method='gradio'):
106
  """
 
113
  Returns:
114
  - Transcribed text as a string.
115
  """
116
+ try:
117
+ if method == 'gradio':
118
+ # Using the local Whisper pipeline
119
+ result = transcription_pipeline(audio_segment, return_timestamps=False)
120
+ transcription = result.get("text", "No transcription available.")
121
+ logger.debug(f"Transcription (gradio): {transcription}")
122
+ return transcription
123
+ elif method == 'openai':
124
+ # Using OpenAI's Whisper API
125
+ headers = {
126
+ "Authorization": f"Bearer {OPENAI_API_KEY}"
127
+ }
128
+ files = {
129
+ "file": ("segment.wav", audio_segment, "audio/wav")
130
+ }
131
+ data = {
132
+ "model": "whisper-1"
133
+ }
134
+ response = requests.post(
135
+ "https://api.openai.com/v1/audio/transcriptions",
136
+ headers=headers,
137
+ files=files,
138
+ data=data
139
+ )
140
+ if response.status_code == 200:
141
+ transcription = response.json().get("text", "No transcription available.")
142
+ logger.debug(f"Transcription (openai): {transcription}")
143
+ return transcription
144
+ else:
145
+ error_msg = f"Transcription failed: {response.text}"
146
+ logger.error(error_msg)
147
+ return error_msg
148
  else:
149
+ error_msg = "Invalid transcription method."
150
+ logger.error(error_msg)
151
+ return error_msg
152
+ except Exception as e:
153
+ logger.error(f"Transcription failed: {e}", exc_info=True)
154
+ return f"[Transcription failed: {e}]"
155
 
156
+ # === Processing Function ===
157
+
158
+ def process_audio(audio_path, resourceId, webhookUrl, transcription_method='gradio'):
159
  """
160
  Processes the audio file by performing speaker diarization and transcription.
161
  Sends the results to the specified webhook URL along with the resourceId.
162
 
163
  Parameters:
164
+ - audio_path: Path to the uploaded audio file.
165
  - resourceId: Identifier for the resource.
166
  - webhookUrl: URL to send the processed results.
167
  - transcription_method: Method to use for transcription ('gradio' or 'openai')
 
170
  - Confirmation message indicating the status of the operation.
171
  """
172
  start_time_total = time.time()
173
+ unique_id = uuid.uuid4().hex
174
+ audio_extension = os.path.splitext(audio_path)[1] if audio_path else '.wav'
175
+ temp_audio_path = f"temp_audio_{unique_id}{audio_extension}"
176
 
177
  try:
178
+ # Validate webhook URL
179
+ if not is_valid_url(webhookUrl):
180
+ error_msg = f"Invalid webhook URL provided: {webhookUrl}"
181
+ logger.error(error_msg)
182
+ return error_msg
183
+
184
+ # Copy the uploaded audio file to a unique temporary location
185
+ shutil.copy(audio_path, temp_audio_path)
186
+ logger.info(f"Copied uploaded audio to {temp_audio_path}.")
187
 
188
+ # Perform Speaker Diarization
189
  diarization_start = time.time()
190
+ diarization_result = diarization_pipeline(temp_audio_path)
191
  diarization_time = time.time() - diarization_start
192
+ logger.info(f"Speaker diarization completed in {diarization_time:.2f} seconds.")
193
 
194
+ # Parse diarization results
195
  speaker_segments = []
196
  for turn, _, speaker in diarization_result.itertracks(yield_label=True):
197
  speaker_segments.append({
 
199
  "start": turn.start,
200
  "end": turn.end
201
  })
202
+ logger.debug(f"Speaker segments: {speaker_segments}")
203
 
204
+ # Perform Transcription on each speaker segment
205
  transcription_start = time.time()
206
  transcribed_text = ""
207
  for segment in speaker_segments:
208
  segment_audio = extract_audio_segment(
209
+ temp_audio_path, segment["start"], segment["end"]
210
  )
211
  transcription = transcribe_segment(segment_audio, method=transcription_method)
212
  transcribed_text += f"Speaker {segment['speaker']} [{segment['start']:.2f}s - {segment['end']:.2f}s]: {transcription}\n"
213
  transcription_time = time.time() - transcription_start
214
+ logger.info(f"Transcription completed in {transcription_time:.2f} seconds.")
215
 
216
+ # Calculate total execution time
217
  total_execution_time = time.time() - start_time_total
218
+ logger.info(f"Total execution time: {total_execution_time:.2f} seconds.")
219
 
220
+ # Prepare metrics
221
  metrics = {
222
  "total_execution_time_sec": total_execution_time,
223
+ "audio_conversion_time_sec": 0.1, # Approximate value
224
  "diarization_time_sec": diarization_time,
225
  "transcription_time_sec": transcription_time
226
  }
227
+ logger.debug(f"Metrics: {metrics}")
228
 
229
+ # Prepare the result payload
230
  result_payload = {
231
  "resourceId": resourceId,
232
  "transcribed_text": transcribed_text.strip(),
233
  "speaker_labels": list({f"Speaker {seg['speaker']}" for seg in speaker_segments}),
234
  "metrics": metrics
235
  }
236
+ logger.info(f"Prepared result payload: {result_payload}")
237
 
238
+ # Send the result to the webhook URL
239
  headers = {"Content-Type": "application/json"}
240
  response = requests.post(webhookUrl, json=result_payload, headers=headers)
241
+ response.raise_for_status() # Raise an error for bad status codes
242
+ logger.info(f"Successfully sent data to webhook: {webhookUrl}")
243
 
244
+ return "Processing complete. Results have been sent to the webhook."
245
 
246
  except requests.exceptions.RequestException as req_err:
247
  error_message = f"Failed to send data to webhook: {req_err}"
248
+ logger.error(error_message, exc_info=True)
249
  return error_message
250
  except Exception as e:
251
  error_message = f"An error occurred during processing: {e}"
252
+ logger.error(error_message, exc_info=True)
253
  return error_message
254
  finally:
255
+ # Clean up the temporary audio file
256
+ if os.path.exists(temp_audio_path):
257
+ os.remove(temp_audio_path)
258
+ logger.info(f"Removed temporary audio file: {temp_audio_path}")
259
 
260
+ # === Gradio Interface ===
261
 
262
  interface = gr.Interface(
263
  fn=process_audio,
264
  inputs=[
265
+ gr.Audio(type="filepath", label="Upload Audio File"), # Changed from "file" to "filepath"
266
  gr.Textbox(label="Resource ID", placeholder="Enter Resource ID"),
267
  gr.Textbox(label="Webhook URL", placeholder="https://your-webhook-url.com/endpoint"),
268
  gr.Radio(
 
282
  [
283
  "path/to/audio1.wav",
284
  "resource_123",
285
+ "https://your-nestjs-webhook-url.com/webhook",
286
  "gradio"
287
  ],
288
  [
289
  "path/to/audio2.mp3",
290
  "resource_456",
291
+ "https://your-nestjs-webhook-url.com/webhook",
292
  "openai"
293
  ]
294
  ],
295
  allow_flagging="never"
296
  )
297
 
298
+ # === Launch the Gradio App ===
299
 
300
  if __name__ == "__main__":
301
  interface.launch(share=True)