Spaces:
Runtime error
Runtime error
Download app.py from MuhammaJamal/Translator: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/spaces/MuhammaJamal/Translator/resolve/main/app.py
- Command line
-
hf download hf://spaces/MuhammaJamal/Translator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/MuhammaJamal/Translator/resolve/main/app.py
11.1 kB
| import base64 | |
| import logging | |
| import os | |
| import random | |
| import shutil | |
| import uuid | |
| import tempfile | |
| import gradio as gr | |
| from pydub import AudioSegment | |
| from gtts import gTTS | |
| import speech_recognition as sr | |
| import requests | |
| from dotenv import load_dotenv | |
| logging.basicConfig(level=logging.DEBUG) | |
| logger = logging.getLogger(__name__) | |
| load_dotenv() | |
| DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY", "") | |
| os.makedirs("uploads", exist_ok=True) | |
| LANGUAGE_MAPPING = { | |
| 'English': {'tts': 'en', 'sr': 'en-US'}, | |
| 'Spanish': {'tts': 'es', 'sr': 'es-ES'}, | |
| 'French': {'tts': 'fr', 'sr': 'fr-FR'}, | |
| 'German': {'tts': 'de', 'sr': 'de-DE'}, | |
| 'Italian': {'tts': 'it', 'sr': 'it-IT'}, | |
| 'Portuguese': {'tts': 'pt', 'sr': 'pt-PT'}, | |
| 'Russian': {'tts': 'ru', 'sr': 'ru-RU'}, | |
| 'Chinese (Simplified)': {'tts': 'zh-CN', 'sr': 'zh-CN'}, | |
| 'Japanese': {'tts': 'ja', 'sr': 'ja-JP'}, | |
| 'Korean': {'tts': 'ko', 'sr': 'ko-KR'}, | |
| 'Hindi': {'tts': 'hi', 'sr': 'hi-IN'}, | |
| 'Arabic': {'tts': 'ar', 'sr': 'ar-EG'}, | |
| 'Dutch': {'tts': 'nl', 'sr': 'nl-NL'}, | |
| 'Turkish': {'tts': 'tr', 'sr': 'tr-TR'}, | |
| 'Polish': {'tts': 'pl', 'sr': 'pl-PL'}, | |
| 'Greek': {'tts': 'el', 'sr': 'el-GR'}, | |
| 'Thai': {'tts': 'th', 'sr': 'th-TH'}, | |
| 'Vietnamese': {'tts': 'vi', 'sr': 'vi-VN'}, | |
| 'Czech': {'tts': 'cs', 'sr': 'cs-CZ'}, | |
| 'Hungarian': {'tts': 'hu', 'sr': 'hu-HU'}, | |
| 'Romanian': {'tts': 'ro', 'sr': 'ro-RO'}, | |
| 'Finnish': {'tts': 'fi', 'sr': 'fi-FI'}, | |
| 'Danish': {'tts': 'da', 'sr': 'da-DK'}, | |
| 'Ukrainian': {'tts': 'uk', 'sr': 'uk-UA'}, | |
| 'Bengali': {'tts': 'bn', 'sr': 'bn-IN'}, | |
| 'Tamil': {'tts': 'ta', 'sr': 'ta-IN'}, | |
| 'Telugu': {'tts': 'te', 'sr': 'te-IN'}, | |
| 'Urdu': {'tts': 'ur', 'sr': 'ur-PK'} | |
| } | |
| def get_language_codes(language_name): | |
| logger.debug(f"Getting language codes for: {language_name}") | |
| if language_name in LANGUAGE_MAPPING: | |
| return LANGUAGE_MAPPING[language_name]['tts'], LANGUAGE_MAPPING[language_name]['sr'] | |
| logger.warning(f"Language '{language_name}' not found in mapping, using English") | |
| return 'en', 'en-US' | |
| def convert_to_wav(input_path, output_path="converted.wav"): | |
| logger.debug(f"Converting audio from {input_path} to WAV") | |
| try: | |
| audio = AudioSegment.from_file(input_path) | |
| audio.export(output_path, format="wav") | |
| logger.debug(f"Audio converted to {output_path}") | |
| return output_path | |
| except Exception as e: | |
| logger.error(f"Failed to convert audio: {e}") | |
| raise RuntimeError(f"Audio conversion failed: {e}") | |
| def transcribe_audio(audio_path, language): | |
| logger.debug(f"Transcribing audio: {audio_path} with language: {language}") | |
| recognizer = sr.Recognizer() | |
| _, sr_lang_code = get_language_codes(language) | |
| try: | |
| with sr.AudioFile(audio_path) as source: | |
| audio_data = recognizer.record(source) | |
| transcription = recognizer.recognize_google(audio_data, language=sr_lang_code) | |
| logger.debug(f"Transcription successful: {transcription}") | |
| return transcription | |
| except sr.UnknownValueError: | |
| logger.warning("Speech recognition could not understand audio") | |
| return "" | |
| except sr.RequestError as e: | |
| logger.error(f"Speech recognition error: {e}") | |
| raise RuntimeError(f"Speech recognition failed: {e}") | |
| def translate_text(text, source_language, target_language): | |
| logger.debug(f"Translating text from {source_language} to {target_language}") | |
| if not text: | |
| return "Could not understand the audio. Please try again." | |
| if not DEEPSEEK_API_KEY: | |
| logger.error("DEEPSEEK_API_KEY is not set") | |
| return "API key is not configured. Please set the DEEPSEEK_API_KEY environment variable." | |
| prompt = f""" | |
| Translate the following text from {source_language} to {target_language}. | |
| Provide only the translation with no additional explanation or notes. | |
| Text to translate: "{text}" | |
| """ | |
| url = "https://api.deepseek.com/v1/chat/completions" | |
| headers = { | |
| "Authorization": f"Bearer {DEEPSEEK_API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| payload = { | |
| "model": "deepseek-chat", | |
| "messages": [ | |
| {"role": "system", "content": "You are a professional translator."}, | |
| {"role": "user", "content": prompt.strip()} | |
| ], | |
| "temperature": 0.3, | |
| "max_tokens": 1000 | |
| } | |
| try: | |
| response = requests.post(url, headers=headers, json=payload) | |
| response.raise_for_status() | |
| translation = response.json()["choices"][0]["message"]["content"].strip() | |
| logger.debug(f"Translation received: {translation[:50]}...") | |
| return translation | |
| except requests.RequestException as e: | |
| logger.error(f"DeepSeek API error: {e}") | |
| return f"Error with DeepSeek API: {str(e)}" | |
| def text_to_speech(message, language): | |
| """ | |
| Convert text to speech using gTTS with improved error handling | |
| and temporary file management to avoid 'Too Many Requests' errors. | |
| Args: | |
| message (str): The text to convert to speech | |
| language (str): Language for the speech | |
| Returns: | |
| str: Path to the generated audio file or None if failed | |
| """ | |
| logger.debug(f"Converting text to speech in language: {language}") | |
| try: | |
| tts_lang_code = get_language_codes(language)[0] # Get the TTS language code | |
| with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as temp_file: | |
| filename = temp_file.name | |
| max_retries = 3 | |
| retry_delay = 2 # Start with 2 seconds delay | |
| for attempt in range(max_retries): | |
| try: | |
| tts = gTTS(text=message, lang=tts_lang_code) | |
| tts.save(filename) | |
| logger.debug(f"Audio saved to {filename}") | |
| return filename | |
| except Exception as e: | |
| if "429" in str(e) and attempt < max_retries - 1: | |
| wait_time = retry_delay * (2 ** attempt) | |
| logger.warning(f"Rate limit hit. Retrying in {wait_time} seconds...") | |
| import time | |
| time.sleep(wait_time) | |
| else: | |
| raise | |
| except Exception as e: | |
| logger.error(f"Text-to-speech failed: {e}") | |
| if 'filename' in locals() and os.path.exists(filename): | |
| try: | |
| os.unlink(filename) | |
| except: | |
| pass | |
| raise RuntimeError(f"Text-to-speech failed: {e}") | |
| def translation_pipeline(audio_path, source_language, target_language): | |
| """Process audio file through the translation pipeline""" | |
| logger.debug(f"Starting translation pipeline for audio: {audio_path} from {source_language} to {target_language}") | |
| temp_files = [] | |
| try: | |
| wav_path = os.path.join("uploads", f"converted_{uuid.uuid4()}.wav") | |
| convert_to_wav(audio_path, wav_path) | |
| temp_files.append(wav_path) | |
| original_text = transcribe_audio(wav_path, source_language) | |
| if not original_text: | |
| return None, "Could not transcribe the audio. Please try again with clearer audio.", None | |
| translated_text = translate_text(original_text, source_language, target_language) | |
| audio_output_path = text_to_speech(translated_text, target_language) | |
| temp_files.append(audio_output_path) | |
| return original_text, translated_text, audio_output_path | |
| except Exception as e: | |
| logger.error(f"Pipeline error: {e}") | |
| return None, f"Error: {str(e)}", None | |
| finally: | |
| pass | |
| def process_audio_file(audio, source_language, target_language): | |
| """Main function to process audio for the Gradio interface""" | |
| logger.debug(f"Processing audio from {source_language} to {target_language}") | |
| if audio is None: | |
| return None, "No audio detected. Please upload an audio file or record one.", None | |
| with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_audio: | |
| temp_path = temp_audio.name | |
| if isinstance(audio, tuple): | |
| import scipy.io.wavfile as wav | |
| sample_rate, audio_data = audio | |
| wav.write(temp_path, sample_rate, audio_data) | |
| else: | |
| shutil.copy(audio, temp_path) | |
| original_text, translated_text, audio_output = translation_pipeline(temp_path, source_language, target_language) | |
| if os.path.exists(temp_path): | |
| os.remove(temp_path) | |
| return original_text, translated_text, audio_output | |
| with gr.Blocks(title="Voice Language Translator") as demo: | |
| gr.Markdown("# 🌐 Voice Language Translator") | |
| gr.Markdown("""Upload or record audio in one language and get it translated to another language! | |
| Hear the translation spoken in your target language.""") | |
| with gr.Row(): | |
| with gr.Column(): | |
| audio_input = gr.Audio( | |
| sources=["microphone", "upload"], | |
| type="filepath", | |
| label="Record or upload audio to translate" | |
| ) | |
| with gr.Row(): | |
| source_language = gr.Dropdown( | |
| choices=sorted(list(LANGUAGE_MAPPING.keys())), | |
| value="English", | |
| label="Source Language" | |
| ) | |
| target_language = gr.Dropdown( | |
| choices=sorted(list(LANGUAGE_MAPPING.keys())), | |
| value="Spanish", | |
| label="Target Language" | |
| ) | |
| process_btn = gr.Button("🔄 Translate", variant="primary") | |
| with gr.Column(): | |
| original_text = gr.Textbox(label="Original Text (Transcribed)") | |
| translated_text = gr.TextArea(label="Translated Text", lines=8) | |
| audio_response = gr.Audio(label="Translation Audio") | |
| process_btn.click( | |
| fn=process_audio_file, | |
| inputs=[audio_input, source_language, target_language], | |
| outputs=[original_text, translated_text, audio_response] | |
| ) | |
| gr.Markdown("### How It Works") | |
| gr.Markdown(""" | |
| 1. **Record or upload audio**: Speak or upload an audio file in your source language | |
| 2. **Select languages**: Choose your source and target languages | |
| 3. **Get translation**: Receive both text and audio translation in your target language | |
| This translator uses speech recognition, DeepSeek AI for translation, and text-to-speech technologies to provide a seamless translation experience. | |
| """) | |
| gr.Markdown("### Examples") | |
| gr.Markdown(""" | |
| Try saying phrases like: | |
| - "Hello, how are you today?" | |
| - "I would like to order food at a restaurant" | |
| - "Where is the nearest train station?" | |
| - "Can you help me find my hotel?" | |
| """) | |
| if __name__ == "__main__": | |
| demo.launch() |