Hassan501 commited on
Commit
d2ef253
·
verified ·
1 Parent(s): cdf4861

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -16
app.py CHANGED
@@ -1,25 +1,25 @@
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."
@@ -47,12 +47,11 @@ def main():
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 ---
@@ -69,13 +68,22 @@ def main():
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
 
@@ -84,27 +92,27 @@ def main():
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
 
 
1
  import streamlit as st
2
  from deep_translator import GoogleTranslator
 
3
 
4
  # --- Configuration and Setup ---
5
 
6
  # Get the dictionary of supported languages for the translator: {'language_name': 'language_code'}
7
+ # Using st.cache_data to run this function only once and speed up the app on refresh
8
  @st.cache_data
9
  def get_supported_languages():
10
  """Fetches and returns the dictionary of supported languages from GoogleTranslator."""
11
  try:
12
  # Use an instance of GoogleTranslator to get supported languages as a dictionary
13
  translator = GoogleTranslator()
14
+ # Returns names like 'english', 'spanish', etc. (all lowercase)
15
  return translator.get_supported_languages(as_dict=True)
16
  except Exception as e:
17
+ st.error(f"Error fetching languages: {e}. Check library and internet connection.")
18
  return {}
19
 
20
  # The main translation function, also cached for performance
21
  @st.cache_data
22
+ def translate_text(text: str, target_lang_code: str):
23
  """Translates the given text to the target language code."""
24
  if not text.strip():
25
  return "Please enter text to translate."
 
47
 
48
  # Get the supported languages map
49
  lang_map = get_supported_languages()
50
+ # Get sorted list of language names (e.g., ['afrikaans', 'albanian', 'english', ...])
 
51
  language_names = sorted(lang_map.keys())
52
 
53
  if not language_names:
54
+ st.error("Cannot load languages. The application cannot proceed.")
55
  return
56
 
57
  # --- UI Components ---
 
68
 
69
  with col2:
70
  st.subheader("Translation Options")
71
+
72
  # Language selection dropdown (Target language)
73
+ # FIX APPLIED: Using 'english' (lowercase) to match the keys returned by deep-translator
74
+ try:
75
+ default_index = language_names.index('english')
76
+ except ValueError:
77
+ # Fallback if 'english' is somehow missing
78
+ default_index = 0
79
+
80
  target_lang_name = st.selectbox(
81
  "Select Target Language",
82
  language_names,
83
+ index=default_index,
84
  key="target_lang_name"
85
  )
86
+
87
  # Get the language code from the selected name
88
  target_lang_code = lang_map.get(target_lang_name)
89
 
 
92
  if not input_text.strip():
93
  st.warning("Please enter some text to translate.")
94
  else:
95
+ # Add a spinner for better UX while waiting for translation
96
+ with st.spinner(f'Translating to **{target_lang_name.capitalize()}**...'):
97
  # Call the cached translation function
98
  translated_output = translate_text(input_text, target_lang_code)
99
 
100
+ # Store the result in session state to persist it
101
  st.session_state['translated_text'] = translated_output
102
+ st.session_state['target_language'] = target_lang_name.capitalize()
103
 
104
+ # Display results outside the button block
105
  st.markdown("---")
106
+ st.subheader(f"Translated Text (Target: {st.session_state.get('target_language', 'Select Language')})")
107
 
108
  # Display the translated text
109
+ st.info(st.session_state.get('translated_text', 'Translation will appear here after clicking "Translate".'))
110
 
111
 
112
  if __name__ == "__main__":
113
  # Initialize session state for the translated output
114
  if 'translated_text' not in st.session_state:
115
+ st.session_state['translated_text'] = 'Translation will appear here after clicking "Translate".'
116
  if 'target_language' not in st.session_state:
117
  st.session_state['target_language'] = 'Select Language'
118