liuyang commited on
Commit
427ce39
·
1 Parent(s): 888e818
Files changed (4) hide show
  1. README.md +3 -3
  2. app.py +458 -4
  3. config.py +69 -0
  4. requirements.txt +34 -0
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
  title: Whisper Transcribe
3
- emoji: 🌖
4
- colorFrom: yellow
5
- colorTo: green
6
  sdk: gradio
7
  sdk_version: 5.35.0
8
  app_file: app.py
 
1
  ---
2
  title: Whisper Transcribe
3
+ emoji: 🎙️
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: gradio
7
  sdk_version: 5.35.0
8
  app_file: app.py
app.py CHANGED
@@ -1,7 +1,461 @@
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
 
 
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import torch
3
+ import torchaudio
4
+ import numpy as np
5
+ import pandas as pd
6
+ import time
7
+ import datetime
8
+ import re
9
+ import subprocess
10
+ import os
11
+ import tempfile
12
+ import spaces
13
+ from transformers import pipeline
14
+ from pyannote.audio import Pipeline
15
+ import requests
16
+ import base64
17
+ from typing import List, Dict, Any, Optional, Tuple
18
 
19
+ # Install flash attention for acceleration
20
+ try:
21
+ subprocess.run(
22
+ "pip install flash-attn --no-build-isolation",
23
+ env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
24
+ shell=True,
25
+ check=True
26
+ )
27
+ except subprocess.CalledProcessError:
28
+ print("Warning: Could not install flash-attn, falling back to default attention")
29
 
