MuhammaJamal commited on
Commit
bbe3da0
·
verified ·
1 Parent(s): 93974c4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -66
app.py CHANGED
@@ -1,13 +1,15 @@
 
1
  import logging
2
  import os
 
3
  import shutil
4
  import uuid
5
  import tempfile
6
- import time
7
  import gradio as gr
8
  from pydub import AudioSegment
9
  from gtts import gTTS
10
  import speech_recognition as sr
 
11
  from dotenv import load_dotenv
12
 
13
  # Configure logging
@@ -17,6 +19,9 @@ logger = logging.getLogger(__name__)
17
  # Load environment variables
18
  load_dotenv()
19
 
 
 
 
20
  # Create uploads directory if it doesn't exist
21
  os.makedirs("uploads", exist_ok=True)
22
 
@@ -40,7 +45,17 @@ LANGUAGE_MAPPING = {
40
  'Polish': {'tts': 'pl', 'sr': 'pl-PL'},
41
  'Greek': {'tts': 'el', 'sr': 'el-GR'},
42
  'Thai': {'tts': 'th', 'sr': 'th-TH'},
43
- 'Vietnamese': {'tts': 'vi', 'sr': 'vi-VN'}
 
 
 
 
 
 
 
 
 
 
44
  }
45
 
46
  def get_language_codes(language_name):
@@ -63,11 +78,10 @@ def convert_to_wav(input_path, output_path="converted.wav"):
63
  logger.error(f"Failed to convert audio: {e}")
64
  raise RuntimeError(f"Audio conversion failed: {e}")
65
 
66
- def transcribe_audio(audio_path, input_language):
67
- """Transcribe audio in the input language"""
68
- logger.debug(f"Transcribing audio: {audio_path} with language: {input_language}")
69
  recognizer = sr.Recognizer()
70
- _, sr_lang_code = get_language_codes(input_language)
71
  try:
72
  with sr.AudioFile(audio_path) as source:
73
  audio_data = recognizer.record(source)
@@ -81,22 +95,63 @@ def transcribe_audio(audio_path, input_language):
81
  logger.error(f"Speech recognition error: {e}")
82
  raise RuntimeError(f"Speech recognition failed: {e}")
83
 
84
- def text_to_speech(message, output_language):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  """
86
- Convert text to speech using gTTS in the output language
 
87
 
88
  Args:
89
  message (str): The text to convert to speech
90
- output_language (str): Language for the speech
91
 
92
  Returns:
93
  str: Path to the generated audio file or None if failed
94
  """
95
- logger.debug(f"Converting text to speech in language: {output_language}")
96
 
97
  try:
98
  # Get language code
99
- tts_lang_code = get_language_codes(output_language)[0]
100
 
101
  # Use tempfile to manage file creation
102
  with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as temp_file:
@@ -117,6 +172,7 @@ def text_to_speech(message, output_language):
117
  # Too Many Requests error - implement backoff
118
  wait_time = retry_delay * (2 ** attempt)
119
  logger.warning(f"Rate limit hit. Retrying in {wait_time} seconds...")
 
120
  time.sleep(wait_time)
121
  else:
122
  # Either not a rate limit error or we've exhausted retries
@@ -132,15 +188,9 @@ def text_to_speech(message, output_language):
132
  pass
133
  raise RuntimeError(f"Text-to-speech failed: {e}")
134
 
135
- def speech_to_speech_translation(audio_path, input_language, output_language):
136
- """
137
- Process audio file through the speech-to-speech translation pipeline:
138
- 1. Convert to WAV for speech recognition
139
- 2. Transcribe the audio in the input language
140
- 3. Convert the transcription to speech in the output language
141
- """
142
- logger.debug(f"Starting speech-to-speech translation for audio: {audio_path}")
143
- logger.debug(f"Input language: {input_language}, Output language: {output_language}")
144
 
145
  temp_files = []
146
 
@@ -150,32 +200,35 @@ def speech_to_speech_translation(audio_path, input_language, output_language):
150
  convert_to_wav(audio_path, wav_path)
151
  temp_files.append(wav_path)
152
 
153
- # Transcribe the audio
154
- transcription = transcribe_audio(wav_path, input_language)
155
- if not transcription:
156
- return None, None
 
 
 
157
 
158
- # Convert transcription to speech in the output language
159
- audio_output_path = text_to_speech(transcription, output_language)
160
  temp_files.append(audio_output_path)
161
 
162
- return transcription, audio_output_path
163
 
