Krishna086 commited on
Commit
da34b5e
·
verified ·
1 Parent(s): 5085eea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -111
app.py CHANGED
@@ -1,131 +1,75 @@
1
  import streamlit as st
2
- import os
3
  import importlib
 
4
 
5
- # Set page config as the absolute first Streamlit command
6
- st.set_page_config(page_title="Multilingual Translator", page_icon="🌐", layout="centered")
7
 
8
- # Main app function
9
  def main():
10
- # Lazy import modules to avoid Streamlit initialization during import
11
  translation = importlib.import_module("translation")
12
  lang_detect = importlib.import_module("lang_detect")
13
  audio_processor = importlib.import_module("audio_processor")
14
 
15
- # Title and header with styling
16
  st.markdown("<h1 style='text-align: center; color: #2E86C1;'>Multilingual Translator</h1>", unsafe_allow_html=True)
17
- st.markdown("<p style='text-align: center; color: #666;'>Translate text or audio for multilingual support.</p>", unsafe_allow_html=True)
18
 
19
- # Tabs for input methods
20
- tab1, tab2, tab3 = st.tabs(["Text Input", "Audio Input", "Document Upload"])
 
 
 
 
 
 
 
21
 
22
- # Initialize session state for results
23
- if 'translated_text' not in st.session_state:
24
- st.session_state.translated_text = None
25
- st.session_state.audio_path = None
26
- st.session_state.source_lang = None
27
- st.session_state.detected_options = []
28
 
29
- with tab1:
30
- # Text input
31
- user_text = st.text_area("Enter Text", placeholder="Type or paste your text here...", height=150, key="text_input").strip()
32
  if user_text:
33
- handle_input(user_text, "text", translation, lang_detect, audio_processor)
34
-
35
- with tab2:
36
- # Audio input
37
- audio_file = st.file_uploader("Upload Audio (MP3/WAV)", type=["mp3", "wav"], key="audio_input")
38
- if audio_file:
39
- user_text = audio_processor.transcribe_audio(audio_file).strip()
40
- st.write(f"Transcribed Text: {user_text}")
41
- handle_input(user_text, "audio", translation, lang_detect, audio_processor)
42
-
43
- with tab3:
44
- # Document input
45
- doc_file = st.file_uploader("Upload Document (TXT)", type=["txt"], key="doc_input")
46
- if doc_file:
47
- user_text = doc_file.read().decode("utf-8").strip() # Explicit decoding and stripping
48
- st.write(f"Raw Document Text: {user_text}") # Debug raw input
49
- handle_input(user_text, "doc", translation, lang_detect, audio_processor)
50
-
51
- # Handle input processing
52
- def handle_input(text, input_type, translation, lang_detect, audio_processor):
53
- # Auto-detect source language with options
54
- if len(text) < 10: # Minimum length for reliable detection
55
- detected_options = [("English", 1.0, "English")]
56
- else:
57
- detected_options = lang_detect.detect_language(text)
58
- st.session_state.detected_options = detected_options
59
-
60
- # Set initial source language to the top detected option
61
- st.session_state.source_lang = detected_options[0][0] if detected_options else "English"
62
-
63
- # Display native language names for detected options
64
- native_lang_map = {
65
- "English": "English",
66
- "French": "Français",
67
- "Spanish": "Español",
68
- "German": "Deutsch",
69
- "Hindi": "हिन्दी",
70
- "Chinese": "中文",
71
- "Arabic": "العربية",
72
- "Russian": "Русский",
73
- "Japanese": "日本語",
74
- }
75
- display_options = ["Auto"] + [f"{native_lang_map.get(lang, lang)} ({conf:.2f})" for lang, conf, _ in detected_options] + list(translation.LANGUAGES.keys())
76
- override_lang = st.selectbox("Override Detected Language", display_options, index=0, key=f"override_lang_{input_type}")
77
-
78
- # Map override selection to supported language
79
- if override_lang != "Auto":
80
- selected_lang = next((lang for lang, _, _ in detected_options if native_lang_map.get(lang, lang) in override_lang), override_lang)
81
- st.session_state.source_lang = selected_lang
82
-
83
- st.info(f"Selected Source Language: {native_lang_map.get(st.session_state.source_lang, st.session_state.source_lang)}")
84
-
85
- # Target language selection with native names
86
- target_options = {lang: native_lang_map.get(lang, lang) for lang in translation.LANGUAGES}
87
- target_lang = st.selectbox("Target Language", [target_options[lang] for lang in translation.LANGUAGES],
88
- index=list(translation.LANGUAGES.keys()).index("Hindi") if "Hindi" in translation.LANGUAGES else 1,
89
- key=f"target_lang_{input_type}", format_func=lambda x: x)
90
- target_lang = next(key for key, value in target_options.items() if value == target_lang)
91
-
92
- # Translate button
93
- if st.button("Translate", key=f"translate_button_{input_type}"):
94
- with st.spinner("Translating..."):
95
- try:
96
- # Translate the text
97
- st.session_state.translated_text = translation.translate(text, st.session_state.source_lang, target_lang)
98
- st.write(f"Translated Text (Debug): {st.session_state.translated_text}") # Debug output
99
- # Display results in a styled container
100
- st.markdown("<h3 style='color: #2E86C1;'>Translation Result</h3>", unsafe_allow_html=True)
101
-
102
- # Output options: Text and Audio
103
- output_option = st.radio("Output Format", ["Text", "Audio"], key=f"output_option_{input_type}")
104
-
105
  if output_option == "Text":
