ghostai1 commited on
Commit
41bdec3
Β·
verified Β·
1 Parent(s): fecb5a0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Text-β†’Translation-β†’Speech | CPU-only Hugging-Face Space
2
+
3
+ import tempfile
4
+ from pathlib import Path
5
+
6
+ import gradio as gr
7
+ from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
8
+ from TTS.api import TTS
9
+
10
+ # ─────────────────────────────
11
+ # Translation pipelines
12
+ # ─────────────────────────────
13
+ PIPE_EN_ES = pipeline(
14
+ "translation", model="Helsinki-NLP/opus-mt-en-es", device=-1
15
+ )
16
+ PIPE_ES_EN = pipeline(
17
+ "translation", model="Helsinki-NLP/opus-mt-es-en", device=-1
18
+ )
19
+
20
+ # ─────────────────────────────
21
+ # TTS models (Coqui TTS)
22
+ # ─────────────────────────────
23
+ TTS_EN = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC", progress_bar=False)
24
+ TTS_ES = TTS(model_name="tts_models/es/mai/tacotron2-DDC", progress_bar=False)
25
+
26
+ # ─────────────────────────────
27
+ # Core function
28
+ # ─────────────────────────────
29
+ def translate_and_speak(text: str, target_lang: str):
30
+ if not text.strip():
31
+ return "", None
32
+
33
+ if target_lang == "Spanish":
34
+ translated = PIPE_EN_ES(text)[0]["translation_text"]
35
+ wav_path = synthesize(TTS_ES, translated)
36
+ else: # English
37
+ translated = PIPE_ES_EN(text)[0]["translation_text"]
38
+ wav_path = synthesize(TTS_EN, translated)
39
+
40
+ return translated, wav_path
41
+
42
+
43
+ def synthesize(tts_model: TTS, text: str) -> str:
44
+ """Generate WAV and return file path."""
45
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
46
+ wav_file = Path(tmp.name)
47
+ tts_model.tts_to_file(text=text, file_path=wav_file)
48
+ return str(wav_file)
49
+
50
+ # ─────────────────────────────
51
+ # Gradio UI
52
+ # ─────────────────────────────
53
+ with gr.Blocks(title="Translator & TTS") as demo:
54
+ gr.Markdown(
55
+ "# πŸŒπŸ’¬ Text β†’ Translate β†’ Speech\n"
56
+ "Type a sentence, choose target language, hear it spoken!"
57
+ )
58
+
59
+ inp = gr.Textbox(label="Your sentence (English or Spanish)", lines=2)
60
+ tgt = gr.Radio(["Spanish", "English"], value="Spanish", label="Translate to")
61
+
62
+ btn = gr.Button("Translate & Speak", variant="primary")
63
+
64
+ out_text = gr.Textbox(label="Translated text", interactive=False)
65
+ out_audio = gr.Audio(label="TTS output", type="filepath")
66
+
67
+ btn.click(translate_and_speak, [inp, tgt], [out_text, out_audio])
68
+
69
+ if __name__ == "__main__":
70
+ demo.launch(server_name="0.0.0.0")