forked from UTSAVS26/PyVerse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslation.py
58 lines (45 loc) · 1.89 KB
/
translation.py
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
51
52
53
54
55
56
57
58
import speech_recognition as sr
from googletrans import Translator
from gtts import gTTS
import pygame
import streamlit as st
# Initialize recognizer and translator
recognizer = sr.Recognizer()
translator = Translator()
# Function to capture and translate speech
def capture_and_translate(source_lang, target_lang):
with sr.Microphone() as source:
st.info("🎙️ Listening... Speak now.")
recognizer.adjust_for_ambient_noise(source, duration=1)
recognizer.energy_threshold = 200
try:
# Capture speech
audio = recognizer.listen(source, timeout=15, phrase_time_limit=15)
st.success("🔄 Processing...")
# Recognize speech
text = recognizer.recognize_google(audio, language=source_lang)
st.write(f"🗣️ Original ({source_lang}): {text}")
# Translate speech
translation = translator.translate(text, src=source_lang, dest=target_lang)
st.write(f"🔊 Translated ({target_lang}): {translation.text}")
# Convert translation to speech
tts = gTTS(text=translation.text, lang=target_lang)
audio_file = "translated_audio.mp3"
tts.save(audio_file)
# Play the audio
pygame.mixer.init()
pygame.mixer.music.load(audio_file)
pygame.mixer.music.play()
st.audio(audio_file)
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
pygame.mixer.music.stop()
pygame.mixer.quit()
return audio_file
except sr.WaitTimeoutError:
st.error("⚠️ No speech detected. Try speaking louder.")
except sr.UnknownValueError:
st.error("⚠️ Could not recognize speech.")
except Exception as e:
st.error(f"⚠️ Error: {str(e)}")
return None