Spaces:
Running
on
Zero
Running
on
Zero
initial commit
Browse files
app.py
CHANGED
@@ -443,154 +443,75 @@ print("--- Model Loading Complete ---")
|
|
443 |
|
444 |
# --- Part 3: Full Pipeline Function for Gradio ---
|
445 |
@spaces.GPU # For ZeroGPU execution context
|
446 |
-
def
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
print(f"--- @spaces.GPU function: STT model not loaded, cannot determine precise pipeline device yet. Target: {DEVICE} ---")
|
456 |
-
|
457 |
-
|
458 |
-
if not all([TTS_MODEL, stt_processor, stt_model, mt_tokenizer, mt_model]):
|
459 |
-
error_msg = "Critical Error: One or more models failed to load during Space initialization. Cannot process."
|
460 |
-
print(error_msg)
|
461 |
-
raise gr.Error(error_msg) # Use Gradio's error for better UI feedback
|
462 |
-
|
463 |
-
if audio_input_path is None: # Gradio sends None if no file
|
464 |
-
raise gr.Error("No audio file provided. Please upload an audio file.")
|
465 |
-
|
466 |
-
# Check if the file path actually exists (Gradio should handle temp file creation)
|
467 |
-
# This check might be redundant if Gradio always provides a valid temp path for uploaded files.
|
468 |
-
if not os.path.exists(audio_input_path):
|
469 |
-
error_msg = f"Error: Audio file path provided by Gradio does not exist: {audio_input_path}"
|
470 |
-
print(error_msg)
|
471 |
-
raise gr.Error("Internal error: Audio file path not found.")
|
472 |
-
|
473 |
-
|
474 |
-
print(f"--- GRADIO PIPELINE START (GPU context): Processing {audio_input_path} ---")
|
475 |
-
|
476 |
-
# STT Stage (aligning with your original logic)
|
477 |
arabic_transcript = "STT Error: Processing failed."
|
478 |
try:
|
479 |
print("STT: Loading and resampling audio...")
|
480 |
wav, sr = torchaudio.load(audio_input_path)
|
481 |
-
if wav.size(0) > 1: wav = wav.mean(dim=0, keepdim=True)
|
482 |
-
|
483 |
-
# Ensure stt_processor is available
|
484 |
-
if not stt_processor: raise gr.Error("STT Processor not loaded.")
|
485 |
target_sr_stt = stt_processor.feature_extractor.sampling_rate
|
|
|
|
|
486 |
|
487 |
-
if sr != target_sr_stt:
|
488 |
-
# Resample op can be on CPU or GPU. If wav is already on GPU, it might be faster.
|
489 |
-
# However, for simplicity and consistency with original, let's keep it default (CPU).
|
490 |
-
resampler = torchaudio.transforms.Resample(sr, target_sr_stt)
|
491 |
-
wav = resampler(wav)
|
492 |
-
|
493 |
-
audio_array_stt = wav.squeeze().cpu().numpy() # Whisper processor expects NumPy array
|
494 |
-
|
495 |
print("STT: Extracting features and transcribing...")
|
496 |
-
|
497 |
-
if not stt_model: raise gr.Error("STT Model not loaded.")
|
498 |
-
inputs_stt = stt_processor(audio_array_stt, sampling_rate=target_sr_stt, return_tensors="pt").input_features.to(DEVICE)
|
499 |
forced_ids = stt_processor.get_decoder_prompt_ids(language="arabic", task="transcribe")
|
500 |
-
|
501 |
with torch.no_grad():
|
502 |
-
generated_ids = stt_model.generate(
|
503 |
-
arabic_transcript = stt_processor.
|
504 |
print(f"STT Output: {arabic_transcript}")
|
505 |
except Exception as e:
|
506 |
print(f"STT Error: {e}")
|
507 |
-
raise gr.Error(f"STT processing failed: {str(e)}") # Show error in Gradio UI
|
508 |
|
509 |
-
# TTT Stage
|
510 |
english_translation = "TTT Error: Processing failed."
|
511 |
if arabic_transcript and not arabic_transcript.startswith("STT Error"):
|
512 |
try:
|
513 |
print("TTT: Translating to English...")
|
514 |
-
|
515 |
-
if not mt_tokenizer: raise gr.Error("Marian Tokenizer not loaded.")
|
516 |
-
if not mt_model: raise gr.Error("Marian Model not loaded.")
|
517 |
-
|
518 |
-
batch = mt_tokenizer(arabic_transcript, return_tensors="pt", padding=True, truncation=True).to(DEVICE) # Added truncation
|
519 |
with torch.no_grad():
|
520 |
translated_ids = mt_model.generate(**batch, max_length=512)
|
521 |
english_translation = mt_tokenizer.batch_decode(translated_ids, skip_special_tokens=True)[0].strip()
|
522 |
print(f"TTT Output: {english_translation}")
|
523 |
except Exception as e:
|
524 |
print(f"TTT Error: {e}")
|
525 |
-
|
526 |
-
|
527 |
-
english_translation = "(Skipped TTT due to STT error)" # More specific message
|
528 |
-
print(english_translation)
|
529 |
-
else: # Handles empty arabic_transcript case
|
530 |
-
english_translation = "(Skipped TTT due to empty STT output)"
|
531 |
print(english_translation)
|
532 |
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
# with_tqdm=False # Not needed for Gradio backend
|
553 |
-
)
|
554 |
-
|
555 |
-
print(f"TTS: Generated mel shape: {generated_mel.shape if generated_mel is not None else 'None'}")
|
556 |
-
if generated_mel is not None and generated_mel.numel() > 0 and generated_mel.shape[1] > 0: # Check time dimension
|
557 |
-
# Your original processing of mel_for_vocoder
|
558 |
-
mel_for_vocoder = generated_mel.detach().squeeze(0).transpose(0, 1)
|
559 |
-
audio_tensor = inverse_mel_spec_to_wav(mel_for_vocoder) # This needs to be correct for your model
|
560 |
-
synthesized_audio_np = audio_tensor.cpu().numpy()
|
561 |
-
print(f"TTS: Synthesized audio shape: {synthesized_audio_np.shape}")
|
562 |
-
|
563 |
-
# Save to a temporary file for Gradio Audio output
|
564 |
-
timestamp = int(time.time()*1000) # For a somewhat unique filename
|
565 |
-
output_tts_audio_filepath = f"synthesized_speech_{timestamp}.wav"
|
566 |
-
sf.write(output_tts_audio_filepath, synthesized_audio_np, hp.sr)
|
567 |
-
print(f"TTS: Synthesized audio saved to: {output_tts_audio_filepath}")
|
568 |
-
else:
|
569 |
-
print("TTS Warning: Generated mel spectrogram was empty or invalid.")
|
570 |
-
# Do not raise gr.Error, let the text pass through.
|
571 |
-
# output_tts_audio_filepath remains None.
|
572 |
-
except Exception as e:
|
573 |
-
print(f"TTS Error: {e}")
|
574 |
-
# Append error to text, don't stop the whole process if text is available
|
575 |
-
english_translation += f" (TTS synthesis failed: {str(e)})"
|
576 |
-
# output_tts_audio_filepath remains None.
|
577 |
-
else:
|
578 |
-
print("TTS SKIPPED: TTS_MODEL not loaded.")
|
579 |
-
elif not TTS_MODEL: # If TTS model didn't load but we reached here
|
580 |
-
print("TTS SKIPPED: Model not loaded.")
|
581 |
-
else: # If english_translation was invalid for TTS
|
582 |
-
print(f"TTS SKIPPED: English text was '{english_translation}'.")
|
583 |
-
|
584 |
-
|
585 |
-
print(f"--- GRADIO PIPELINE END (GPU context) ---")
|
586 |
-
# Return values in the order expected by Gradio's `outputs` components
|
587 |
-
return arabic_transcript, english_translation, output_tts_audio_filepath
|
588 |
|
589 |
|
590 |
# --- Part 4: Gradio Interface Definition ---
|
591 |
# (Same as before)
|
592 |
iface = gr.Interface(
|
593 |
-
fn=
|
594 |
inputs=[
|
595 |
gr.Audio(type="filepath", label="Upload Arabic Speech")
|
596 |
],
|
|
|
443 |
|
444 |
# --- Part 3: Full Pipeline Function for Gradio ---
|
445 |
@spaces.GPU # For ZeroGPU execution context
|
446 |
+
def full_speech_translation_pipeline(audio_input_path: str):
|
447 |
+
print(f"--- PIPELINE START: Processing {audio_input_path} ---")
|
448 |
+
if audio_input_path is None or not os.path.exists(audio_input_path):
|
449 |
+
msg = "Error: Audio file not provided or not found."
|
450 |
+
print(msg)
|
451 |
+
# Return empty/default values
|
452 |
+
return "Error: No file", "", (hp.sr, np.array([]).astype(np.float32))
|
453 |
+
|
454 |
+
# STT Stage
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
455 |
arabic_transcript = "STT Error: Processing failed."
|
456 |
try:
|
457 |
print("STT: Loading and resampling audio...")
|
458 |
wav, sr = torchaudio.load(audio_input_path)
|
459 |
+
if wav.size(0) > 1: wav = wav.mean(dim=0, keepdim=True)
|
|
|
|
|
|
|
460 |
target_sr_stt = stt_processor.feature_extractor.sampling_rate
|
461 |
+
if sr != target_sr_stt: wav = torchaudio.transforms.Resample(sr, target_sr_stt)(wav)
|
462 |
+
audio_array_stt = wav.squeeze().cpu().numpy()
|
463 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
464 |
print("STT: Extracting features and transcribing...")
|
465 |
+
inputs = stt_processor(audio_array_stt, sampling_rate=target_sr_stt, return_tensors="pt").input_features.to(DEVICE)
|
|
|
|
|
466 |
forced_ids = stt_processor.get_decoder_prompt_ids(language="arabic", task="transcribe")
|
|
|
467 |
with torch.no_grad():
|
468 |
+
generated_ids = stt_model.generate(inputs, forced_decoder_ids=forced_ids, max_length=448)
|
469 |
+
arabic_transcript = stt_processor.decode(generated_ids[0], skip_special_tokens=True).strip()
|
470 |
print(f"STT Output: {arabic_transcript}")
|
471 |
except Exception as e:
|
472 |
print(f"STT Error: {e}")
|
|
|
473 |
|
474 |
+
# TTT Stage
|
475 |
english_translation = "TTT Error: Processing failed."
|
476 |
if arabic_transcript and not arabic_transcript.startswith("STT Error"):
|
477 |
try:
|
478 |
print("TTT: Translating to English...")
|
479 |
+
batch = mt_tokenizer(arabic_transcript, return_tensors="pt", padding=True).to(DEVICE)
|
|
|
|
|
|
|
|
|
480 |
with torch.no_grad():
|
481 |
translated_ids = mt_model.generate(**batch, max_length=512)
|
482 |
english_translation = mt_tokenizer.batch_decode(translated_ids, skip_special_tokens=True)[0].strip()
|
483 |
print(f"TTT Output: {english_translation}")
|
484 |
except Exception as e:
|
485 |
print(f"TTT Error: {e}")
|
486 |
+
else:
|
487 |
+
english_translation = "(Skipped TTT due to STT failure)"
|
|
|
|
|
|
|
|
|
488 |
print(english_translation)
|
489 |
|
490 |
+
# TTS Stage
|
491 |
+
synthesized_audio_np = np.array([]).astype(np.float32)
|
492 |
+
if english_translation and not english_translation.startswith("TTT Error"):
|
493 |
+
try:
|
494 |
+
print("TTS: Synthesizing English speech...")
|
495 |
+
sequence = text_to_seq(english_translation).unsqueeze(0).to(DEVICE)
|
496 |
+
generated_mel, _ = TTS_MODEL.inference(sequence, max_length=hp.max_mel_time-20, stop_token_threshold=0.5, with_tqdm=False)
|
497 |
+
|
498 |
+
print(f"TTS: Generated mel shape: {generated_mel.shape if generated_mel is not None else 'None'}")
|
499 |
+
if generated_mel is not None and generated_mel.numel() > 0:
|
500 |
+
mel_for_vocoder = generated_mel.detach().squeeze(0).transpose(0, 1)
|
501 |
+
audio_tensor = inverse_mel_spec_to_wav(mel_for_vocoder)
|
502 |
+
synthesized_audio_np = audio_tensor.cpu().numpy()
|
503 |
+
print(f"TTS: Synthesized audio shape: {synthesized_audio_np.shape}")
|
504 |
+
except Exception as e:
|
505 |
+
print(f"TTS Error: {e}")
|
506 |
+
|
507 |
+
print(f"--- PIPELINE END ---")
|
508 |
+
return arabic_transcript, english_translation, (hp.sr, synthesized_audio_np)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
509 |
|
510 |
|
511 |
# --- Part 4: Gradio Interface Definition ---
|
512 |
# (Same as before)
|
513 |
iface = gr.Interface(
|
514 |
+
fn=full_speech_translation_pipeline,
|
515 |
inputs=[
|
516 |
gr.Audio(type="filepath", label="Upload Arabic Speech")
|
517 |
],
|