prajyot2003 commited on
Commit
7db2e4c
Β·
verified Β·
1 Parent(s): 29526ce

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -77
app.py CHANGED
@@ -1,101 +1,58 @@
 
1
  from transformers import pipeline
2
  from langdetect import detect
3
  from gtts import gTTS
4
- import gradio as gr
5
- import tempfile
6
-
7
- # 🌍 Supported language codes (Portuguese removed)
8
- LANG_CODE = {
9
- "en": "English", "es": "Spanish", "fr": "French", "de": "German",
10
- "it": "Italian", "nl": "Dutch", "ru": "Russian", "zh": "Chinese"
11
- }
12
 
13
- # Reverse map: English β†’ "en"
14
- LANG_NAME_TO_CODE = {v: k for k, v in LANG_CODE.items()}
15
 
16
- # Cache translation pipelines
17
- translation_cache = {}
18
-
19
- def detect_language(text):
20
  try:
21
- lang_code = detect(text)
22
- return LANG_CODE.get(lang_code, lang_code)
23
- except:
24
- return "Unknown"
25
-
26
- def get_translation_pipeline(src_code, tgt_code):
27
- model_name = f"Helsinki-NLP/opus-mt-{src_code}-{tgt_code}"
28
- key = (src_code, tgt_code)
29
- if key not in translation_cache:
30
- try:
31
- translation_cache[key] = pipeline("translation", model=model_name, device=-1)
32
- except:
33
- translation_cache[key] = None
34
- return translation_cache[key]
35
 
36
- def generate_audio_file(text, lang_code):
37
- try:
38
- tts = gTTS(text=text, lang=lang_code)
39
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
40
- tts.save(temp_file.name)
41
- return temp_file.name
42
- except:
43
- return None
44
 
45
- def translate_text(input_text, target_lang, speak=False):
46
- if not input_text.strip():
47
- return "Please enter some text to translate.", None, "Unknown"
 
 
 
48
 
49
- detected_lang = detect_language(input_text)
50
- if detected_lang == "Unknown":
51
- return "Could not detect source language.", None, detected_lang
52
 
53
- if detected_lang == target_lang:
54
- return f"Source and target languages are the same. Text: {input_text}", None, detected_lang
55
-
56
- src_code = LANG_NAME_TO_CODE.get(detected_lang)
57
- tgt_code = LANG_NAME_TO_CODE.get(target_lang)
58
-
59
- if not src_code or not tgt_code:
60
- return f"Unsupported language pair: {detected_lang} β†’ {target_lang}", None, detected_lang
61
-
62
- translator = get_translation_pipeline(src_code, tgt_code)
63
- if not translator:
64
- return f"No model found for {detected_lang} β†’ {target_lang}", None, detected_lang
65
-
66
- try:
67
- result = translator(input_text, max_length=512)
68
- translated_text = result[0]['translation_text']
69
- audio_path = generate_audio_file(translated_text, tgt_code) if speak else None
70
- return translated_text, audio_path, detected_lang
71
  except Exception as e:
72
- return f"Translation failed: {str(e)}", None, detected_lang
73
 
74
- # Gradio UI
75
- with gr.Blocks() as app:
76
- gr.Markdown("# 🌍 AI Translator with Auto-Detect and Speech Output")
77
 
78
  with gr.Row():
79
  with gr.Column():
80
- input_text = gr.Textbox(lines=4, label="Enter text to translate")
81
  target_lang = gr.Dropdown(
82
- choices=list(LANG_NAME_TO_CODE.keys()),
83
- value="French",
84
- label="Target Language"
85
  )
86
- speak_checkbox = gr.Checkbox(label="πŸ”Š Enable speech output", value=True)
87
- translate_button = gr.Button("πŸ” Translate")
88
 
89
  with gr.Column():
90
- output_text = gr.Textbox(lines=4, label="Translated Text")
91
- output_audio = gr.Audio(label="Speech Output", autoplay=True)
92
- detected_lang = gr.Textbox(label="Detected Language", interactive=False)
93
 
94
- translate_button.click(
95
  translate_text,
96
- inputs=[input_text, target_lang, speak_checkbox],
97
- outputs=[output_text, output_audio, detected_lang]
98
  )
99
 
 
100
  if __name__ == "__main__":
101
- app.launch()
 
1
+ import gradio as gr
2
  from transformers import pipeline
3
  from langdetect import detect
4
  from gtts import gTTS
5
+ import os
 
 
 
 
 
 
 
6
 
7
+ # πŸ”₯ Load Hugging Face translation model
8
+ translator = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en")
9
 
10
+ def translate_text(text, target_lang, speech_output):
 
 
 
11
  try:
12
+ # Detect source language
13
+ source_lang = detect(text)
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ # Translate text
16
+ translation = translator(text, tgt_lang=target_lang)
17
+ translated_text = translation[0]['translation_text']
 
 
 
 
 
18
 
19
+ # Generate speech if enabled
20
+ audio_file = None
21
+ if speech_output:
22
+ tts = gTTS(translated_text, lang=target_lang)
23
+ audio_file = "output.mp3"
24
+ tts.save(audio_file)
25
 
26
+ return f"Detected Language: {source_lang}\n\nTranslation: {translated_text}", audio_file
 
 
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  except Exception as e:
29
+ return f"⚠️ Error: {str(e)}", None
30
 
31
+ # 🎨 Gradio UI
32
+ with gr.Blocks() as demo:
33
+ gr.Markdown("# 🌍 LinguaCast\nAI-Powered Multilingual Translator with Speech Output")
34
 
35
  with gr.Row():
36
  with gr.Column():
37
+ text_input = gr.Textbox(label="Enter your text", placeholder="Type here...")
38
  target_lang = gr.Dropdown(
39
+ ["en", "es", "fr", "de", "it", "nl", "ru", "zh"],
40
+ label="Select Target Language",
41
+ value="en"
42
  )
43
+ speech_output = gr.Checkbox(label="Enable Speech Output", value=False)
44
+ submit_btn = gr.Button("Translate")
45
 
46
  with gr.Column():
47
+ result_output = gr.Textbox(label="Translation Result")
48
+ audio_output = gr.Audio(label="Speech Output", type="filepath")
 
49
 
50
+ submit_btn.click(
51
  translate_text,
52
+ inputs=[text_input, target_lang, speech_output],
53
+ outputs=[result_output, audio_output]
54
  )
55
 
56
+ # Run the app
57
  if __name__ == "__main__":
58
+ demo.launch()