File size: 1,502 Bytes
3f9a435
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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