Spaces:
Runtime error
Runtime error
Download app.py from NehaSoniHire/TextToSpeech_languageTranslator: direct link, hf CLI and curl.
- Browser
- Download file 2.36 kB
-
https://huggingface.co/spaces/NehaSoniHire/TextToSpeech_languageTranslator/resolve/main/app.py
- Command line
-
hf download hf://spaces/NehaSoniHire/TextToSpeech_languageTranslator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/NehaSoniHire/TextToSpeech_languageTranslator/resolve/main/app.py
2.36 kB
| import sys, os | |
| print("🐍 Python:", sys.version) | |
| try: | |
| import transformers | |
| print("🤗 transformers version:", transformers.__version__) | |
| except Exception as e: | |
| print("Transformers import failed:", e) | |
| from transformers import AutoProcessor, AutoModelForTextToSpeech # <- your original import | |
| import gradio as gr | |
| import torch | |
| import numpy as np | |
| import soundfile as sf | |
| from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM | |
| from transformers import AutoProcessor, AutoModelForTextToSpeech | |
| DEVICE = 0 if torch.cuda.is_available() else -1 | |
| # 1) Translator (EN -> DE) | |
| MT_ID = "Helsinki-NLP/opus-mt-en-de" | |
| mt_pipe = pipeline("translation", model=MT_ID, device=DEVICE) | |
| # 2) TTS (German) — MMS-TTS (language-specific model) | |
| # For English use: "facebook/mms-tts-eng" | |
| TTS_ID = "facebook/mms-tts-deu" | |
| tts_proc = AutoProcessor.from_pretrained(TTS_ID) | |
| tts_model = AutoModelForTextToSpeech.from_pretrained(TTS_ID).to("cuda" if DEVICE == 0 else "cpu") | |
| SR = 16000 # MMS-TTS default | |
| def translate_then_tts(text_en: str): | |
| text_en = (text_en or "").strip() | |
| if not text_en: | |
| return "", None | |
| # --- Translate EN -> DE --- | |
| out = mt_pipe(text_en, max_length=512) | |
| text_de = out[0]["translation_text"] | |
| # --- TTS (DE) --- | |
| device = "cuda" if DEVICE == 0 else "cpu" | |
| inputs = tts_proc(text=text_de, return_tensors="pt").to(device) | |
| with torch.no_grad(): | |
| audio_out = tts_model.generate(**inputs) | |
| # Convert to a numpy waveform (float32, SR) | |
| if isinstance(audio_out, torch.Tensor): | |
| wav = audio_out.squeeze().detach().cpu().float().numpy() | |
| else: | |
| wav = np.array(audio_out, dtype=np.float32) | |
| # Light normalization/guard | |
| if np.max(np.abs(wav)) > 0: | |
| wav = wav / (np.max(np.abs(wav)) + 1e-8) | |
| return text_de, (SR, wav) | |
| with gr.Blocks(title="EN → DE Translator + TTS (MMS)") as demo: | |
| gr.Markdown("### EN → DE Text Translator → German Speech (MMS-TTS)") | |
| inp = gr.Textbox(label="English text", placeholder="Type a sentence in English…") | |
| trans_out = gr.Textbox(label="German translation", interactive=False) | |
| audio_out = gr.Audio(label="Spoken German (WAV)", type="numpy") | |
| btn = gr.Button("Translate & Speak") | |
| btn.click(translate_then_tts, inputs=[inp], outputs=[trans_out, audio_out]) | |
| if __name__ == "__main__": | |
| demo.launch() |