164
  except Exception as e:
165
  logger.error(f"Pipeline error: {e}")
166
- return None, None
167
 
168
  finally:
169
  # We don't remove temp files here since Gradio needs them for display
170
  # They'll be removed when the app restarts or by the OS temp file cleaner
171
  pass
172
 
173
- def process_audio_file(audio, input_language, output_language):
174
  """Main function to process audio for the Gradio interface"""
175
- logger.debug(f"Processing audio with input language: {input_language}, output language: {output_language}")
176
 
177
  if audio is None:
178
- return "No audio detected. Please upload an audio file or record one.", None
179
 
180
  # Save temporary audio file
181
  with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_audio:
@@ -191,71 +244,70 @@ def process_audio_file(audio, input_language, output_language):
191
  shutil.copy(audio, temp_path)
192
 
193
  # Process the audio
194
- transcript, audio_output = speech_to_speech_translation(temp_path, input_language, output_language)
195
 
196
  # Clean up the temporary input file
197
  if os.path.exists(temp_path):
198
  os.remove(temp_path)
199
 
200
- if transcript is None:
201
- return "Could not transcribe the audio. Please try again with clearer audio.", None
202
-
203
- return transcript, audio_output
204
 
205
  # Create Gradio interface
206
- with gr.Blocks(title="Speech-to-Speech Translator") as demo:
207
- gr.Markdown("# 🗣️ Speech-to-Speech Translator")
208
- gr.Markdown("""Upload or record audio in one language and hear it in another!
209
- This app uses speech recognition to transcribe your speech and then
210
- converts it to spoken audio in your target language.""")
211
 
212
  with gr.Row():
213
  with gr.Column():
214
  audio_input = gr.Audio(
215
  sources=["microphone", "upload"],
216
  type="filepath",
217
- label="Record or upload audio"
218
  )
219
 
220
- input_language = gr.Dropdown(
221
- choices=sorted(list(LANGUAGE_MAPPING.keys())),
222
- value="English",
223
- label="Input Language"
224
- )
225
-
226
- output_language = gr.Dropdown(
227
- choices=sorted(list(LANGUAGE_MAPPING.keys())),
228
- value="Spanish",
229
- label="Output Language"
230
- )
 
231
 
232
  process_btn = gr.Button("🔄 Translate", variant="primary")
233
 
234
  with gr.Column():
235
- transcript_output = gr.Textbox(label="Transcription (in input language)")
236
- audio_response = gr.Audio(label="Translated Speech")
 
237
 
238
  process_btn.click(
239
  fn=process_audio_file,
240
- inputs=[audio_input, input_language, output_language],
241
- outputs=[transcript_output, audio_response]
242
  )
243
 
244
  gr.Markdown("### How It Works")
245
  gr.Markdown("""
246
- 1. **Record or upload audio**: Speak or upload audio in your chosen input language
247
- 2. **Select languages**: Choose the language you're speaking and the language you want to hear
248
- 3. **Get translation**: Receive both text transcription and audio translation
249
 
250
- This translation app uses speech recognition and text-to-speech technologies to convert spoken language from one language to another without using traditional text translation APIs.
251
  """)
252
 
253
- gr.Markdown("### Tips for Best Results")
254
  gr.Markdown("""
255
- - Speak clearly and at a moderate pace
256
- - Minimize background noise when recording
257
- - For best results, use common languages like English, Spanish, French, etc.
258
- - Short to medium length sentences work better than very long ones
 
259
  """)
260
 
261
  if __name__ == "__main__":
 
1
+ import base64
2
  import logging
3
  import os
4
+ import random
5
  import shutil
6
  import uuid
7
  import tempfile
 
8
  import gradio as gr
9
  from pydub import AudioSegment
10
  from gtts import gTTS
11
  import speech_recognition as sr
12
+ import requests
13
  from dotenv import load_dotenv
14
 
15
  # Configure logging
 
19
  # Load environment variables
20
  load_dotenv()
21
 
22
+ # Set your DeepSeek API Key (for development only, use environment variables in production)
23
+ DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY", "")
24
+
25
  # Create uploads directory if it doesn't exist
26
  os.makedirs("uploads", exist_ok=True)
27
 
 
45
  'Polish': {'tts': 'pl', 'sr': 'pl-PL'},
46
  'Greek': {'tts': 'el', 'sr': 'el-GR'},
47
  'Thai': {'tts': 'th', 'sr': 'th-TH'},
