mgbam commited on
Commit
c2616df
·
verified ·
1 Parent(s): a1eecf7

Update translation_models.py

Browse files
Files changed (1) hide show
  1. translation_models.py +25 -15
translation_models.py CHANGED
@@ -10,6 +10,9 @@ Dependency Handling:
10
  - If the import fails, a WARNING is logged once, and translation/detection
11
  functions will return None without further error messages about the missing library.
12
  - Ensure 'deep-translator' is installed in the correct Python environment.
 
 
 
13
  """
14
 
15
  import logging
@@ -27,25 +30,29 @@ TRANSLATE_WARN_LENGTH = 4800 # Warn if text exceeds this length
27
  # --- Dependency Import and Check ---
28
  DEEP_TRANSLATOR_AVAILABLE = False
29
  GoogleTranslator = None
30
- TranslationNotFound: Type[Exception] = Exception # Default to base Exception
 
31
  NotValidPayload: Type[Exception] = Exception
32
  NotValidLength: Type[Exception] = Exception
33
  RequestError: Type[Exception] = Exception
34
  TooManyRequests: Type[Exception] = Exception
 
 
35
  BadSourceLanguage: Type[Exception] = Exception
36
  BadTargetLanguage: Type[Exception] = Exception
37
 
 
38
  try:
39
  # Attempt to import the necessary components
40
  from deep_translator import GoogleTranslator as _GoogleTranslator
 
41
  from deep_translator.exceptions import (
42
  TranslationNotFound as _TranslationNotFound,
43
  NotValidPayload as _NotValidPayload,
44
  NotValidLength as _NotValidLength,
45
  RequestError as _RequestError,
46
- TooManyRequests as _TooManyRequests,
47
- BadSourceLanguage as _BadSourceLanguage,
48
- BadTargetLanguage as _BadTargetLanguage
49
  )
50
 
51
  # If import successful, assign to module-level variables and set flag
@@ -55,19 +62,19 @@ try:
55
  NotValidLength = _NotValidLength
56
  RequestError = _RequestError
57
  TooManyRequests = _TooManyRequests
58
- BadSourceLanguage = _BadSourceLanguage
59
- BadTargetLanguage = _BadTargetLanguage
60
  DEEP_TRANSLATOR_AVAILABLE = True
61
- logger.info("Successfully imported 'deep-translator'. Translation features enabled.")
62
 
 
 
63
  except ImportError as import_error:
64
  # Log the specific import error once when the module is loaded
65
  logger.warning(
66
- f"Could not import 'deep-translator' library. Translation features will be disabled. "
67
  f"Ensure it is installed in the correct environment. Error details: {import_error}"
68
  )
69
  # DEEP_TRANSLATOR_AVAILABLE remains False
70
- # Exception types remain the base Exception class for graceful failure in except blocks below
71
 
72
  except Exception as general_error:
73
  # Catch other potential issues during import setup
@@ -78,6 +85,7 @@ except Exception as general_error:
78
  )
79
  # DEEP_TRANSLATOR_AVAILABLE remains False
80
 
 
81
  # --- Language Configuration ---
82
  # (Using user-friendly names as keys for easier UI integration)
83
  LANGUAGE_CODES: Dict[str, str] = {
@@ -225,7 +233,7 @@ def translate(
225
  # This can happen, e.g., if translating empty strings after HTML stripping by the lib
226
  logger.warning("Translation API returned None. Input may have become empty after processing.")
227
  # Return original text if input was non-empty, otherwise empty string is fine
228
- return text if text.strip() else ""
229
  if not isinstance(translated_text, str):
230
  logger.error(f"Translation API returned a non-string result: {type(translated_text)}. Value: {translated_text!r}")
231
  return None # Indicate failure
@@ -247,19 +255,21 @@ def translate(
247
  except NotValidLength as e:
248
  logger.error(f"Text length issue during translation: {e}", exc_info=True)
249
  return None
250
- except (BadSourceLanguage, BadTargetLanguage) as e:
251
- # Should be less common with our code lookups, but possible with 'auto' or new languages
252
- logger.error(f"Invalid source/target language code used for translation API: {e}", exc_info=True)
253
- return None
254
  except (RequestError, TooManyRequests) as e:
255
  logger.error(f"API request error during translation (network issue, quota exceeded, etc.): {e}", exc_info=True)
256
  return None
257
  except Exception as e:
258
- # Catch any other unexpected errors from the library or logic
 
259
  logger.error(f"Unexpected error during translation: {e}", exc_info=True)
260
  return None
261
 
262
  # --- Test Code (for direct execution) ---
 
263
  if __name__ == "__main__":
264
  import sys
265
  # Setup basic logging to console for testing
 
10
  - If the import fails, a WARNING is logged once, and translation/detection
11
  functions will return None without further error messages about the missing library.
12
  - Ensure 'deep-translator' is installed in the correct Python environment.
13
+
14
+ WORKAROUND APPLIED: Removed import/handling of BadSourceLanguage/BadTargetLanguage
15
+ due to persistent ImportError on the platform, even when the library version seems correct.
16
  """
