Krishna086 commited on
Commit
1549aa1
·
verified ·
1 Parent(s): a6fc19e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -77
app.py CHANGED
@@ -11,98 +11,97 @@ def main():
11
  audio_processor = importlib.import_module("audio_processor")
12
 
13
  # Header
14
- st.markdown("<h1 style='text-align: center; color: #2E86C1;'>Multilingual Translator</h1>", unsafe_allow_html=True)
15
  st.markdown("<p style='text-align: center; color: #666;'>Translate text like Google Translate</p>", unsafe_allow_html=True)
16
 
17
  # Language Controls
18
- col_lang, col_target = st.columns([1, 1])
19
- with col_lang:
20
  detected_options = lang_detect.detect_language(st.session_state.get("user_text", "")) if st.session_state.get("user_text", "").strip() and len(st.session_state.get("user_text", "").strip()) >= 10 else [("English", 1.0, "English")]
21
  source_lang = detected_options[0][0] if detected_options else "English"
22
  native_lang_map = {
23
- "English": "English", "French": "Français", "Spanish": "Español",
24
- "German": "Deutsch", "Hindi": "हिन्दी", "Chinese": "中文",
25
- "Arabic": "العربية", "Russian": "Русский", "Japanese": "日本語"
26
  }
27
- source_lang_display = st.selectbox("Source Language (Auto-Detected)", [native_lang_map.get(source_lang, source_lang)] + list(native_lang_map.values()), index=0, key="source_lang", label_visibility="collapsed", help="Auto-detected language, override if needed")
28
- with col_target:
29
- target_options = list(native_lang_map.values())
30
- target_lang_display = st.selectbox("Target Language", target_options, index=target_options.index("हिन्दी") if "हिन्दी" in target_options else 0, key="target_lang", label_visibility="collapsed")
31
- target_lang = next((k for k, v in native_lang_map.items() if v == target_lang_display), "Hindi")
 
32
 
33
  # Input Section
34
- col_input, col_output = st.columns([1, 1])
 
 
35
  with col_input:
36
- st.markdown("<div style='margin-bottom: 10px;'></div>", unsafe_allow_html=True)
37
- input_type = st.radio("Input", ["Text", "File Upload"], horizontal=True, label_visibility="collapsed", key="input_type")
38
- user_text = st.text_area("Enter or paste text", height=200, key="user_text").strip() if input_type == "Text" else ""
39
- if input_type == "File Upload":
40
- doc_file = st.file_uploader("Upload File", type=["txt", "docx", "pdf"], key="doc_input", accept_multiple_files=False, label_visibility="collapsed", help="Drag and drop or browse files")
41
- user_text = doc_file.read().decode("utf-8").strip() if doc_file else st.session_state.get("user_text", "")
42
- char_count = len(user_text)
43
- st.markdown(f"<small style='color: grey;'>Characters: {char_count}/1000</small>", unsafe_allow_html=True)
44
-
45
- if user_text and (st.session_state.get("last_text", "") != user_text or st.button("Translate", key="translate_btn")):
46
- st.session_state.last_text = user_text
47
- spinner = st.empty()
48
- spinner.info("Translating...")
49
- start_time = time.time()
50
- try:
51
- # Use English as buffer for translation with validation
52
- if source_lang != "English" and target_lang != "English":
53
- temp_translation = translation.translate(user_text, source_lang, "English")
54
- if not temp_translation or len(temp_translation.split()) < 2: # Validate intermediate result
55
- raise ValueError("Intermediate translation failed")
56
- translated_text = translation.translate(temp_translation, "English", target_lang)
57
- else:
58
- translated_text = translation.translate(user_text, source_lang, target_lang)
59
- if not translated_text or len(translated_text.split()) < 2: # Validate final result
60
- raise ValueError("Final translation failed")
61
- st.session_state.translated_text = translated_text
62
- st.session_state.translation_time = time.time() - start_time
63
- except Exception as e:
64
- st.session_state.translated_text = user_text
65
- st.session_state.translation_time = time.time() - start_time
66
- st.warning(f"Translation issue: {str(e)}. Using input as fallback.")
67
- finally:
68
- spinner.empty()
69
 
70
  # Output Section
 
71
  with col_output:
