Ervinoreo commited on
Commit
b9d31ad
·
1 Parent(s): d8cd76e

Add application file

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import speech_recognition as sr
3
+ from deep_translator import GoogleTranslator
4
+ from gtts import gTTS
5
+ import os
6
+
7
+ # Recognize and translate audio to Chinese
8
+ def recognize_and_translate(audio_file_path):
9
+ # Use the file path directly from Gradio input
10
+ recognizer = sr.Recognizer()
11
+ with sr.AudioFile(audio_file_path) as source:
12
+ audio_data = recognizer.record(source)
13
+ try:
14
+ text = recognizer.recognize_google(audio_data)
15
+ except sr.UnknownValueError:
16
+ return "Could not understand the audio."
17
+ except sr.RequestError:
18
+ return "Network error. Please try again."
19
+
20
+ # Translate the recognized text to Chinese
21
+ translated_text = GoogleTranslator(source="en", target="zh-CN").translate(text)
22
+ return f"Recognized: {text}\nTranslated to Chinese: {translated_text}"
23
+
24
+ # Translate Chinese input to English and convert to speech
25
+ def translate_to_english(chinese_text):
26
+ # Translate Chinese text to English
27
+ translated_text = GoogleTranslator(source="zh-CN", target="en").translate(chinese_text)
28
+
29
+ # Convert the translated text to speech
30
+ tts = gTTS(text=translated_text, lang="en", slow=False)
31
+ tts.save("output.mp3")
32
+
33
+ return translated_text, "output.mp3"
34
+
35
+ # Create Gradio interfaces
36
+ interface1 = gr.Interface(
37
+ fn=recognize_and_translate,
38
+ inputs=gr.Audio(type="filepath"),
39
+ outputs="text",
40
+ title="Speech Recognition and Translation to Chinese",
41
+ )
42
+
43
+ interface2 = gr.Interface(
44
+ fn=translate_to_english,
45
+ inputs="text",
46
+ outputs=["text", "audio"],
47
+ title="Translate Chinese to English and Play",
48
+ )
49
+
50
+ # Combine both interfaces into a tabbed layout
51
+ app = gr.TabbedInterface([interface1, interface2], ["Speech to Chinese", "Chinese to English"])
52
+
53
+ # Launch the app
54
+ if __name__ == "__main__":
55
+ app.launch()