Spaces:
Sleeping

RillSvai commited on
Commit
5934c5c
·
1 Parent(s): 7140fa1

clean repo

Browse files
Files changed (2) hide show
  1. app.py +1 -304
  2. requirements.txt +0 -7
app.py CHANGED
@@ -1,304 +1 @@
1
- import os
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")
23
-
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
- """
83
- Extracts a segment from the audio file.
84
-
85
- Parameters:
86
- - audio_path: Path to the audio file.
87
- - start_time: Start time in seconds.
88
- - end_time: End time in seconds.
89
-
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
- """
107
- Transcribes an audio segment using the specified method.
108
-
109
- Parameters:
110
- - audio_segment: BytesIO object containing the audio segment.
111
- - method: 'gradio' or 'openai'
112
-
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')
168
-
169
- Returns:
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
- # Generate unique temporary filename and copy the uploaded audio file
185
- shutil.copy(audio_path, temp_audio_path)
186
- logger.info(f"Copied uploaded audio to {temp_audio_path}.")
187
-
188
- # Initialize progress
189
- progress = gr.Progress(steps=4)
190
-
191
- with progress:
192
- # Step 1: Speaker Diarization
193
- progress(1, "Performing speaker diarization...")
194
- diarization_start = time.time()
195
- diarization_result = diarization_pipeline(temp_audio_path)
196
- diarization_time = time.time() - diarization_start
197
- logger.info(f"Speaker diarization completed in {diarization_time:.2f} seconds.")
198
-
199
- # Step 2: Parse diarization results
200
- speaker_segments = []
201
- for turn, _, speaker in diarization_result.itertracks(yield_label=True):
202
- speaker_segments.append({
203
- "speaker": speaker,
204
- "start": turn.start,
205
- "end": turn.end
206
- })
207
- logger.debug(f"Speaker segments: {speaker_segments}")
208
-
209
- # Step 3: Transcription
210
- progress(2, "Transcribing audio segments...")
211
- transcription_start = time.time()
212
- transcribed_text = ""
213
- for segment in speaker_segments:
214
- segment_audio = extract_audio_segment(
215
- temp_audio_path, segment["start"], segment["end"]
216
- )
217
- transcription = transcribe_segment(segment_audio, method=transcription_method)
218
- transcribed_text += f"Speaker {segment['speaker']} [{segment['start']:.2f}s - {segment['end']:.2f}s]: {transcription}\n"
219
- transcription_time = time.time() - transcription_start
220
- logger.info(f"Transcription completed in {transcription_time:.2f} seconds.")
221
-
222
- # Step 4: Sending to Webhook
223
- progress(3, "Sending results to webhook...")
224
- total_execution_time = time.time() - start_time_total
225
- metrics = {
226
- "total_execution_time_sec": total_execution_time,
227
- "audio_conversion_time_sec": 0.1, # Approximate value
228
- "diarization_time_sec": diarization_time,
229
- "transcription_time_sec": transcription_time
230
- }
231
- logger.debug(f"Metrics: {metrics}")
232
-
233
- result_payload = {
234
- "resourceId": resourceId,
235
- "transcribed_text": transcribed_text.strip(),
236
- "speaker_labels": list({f"Speaker {seg['speaker']}" for seg in speaker_segments}),
237
- "metrics": metrics
238
- }
239
- logger.info(f"Prepared result payload: {result_payload}")
240
-
241
- headers = {"Content-Type": "application/json"}
242
- response = requests.post(webhookUrl, json=result_payload, headers=headers)
243
- response.raise_for_status() # Raise an error for bad status codes
244
- logger.info(f"Successfully sent data to webhook: {webhookUrl}")
245
- progress(4, "Results sent successfully.")
246
-
247
- return "Processing complete. Results have been sent to the webhook."
248
-
249
- except requests.exceptions.RequestException as req_err:
250
- error_message = f"Failed to send data to webhook: {req_err}"
251
- logger.error(error_message, exc_info=True)
252
- return error_message
253
- except Exception as e:
254
- error_message = f"An error occurred during processing: {e}"
255
- logger.error(error_message, exc_info=True)
256
- return error_message
257
- finally:
258
- # Clean up the temporary audio file
259
- if os.path.exists(temp_audio_path):
260
- os.remove(temp_audio_path)
261
- logger.info(f"Removed temporary audio file: {temp_audio_path}")
262
-
263
- # === Gradio Interface ===
264
-
265
- interface = gr.Interface(
266
- fn=process_audio,
267
- inputs=[
268
- gr.Audio(type="filepath", label="Upload Audio File"), # Changed from "file" to "filepath"
269
- gr.Textbox(label="Resource ID", placeholder="Enter Resource ID"),
270
- gr.Textbox(label="Webhook URL", placeholder="https://your-webhook-url.com/endpoint"),
271
- gr.Radio(
272
- choices=["gradio", "openai"],
273
- value="gradio",
274
- label="Transcription Method",
275
- info="Choose the method for transcription: 'gradio' uses the local Whisper model, 'openai' uses OpenAI's Whisper API."
276
- )
277
- ],
278
- outputs="text",
279
- title="Unified Diarization and Transcription Service",
280
- description=(
281
- "Upload an audio file, provide a resource ID and a webhook URL. "
282
- "Choose the transcription method, and the service will perform speaker diarization and transcription, then send the results to the specified webhook."
283
- ),
284
- examples=[
285
- [
286
- "path/to/audio1.wav",
287
- "resource_123",
288
- "https://your-nestjs-webhook-url.com/webhook",
289
- "gradio"
290
- ],
291
- [
292
- "path/to/audio2.mp3",
293
- "resource_456",
294
- "https://your-nestjs-webhook-url.com/webhook",
295
- "openai"
296
- ]
297
- ],
298
- allow_flagging="never"
299
- )
300
-
301
- # === Launch the Gradio App ===
302
-
303
- if __name__ == "__main__":
304
- interface.launch(share=True)
 
1
+ print('Hello world')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,7 +0,0 @@
1
- gradio
2
- requests
3
- huggingface_hub
4
- pyannote.audio
5
- transformers
6
- pydub
7
- torch