Create audio_processor.py
Browse files- audio_processor.py +50 -0
audio_processor.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import speech_recognition as sr
|
3 |
+
from gtts import gTTS
|
4 |
+
import os
|
5 |
+
|
6 |
+
def transcribe_audio(audio_file):
|
7 |
+
"""Transcribe uploaded audio file to text."""
|
8 |
+
recognizer = sr.Recognizer()
|
9 |
+
try:
|
10 |
+
# Save uploaded file temporarily
|
11 |
+
with open("temp_audio.wav", "wb") as f:
|
12 |
+
f.write(audio_file.read())
|
13 |
+
|
14 |
+
# Transcribe using SpeechRecognition
|
15 |
+
with sr.AudioFile("temp_audio.wav") as source:
|
16 |
+
audio = recognizer.record(source)
|
17 |
+
text = recognizer.recognize_google(audio)
|
18 |
+
|
19 |
+
# Clean up
|
20 |
+
os.remove("temp_audio.wav")
|
21 |
+
return text
|
22 |
+
except Exception as e:
|
23 |
+
st.error(f"Audio transcription failed: {str(e)}")
|
24 |
+
return ""
|
25 |
+
|
26 |
+
def text_to_speech(text, target_lang):
|
27 |
+
"""Convert translated text to audio."""
|
28 |
+
try:
|
29 |
+
# Map target language to gTTS codes
|
30 |
+
lang_map = {
|
31 |
+
"English": "en",
|
32 |
+
"French": "fr",
|
33 |
+
"Spanish": "es",
|
34 |
+
"German": "de",
|
35 |
+
"Chinese": "zh",
|
36 |
+
"Arabic": "ar",
|
37 |
+
"Russian": "ru",
|
38 |
+
"Hindi": "hi",
|
39 |
+
"Japanese": "ja"
|
40 |
+
}
|
41 |
+
lang_code = lang_map.get(target_lang, "en")
|
42 |
+
|
43 |
+
# Generate audio
|
44 |
+
tts = gTTS(text=text, lang=lang_code, slow=False)
|
45 |
+
audio_path = "output_audio.mp3"
|
46 |
+
tts.save(audio_path)
|
47 |
+
return audio_path
|
48 |
+
except Exception as e:
|
49 |
+
st.error(f"Audio generation failed: {str(e)}")
|
50 |
+
return None
|