Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,9 +3,11 @@ import torch
|
|
| 3 |
import logging
|
| 4 |
import gc
|
| 5 |
import time
|
|
|
|
| 6 |
from pathlib import Path
|
| 7 |
from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
|
| 8 |
import librosa
|
|
|
|
| 9 |
|
| 10 |
# Try to import flash attention, but don't fail if not available
|
| 11 |
try:
|
|
@@ -20,6 +22,25 @@ except ImportError:
|
|
| 20 |
logging.basicConfig(level=logging.INFO)
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
class OptimizedWhisperApp:
|
| 24 |
def __init__(self):
|
| 25 |
self.pipe = None
|
|
@@ -37,30 +58,34 @@ class OptimizedWhisperApp:
|
|
| 37 |
]
|
| 38 |
|
| 39 |
def create_pipe(self, model_name, use_flash_attention=True):
|
| 40 |
-
"""Create pipeline
|
| 41 |
try:
|
|
|
|
|
|
|
| 42 |
# Device selection
|
| 43 |
if torch.cuda.is_available():
|
| 44 |
device = "cuda:0"
|
| 45 |
torch_dtype = torch.float16
|
|
|
|
| 46 |
else:
|
| 47 |
device = "cpu"
|
| 48 |
torch_dtype = torch.float32
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
# Attention implementation - gracefully handle missing flash attention
|
| 53 |
if use_flash_attention and FLASH_ATTN_AVAILABLE and is_flash_attn_2_available() and torch.cuda.is_available():
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
logger.info("Flash Attention
|
| 60 |
-
|
| 61 |
-
|
| 62 |
|
| 63 |
-
# Load model
|
|
|
|
| 64 |
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
| 65 |
model_name,
|
| 66 |
torch_dtype=torch_dtype,
|
|
@@ -69,12 +94,15 @@ class OptimizedWhisperApp:
|
|
| 69 |
attn_implementation=attn_implementation,
|
| 70 |
cache_dir="./cache"
|
| 71 |
)
|
|
|
|
| 72 |
model.to(device)
|
| 73 |
|
| 74 |
# Load processor
|
|
|
|
| 75 |
processor = AutoProcessor.from_pretrained(model_name)
|
| 76 |
|
| 77 |
-
# Create pipeline
|
|
|
|
| 78 |
pipe = pipeline(
|
| 79 |
"automatic-speech-recognition",
|
| 80 |
model=model,
|
|
@@ -89,25 +117,38 @@ class OptimizedWhisperApp:
|
|
| 89 |
|
| 90 |
except Exception as e:
|
| 91 |
logger.error(f"Failed to create pipeline: {e}")
|
|
|
|
|
|
|
| 92 |
return None
|
| 93 |
|
| 94 |
def load_model(self, model_name, use_flash_attention=True):
|
| 95 |
-
"""Load model
|
| 96 |
if self.current_model != model_name or self.pipe is None:
|
| 97 |
logger.info(f"Loading new model: {model_name}")
|
| 98 |
|
| 99 |
# Clear previous model
|
| 100 |
if self.pipe is not None:
|
|
|
|
| 101 |
del self.pipe
|
| 102 |
if torch.cuda.is_available():
|
| 103 |
torch.cuda.empty_cache()
|
| 104 |
gc.collect()
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
else:
|
| 112 |
logger.info("Model already loaded")
|
| 113 |
return True
|
|
@@ -116,32 +157,33 @@ class OptimizedWhisperApp:
|
|
| 116 |
language="Automatic Detection", task="transcribe",
|
| 117 |
chunk_length_s=30, batch_size=16, use_flash_attention=True,
|
| 118 |
return_timestamps=True):
|
| 119 |
-
"""Transcribe
|
| 120 |
|
| 121 |
if audio_file is None:
|
| 122 |
return "Please upload an audio file", "", ""
|
| 123 |
|
| 124 |
try:
|
|
|
|
| 125 |
start_time = time.time()
|
| 126 |
|
| 127 |
-
# Load model
|
|
|
|
| 128 |
success = self.load_model(model_name, use_flash_attention)
|
| 129 |
if not success:
|
| 130 |
-
return "Failed to load model", "", ""
|
| 131 |
|
| 132 |
-
logger.info(f"Processing: {audio_file}")
|
| 133 |
-
logger.info(f"Settings: {model_name}, {language}, {task}")
|
| 134 |
logger.info(f"Chunk length: {chunk_length_s}s, Batch size: {batch_size}")
|
| 135 |
|
| 136 |
# Prepare generation kwargs
|
| 137 |
generate_kwargs = {}
|
| 138 |
|
| 139 |
-
#
|
| 140 |
if language != "Automatic Detection" and not model_name.endswith(".en"):
|
| 141 |
-
# Map common language names
|
| 142 |
language_map = {
|
| 143 |
"Greek": "greek",
|
| 144 |
-
"English": "english",
|
| 145 |
"Spanish": "spanish",
|
| 146 |
"French": "french",
|
| 147 |
"German": "german",
|
|
@@ -151,29 +193,37 @@ class OptimizedWhisperApp:
|
|
| 151 |
generate_kwargs["language"] = lang_code
|
| 152 |
logger.info(f"Set language: {lang_code}")
|
| 153 |
|
| 154 |
-
#
|
| 155 |
if not model_name.endswith(".en"):
|
| 156 |
generate_kwargs["task"] = task
|
| 157 |
logger.info(f"Set task: {task}")
|
| 158 |
|
| 159 |
-
# Transcribe
|
| 160 |
-
logger.info("Starting transcription...")
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
transcription_time = time.time() - start_time
|
| 170 |
-
logger.info(f"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
chunks = outputs.get("chunks", [])
|
| 175 |
|
| 176 |
-
#
|
| 177 |
timestamp_text = ""
|
| 178 |
if return_timestamps:
|
| 179 |
try:
|
|
@@ -181,9 +231,9 @@ class OptimizedWhisperApp:
|
|
| 181 |
timestamp_text = self._format_timestamps(chunks)
|
| 182 |
else:
|
| 183 |
timestamp_text = "=== TIMESTAMPS ===\nNo chunks returned by the model.\n"
|
| 184 |
-
except Exception as
|
| 185 |
-
logger.warning(f"Error formatting timestamps: {
|
| 186 |
-
timestamp_text = f"=== TIMESTAMPS ===\nError formatting timestamps: {str(
|
| 187 |
else:
|
| 188 |
timestamp_text = "=== TIMESTAMPS ===\nTimestamp output disabled.\n"
|
| 189 |
|
|
@@ -194,44 +244,50 @@ class OptimizedWhisperApp:
|
|
| 194 |
use_flash_attention, len(chunks)
|
| 195 |
)
|
| 196 |
|
|
|
|
| 197 |
return transcription.strip(), timestamp_text, detailed_output
|
| 198 |
|
| 199 |
except Exception as e:
|
| 200 |
error_msg = f"Transcription error: {str(e)}"
|
| 201 |
logger.error(error_msg)
|
|
|
|
|
|
|
| 202 |
return error_msg, "", error_msg
|
| 203 |
|
| 204 |
def _format_timestamps(self, chunks):
|
| 205 |
-
"""Format timestamp information with
|
| 206 |
timestamp_text = "=== TIMESTAMPS ===\n"
|
| 207 |
|
| 208 |
if not chunks:
|
| 209 |
timestamp_text += "No timestamp information available.\n"
|
| 210 |
return timestamp_text
|
| 211 |
|
|
|
|
|
|
|
| 212 |
for i, chunk in enumerate(chunks):
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
else:
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
except (ValueError, TypeError):
|
| 231 |
-
timestamp_text += f"[Invalid timestamp format]: {text}\n"
|
| 232 |
-
else:
|
| 233 |
-
# Handle unexpected timestamp format
|
| 234 |
-
timestamp_text += f"[Timestamp format error]: {text}\n"
|
| 235 |
|
| 236 |
return timestamp_text
|
| 237 |
|
|
@@ -254,21 +310,24 @@ class OptimizedWhisperApp:
|
|
| 254 |
output += f"Batch size: {batch_size}\n"
|
| 255 |
output += f"Flash Attention: {'Enabled' if use_flash_attention else 'Disabled'}\n"
|
| 256 |
|
| 257 |
-
if self.pipe:
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
| 262 |
|
| 263 |
output += f"Flash Attention 2 available: {FLASH_ATTN_AVAILABLE and is_flash_attn_2_available()}\n"
|
| 264 |
|
| 265 |
-
output += "\n===
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
|
| 273 |
return output
|
| 274 |
|
|
@@ -277,10 +336,12 @@ class OptimizedWhisperApp:
|
|
| 277 |
if self.pipe is None:
|
| 278 |
return "No model loaded"
|
| 279 |
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
|
|
|
|
|
|
| 284 |
|
| 285 |
# Initialize the app
|
| 286 |
logger.info("Initializing Optimized Whisper App...")
|
|
@@ -288,11 +349,17 @@ whisper_app = OptimizedWhisperApp()
|
|
| 288 |
|
| 289 |
def transcribe_wrapper(audio, model_name, language, task, chunk_length_s,
|
| 290 |
batch_size, use_flash_attention, return_timestamps):
|
| 291 |
-
"""Wrapper for Gradio interface"""
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
def get_model_status():
|
| 298 |
"""Get current model status"""
|
|
@@ -306,13 +373,13 @@ def create_interface():
|
|
| 306 |
"""
|
| 307 |
# 🚀 Optimized Whisper Transcription
|
| 308 |
|
| 309 |
-
**High-Performance Speech-to-Text
|
| 310 |
|
| 311 |
-
|
| 312 |
-
-
|
| 313 |
-
-
|
| 314 |
-
-
|
| 315 |
-
-
|
| 316 |
"""
|
| 317 |
)
|
| 318 |
|
|
@@ -335,9 +402,9 @@ def create_interface():
|
|
| 335 |
# Model selection
|
| 336 |
model_dropdown = gr.Dropdown(
|
| 337 |
choices=whisper_app.available_models,
|
| 338 |
-
value="openai/whisper-
|
| 339 |
label="Model",
|
| 340 |
-
info="
|
| 341 |
)
|
| 342 |
|
| 343 |
# Basic settings
|
|
@@ -367,18 +434,17 @@ def create_interface():
|
|
| 367 |
|
| 368 |
batch_size = gr.Slider(
|
| 369 |
minimum=1,
|
| 370 |
-
maximum=
|
| 371 |
-
value=
|
| 372 |
step=1,
|
| 373 |
label="Batch Size",
|
| 374 |
-
info="
|
| 375 |
)
|
| 376 |
|
| 377 |
use_flash_attention = gr.Checkbox(
|
| 378 |
label="Flash Attention 2",
|
| 379 |
-
value=
|
| 380 |
-
info="
|
| 381 |
-
interactive=FLASH_ATTN_AVAILABLE
|
| 382 |
)
|
| 383 |
|
| 384 |
return_timestamps = gr.Checkbox(
|
|
@@ -432,24 +498,19 @@ def create_interface():
|
|
| 432 |
# Footer
|
| 433 |
gr.Markdown(
|
| 434 |
"""
|
| 435 |
-
###
|
| 436 |
-
|
| 437 |
-
**For Greek dialect of Lesbos:**
|
| 438 |
-
- `ilsp/whisper_greek_dialect_of_lesbos` - Specialized but may have issues
|
| 439 |
-
- `openai/whisper-medium` - Often better for real-world usage
|
| 440 |
-
- `openai/whisper-large-v2` - More accurate but slower
|
| 441 |
|
| 442 |
-
**
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
|
| 448 |
-
|
| 449 |
-
-
|
| 450 |
-
-
|
| 451 |
-
-
|
| 452 |
-
-
|
| 453 |
"""
|
| 454 |
)
|
| 455 |
|
|
@@ -458,4 +519,4 @@ def create_interface():
|
|
| 458 |
# Launch the app
|
| 459 |
if __name__ == "__main__":
|
| 460 |
interface = create_interface()
|
| 461 |
-
interface.launch(share=True)
|
|
|
|
| 3 |
import logging
|
| 4 |
import gc
|
| 5 |
import time
|
| 6 |
+
import signal
|
| 7 |
from pathlib import Path
|
| 8 |
from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
|
| 9 |
import librosa
|
| 10 |
+
from functools import wraps
|
| 11 |
|
| 12 |
# Try to import flash attention, but don't fail if not available
|
| 13 |
try:
|
|
|
|
| 22 |
logging.basicConfig(level=logging.INFO)
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
| 25 |
+
def timeout_handler(signum, frame):
|
| 26 |
+
raise TimeoutError("Operation timed out")
|
| 27 |
+
|
| 28 |
+
def with_timeout(seconds):
|
| 29 |
+
def decorator(func):
|
| 30 |
+
@wraps(func)
|
| 31 |
+
def wrapper(*args, **kwargs):
|
| 32 |
+
# Set the signal handler and a timeout alarm
|
| 33 |
+
old_handler = signal.signal(signal.SIGALRM, timeout_handler)
|
| 34 |
+
signal.alarm(seconds)
|
| 35 |
+
try:
|
| 36 |
+
result = func(*args, **kwargs)
|
| 37 |
+
finally:
|
| 38 |
+
signal.alarm(0) # Disable the alarm
|
| 39 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 40 |
+
return result
|
| 41 |
+
return wrapper
|
| 42 |
+
return decorator
|
| 43 |
+
|
| 44 |
class OptimizedWhisperApp:
|
| 45 |
def __init__(self):
|
| 46 |
self.pipe = None
|
|
|
|
| 58 |
]
|
| 59 |
|
| 60 |
def create_pipe(self, model_name, use_flash_attention=True):
|
| 61 |
+
"""Create pipeline with better error handling"""
|
| 62 |
try:
|
| 63 |
+
logger.info(f"Starting to load model: {model_name}")
|
| 64 |
+
|
| 65 |
# Device selection
|
| 66 |
if torch.cuda.is_available():
|
| 67 |
device = "cuda:0"
|
| 68 |
torch_dtype = torch.float16
|
| 69 |
+
logger.info("Using CUDA device")
|
| 70 |
else:
|
| 71 |
device = "cpu"
|
| 72 |
torch_dtype = torch.float32
|
| 73 |
+
logger.info("Using CPU device")
|
| 74 |
|
| 75 |
+
# Simpler attention implementation selection
|
| 76 |
+
attn_implementation = "eager" # Start with most compatible
|
|
|
|
| 77 |
if use_flash_attention and FLASH_ATTN_AVAILABLE and is_flash_attn_2_available() and torch.cuda.is_available():
|
| 78 |
+
try:
|
| 79 |
+
attn_implementation = "flash_attention_2"
|
| 80 |
+
logger.info("Attempting Flash Attention 2")
|
| 81 |
+
except:
|
| 82 |
+
attn_implementation = "eager"
|
| 83 |
+
logger.info("Flash Attention 2 failed, using eager")
|
| 84 |
+
|
| 85 |
+
logger.info(f"Using attention implementation: {attn_implementation}")
|
| 86 |
|
| 87 |
+
# Load model with timeout protection
|
| 88 |
+
logger.info("Loading model...")
|
| 89 |
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
| 90 |
model_name,
|
| 91 |
torch_dtype=torch_dtype,
|
|
|
|
| 94 |
attn_implementation=attn_implementation,
|
| 95 |
cache_dir="./cache"
|
| 96 |
)
|
| 97 |
+
logger.info("Model loaded, moving to device...")
|
| 98 |
model.to(device)
|
| 99 |
|
| 100 |
# Load processor
|
| 101 |
+
logger.info("Loading processor...")
|
| 102 |
processor = AutoProcessor.from_pretrained(model_name)
|
| 103 |
|
| 104 |
+
# Create pipeline
|
| 105 |
+
logger.info("Creating pipeline...")
|
| 106 |
pipe = pipeline(
|
| 107 |
"automatic-speech-recognition",
|
| 108 |
model=model,
|
|
|
|
| 117 |
|
| 118 |
except Exception as e:
|
| 119 |
logger.error(f"Failed to create pipeline: {e}")
|
| 120 |
+
import traceback
|
| 121 |
+
logger.error(traceback.format_exc())
|
| 122 |
return None
|
| 123 |
|
| 124 |
def load_model(self, model_name, use_flash_attention=True):
|
| 125 |
+
"""Load model with timeout protection"""
|
| 126 |
if self.current_model != model_name or self.pipe is None:
|
| 127 |
logger.info(f"Loading new model: {model_name}")
|
| 128 |
|
| 129 |
# Clear previous model
|
| 130 |
if self.pipe is not None:
|
| 131 |
+
logger.info("Clearing previous model...")
|
| 132 |
del self.pipe
|
| 133 |
if torch.cuda.is_available():
|
| 134 |
torch.cuda.empty_cache()
|
| 135 |
gc.collect()
|
| 136 |
|
| 137 |
+
try:
|
| 138 |
+
# Create new pipeline with timeout
|
| 139 |
+
self.pipe = self.create_pipe(model_name, use_flash_attention)
|
| 140 |
+
self.current_model = model_name if self.pipe else None
|
| 141 |
+
|
| 142 |
+
if self.pipe:
|
| 143 |
+
logger.info(f"Model {model_name} loaded successfully")
|
| 144 |
+
return True
|
| 145 |
+
else:
|
| 146 |
+
logger.error(f"Failed to load model {model_name}")
|
| 147 |
+
return False
|
| 148 |
+
|
| 149 |
+
except Exception as e:
|
| 150 |
+
logger.error(f"Error loading model: {e}")
|
| 151 |
+
return False
|
| 152 |
else:
|
| 153 |
logger.info("Model already loaded")
|
| 154 |
return True
|
|
|
|
| 157 |
language="Automatic Detection", task="transcribe",
|
| 158 |
chunk_length_s=30, batch_size=16, use_flash_attention=True,
|
| 159 |
return_timestamps=True):
|
| 160 |
+
"""Transcribe with comprehensive error handling"""
|
| 161 |
|
| 162 |
if audio_file is None:
|
| 163 |
return "Please upload an audio file", "", ""
|
| 164 |
|
| 165 |
try:
|
| 166 |
+
logger.info("=== Starting transcription ===")
|
| 167 |
start_time = time.time()
|
| 168 |
|
| 169 |
+
# Load model
|
| 170 |
+
logger.info(f"Loading model: {model_name}")
|
| 171 |
success = self.load_model(model_name, use_flash_attention)
|
| 172 |
if not success:
|
| 173 |
+
return "Failed to load model - check logs for details", "", ""
|
| 174 |
|
| 175 |
+
logger.info(f"Processing audio file: {audio_file}")
|
| 176 |
+
logger.info(f"Settings - Model: {model_name}, Language: {language}, Task: {task}")
|
| 177 |
logger.info(f"Chunk length: {chunk_length_s}s, Batch size: {batch_size}")
|
| 178 |
|
| 179 |
# Prepare generation kwargs
|
| 180 |
generate_kwargs = {}
|
| 181 |
|
| 182 |
+
# Language handling
|
| 183 |
if language != "Automatic Detection" and not model_name.endswith(".en"):
|
|
|
|
| 184 |
language_map = {
|
| 185 |
"Greek": "greek",
|
| 186 |
+
"English": "english",
|
| 187 |
"Spanish": "spanish",
|
| 188 |
"French": "french",
|
| 189 |
"German": "german",
|
|
|
|
| 193 |
generate_kwargs["language"] = lang_code
|
| 194 |
logger.info(f"Set language: {lang_code}")
|
| 195 |
|
| 196 |
+
# Task handling
|
| 197 |
if not model_name.endswith(".en"):
|
| 198 |
generate_kwargs["task"] = task
|
| 199 |
logger.info(f"Set task: {task}")
|
| 200 |
|
| 201 |
+
# Transcribe with error handling
|
| 202 |
+
logger.info("Starting transcription process...")
|
| 203 |
+
try:
|
| 204 |
+
outputs = self.pipe(
|
| 205 |
+
audio_file,
|
| 206 |
+
chunk_length_s=chunk_length_s,
|
| 207 |
+
batch_size=batch_size,
|
| 208 |
+
generate_kwargs=generate_kwargs,
|
| 209 |
+
return_timestamps=return_timestamps,
|
| 210 |
+
)
|
| 211 |
+
logger.info("Transcription completed")
|
| 212 |
+
except Exception as transcribe_error:
|
| 213 |
+
logger.error(f"Transcription failed: {transcribe_error}")
|
| 214 |
+
return f"Transcription failed: {str(transcribe_error)}", "", ""
|
| 215 |
|
| 216 |
transcription_time = time.time() - start_time
|
| 217 |
+
logger.info(f"Total processing time: {transcription_time:.2f} seconds")
|
| 218 |
+
|
| 219 |
+
# Extract and validate results
|
| 220 |
+
transcription = outputs.get("text", "") if outputs else ""
|
| 221 |
+
chunks = outputs.get("chunks", []) if outputs else []
|
| 222 |
|
| 223 |
+
logger.info(f"Extracted transcription length: {len(transcription)} chars")
|
| 224 |
+
logger.info(f"Number of chunks: {len(chunks)}")
|
|
|
|
| 225 |
|
| 226 |
+
# Handle timestamps safely
|
| 227 |
timestamp_text = ""
|
| 228 |
if return_timestamps:
|
| 229 |
try:
|
|
|
|
| 231 |
timestamp_text = self._format_timestamps(chunks)
|
| 232 |
else:
|
| 233 |
timestamp_text = "=== TIMESTAMPS ===\nNo chunks returned by the model.\n"
|
| 234 |
+
except Exception as ts_error:
|
| 235 |
+
logger.warning(f"Error formatting timestamps: {ts_error}")
|
| 236 |
+
timestamp_text = f"=== TIMESTAMPS ===\nError formatting timestamps: {str(ts_error)}\n"
|
| 237 |
else:
|
| 238 |
timestamp_text = "=== TIMESTAMPS ===\nTimestamp output disabled.\n"
|
| 239 |
|
|
|
|
| 244 |
use_flash_attention, len(chunks)
|
| 245 |
)
|
| 246 |
|
| 247 |
+
logger.info("=== Transcription completed successfully ===")
|
| 248 |
return transcription.strip(), timestamp_text, detailed_output
|
| 249 |
|
| 250 |
except Exception as e:
|
| 251 |
error_msg = f"Transcription error: {str(e)}"
|
| 252 |
logger.error(error_msg)
|
| 253 |
+
import traceback
|
| 254 |
+
logger.error(traceback.format_exc())
|
| 255 |
return error_msg, "", error_msg
|
| 256 |
|
| 257 |
def _format_timestamps(self, chunks):
|
| 258 |
+
"""Format timestamp information with comprehensive error handling"""
|
| 259 |
timestamp_text = "=== TIMESTAMPS ===\n"
|
| 260 |
|
| 261 |
if not chunks:
|
| 262 |
timestamp_text += "No timestamp information available.\n"
|
| 263 |
return timestamp_text
|
| 264 |
|
| 265 |
+
logger.info(f"Formatting {len(chunks)} chunks")
|
| 266 |
+
|
| 267 |
for i, chunk in enumerate(chunks):
|
| 268 |
+
try:
|
| 269 |
+
timestamp = chunk.get('timestamp', None)
|
| 270 |
+
text = chunk.get('text', '')
|
| 271 |
+
|
| 272 |
+
if timestamp is None:
|
| 273 |
+
timestamp_text += f"[No timestamp]: {text}\n"
|
| 274 |
+
elif isinstance(timestamp, (list, tuple)) and len(timestamp) >= 2:
|
| 275 |
+
start, end = timestamp[0], timestamp[1]
|
| 276 |
+
if start is None or end is None:
|
| 277 |
+
timestamp_text += f"[Invalid timestamp]: {text}\n"
|
| 278 |
+
else:
|
| 279 |
+
try:
|
| 280 |
+
start_f = float(start) if start is not None else 0.0
|
| 281 |
+
end_f = float(end) if end is not None else 0.0
|
| 282 |
+
timestamp_text += f"[{start_f:.1f}s - {end_f:.1f}s]: {text}\n"
|
| 283 |
+
except (ValueError, TypeError) as ve:
|
| 284 |
+
timestamp_text += f"[Format error]: {text}\n"
|
| 285 |
else:
|
| 286 |
+
timestamp_text += f"[Unexpected format]: {text}\n"
|
| 287 |
+
|
| 288 |
+
except Exception as chunk_error:
|
| 289 |
+
logger.warning(f"Error processing chunk {i}: {chunk_error}")
|
| 290 |
+
timestamp_text += f"[Chunk {i} error]: Processing failed\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
|
| 292 |
return timestamp_text
|
| 293 |
|
|
|
|
| 310 |
output += f"Batch size: {batch_size}\n"
|
| 311 |
output += f"Flash Attention: {'Enabled' if use_flash_attention else 'Disabled'}\n"
|
| 312 |
|
| 313 |
+
if self.pipe and hasattr(self.pipe, 'model'):
|
| 314 |
+
try:
|
| 315 |
+
device = next(self.pipe.model.parameters()).device
|
| 316 |
+
dtype = next(self.pipe.model.parameters()).dtype
|
| 317 |
+
output += f"Device: {device}\n"
|
| 318 |
+
output += f"Data type: {dtype}\n"
|
| 319 |
+
except:
|
| 320 |
+
output += "Device info: Unable to retrieve\n"
|
| 321 |
|
| 322 |
output += f"Flash Attention 2 available: {FLASH_ATTN_AVAILABLE and is_flash_attn_2_available()}\n"
|
| 323 |
|
| 324 |
+
output += "\n=== SYSTEM STATUS ===\n"
|
| 325 |
+
if torch.cuda.is_available():
|
| 326 |
+
output += f"GPU Available: Yes\n"
|
| 327 |
+
output += f"GPU Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f}GB\n"
|
| 328 |
+
output += f"GPU Memory Used: {torch.cuda.memory_allocated() / 1e9:.1f}GB\n"
|
| 329 |
+
else:
|
| 330 |
+
output += "GPU Available: No\n"
|
| 331 |
|
| 332 |
return output
|
| 333 |
|
|
|
|
| 336 |
if self.pipe is None:
|
| 337 |
return "No model loaded"
|
| 338 |
|
| 339 |
+
try:
|
| 340 |
+
device = next(self.pipe.model.parameters()).device
|
| 341 |
+
dtype = next(self.pipe.model.parameters()).dtype
|
| 342 |
+
return f"✅ {self.current_model} loaded on {device} ({dtype})"
|
| 343 |
+
except:
|
| 344 |
+
return f"✅ {self.current_model} loaded (device info unavailable)"
|
| 345 |
|
| 346 |
# Initialize the app
|
| 347 |
logger.info("Initializing Optimized Whisper App...")
|
|
|
|
| 349 |
|
| 350 |
def transcribe_wrapper(audio, model_name, language, task, chunk_length_s,
|
| 351 |
batch_size, use_flash_attention, return_timestamps):
|
| 352 |
+
"""Wrapper for Gradio interface with additional safety"""
|
| 353 |
+
try:
|
| 354 |
+
logger.info(f"Transcribe wrapper called with model: {model_name}")
|
| 355 |
+
return whisper_app.transcribe_audio(
|
| 356 |
+
audio, model_name, language, task,
|
| 357 |
+
chunk_length_s, batch_size, use_flash_attention, return_timestamps
|
| 358 |
+
)
|
| 359 |
+
except Exception as e:
|
| 360 |
+
error_msg = f"Wrapper error: {str(e)}"
|
| 361 |
+
logger.error(error_msg)
|
| 362 |
+
return error_msg, "", error_msg
|
| 363 |
|
| 364 |
def get_model_status():
|
| 365 |
"""Get current model status"""
|
|
|
|
| 373 |
"""
|
| 374 |
# 🚀 Optimized Whisper Transcription
|
| 375 |
|
| 376 |
+
**High-Performance Speech-to-Text with Enhanced Error Handling**
|
| 377 |
|
| 378 |
+
Features:
|
| 379 |
+
- Comprehensive error handling and timeout protection
|
| 380 |
+
- Better logging for debugging
|
| 381 |
+
- Graceful handling of model loading issues
|
| 382 |
+
- Robust timestamp processing
|
| 383 |
"""
|
| 384 |
)
|
| 385 |
|
|
|
|
| 402 |
# Model selection
|
| 403 |
model_dropdown = gr.Dropdown(
|
| 404 |
choices=whisper_app.available_models,
|
| 405 |
+
value="openai/whisper-small", # Start with smaller model
|
| 406 |
label="Model",
|
| 407 |
+
info="Start with 'small' model for testing"
|
| 408 |
)
|
| 409 |
|
| 410 |
# Basic settings
|
|
|
|
| 434 |
|
| 435 |
batch_size = gr.Slider(
|
| 436 |
minimum=1,
|
| 437 |
+
maximum=8, # Reduced default
|
| 438 |
+
value=4, # Smaller batch size
|
| 439 |
step=1,
|
| 440 |
label="Batch Size",
|
| 441 |
+
info="Start with smaller batch size"
|
| 442 |
)
|
| 443 |
|
| 444 |
use_flash_attention = gr.Checkbox(
|
| 445 |
label="Flash Attention 2",
|
| 446 |
+
value=False, # Disabled by default for stability
|
| 447 |
+
info="Enable only if you have compatible GPU and flash-attn installed"
|
|
|
|
| 448 |
)
|
| 449 |
|
| 450 |
return_timestamps = gr.Checkbox(
|
|
|
|
| 498 |
# Footer
|
| 499 |
gr.Markdown(
|
| 500 |
"""
|
| 501 |
+
### 🔧 Troubleshooting
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 502 |
|
| 503 |
+
**If processing hangs:**
|
| 504 |
+
1. Start with `whisper-small` model
|
| 505 |
+
2. Disable Flash Attention
|
| 506 |
+
3. Use smaller batch size (1-4)
|
| 507 |
+
4. Check the console logs for errors
|
| 508 |
|
| 509 |
+
**For best results:**
|
| 510 |
+
- Test with small model first
|
| 511 |
+
- Gradually increase model size if needed
|
| 512 |
+
- Monitor GPU memory usage
|
| 513 |
+
- Check logs for any error messages
|
| 514 |
"""
|
| 515 |
)
|
| 516 |
|
|
|
|
| 519 |
# Launch the app
|
| 520 |
if __name__ == "__main__":
|
| 521 |
interface = create_interface()
|
| 522 |
+
interface.launch(share=True, debug=True)
|