Add error handling to translation functions
Added try-except blocks to both DeepSeek and Google translation functions to handle API errors gracefully and return an empty string on failure. Also added a check for the AI_API_KEY environment variable and improved cache update logic in translate_po_file.
This commit is contained in:
+14
-1
@@ -58,10 +58,15 @@ def contains_target_language_characters(text, target_lang):
|
||||
return False
|
||||
|
||||
def translate_text_deepseek(text, target_lang):
|
||||
api_key = os.getenv("AI_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("AI_API_KEY environment variable is not set.")
|
||||
|
||||
client = OpenAI(
|
||||
api_key=os.getenv("AI_API_KEY"),
|
||||
api_key=api_key,
|
||||
base_url="https://api.deepseek.com",
|
||||
)
|
||||
try:
|
||||
completion = client.chat.completions.create(
|
||||
model="deepseek-chat",
|
||||
messages=[
|
||||
@@ -74,12 +79,19 @@ def translate_text_deepseek(text, target_lang):
|
||||
for chunk in completion:
|
||||
full_content += chunk.choices[0].delta.content
|
||||
return full_content.capitalize().lower().rstrip('.,!?;:')
|
||||
except Exception as e:
|
||||
print(f"DeepSeek translation failed: {e}")
|
||||
return ""
|
||||
|
||||
def translate_text_google(text, target_lang):
|
||||
try:
|
||||
translator = Translator(service_urls=['translate.google.com'])
|
||||
translation = translator.translate(text, src='auto', dest=target_lang)
|
||||
translated_text = translation.text
|
||||
return translated_text.capitalize().lower().rstrip('.,!?;:')
|
||||
except Exception as e:
|
||||
print(f"Google Translate failed: {e}")
|
||||
return ""
|
||||
|
||||
def needs_fallback_translation(translated_text):
|
||||
return '\n' in translated_text or '"' in translated_text
|
||||
@@ -198,6 +210,7 @@ def translate_po_file(input_file, output_file, target_lang_code, target_lang_nam
|
||||
if key not in used_translations:
|
||||
print(f"Removing unused cache entry: {key}")
|
||||
del translations[key]
|
||||
updated = True
|
||||
|
||||
if updated:
|
||||
save_translation_cache(cache_file, translations)
|
||||
|
||||
Reference in New Issue
Block a user