48
+ 'Vietnamese': {'tts': 'vi', 'sr': 'vi-VN'},
49
+ 'Czech': {'tts': 'cs', 'sr': 'cs-CZ'},
50
+ 'Hungarian': {'tts': 'hu', 'sr': 'hu-HU'},
51
+ 'Romanian': {'tts': 'ro', 'sr': 'ro-RO'},
52
+ 'Finnish': {'tts': 'fi', 'sr': 'fi-FI'},
53
+ 'Danish': {'tts': 'da', 'sr': 'da-DK'},
54
+ 'Ukrainian': {'tts': 'uk', 'sr': 'uk-UA'},
55
+ 'Bengali': {'tts': 'bn', 'sr': 'bn-IN'},
56
+ 'Tamil': {'tts': 'ta', 'sr': 'ta-IN'},
57
+ 'Telugu': {'tts': 'te', 'sr': 'te-IN'},
58
+ 'Urdu': {'tts': 'ur', 'sr': 'ur-PK'}
59
  }
60
 
61
  def get_language_codes(language_name):
 
78
  logger.error(f"Failed to convert audio: {e}")
79
  raise RuntimeError(f"Audio conversion failed: {e}")
80
 
81
+ def transcribe_audio(audio_path, language):
82
+ logger.debug(f"Transcribing audio: {audio_path} with language: {language}")
 
83
  recognizer = sr.Recognizer()
84
+ _, sr_lang_code = get_language_codes(language)
85
  try:
86
  with sr.AudioFile(audio_path) as source:
87
  audio_data = recognizer.record(source)
 
95
  logger.error(f"Speech recognition error: {e}")
96
  raise RuntimeError(f"Speech recognition failed: {e}")
97
 
98
+ def translate_text(text, source_language, target_language):
99
+ logger.debug(f"Translating text from {source_language} to {target_language}")
100
+ if not text:
101
+ return "Could not understand the audio. Please try again."
102
+
103
+ # Check if API key is set
104
+ if not DEEPSEEK_API_KEY:
105
+ logger.error("DEEPSEEK_API_KEY is not set")
106
+ return "API key is not configured. Please set the DEEPSEEK_API_KEY environment variable."
107
+
108
+ prompt = f"""
109
+ Translate the following text from {source_language} to {target_language}.
110
+ Provide only the translation with no additional explanation or notes.
111
+
112
+ Text to translate: "{text}"
113
+ """
114
+ url = "https://api.deepseek.com/v1/chat/completions"
115
+ headers = {
116
+ "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
117
+ "Content-Type": "application/json"
118
+ }
119
+ payload = {
120
+ "model": "deepseek-chat",
121
+ "messages": [
122
+ {"role": "system", "content": "You are a professional translator."},
123
+ {"role": "user", "content": prompt.strip()}
124
+ ],
125
+ "temperature": 0.3,
126
+ "max_tokens": 1000
127
+ }
128
+ try:
129
+ response = requests.post(url, headers=headers, json=payload)
130
+ response.raise_for_status()
131
+ translation = response.json()["choices"][0]["message"]["content"].strip()
132
+ logger.debug(f"Translation received: {translation[:50]}...")
133
+ return translation
134
+ except requests.RequestException as e:
135
+ logger.error(f"DeepSeek API error: {e}")
136
+ return f"Error with DeepSeek API: {str(e)}"
137
+
138
+ def text_to_speech(message, language):
139
  """
140
+ Convert text to speech using gTTS with improved error handling
141
+ and temporary file management to avoid 'Too Many Requests' errors.
142
 
143
  Args:
144
  message (str): The text to convert to speech
145
+ language (str): Language for the speech
146
 
147
  Returns:
148
  str: Path to the generated audio file or None if failed
149
  """
150
+ logger.debug(f"Converting text to speech in language: {language}")
151
 
152
  try:
153
  # Get language code
154
+ tts_lang_code = get_language_codes(language)[0] # Get the TTS language code
155
 
156
  # Use tempfile to manage file creation
157
  with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as temp_file:
 
172
  # Too Many Requests error - implement backoff
173
  wait_time = retry_delay * (2 ** attempt)
174
  logger.warning(f"Rate limit hit. Retrying in {wait_time} seconds...")
175
+ import time
176
  time.sleep(wait_time)
177
  else:
178
  # Either not a rate limit error or we've exhausted retries
 
188
  pass
189
  raise RuntimeError(f"Text-to-speech failed: {e}")
190
 