17
 
18
  import logging
 
30
  # --- Dependency Import and Check ---
31
  DEEP_TRANSLATOR_AVAILABLE = False
32
  GoogleTranslator = None
33
+ # Define base types first
34
+ TranslationNotFound: Type[Exception] = Exception
35
  NotValidPayload: Type[Exception] = Exception
36
  NotValidLength: Type[Exception] = Exception
37
  RequestError: Type[Exception] = Exception
38
  TooManyRequests: Type[Exception] = Exception
39
+ # WORKAROUND: Initialize BadSourceLanguage/BadTargetLanguage to base Exception
40
+ # as we won't import/catch them specifically due to the persistent ImportError.
41
  BadSourceLanguage: Type[Exception] = Exception
42
  BadTargetLanguage: Type[Exception] = Exception
43
 
44
+
45
  try:
46
  # Attempt to import the necessary components
47
  from deep_translator import GoogleTranslator as _GoogleTranslator
48
+ # WORKAROUND: Import only the exceptions known NOT to cause the ImportError
49
  from deep_translator.exceptions import (
50
  TranslationNotFound as _TranslationNotFound,
51
  NotValidPayload as _NotValidPayload,
52
  NotValidLength as _NotValidLength,
53
  RequestError as _RequestError,
54
+ TooManyRequests as _TooManyRequests
55
+ # EXCLUDED: BadSourceLanguage, BadTargetLanguage
 
56
  )
57
 
58
  # If import successful, assign to module-level variables and set flag
 
62
  NotValidLength = _NotValidLength
63
  RequestError = _RequestError
64
  TooManyRequests = _TooManyRequests
65
+ # BadSourceLanguage/BadTargetLanguage remain as base Exception type
 
66
  DEEP_TRANSLATOR_AVAILABLE = True
67
+ logger.info("Successfully imported 'deep-translator' (with workaround for language exceptions). Translation features enabled.")
68
 
69
+ # NOTE: The ImportError below should NO LONGER be triggered by BadSourceLanguage,
70
+ # but we keep it for general import failures of deep_translator itself.
71
  except ImportError as import_error:
72
  # Log the specific import error once when the module is loaded
73
  logger.warning(
74
+ f"Could not import 'deep-translator' library components. Translation features will be disabled. "
75
  f"Ensure it is installed in the correct environment. Error details: {import_error}"
76
  )
77
  # DEEP_TRANSLATOR_AVAILABLE remains False
 
78
 
79
  except Exception as general_error:
80
  # Catch other potential issues during import setup
 
85
  )
86
  # DEEP_TRANSLATOR_AVAILABLE remains False
87
 
88
+
89
  # --- Language Configuration ---
90
  # (Using user-friendly names as keys for easier UI integration)
91
  LANGUAGE_CODES: Dict[str, str] = {
 
233
  # This can happen, e.g., if translating empty strings after HTML stripping by the lib
234
  logger.warning("Translation API returned None. Input may have become empty after processing.")
235
  # Return original text if input was non-empty, otherwise empty string is fine
236
+ return text if text.strip() else "" # Return original text if API gives None for non-empty input
237
  if not isinstance(translated_text, str):
238
  logger.error(f"Translation API returned a non-string result: {type(translated_text)}. Value: {translated_text!r}")
239
  return None # Indicate failure
 
255
  except NotValidLength as e:
256
  logger.error(f"Text length issue during translation: {e}", exc_info=True)
257
  return None
258
+ # WORKAROUND: Removed specific catch for BadSourceLanguage/BadTargetLanguage
259
+ # except (BadSourceLanguage, BadTargetLanguage) as e:
260
+ # logger.error(f"Invalid source/target language code used for translation API: {e}", exc_info=True)
261
+ # return None
262
  except (RequestError, TooManyRequests) as e:
263
  logger.error(f"API request error during translation (network issue, quota exceeded, etc.): {e}", exc_info=True)
264
  return None
265
  except Exception as e:
266
+ # Catch any other unexpected errors from the library or logic, including potentially
267
+ # the underlying errors that BadSource/TargetLanguage would have represented.
268
  logger.error(f"Unexpected error during translation: {e}", exc_info=True)
269
  return None
270
 
271
  # --- Test Code (for direct execution) ---
272
+ # (Self-test remains the same)
273
  if __name__ == "__main__":
274
  import sys
275
  # Setup basic logging to console for testing