Krishna086's picture
Create audio_processor.py
3f9a435 verified
raw
history blame
1.5 kB
import streamlit as st
import speech_recognition as sr
from gtts import gTTS
import os
def transcribe_audio(audio_file):
"""Transcribe uploaded audio file to text."""
recognizer = sr.Recognizer()
try:
# Save uploaded file temporarily
with open("temp_audio.wav", "wb") as f:
f.write(audio_file.read())
# Transcribe using SpeechRecognition
with sr.AudioFile("temp_audio.wav") as source:
audio = recognizer.record(source)
text = recognizer.recognize_google(audio)
# Clean up
os.remove("temp_audio.wav")
return text
except Exception as e:
st.error(f"Audio transcription failed: {str(e)}")
return ""
def text_to_speech(text, target_lang):
"""Convert translated text to audio."""
try:
# Map target language to gTTS codes
lang_map = {
"English": "en",
"French": "fr",
"Spanish": "es",
"German": "de",
"Chinese": "zh",
"Arabic": "ar",
"Russian": "ru",
"Hindi": "hi",
"Japanese": "ja"
}
lang_code = lang_map.get(target_lang, "en")
# Generate audio
tts = gTTS(text=text, lang=lang_code, slow=False)
audio_path = "output_audio.mp3"
tts.save(audio_path)
return audio_path
except Exception as e:
st.error(f"Audio generation failed: {str(e)}")
return None