File size: 11,128 Bytes
bbe3da0
9405cd8
 
bbe3da0
9405cd8
 
 
 
 
 
 
bbe3da0
9405cd8
 
6a2464c
9405cd8
 
 
6a2464c
9405cd8
 
6a2464c
bbe3da0
 
6a2464c
9405cd8
 
6a2464c
9405cd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbe3da0
 
 
 
 
 
 
 
 
 
 
9405cd8
 
 
6a2464c
9405cd8
 
 
6a2464c
9405cd8
 
 
 
 
 
 
 
 
 
 
 
 
 
bbe3da0
 
9405cd8
bbe3da0
9405cd8
 
 
 
 
 
 
 
 
 
 
 
 
bbe3da0
 
 
 
 
6a2464c
bbe3da0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9405cd8
bbe3da0
 
9405cd8
 
 
bbe3da0
9405cd8
 
 
 
bbe3da0
9405cd8
 
6a2464c
bbe3da0
9405cd8
6a2464c
9405cd8
 
 
6a2464c
9405cd8
 
 
 
 
 
 
 
 
 
 
6a2464c
9405cd8
 
bbe3da0
9405cd8
 
6a2464c
9405cd8
 
 
 
6a2464c
9405cd8
 
 
 
 
 
 
bbe3da0
 
 
9405cd8
 
 
 
6a2464c
9405cd8
 
 
 
6a2464c
bbe3da0
 
 
 
6a2464c
bbe3da0
9405cd8
6a2464c
bbe3da0
9405cd8
 
bbe3da0
9405cd8
 
 
bbe3da0
9405cd8
 
6a2464c
9405cd8
 
bbe3da0
9405cd8
bbe3da0
9405cd8
 
bbe3da0
9405cd8
6a2464c
9405cd8
 
 
6a2464c
9405cd8
 
 
 
 
6a2464c
9405cd8
 
6a2464c
bbe3da0
9405cd8
6a2464c
9405cd8
 
 
bbe3da0
9405cd8
6a2464c
bbe3da0
 
 
 
9405cd8
 
 
 
 
 
bbe3da0
9405cd8
 
bbe3da0
 
 
 
 
 
 
 
 
 
 
 
9405cd8
 
 
 
bbe3da0
 
 
9405cd8
 
 
bbe3da0
 
9405cd8
 
 
 
bbe3da0
 
 
9405cd8
bbe3da0
9405cd8
 
bbe3da0
9405cd8
bbe3da0
 
 
 
 
9405cd8
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
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()