prajyot2003 commited on
Commit
41ec8ae
Β·
verified Β·
1 Parent(s): b4fcc11

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -0
app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+ from langdetect import detect
3
+ from gtts import gTTS
4
+ import pyttsx3
5
+ import gradio as gr
6
+ import os
7
+ import tempfile
8
+
9
+ # 🌍 Supported language codes
10
+ LANG_CODE = {
11
+ "en": "English", "es": "Spanish", "fr": "French", "de": "German",
12
+ "it": "Italian", "nl": "Dutch", "ru": "Russian", "zh": "Chinese"
13
+ }
14
+
15
+ # Reverse lookup
16
+ LANG_NAME_TO_CODE = {v: k for k, v in LANG_CODE.items()}
17
+
18
+ # Cache for loaded models
19
+ translation_cache = {}
20
+
21
+ # Detect language
22
+ def detect_language(text):
23
+ try:
24
+ lang_code = detect(text)
25
+ return LANG_CODE.get(lang_code, lang_code)
26
+ except:
27
+ return "Unknown"
28
+
29
+ # Load pipeline per language pair
30
+ def get_translation_pipeline(src_code, tgt_code):
31
+ model_name = f"Helsinki-NLP/opus-mt-{src_code}-{tgt_code}"
32
+ key = (src_code, tgt_code)
33
+ if key not in translation_cache:
34
+ try:
35
+ translation_cache[key] = pipeline("translation", model=model_name, device=-1)
36
+ except:
37
+ translation_cache[key] = None
38
+ return translation_cache[key]
39
+
40
+ # Offline TTS
41
+ def speak_text(text, lang="en"):
42
+ engine = pyttsx3.init()
43
+ engine.setProperty("rate", 150)
44
+ engine.setProperty("voice", lang)
45
+ engine.say(text)
46
+ engine.runAndWait()
47
+
48
+ # Optional audio file (gTTS)
49
+ def generate_audio_file(text, lang_code):
50
+ try:
51
+ tts = gTTS(text=text, lang=lang_code)
52
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
53
+ tts.save(temp_file.name)
54
+ return temp_file.name
55
+ except:
56
+ return None
57
+
58
+ # Main translation logic
59
+ def translate_text(input_text, target_lang, speak=False):
60
+ if not input_text.strip():
61
+ return "Please enter some text to translate.", None, "Unknown"
62
+
63
+ detected_lang = detect_language(input_text)
64
+ if detected_lang == "Unknown":
65
+ return "Could not detect source language.", None, detected_lang
66
+
67
+ if detected_lang == target_lang:
68
+ return f"Source and target languages are the same. Text: {input_text}", None, detected_lang
69
+
70
+ src_code = LANG_NAME_TO_CODE.get(detected_lang)
71
+ tgt_code = LANG_NAME_TO_CODE.get(target_lang)
72
+
73
+ if not src_code or not tgt_code:
74
+ return f"Unsupported language pair: {detected_lang} β†’ {target_lang}", None, detected_lang
75
+
76
+ translator = get_translation_pipeline(src_code, tgt_code)
77
+ if not translator:
78
+ return f"No model found for {detected_lang} β†’ {target_lang}", None, detected_lang
79
+
80
+ try:
81
+ result = translator(input_text, max_length=512)
82
+ translated_text = result[0]['translation_text']
83
+ audio_path = generate_audio_file(translated_text, tgt_code) if speak else None
84
+ return translated_text, audio_path, detected_lang
85
+ except Exception as e:
86
+ return f"Translation failed: {str(e)}", None, detected_lang
87
+
88
+ # Gradio UI
89
+ with gr.Blocks() as app:
90
+ gr.Markdown("# 🌍 AI Translator with Speech & Auto-Language Detection")
91
+
92
+ with gr.Row():
93
+ with gr.Column():
94
+ input_text = gr.Textbox(lines=4, label="Enter text to translate")
95
+ target_lang = gr.Dropdown(
96
+ choices=list(LANG_NAME_TO_CODE.keys()),
97
+ value="French",
98
+ label="Target Language"
99
+ )
100
+ speak_checkbox = gr.Checkbox(label="πŸ”Š Enable speech output", value=True)
101
+ translate_button = gr.Button("πŸ” Translate")
102
+
103
+ with gr.Column():
104
+ output_text = gr.Textbox(lines=4, label="Translated Text")
105
+ output_audio = gr.Audio(label="Speech Output", autoplay=True)
106
+ detected_lang = gr.Textbox(label="Detected Language", interactive=False)
107
+
108
+ translate_button.click(
109
+ translate_text,
110
+ inputs=[input_text, target_lang, speak_checkbox],
111
+ outputs=[output_text, output_audio, detected_lang]
112
+ )
113
+
114
+ if __name__ == "__main__":
115
+ app.launch(share=True, server_name="0.0.0.0", server_port=7862)