Hassan501 commited on
Commit
28fbb52
·
verified ·
1 Parent(s): 678f7b1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -0
app.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from deep_translator import GoogleTranslator
3
+ import time # For optional progress bar
4
+
5
+ # --- Configuration and Setup ---
6
+
7
+ # Get the dictionary of supported languages for the translator: {'language_name': 'language_code'}
8
+ # We use st.cache_data to run this function only once and speed up the app
9
+ @st.cache_data
10
+ def get_supported_languages():
11
+ """Fetches and returns the dictionary of supported languages from GoogleTranslator."""
12
+ try:
13
+ # Use an instance of GoogleTranslator to get supported languages as a dictionary
14
+ translator = GoogleTranslator()
15
+ return translator.get_supported_languages(as_dict=True)
16
+ except Exception as e:
17
+ st.error(f"Error fetching languages: {e}. Please check your internet connection or library installation.")
18
+ return {}
19
+
20
+ # The main translation function, also cached for performance
21
+ @st.cache_data
22
+ def translate_text(text, target_lang_code):
23
+ """Translates the given text to the target language code."""
24
+ if not text.strip():
25
+ return "Please enter text to translate."
26
+ try:
27
+ # Source language is 'auto' (automatic detection)
28
+ # Using a context manager for the translator is efficient
29
+ with GoogleTranslator(source='auto', target=target_lang_code) as translator:
30
+ translated_text = translator.translate(text)
31
+ return translated_text
32
+ except Exception as e:
33
+ # Catch network or API-related errors
34
+ return f"Translation Error: {e}"
35
+
36
+ def main():
37
+ # Set Streamlit page configuration
38
+ st.set_page_config(
39
+ page_title="Multilingual Translator App",
40
+ page_icon="🌍",
41
+ layout="wide"
42
+ )
43
+
44
+ st.title("🌍 Simple Multilingual Translator")
45
+ st.markdown("Translate text using the **Google Translate** backend via `deep-translator`.")
46
+ st.markdown("---")
47
+
48
+ # Get the supported languages map
49
+ lang_map = get_supported_languages()
50
+ # Invert the map for easier lookup when user selects a language name
51
+ # We only want the names for the dropdown
52
+ language_names = sorted(lang_map.keys())
53
+
54
+ if not language_names:
55
+ st.error("Cannot load languages. Please check the `requirements.txt` and ensure `deep-translator` is installed correctly.")
56
+ return
57
+
58
+ # --- UI Components ---
59
+ col1, col2 = st.columns([3, 2])
60
+
61
+ with col1:
62
+ st.subheader("Text to Translate")
63
+ # Text input area
64
+ input_text = st.text_area(
65
+ "Enter text here...",
66
+ height=200,
67
+ key="input_text"
68
+ )
69
+
70
+ with col2:
71
+ st.subheader("Translation Options")
72
+ # Language selection dropdown (Target language)
73
+ target_lang_name = st.selectbox(
74
+ "Select Target Language",
75
+ language_names,
76
+ index=language_names.index('English'), # Default to English
77
+ key="target_lang_name"
78
+ )
79
+ # Get the language code from the selected name
80
+ target_lang_code = lang_map.get(target_lang_name)
81
+
82
+ # Translation button
83
+ if st.button("Translate", use_container_width=True, type="primary"):
84
+ if not input_text.strip():
85
+ st.warning("Please enter some text to translate.")
86
+ else:
87
+ # Add a spinner/progress bar for better UX
88
+ with st.spinner(f'Translating to **{target_lang_name}**...'):
89
+ # Call the cached translation function
90
+ translated_output = translate_text(input_text, target_lang_code)
91
+
92
+ # Store the result in session state to persist it after the button click
93
+ st.session_state['translated_text'] = translated_output
94
+ st.session_state['target_language'] = target_lang_name
95
+
96
+ # Display results outside the button block to show the stored result
97
+ st.markdown("---")
98
+ st.subheader(f"Translated Text (to: {st.session_state.get('target_language', 'Select Language')})")
99
+
100
+ # Display the translated text
101
+ st.success(st.session_state.get('translated_text', 'Translation will appear here.'))
102
+
103
+
104
+ if __name__ == "__main__":
105
+ # Initialize session state for the translated output
106
+ if 'translated_text' not in st.session_state:
107
+ st.session_state['translated_text'] = 'Translation will appear here.'
108
+ if 'target_language' not in st.session_state:
109
+ st.session_state['target_language'] = 'Select Language'
110
+
111
+ main()