Update audio_processor.py
Browse files- audio_processor.py +19 -12
audio_processor.py
CHANGED
@@ -2,6 +2,7 @@ import streamlit as st
|
|
2 |
import speech_recognition as sr
|
3 |
from gtts import gTTS
|
4 |
import io
|
|
|
5 |
|
6 |
def transcribe_audio(audio_file):
|
7 |
recognizer = sr.Recognizer()
|
@@ -16,7 +17,7 @@ def transcribe_audio(audio_file):
|
|
16 |
st.error(f"Transcription failed: {str(e)}")
|
17 |
return ""
|
18 |
|
19 |
-
def text_to_speech(text, target_lang):
|
20 |
try:
|
21 |
if not text:
|
22 |
st.error("No text to convert to audio.")
|
@@ -27,16 +28,22 @@ def text_to_speech(text, target_lang):
|
|
27 |
}
|
28 |
lang_code = lang_map.get(target_lang, "en")
|
29 |
st.write(f"Generating audio for {lang_code}")
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
except Exception as e:
|
41 |
-
st.error(f"Audio
|
42 |
return None
|
|
|
2 |
import speech_recognition as sr
|
3 |
from gtts import gTTS
|
4 |
import io
|
5 |
+
import time
|
6 |
|
7 |
def transcribe_audio(audio_file):
|
8 |
recognizer = sr.Recognizer()
|
|
|
17 |
st.error(f"Transcription failed: {str(e)}")
|
18 |
return ""
|
19 |
|
20 |
+
def text_to_speech(text, target_lang, max_retries=2):
|
21 |
try:
|
22 |
if not text:
|
23 |
st.error("No text to convert to audio.")
|
|
|
28 |
}
|
29 |
lang_code = lang_map.get(target_lang, "en")
|
30 |
st.write(f"Generating audio for {lang_code}")
|
31 |
+
for attempt in range(max_retries):
|
32 |
+
try:
|
33 |
+
tts = gTTS(text=text[:200], lang=lang_code, slow=False)
|
34 |
+
audio_buffer = io.BytesIO()
|
35 |
+
tts.write_to_fp(audio_buffer)
|
36 |
+
audio_buffer.seek(0)
|
37 |
+
if audio_buffer.getbuffer().nbytes > 0:
|
38 |
+
st.success(f"Audio generated for {target_lang} on attempt {attempt + 1}")
|
39 |
+
return audio_buffer
|
40 |
+
time.sleep(2 ** attempt) # Exponential backoff
|
41 |
+
except Exception as e:
|
42 |
+
st.warning(f"Attempt {attempt + 1} failed: {str(e)}")
|
43 |
+
if attempt == max_retries - 1:
|
44 |
+
st.error(f"Audio failed after {max_retries} attempts. Try English/French.")
|
45 |
+
return None
|
46 |
+
return None
|
47 |
except Exception as e:
|
48 |
+
st.error(f"Audio processing error: {str(e)}. Try English/French.")
|
49 |
return None
|