191
+ def translation_pipeline(audio_path, source_language, target_language):
192
+ """Process audio file through the translation pipeline"""
193
+ logger.debug(f"Starting translation pipeline for audio: {audio_path} from {source_language} to {target_language}")
 
 
 
 
 
 
194
 
195
  temp_files = []
196
 
 
200
  convert_to_wav(audio_path, wav_path)
201
  temp_files.append(wav_path)
202
 
203
+ # Transcribe the audio in source language
204
+ original_text = transcribe_audio(wav_path, source_language)
205
+ if not original_text:
206
+ return None, "Could not transcribe the audio. Please try again with clearer audio.", None
207
+
208
+ # Translate the transcribed text
209
+ translated_text = translate_text(original_text, source_language, target_language)
210
 
211
+ # Convert translated text to speech in target language
212
+ audio_output_path = text_to_speech(translated_text, target_language)
213
  temp_files.append(audio_output_path)
214
 
215
+ return original_text, translated_text, audio_output_path
216
 
217
  except Exception as e:
218
  logger.error(f"Pipeline error: {e}")
219
+ return None, f"Error: {str(e)}", None
220
 
221
  finally:
222
  # We don't remove temp files here since Gradio needs them for display
223
  # They'll be removed when the app restarts or by the OS temp file cleaner
224
  pass
225
 
226
+ def process_audio_file(audio, source_language, target_language):
227
  """Main function to process audio for the Gradio interface"""
228
+ logger.debug(f"Processing audio from {source_language} to {target_language}")
229
 
230
  if audio is None:
231
+ return None, "No audio detected. Please upload an audio file or record one.", None
232
 
233
  # Save temporary audio file
234
  with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_audio:
 
244
  shutil.copy(audio, temp_path)
245
 
246
  # Process the audio
247
+ original_text, translated_text, audio_output = translation_pipeline(temp_path, source_language, target_language)
248
 
249
  # Clean up the temporary input file
250
  if os.path.exists(temp_path):
251
  os.remove(temp_path)
252
 
253
+ return original_text, translated_text, audio_output
 
 
 
254
 
255
  # Create Gradio interface
256
+ with gr.Blocks(title="Voice Language Translator") as demo:
257
+ gr.Markdown("# 🌐 Voice Language Translator")
258
+ gr.Markdown("""Upload or record audio in one language and get it translated to another language!
259
+ Hear the translation spoken in your target language.""")
 
260
 
261
  with gr.Row():
262
  with gr.Column():
263
  audio_input = gr.Audio(
264
  sources=["microphone", "upload"],
265
  type="filepath",
266
+ label="Record or upload audio to translate"
267
  )
268
 
269
+ with gr.Row():
270
+ source_language = gr.Dropdown(
271
+ choices=sorted(list(LANGUAGE_MAPPING.keys())),
272
+ value="English",
273
+ label="Source Language"
274
+ )
275
+
276
+ target_language = gr.Dropdown(
277
+ choices=sorted(list(LANGUAGE_MAPPING.keys())),
278
+ value="Spanish",
279
+ label="Target Language"
280
+ )
281
 
282
  process_btn = gr.Button("🔄 Translate", variant="primary")
283
 
284
  with gr.Column():
285
+ original_text = gr.Textbox(label="Original Text (Transcribed)")
286
+ translated_text = gr.TextArea(label="Translated Text", lines=8)
287
+ audio_response = gr.Audio(label="Translation Audio")
288
 
289
  process_btn.click(
290
  fn=process_audio_file,
291
+ inputs=[audio_input, source_language, target_language],
292
+ outputs=[original_text, translated_text, audio_response]
293
  )
294
 
295
  gr.Markdown("### How It Works")
296
  gr.Markdown("""
297
+ 1. **Record or upload audio**: Speak or upload an audio file in your source language
298
+ 2. **Select languages**: Choose your source and target languages
299
+ 3. **Get translation**: Receive both text and audio translation in your target language
300
 
301
+ This translator uses speech recognition, DeepSeek AI for translation, and text-to-speech technologies to provide a seamless translation experience.
302
  """)
303
 
304
+ gr.Markdown("### Examples")
305
  gr.Markdown("""
306
+ Try saying phrases like:
307
+ - "Hello, how are you today?"
308
+ - "I would like to order food at a restaurant"
309
+ - "Where is the nearest train station?"
310
+ - "Can you help me find my hotel?"
311
  """)
312
 
313
  if __name__ == "__main__":