Update app.py
Browse files4 unmodified lines56789101112138 unmodified lines22232425262728293031323334353637383940414243444546474849505152533 unmodified lines5758596061626364656667686970717273747576777879804 unmodified linesimport librosaimport numpy as np# 1. SWITCH TO MEDIUM MODEL (Faster, lighter, same high quality)device = "cuda" if torch.cuda.is_available() else "cpu"model_id = "facebook/seamless-m4t-v2-large" # Change to "facebook/seamless-m4t-medium" if CPU is still too slowprocessor = AutoProcessor.from_pretrained(model_id)model = SeamlessM4Tv2Model.from_pretrained(model_id).to(device)8 unmodified lines}def translate_audio(audio_path, source_lang_name, target_lang_name):# Fix for "No Speech Recorded"if audio_path is None:return "Microphone Error: Please ensure you clicked 'Stop Recording' before 'Translate'.", Nonetry:src_lang = LANG_MAP[source_lang_name]tgt_lang = LANG_MAP[target_lang_name]# Load and Resample (Crucial for Whisper/Seamless models)audio, _ = librosa.load(audio_path, sr=16000)# Check if the audio is basically silentif np.abs(audio).mean() < 0.005:return "Sound too faint. Please speak closer to the mic.", Noneinputs = processor(audios=audio, return_tensors="pt", sampling_rate=16000).to(device)# Direct Translation Logicwith torch.no_grad():output = model.generate(**inputs, tgt_lang=tgt_lang, src_lang=src_lang)# Decode Text Resulttranslated_text = processor.batch_decode(output[1], skip_special_tokens=True)[0]# Synthesize High-Quality Audioaudio_array = output[0].cpu().numpy().squeeze()sample_rate = model.config.sampling_rateoutput_path = "output_voice.wav"wavfile.write(output_path, sample_rate, audio_array)3 unmodified linesexcept Exception as e:return f"System Error: {str(e)}", None# Clean, Professional UIwith gr.Blocks(title="Neural Voice Bridge") as demo:gr.Markdown("# 🌐 Neural Voice Bridge")gr.Markdown("High-speed bidirectional speech translation for Indian languages.")with gr.Row():with gr.Column():audio_in = gr.Audio(sources=["microphone"], type="filepath", label="Click to Record")with gr.Row():src_lang = gr.Dropdown(choices=list(LANG_MAP.keys()), value="English", label="Source Language")tgt_lang = gr.Dropdown(choices=list(LANG_MAP.keys()), value="Hindi", label="Target Language")submit_btn = gr.Button("TRANSLATE", variant="primary")with gr.Column():text_out = gr.Textbox(label="Translated Text", interactive=False)audio_out = gr.Audio(label="Neural Speech Output", autoplay=True)submit_btn.click(fn=translate_audio, inputs=[audio_in, src_lang, tgt_lang], outputs=[text_out, audio_out])if __name__ == "__main__":demo.launch()4 unmodified lines5678910111213148 unmodified lines232425262728293031323334353637383940414243444546474849503 unmodified lines5455565758596061626364656667686970717273747576774 unmodified linesimport librosaimport numpy as np# Load the Medium model for better speed on standard serversdevice = "cuda" if torch.cuda.is_available() else "cpu"# Using 'medium' instead of 'large' prevents crashes on Hugging Face Free Tiermodel_id = "facebook/hf-seamless-m4t-medium"processor = AutoProcessor.from_pretrained(model_id)model = SeamlessM4Tv2Model.from_pretrained(model_id).to(device)8 unmodified lines}def translate_audio(audio_path, source_lang_name, target_lang_name):if audio_path is None:return "Microphone Error: No audio detected. Click 'Stop' before 'Translate'.", Nonetry:src_lang = LANG_MAP[source_lang_name]tgt_lang = LANG_MAP[target_lang_name]# 1. Load and Standardize Audioaudio, _ = librosa.load(audio_path, sr=16000)# 2. FIXED: Use 'audio' instead of 'audios' to resolve System Errorinputs = processor(audio=audio, return_tensors="pt", sampling_rate=16000).to(device)# 3. Generate Translationwith torch.no_grad():output = model.generate(**inputs, tgt_lang=tgt_lang, src_lang=src_lang)# 4. Decode Resultstranslated_text = processor.batch_decode(output[1], skip_special_tokens=True)[0]audio_array = output[0].cpu().numpy().squeeze()# 5. Save and Returnsample_rate = model.config.sampling_rateoutput_path = "output_voice.wav"wavfile.write(output_path, sample_rate, audio_array)3 unmodified linesexcept Exception as e:return f"System Error: {str(e)}", None# Standard Professional Layoutwith gr.Blocks(title="Neural Voice Bridge") as demo:gr.Markdown("# 🌐 Neural Voice Bridge")gr.Markdown("Direct Speech-to-Speech translation. **Tip:** Stop the recording before clicking Translate.")with gr.Row():with gr.Column():audio_in = gr.Audio(sources=["microphone"], type="filepath", label="Record Speech")with gr.Row():src_dropdown = gr.Dropdown(choices=list(LANG_MAP.keys()), value="English", label="From")tgt_dropdown = gr.Dropdown(choices=list(LANG_MAP.keys()), value="Hindi", label="To")submit_btn = gr.Button("TRANSLATE", variant="primary")with gr.Column():text_out = gr.Textbox(label="Translated Text", interactive=False)audio_out = gr.Audio(label="Neural Voice Output", autoplay=True)submit_btn.click(fn=translate_audio, inputs=[audio_in, src_dropdown, tgt_dropdown], outputs=[text_out, audio_out])if __name__ == "__main__":demo.launch()
app.py+18-21