106
- st.success("Translated Text:")
107
  st.write(st.session_state.translated_text)
108
-
109
- elif output_option == "Audio":
110
- st.success("Translated Audio:")
111
- st.session_state.audio_path = audio_processor.text_to_speech(st.session_state.translated_text, target_lang)
112
- if st.session_state.audio_path:
113
- st.audio(st.session_state.audio_path)
114
  else:
115
- st.error("Failed to generate audio. Please check the target language or server permissions.")
116
-
117
- # Show footer after translation
118
- st.markdown("""
119
- <p style='font-size: small; color: grey; text-align: center; margin-top: 20px;'>
120
- Developed By: Krishna Prakash
121
- <a href='https://www.linkedin.com/in/krishnaprakash-profile/' target='_blank'>
122
- <img src='https://img.icons8.com/ios-filled/30/0077b5/linkedin.png' alt='LinkedIn' style='vertical-align: middle; margin: 0 5px;'/>
123
- </a>
124
- </p>
125
- """, unsafe_allow_html=True)
126
- except Exception as e:
127
- st.error(f"Translation failed: {str(e)}")
128
 
129
- # Run the app
130
  if __name__ == "__main__":
131
  main()
 
1
  import streamlit as st
 
2
  import importlib
3
+ from io import BytesIO
4
 
5
+ st.set_page_config(page_title="Multilingual Translator", page_icon="🌐", layout="wide")
 
6
 
 
7
  def main():
 
8
  translation = importlib.import_module("translation")
9
  lang_detect = importlib.import_module("lang_detect")
10
  audio_processor = importlib.import_module("audio_processor")
11
 
 
12
  st.markdown("<h1 style='text-align: center; color: #2E86C1;'>Multilingual Translator</h1>", unsafe_allow_html=True)
13
+ st.markdown("<p style='text-align: center; color: #666;'>Translate text like Google Translate</p>", unsafe_allow_html=True)
14
 
15
+ # Single-page layout
16
+ col1, col2 = st.columns([1, 1])
17
+ with col1:
18
+ input_type = st.radio("Input Method", ["Text", "File Upload"], horizontal=True)
19
+ if input_type == "Text":
20
+ user_text = st.text_area("Enter Text", height=200, key="text_input").strip()
21
+ else:
22
+ doc_file = st.file_uploader("Upload TXT File", type=["txt"], key="doc_input")
23
+ user_text = doc_file.read().decode("utf-8").strip() if doc_file else ""
24
 
25
+ st.write(f"Raw Input: {user_text}") # Debug
 
 
 
 
 
26
 
27
+ with col2:
 
 
28
  if user_text:
29
+ detected_options = lang_detect.detect_language(user_text) if len(user_text) >= 10 else [("English", 1.0, "English")]
30
+ source_lang = detected_options[0][0] if detected_options else "English"
31
+
32
+ native_lang_map = {
33
+ "English": "English", "French": "Français", "Spanish": "Español",
34
+ "German": "Deutsch", "Hindi": "हिन्दी", "Chinese": "中文",
35
+ "Arabic": "العربية", "Russian": "Русский", "Japanese": "日本語"
36
+ }
37
+ display_options = ["Auto"] + [f"{native_lang_map.get(lang, lang)} ({conf:.2f})" for lang, conf, _ in detected_options] + list(translation.LANGUAGES.keys())
38
+ source_lang = st.selectbox("Source Language", display_options, index=0, key="source_lang").replace("Auto", source_lang)
39
+
40
+ target_lang = st.selectbox("Target Language", [native_lang_map[lang] for lang in translation.LANGUAGES],
41
+ index=list(translation.LANGUAGES.keys()).index("Hindi") if "Hindi" in translation.LANGUAGES else 0,
42
+ key="target_lang", format_func=lambda x: x)
43
+ target_lang = next(key for key, value in native_lang_map.items() if value == target_lang)
44
+
45
+ if st.button("Translate", key="translate_btn"):
46
+ try:
47
+ translated_text = translation.translate(user_text, source_lang, target_lang)
48
+ st.session_state.translated_text = translated_text
49
+ st.write(f"Translated Text (Debug): {translated_text}")
50
+ except Exception as e:
51
+ st.error(f"Translation failed: {str(e)}. Using fallback text.")
52
+ st.session_state.translated_text = f"Translation not supported for {source_lang} to {target_lang}. Input: {user_text}"
53
+
54
+ output_option = st.radio("Output", ["Text", "Audio"], horizontal=True, key="output_option")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  if output_option == "Text":
56
+ st.success("Result:")
57
  st.write(st.session_state.translated_text)
58
+ else:
59
+ audio_path = audio_processor.text_to_speech(st.session_state.translated_text, target_lang)
60
+ if audio_path:
61
+ st.audio(audio_path, format="audio/mp3")
 
 
62
  else:
63
+ st.error("Audio generation failed. Try a supported language like English or French.")
64
+
65
+ st.markdown("""
66
+ <p style='font-size: small; color: grey; text-align: center; margin-top: 20px;'>
67
+ Developed By: Krishna Prakash
68
+ <a href='https://www.linkedin.com/in/krishnaprakash-profile/' target='_blank'>
69
+ <img src='https://img.icons8.com/ios-filled/30/0077b5/linkedin.png' alt='LinkedIn' style='vertical-align: middle; margin: 0 5px;'/>
70
+ </a>
71
+ </p>
72
+ """, unsafe_allow_html=True)
 
 
 
73
 
 
74
  if __name__ == "__main__":
75
  main()