Spaces:
Sleeping
Sleeping
initial commit
Browse files
app.py
CHANGED
|
@@ -442,112 +442,148 @@ print("--- Model Loading Complete ---")
|
|
| 442 |
|
| 443 |
|
| 444 |
# --- Part 3: Full Pipeline Function for Gradio ---
|
| 445 |
-
@spaces.GPU #
|
| 446 |
-
def full_speech_translation_pipeline_gradio(audio_input_path):
|
| 447 |
# This print will show the device context *inside* the decorated function
|
| 448 |
# For ZeroGPU, this should ideally show 'cuda:X' when the function is executed
|
| 449 |
-
|
| 450 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 451 |
|
| 452 |
|
| 453 |
if not all([TTS_MODEL, stt_processor, stt_model, mt_tokenizer, mt_model]):
|
| 454 |
error_msg = "Critical Error: One or more models failed to load during Space initialization. Cannot process."
|
| 455 |
print(error_msg)
|
| 456 |
-
|
| 457 |
-
raise gr.Error(error_msg)
|
| 458 |
-
|
| 459 |
|
| 460 |
-
if audio_input_path is None:
|
| 461 |
-
# This case should ideally be handled by Gradio's input validation or a check before calling.
|
| 462 |
-
# If it still occurs, provide a clear message.
|
| 463 |
raise gr.Error("No audio file provided. Please upload an audio file.")
|
| 464 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
print(f"--- GRADIO PIPELINE START (GPU context): Processing {audio_input_path} ---")
|
| 466 |
|
| 467 |
-
# STT Stage
|
| 468 |
arabic_transcript = "STT Error: Processing failed."
|
| 469 |
try:
|
| 470 |
print("STT: Loading and resampling audio...")
|
| 471 |
wav, sr = torchaudio.load(audio_input_path)
|
| 472 |
-
if wav.size(0) > 1: wav = wav.mean(dim=0, keepdim=True)
|
|
|
|
|
|
|
|
|
|
| 473 |
target_sr_stt = stt_processor.feature_extractor.sampling_rate
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 477 |
|
| 478 |
print("STT: Extracting features and transcribing...")
|
| 479 |
-
# Ensure
|
|
|
|
| 480 |
inputs_stt = stt_processor(audio_array_stt, sampling_rate=target_sr_stt, return_tensors="pt").input_features.to(DEVICE)
|
| 481 |
forced_ids = stt_processor.get_decoder_prompt_ids(language="arabic", task="transcribe")
|
|
|
|
| 482 |
with torch.no_grad():
|
| 483 |
-
generated_ids = stt_model.generate(inputs_stt, forced_decoder_ids=forced_ids,
|
| 484 |
arabic_transcript = stt_processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
|
| 485 |
print(f"STT Output: {arabic_transcript}")
|
| 486 |
except Exception as e:
|
| 487 |
print(f"STT Error: {e}")
|
| 488 |
-
raise gr.Error(f"STT processing failed: {e}")
|
| 489 |
-
|
| 490 |
|
| 491 |
-
# TTT Stage
|
| 492 |
english_translation = "TTT Error: Processing failed."
|
| 493 |
if arabic_transcript and not arabic_transcript.startswith("STT Error"):
|
| 494 |
try:
|
| 495 |
print("TTT: Translating to English...")
|
| 496 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 497 |
with torch.no_grad():
|
| 498 |
-
translated_ids = mt_model.generate(**batch, max_length=512)
|
| 499 |
english_translation = mt_tokenizer.batch_decode(translated_ids, skip_special_tokens=True)[0].strip()
|
| 500 |
print(f"TTT Output: {english_translation}")
|
| 501 |
except Exception as e:
|
| 502 |
print(f"TTT Error: {e}")
|
| 503 |
-
raise gr.Error(f"TTT processing failed: {e}")
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
|
|
|
| 508 |
print(english_translation)
|
| 509 |
|
| 510 |
|
| 511 |
-
# TTS Stage
|
| 512 |
-
output_tts_audio_filepath = None
|
| 513 |
-
if english_translation and not english_translation.startswith("TTT Error") and
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
# max_length for TTS inference refers to max output mel frames
|
| 521 |
-
generated_mel = TTS_MODEL.inference(sequence, max_length=hp.max_mel_time - 50, stop_token_threshold=0.5)
|
| 522 |
-
|
| 523 |
-
print(f"TTS: Generated mel shape: {generated_mel.shape if generated_mel is not None else 'None'}")
|
| 524 |
-
if generated_mel is not None and generated_mel.numel() > 0 and generated_mel.shape[1] > 0 :
|
| 525 |
-
# TTS model's inverse_mel_spec_to_wav expects mel on DEVICE and returns wav on CPU
|
| 526 |
-
# The mel from inference should be [N, mel_len, mel_bins]
|
| 527 |
-
# inverse_mel_spec_to_wav might expect [mel_bins, mel_len]
|
| 528 |
-
mel_for_vocoder = generated_mel.detach().squeeze(0).transpose(0, 1) # to [mel_len, mel_bins]
|
| 529 |
-
audio_tensor = inverse_mel_spec_to_wav(mel_for_vocoder) # This function handles .to(DEVICE) internally
|
| 530 |
-
synthesized_audio_np = audio_tensor.cpu().numpy() # Ensure output is on CPU for soundfile
|
| 531 |
-
print(f"TTS: Synthesized audio shape: {synthesized_audio_np.shape}")
|
| 532 |
-
|
| 533 |
-
timestamp = int(time.time()*1000) # more unique
|
| 534 |
-
output_tts_audio_filepath = f"output_audio_{timestamp}.wav"
|
| 535 |
-
sf.write(output_tts_audio_filepath, synthesized_audio_np, hp.sr)
|
| 536 |
-
print(f"TTS: Synthesized audio saved to: {output_tts_audio_filepath}")
|
| 537 |
else:
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
|
| 549 |
|
| 550 |
print(f"--- GRADIO PIPELINE END (GPU context) ---")
|
|
|
|
| 551 |
return arabic_transcript, english_translation, output_tts_audio_filepath
|
| 552 |
|
| 553 |
|
|
|
|
| 442 |
|
| 443 |
|
| 444 |
# --- Part 3: Full Pipeline Function for Gradio ---
|
| 445 |
+
@spaces.GPU # For ZeroGPU execution context
|
| 446 |
+
def full_speech_translation_pipeline_gradio(audio_input_path: str):
|
| 447 |
# This print will show the device context *inside* the decorated function
|
| 448 |
# For ZeroGPU, this should ideally show 'cuda:X' when the function is executed
|
| 449 |
+
# Ensure models are loaded and on the correct device before this function is called.
|
| 450 |
+
# The global DEVICE variable should reflect the GPU if available.
|
| 451 |
+
if stt_model: # Check if at least one model is loaded to get device
|
| 452 |
+
current_pipeline_device = next(stt_model.parameters()).device
|
| 453 |
+
print(f"--- @spaces.GPU function: Pipeline attempting to run on device: {current_pipeline_device} ---")
|
| 454 |
+
else:
|
| 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) # Ensure mono
|
| 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 |
+
# Ensure stt_model is available
|
| 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(inputs_stt, forced_decoder_ids=forced_ids, max_length=448) # Using your original max_length
|
| 503 |
arabic_transcript = stt_processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
|
| 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 (aligning with your original logic)
|
| 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 |
+
# Ensure mt_tokenizer and mt_model are available
|
| 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 |
+
raise gr.Error(f"TTT processing failed: {str(e)}") # Show error in Gradio UI
|
| 526 |
+
elif arabic_transcript.startswith("STT Error"):
|
| 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 |
+
# TTS Stage (aligning with your original logic for inference call)
|
| 535 |
+
output_tts_audio_filepath = None # Initialize for Gradio output
|
| 536 |
+
if english_translation and not english_translation.startswith("TTT Error") and not english_translation.startswith("(Skipped TTT"):
|
| 537 |
+
if TTS_MODEL:
|
| 538 |
+
try:
|
| 539 |
+
print("TTS: Synthesizing English speech...")
|
| 540 |
+
if not english_translation.strip():
|
| 541 |
+
print("TTS Warning: Empty string provided for synthesis. Skipping TTS.")
|
| 542 |
+
# No gr.Error here, just skip TTS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 543 |
else:
|
| 544 |
+
sequence = text_to_seq(english_translation).unsqueeze(0).to(DEVICE)
|
| 545 |
+
|
| 546 |
+
# Call TTS_MODEL.inference exactly as in your original, working pipeline
|
| 547 |
+
# This assumes your TTS_MODEL.inference returns (mel_spectrogram, other_data_like_stop_tokens)
|
| 548 |
+
generated_mel, _ = TTS_MODEL.inference(
|
| 549 |
+
sequence,
|
| 550 |
+
max_length=hp.max_mel_time-20, # Your original max_length
|
| 551 |
+
stop_token_threshold=0.5 # Your original threshold
|
| 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 |
|