30
+ class WhisperTranscriber:
31
+ def __init__(self):
32
+ self.pipe = None
33
+ self.diarization_model = None
34
+
35
+ @spaces.GPU
36
+ def setup_models(self):
37
+ """Initialize models with GPU acceleration"""
38
+ if self.pipe is None:
39
+ print("Loading Whisper model...")
40
+ self.pipe = pipeline(
41
+ "automatic-speech-recognition",
42
+ model="openai/whisper-large-v3-turbo",
43
+ torch_dtype=torch.float16,
44
+ device="cuda:0",
45
+ model_kwargs={"attn_implementation": "flash_attention_2"},
46
+ return_timestamps=True,
47
+ )
48
+
49
+ if self.diarization_model is None:
50
+ print("Loading diarization model...")
51
+ # Note: You'll need to set up authentication for pyannote models
52
+ # For demo purposes, we'll handle the case where it's not available
53
+ try:
54
+ self.diarization_model = Pipeline.from_pretrained(
55
+ "pyannote/speaker-diarization-3.1",
56
+ use_auth_token=os.getenv("HF_TOKEN")
57
+ ).to(torch.device("cuda"))
58
+ except Exception as e:
59
+ print(f"Could not load diarization model: {e}")
60
+ self.diarization_model = None
61
+
62
+ def convert_audio_format(self, audio_path: str) -> str:
63
+ """Convert audio to 16kHz mono WAV format"""
64
+ temp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
65
+ temp_wav_path = temp_wav.name
66
+ temp_wav.close()
67
+
68
+ try:
69
+ subprocess.run([
70
+ "ffmpeg", "-i", audio_path,
71
+ "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le",
72
+ temp_wav_path, "-y"
73
+ ], check=True, capture_output=True)
74
+ return temp_wav_path
75
+ except subprocess.CalledProcessError as e:
76
+ raise RuntimeError(f"Audio conversion failed: {e}")
77
+
78
+ @spaces.GPU
79
+ def transcribe_audio(
80
+ self,
81
+ audio_path: str,
82
+ language: Optional[str] = None,
83
+ translate: bool = False,
84
+ prompt: Optional[str] = None
85
+ ) -> Tuple[List[Dict], str]:
86
+ """Transcribe audio using Whisper with flash attention"""
87
+ if self.pipe is None:
88
+ self.setup_models()
89
+
90
+ print("Starting transcription...")
91
+ start_time = time.time()
92
+
93
+ # Prepare generation kwargs
94
+ generate_kwargs = {}
95
+ if language:
96
+ generate_kwargs["language"] = language
97
+ if translate:
98
+ generate_kwargs["task"] = "translate"
99
+ if prompt:
100
+ generate_kwargs["prompt_ids"] = self.pipe.tokenizer.encode(prompt)
101
+
102
+ # Transcribe with timestamps
103
+ result = self.pipe(
104
+ audio_path,
105
+ return_timestamps=True,
106
+ generate_kwargs=generate_kwargs
107
+ )
108
+
109
+ # Extract segments and detected language
110
+ segments = []
111
+ if "chunks" in result:
112
+ for chunk in result["chunks"]:
113
+ segment = {
114
+ "start": float(chunk["timestamp"][0] or 0),
115
+ "end": float(chunk["timestamp"][1] or 0),
116
+ "text": chunk["text"].strip(),
117
+ }
118
+ segments.append(segment)
119
+ else:
120
+ # Fallback for different result format
121
+ segments = [{
122
+ "start": 0.0,
123
+ "end": 0.0,
124
+ "text": result["text"]
125
+ }]
126
+
127
+ detected_language = getattr(result, 'language', language or 'unknown')
128
+
129
+ transcription_time = time.time() - start_time
130
+ print(f"Transcription completed in {transcription_time:.2f} seconds")
131
+
132
+ return segments, detected_language
133
+
134
+ @spaces.GPU
135
+ def perform_diarization(
136
+ self,
137
+ audio_path: str,
138
+ num_speakers: Optional[int] = None
139
+ ) -> Tuple[List[Dict], int]:
140
+ """Perform speaker diarization"""
141
+ if self.diarization_model is None:
142
+ print("Diarization model not available, assigning single speaker")
143
+ return [], 1
144
+
145
+ print("Starting diarization...")
146
+ start_time = time.time()
147
+
148
+ # Load audio for diarization
149
+ waveform, sample_rate = torchaudio.load(audio_path)
150
+
151
+ # Perform diarization
152
+ diarization = self.diarization_model(
153
+ {"waveform": waveform, "sample_rate": sample_rate},
154
+ num_speakers=num_speakers,
155
+ )
156
+
157
+ # Convert to list format
158
+ diarize_segments = []
159
+ diarization_list = list(diarization.itertracks(yield_label=True))
160
+
161
+ for turn, _, speaker in diarization_list:
162
+ diarize_segments.append({
163
+ "start": turn.start,
164
+ "end": turn.end,
165
+ "speaker": speaker
166
+ })
167
+
168
+ unique_speakers = {speaker for _, _, speaker in diarization_list}
169
+ detected_num_speakers = len(unique_speakers)
170
+
171
+ diarization_time = time.time() - start_time
172
+ print(f"Diarization completed in {diarization_time:.2f} seconds")
173
+
174
+ return diarize_segments, detected_num_speakers
175
+
176
+ def merge_transcription_and_diarization(
177
+ self,
178
+ transcription_segments: List[Dict],
179
+ diarization_segments: List[Dict]
180
+ ) -> List[Dict]:
181
+ """Merge transcription segments with speaker information"""
182
+ if not diarization_segments:
183
+ # No diarization available, assign single speaker
184
+ for segment in transcription_segments:
185
+ segment["speaker"] = "SPEAKER_00"
186
+ return transcription_segments
187
+
188
+ print("Merging transcription and diarization...")
189
+ diarize_df = pd.DataFrame(diarization_segments)
190
+
191
+ final_segments = []
192
+ for segment in transcription_segments:
193
+ # Calculate intersection with diarization segments
194
+ diarize_df["intersection"] = np.maximum(0,
195
+ np.minimum(diarize_df["end"], segment["end"]) -
196
+ np.maximum(diarize_df["start"], segment["start"])
197
+ )
198
+
199
+ # Find speaker with maximum intersection
200
+ dia_tmp = diarize_df[diarize_df["intersection"] > 0]
201
+ if len(dia_tmp) > 0:
202
+ speaker = (
203
+ dia_tmp.groupby("speaker")["intersection"]
204
+ .sum()
205
+ .sort_values(ascending=False)
206
+ .index[0]
207
+ )
208
+ else:
209
+ speaker = "SPEAKER_00"
210
+
211
+ segment["speaker"] = speaker
212
+ segment["duration"] = segment["end"] - segment["start"]
213
+ final_segments.append(segment)
214
+
215
+ return final_segments
216
+
217
+ def group_segments_by_speaker(
218
+ self,
219
+ segments: List[Dict],
220
+ max_gap: float = 1.0,
221
+ max_duration: float = 30.0
222
+ ) -> List[Dict]:
223
+ """Group consecutive segments from the same speaker"""
224
+ if not segments:
225
+ return segments
226
+
227
+ grouped_segments = []
228
+ current_group = segments[0].copy()
229
+ sentence_end_pattern = r"[.!?]+\s*$"
230
+
231
+ for segment in segments[1:]:
232
+ time_gap = segment["start"] - current_group["end"]
233
+ current_duration = current_group["end"] - current_group["start"]
234
+
235
+ # Conditions for combining segments
236
+ can_combine = (
237
+ segment["speaker"] == current_group["speaker"] and
238
+ time_gap <= max_gap and
239
+ current_duration < max_duration and
240
+ not re.search(sentence_end_pattern, current_group["text"])
241
+ )
242
+
243
+ if can_combine:
244
+ # Merge segments
245
+ current_group["end"] = segment["end"]
246
+ current_group["text"] += " " + segment["text"]
247
+ current_group["duration"] = current_group["end"] - current_group["start"]
248
+ else:
249
+ # Start new group
250
+ grouped_segments.append(current_group)
251
+ current_group = segment.copy()
252
+
253
+ grouped_segments.append(current_group)
254
+
255
+ # Clean up text
256
+ for segment in grouped_segments:
257
+ segment["text"] = re.sub(r"\s+", " ", segment["text"]).strip()
258
+ segment["text"] = re.sub(r"\s+([.,!?])", r"\1", segment["text"])
259
+
260
+ return grouped_segments
261
+
262
+ @spaces.GPU
263
+ def process_audio(
264
+ self,
265
+ audio_file,
266
+ num_speakers: Optional[int] = None,
267
+ language: Optional[str] = None,
268
+ translate: bool = False,
269
+ prompt: Optional[str] = None,
270
+ group_segments: bool = True
271
+ ) -> Dict[str, Any]:
272
+ """Main processing function"""
273
+ if audio_file is None:
274
+ return {"error": "No audio file provided"}
275
+
276
+ try:
277
+ # Setup models if not already done
278
+ self.setup_models()
279
+
280
+ # Convert audio format
281
+ wav_path = self.convert_audio_format(audio_file)
282
+
283
+ try:
284
+ # Transcribe audio
285
+ transcription_segments, detected_language = self.transcribe_audio(
286
+ wav_path, language, translate, prompt
287
+ )
288
+
289
+ # Perform diarization
290
+ diarization_segments, detected_num_speakers = self.perform_diarization(
291
+ wav_path, num_speakers
292
+ )
293
+
294
+ # Merge transcription and diarization
295
+ final_segments = self.merge_transcription_and_diarization(
296
+ transcription_segments, diarization_segments
297
+ )
298
+
299
+ # Group segments if requested
300
+ if group_segments:
301
+ final_segments = self.group_segments_by_speaker(final_segments)
302
+
303
+ return {
304
+ "segments": final_segments,
305
+ "language": detected_language,
306
+ "num_speakers": detected_num_speakers or 1,
307
+ "total_segments": len(final_segments)
308
+ }
309
+
310
+ finally:
311
+ # Clean up temporary file
312
+ if os.path.exists(wav_path):
313
+ os.unlink(wav_path)
314
+
315
+ except Exception as e:
316
+ return {"error": f"Processing failed: {str(e)}"}
317
+
318
+ # Initialize transcriber
319
+ transcriber = WhisperTranscriber()
320
+
321
+ def format_segments_for_display(result: Dict[str, Any]) -> str:
322
+ """Format segments for display in Gradio"""
323
+ if "error" in result:
324
+ return f"❌ Error: {result['error']}"
325
+
326
+ segments = result.get("segments", [])
327
+ language = result.get("language", "unknown")
328
+ num_speakers = result.get("num_speakers", 1)
329
+
330
+ output = f"🎯 **Detection Results:**\n"
331
+ output += f"- Language: {language}\n"
332
+ output += f"- Speakers: {num_speakers}\n"
333
+ output += f"- Segments: {len(segments)}\n\n"
334
+
335
+ output += "📝 **Transcription:**\n\n"
336
+
337
+ for i, segment in enumerate(segments, 1):
338
+ start_time = str(datetime.timedelta(seconds=int(segment["start"])))
339
+ end_time = str(datetime.timedelta(seconds=int(segment["end"])))
340
+ speaker = segment.get("speaker", "SPEAKER_00")
341
+ text = segment["text"]
342
+
343
+ output += f"**{speaker}** ({start_time} → {end_time})\n"
344
+ output += f"{text}\n\n"
345
+
346
+ return output
347
+
348
+ def process_audio_gradio(
349
+ audio_file,
350
+ num_speakers,
351
+ language,
352
+ translate,
353
+ prompt,
354
+ group_segments
355
+ ):
356
+ """Gradio interface function"""
357
+ result = transcriber.process_audio(
358
+ audio_file=audio_file,
359
+ num_speakers=num_speakers if num_speakers > 0 else None,
360
+ language=language if language != "auto" else None,
361
+ translate=translate,
362
+ prompt=prompt if prompt.strip() else None,
363
+ group_segments=group_segments
364
+ )
365
+
366
+ formatted_output = format_segments_for_display(result)
367
+ return formatted_output, result
368
+
369
+ # Create Gradio interface
370
+ with gr.Blocks(
371
+ title="🎙️ Whisper Transcription with Speaker Diarization",
372
+ theme=gr.themes.Soft()
373
+ ) as demo:
374
+ gr.Markdown("""
375
+ # 🎙️ Advanced Audio Transcription & Speaker Diarization
376
+
377
+ Upload an audio file to get accurate transcription with speaker identification, powered by:
378
+ - **Whisper Large V3 Turbo** with Flash Attention for fast transcription
379
+ - **Pyannote 3.1** for speaker diarization
380
+ - **ZeroGPU** acceleration for optimal performance
381
+ """)
382
+
383
+ with gr.Row():
384
+ with gr.Column():
385
+ audio_input = gr.Audio(
386
+ label="🎵 Upload Audio File",
387
+ type="filepath",
388
+ sources=["upload", "microphone"]
389
+ )
390
+
391
+ with gr.Accordion("⚙️ Advanced Settings", open=False):
392
+ num_speakers = gr.Slider(
393
+ minimum=0,
394
+ maximum=20,
395
+ value=0,
396
+ step=1,
397
+ label="Number of Speakers (0 = auto-detect)"
398
+ )
399
+
400
+ language = gr.Dropdown(
401
+ choices=["auto", "en", "es", "fr", "de", "it", "pt", "ru", "ja", "ko", "zh"],
402
+ value="auto",
403
+ label="Language"
404
+ )
405
+
406
+ translate = gr.Checkbox(
407
+ label="Translate to English",
408
+ value=False
409
+ )
410
+
411
+ prompt = gr.Textbox(
412
+ label="Vocabulary Prompt (names, acronyms, etc.)",
413
+ placeholder="Enter names, technical terms, or context...",
414
+ lines=2
415
+ )
416
+
417
+ group_segments = gr.Checkbox(
418
+ label="Group segments by speaker",
419
+ value=True
420
+ )
421
+
422
+ process_btn = gr.Button("🚀 Transcribe Audio", variant="primary", size="lg")
423
+
424
+ with gr.Column():
425
+ output_text = gr.Markdown(
426
+ label="📝 Transcription Results",
427
+ value="Upload an audio file and click 'Transcribe Audio' to get started!"
428
+ )
429
+
430
+ output_json = gr.JSON(
431
+ label="🔧 Raw Output (JSON)",
432
+ visible=False
433
+ )
434
+
435
+ # Event handlers
436
+ process_btn.click(
437
+ fn=process_audio_gradio,
438
+ inputs=[
439
+ audio_input,
440
+ num_speakers,
441
+ language,
442
+ translate,
443
+ prompt,
444
+ group_segments
445
+ ],
446
+ outputs=[output_text, output_json],
447
+ show_progress=True
448
+ )
449
+
450
+ # Examples
451
+ gr.Markdown("### 📋 Usage Tips:")
452
+ gr.Markdown("""
453
+ - **Supported formats**: MP3, WAV, M4A, FLAC, OGG, and more
454
+ - **Max duration**: Recommended under 10 minutes for optimal performance
455
+ - **Speaker detection**: Works best with clear, distinct voices
456
+ - **Languages**: Supports 100+ languages with auto-detection
457
+ - **Vocabulary**: Add names and technical terms in the prompt for better accuracy
458
+ """)
459
+
460
+ if __name__ == "__main__":
461
+ demo.launch(debug=True)
config.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration settings for the Whisper Transcription Space
2
+
3
+ # Model configurations
4
+ WHISPER_MODEL = "openai/whisper-large-v3-turbo"
5
+ DIARIZATION_MODEL = "pyannote/speaker-diarization-3.1"
6
+
7
+ # Audio processing settings
8
+ AUDIO_SAMPLE_RATE = 16000
9
+ AUDIO_CHANNELS = 1
10
+ MAX_AUDIO_DURATION = 600 # 10 minutes in seconds
11
+
12
+ # Transcription settings
13
+ DEFAULT_BEAM_SIZE = 5
14
+ DEFAULT_LANGUAGE = None # Auto-detect
15
+ DEFAULT_TRANSLATE = False
16
+
17
+ # Diarization settings
18
+ MAX_SPEAKERS = 20
19
+ DEFAULT_NUM_SPEAKERS = None # Auto-detect
20
+
21
+ # Segment grouping settings
22
+ MAX_SEGMENT_GAP = 1.0 # seconds
23
+ MAX_SEGMENT_DURATION = 30.0 # seconds
24
+
25
+ # Flash attention settings
26
+ FLASH_ATTENTION_ENABLED = True
27
+ TORCH_DTYPE = "float16"
28
+
29
+ # ZeroGPU settings
30
+ GPU_MEMORY_FRACTION = 0.8
31
+ CUDA_DEVICE = "cuda:0"
32
+
33
+ # Gradio interface settings
34
+ GRADIO_THEME = "soft"
35
+ GRADIO_DEBUG = False
36
+ GRADIO_SHARE = False
37
+
38
+ # Environment variables
39
+ HF_TOKEN_ENV_VAR = "HF_TOKEN"
40
+
41
+ # Supported audio formats
42
+ SUPPORTED_AUDIO_FORMATS = [
43
+ ".mp3", ".wav", ".m4a", ".flac", ".ogg",
44
+ ".aac", ".wma", ".opus", ".webm"
45
+ ]
46
+
47
+ # Language codes
48
+ SUPPORTED_LANGUAGES = {
49
+ "auto": "Auto-detect",
50
+ "en": "English",
51
+ "es": "Spanish",
52
+ "fr": "French",
53
+ "de": "German",
54
+ "it": "Italian",
55
+ "pt": "Portuguese",
56
+ "ru": "Russian",
57
+ "ja": "Japanese",
58
+ "ko": "Korean",
59
+ "zh": "Chinese",
60
+ "ar": "Arabic",
61
+ "hi": "Hindi",
62
+ "tr": "Turkish",
63
+ "pl": "Polish",
64
+ "nl": "Dutch",
65
+ "sv": "Swedish",
66
+ "da": "Danish",
67
+ "no": "Norwegian",
68
+ "fi": "Finnish"
69
+ }
requirements.txt ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core ML libraries
2
+ torch>=2.0.0
3
+ torchaudio>=2.0.0
4
+ transformers>=4.35.0
5
+ accelerate>=0.24.0
6
+
7
+ # Gradio and Spaces
8
+ gradio>=4.0.0
9
+ spaces>=0.19.0
10
+
11
+ # Audio processing and transcription
12
+ ffmpeg-python>=0.2.0
13
+ librosa>=0.10.0
14
+ soundfile>=0.12.0
15
+
16
+ # Speaker diarization
17
+ pyannote.audio>=3.1.0
18
+ pyannote.core>=5.0.0
19
+ pyannote.database>=5.0.0
20
+ pyannote.metrics>=3.2.0
21
+
22
+ # Data processing
23
+ pandas>=1.5.0
24
+ numpy>=1.24.0
25
+
26
+ # Utility libraries
27
+ requests>=2.28.0
28
+ typing-extensions>=4.5.0
29
+
30
+ # Flash attention (will be installed at runtime)
31
+ # flash-attn (installed dynamically in app.py)
32
+
33
+ # Additional dependencies for ZeroGPU
34
+ huggingface_hub>=0.16.0