72
- st.markdown("<div style='margin-bottom: 10px;'></div>", unsafe_allow_html=True)
73
  if "translated_text" in st.session_state and st.session_state.translated_text:
74
- line_count = max(len(st.session_state.translated_text.splitlines()), len(user_text.splitlines()))
75
- output_height = max(200, line_count * 20 + 50)
76
- st.text_area("Translation:", value=st.session_state.translated_text, height=output_height, key="output_area")
77
- st.write(f"Translation time: {st.session_state.translation_time:.2f} seconds")
78
- col_copy, col_audio = st.columns([0.5, 0.5])
79
- with col_copy:
80
- if st.button("📋", key="copy_btn", help="Copy to clipboard"):
81
- st.clipboard(st.session_state.translated_text)
82
- st.success("Copied to clipboard!")
83
- with col_audio:
84
- output_option = st.radio("Output", ["Text", "Audio"], horizontal=True, label_visibility="collapsed", key="output_option")
85
- if output_option == "Audio" and "translated_text" in st.session_state:
86
- audio = audio_processor.text_to_speech(st.session_state.translated_text, target_lang)
87
- if audio and audio.getbuffer().nbytes > 0:
88
- st.audio(audio, format="audio/mp3", start_time=0)
89
- st.success("Audio playing.")
90
- else:
91
- audio_fallback = audio_processor.text_to_speech(st.session_state.translated_text, "English")
92
- if audio_fallback and audio_fallback.getbuffer().nbytes > 0:
93
- st.audio(audio_fallback, format="audio/mp3", start_time=0)
94
- st.success("Fallback audio in English playing.")
95
- else:
96
- st.error("Audio generation failed. Try again later.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
- # Footer
99
- st.markdown("""
100
- <p style='font-size: small; color: grey; text-align: center; margin-top: 20px;'>
101
- Developed by: Krishna Prakash <a href='https://www.linkedin.com/in/krishnaprakash-profile/' target='_blank'>
102
- <img src='https://img.icons8.com/ios-filled/30/0077b5/linkedin.png' alt='LinkedIn' style='vertical-align: middle; margin: 0 5px;'/>
103
- </a>
104
- </p>
105
- """, unsafe_allow_html=True)
 
 
 
 
 
 
106
 
107
  if __name__ == "__main__":
108
  main()
 
11
  audio_processor = importlib.import_module("audio_processor")
12
 
13
  # Header
14
+ st.markdown("<h1 style='text-align: center; color: #4285F4;'>Multilingual Translator</h1>", unsafe_allow_html=True)
15
  st.markdown("<p style='text-align: center; color: #666;'>Translate text like Google Translate</p>", unsafe_allow_html=True)
16
 
17
  # Language Controls
18
+ col1, col2 = st.columns([1, 1])
19
+ with col1:
20
  detected_options = lang_detect.detect_language(st.session_state.get("user_text", "")) if st.session_state.get("user_text", "").strip() and len(st.session_state.get("user_text", "").strip()) >= 10 else [("English", 1.0, "English")]
21
  source_lang = detected_options[0][0] if detected_options else "English"
22
  native_lang_map = {
23
+ "en": ("English", "English"), "fr": ("Français", "French"), "es": ("Español", "Spanish"),
24
+ "de": ("Deutsch", "German"), "hi": ("हिन्दी", "Hindi"), "zh": ("中文", "Chinese"),
25
+ "ar": ("العربية", "Arabic"), "ru": ("Русский", "Russian"), "ja": ("日本語", "Japanese")
26
  }
27
+ source_lang_code = next((k for k, v in LANGUAGES.items() if v[1] == source_lang), "en")
28
+ source_lang_display = st.selectbox("Source Language", [native_lang_map[source_lang_code][0]] + [v[0] for v in native_lang_map.values()], index=0, key="source_lang", help="Auto-detected, override if needed")
29
+ source_lang = next((k for k, v in native_lang_map.items() if v[0] == source_lang_display), "en")
30
+ with col2:
31
+ target_lang_display = st.selectbox("Target Language", [v[0] for v in native_lang_map.values()], index=list(native_lang_map.values()).index(native_lang_map["hi"]), key="target_lang")
32
+ target_lang = next((k for k, v in native_lang_map.items() if v[0] == target_lang_display), "hi")
33
 
34
  # Input Section
35
+ if "user_text" not in st.session_state:
36
+ st.session_state.user_text = ""
37
+ col_input = st.container()
38
  with col_input:
39
+ input_type = st.radio("Input", ["Text", "File Upload"], horizontal=True, label_visibility="collapsed")
40
+ if input_type == "Text":
41
+ user_text = st.text_area("", height=200, key="user_text", on_change=trigger_translation, args=(translation, lang_detect, audio_processor,))
42
+ else:
43
+ user_text = st.file_uploader("Drag and drop or upload file", type=["txt", "docx", "pdf"], key="doc_input", on_change=trigger_translation, args=(translation, lang_detect, audio_processor,))
44
+ if user_text:
45
+ st.session_state.user_text = user_text.read().decode("utf-8").strip()
46
+ st.markdown(f"<small style='color: grey;'>Characters: {len(st.session_state.user_text)}/1000</small>", unsafe_allow_html=True)
47
+ st.button("Translate", key="translate_btn", on_click=trigger_translation, args=(translation, lang_detect, audio_processor,))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  # Output Section
50
+ col_output = st.container()
51
  with col_output:
 
52
  if "translated_text" in st.session_state and st.session_state.translated_text:
53
+ st.text_area("", value=st.session_state.translated_text, height=200, key="output_area", disabled=True)
54
+ col_c, col_a = st.columns([1, 1])
55
+ with col_c:
56
+ st.button("📋", key="copy_btn", on_click=copy_to_clipboard, help="Copy translation")
57
+ with col_a:
58
+ if st.button("🔊", key="audio_btn", on_click=play_audio, args=(audio_processor,)):
59
+ pass # Handled by play_audio function
60
+
61
+ def trigger_translation(translation, lang_detect, audio_processor):
62
+ user_text = st.session_state.user_text.strip()
63
+ if user_text:
64
+ spinner = st.empty()
65
+ spinner.info("Translating...")
66
+ start_time = time.time()
67
+ try:
68
+ source_lang = next((k for k, v in LANGUAGES.items() if v[0] == st.session_state.source_lang), "en")
69
+ target_lang = next((k for k, v in LANGUAGES.items() if v[0] == st.session_state.target_lang), "hi")
70
+ if source_lang != "en" and target_lang != "en":
71
+ temp_translation = translation.translate(user_text, source_lang, "en")
72
+ if not temp_translation or len(temp_translation.split()) < 2:
73
+ raise ValueError("Intermediate translation invalid")
74
+ translated_text = translation.translate(temp_translation, "en", target_lang)
75
+ else:
76
+ translated_text = translation.translate(user_text, source_lang, target_lang)
77
+ if not translated_text or len(translated_text.split()) < 2:
78
+ raise ValueError("Final translation invalid")
79
+ st.session_state.translated_text = translated_text
80
+ except Exception as e:
81
+ st.session_state.translated_text = user_text
82
+ st.warning(f"Translation issue: {str(e)}. Using input as fallback.")
83
+ finally:
84
+ spinner.empty()
85
+ st.session_state.translation_time = time.time() - start_time
86
+
87
+ def copy_to_clipboard():
88
+ st.clipboard(st.session_state.translated_text)
89
+ st.success("Copied to clipboard!")
90
 
91
+ def play_audio(audio_processor):
92
+ if "translated_text" in st.session_state and st.session_state.translated_text:
93
+ target_lang = next((k for k, v in LANGUAGES.items() if v[0] == st.session_state.target_lang), "hi")
94
+ audio = audio_processor.text_to_speech(st.session_state.translated_text, target_lang)
95
+ if audio and audio.getbuffer().nbytes > 0:
96
+ st.audio(audio, format="audio/mp3", start_time=0)
97
+ st.success("Audio playing.")
98
+ else:
99
+ audio_fallback = audio_processor.text_to_speech(st.session_state.translated_text, "en")
100
+ if audio_fallback and audio_fallback.getbuffer().nbytes > 0:
101
+ st.audio(audio_fallback, format="audio/mp3", start_time=0)
102
+ st.success("Fallback audio in English playing.")
103
+ else:
104
+ st.error("Audio generation failed. Try again later.")
105
 
106
  if __name__ == "__main__":
107
  main()