forked from RimSort/RimSort
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslation_helper.py
More file actions
2693 lines (2227 loc) · 96.2 KB
/
translation_helper.py
File metadata and controls
2693 lines (2227 loc) · 96.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Enhanced Translation Helper Script for RimSort
This script helps translators by:
1. Checking translation completeness against source language
2. Validating translation files and fixing common issues
3. Generating translation statistics (with optional JSON output)
4. Running PySide6 translation tools (lupdate, lrelease)
5. Auto-translating unfinished strings using various services (Google, DeepL, OpenAI)
6. Interactive guided mode for new users
Usage:
# Interactive guided mode
python translation_helper.py --interactive
python translation_helper.py -i
# Command-line mode
python translation_helper.py check [language] [--json]
python translation_helper.py stats [--json]
python translation_helper.py validate [language]
python translation_helper.py update-ts [language]
python translation_helper.py compile [language]
python translation_helper.py auto-translate [language] --service [google|deepl|openai] [--api-key YOUR_KEY] [--model MODEL_NAME] [--continue-on-failure]
python translation_helper.py process [language] --service [google|deepl|openai] [--api-key YOUR_KEY] [--model MODEL_NAME] [--continue-on-failure]
Interactive Mode:
- Launch with --interactive or -i flag for a guided menu-driven workflow
- Perfect for new users who want step-by-step guidance
- Includes configuration options and confirmation prompts
Note:
- [language] is optional; if omitted, the command applies to all languages except en_US.
- The check command verifies that all strings are present in the specified language's translation file.
- The validate command checks for common issues like empty translations and obsolete entries and fixes them automatically.
- The stats command generates a summary of translation status across all languages.
- The update-ts command updates the .ts files with new strings from the source language.
- The compile command compiles .ts files into binary format (.qm).
- The auto-translate command uses selected translation services to fill in missing translations. By default, it continues translating even if some translations fail.
- The process command runs update-ts, auto-translate, and compile in sequence for a language. By default, it continues translating even if some translations fail.
- The --json flag on check and stats commands outputs structured JSON for programmatic consumption.
"""
import argparse
import asyncio
import hashlib
import importlib
import json
import re
import shutil
import subprocess
import sys
import time
import types
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, TypedDict, cast
# Global variables for caching and configuration
import aiohttp
import lxml.etree as ET
import requests
# Try to import googletrans library (optional dependency)
try:
from googletrans import Translator as GoogleTranslator # type: ignore
except ImportError:
GoogleTranslator = None
# Try to import openai library (optional dependency)
openai_module: Optional[types.ModuleType]
try:
openai_module = importlib.import_module("openai")
except ImportError:
openai_module = None
@dataclass
class RetryConfig:
"""Configuration for retry mechanisms with exponential backoff.
Controls automatic retry behavior for transient API failures with configurable
delays that increase exponentially with each retry attempt.
Attributes:
max_retries: Maximum number of retry attempts (default: 3)
initial_delay: Starting delay in seconds between retries (default: 1.0)
max_delay: Maximum delay cap in seconds (default: 30.0)
exponential_base: Base for exponential backoff calculation (default: 2.0)
"""
max_retries: int = 3
initial_delay: float = 1.0
max_delay: float = 30.0
exponential_base: float = 2.0
def get_delay(self, attempt: int) -> float:
"""Calculate delay for a given attempt number using exponential backoff.
Formula: initial_delay * (exponential_base ** attempt), capped at max_delay
Args:
attempt: The current attempt number (0-indexed)
Returns:
Delay in seconds to wait before the next retry
"""
# Calculate exponential backoff: each retry waits longer than the previous one
# This prevents overwhelming the API and helps transient errors recover
# Example: initial=1.0, base=2.0 gives: 1s, 2s, 4s, 8s, 16s...
delay = self.initial_delay * (self.exponential_base**attempt)
# Cap at max_delay to prevent unreasonably long wait times
return min(delay, self.max_delay)
@dataclass
class TimeoutConfig:
"""Configuration for request timeouts per service.
Defines timeout values (in seconds) for different translation services.
Helps prevent hanging requests and allows graceful fallback/retry.
Attributes:
default_timeout: Fallback timeout for unspecified services (default: 10.0s)
deepl_timeout: Timeout for DeepL API requests (default: 10.0s)
openai_timeout: Timeout for OpenAI API requests (default: 10.0s)
google_timeout: Timeout for Google Translate requests (default: 10.0s)
"""
default_timeout: float = 10.0
deepl_timeout: float = 10.0
openai_timeout: float = 10.0
google_timeout: float = 10.0
@dataclass
class TranslationConfig:
"""Global configuration for translation operations.
Centralizes all configuration settings for the translation system including
retry behavior, timeouts, and concurrency limits. Allows runtime customization
of translation behavior without code changes.
Attributes:
retry_config: Configuration for retry mechanisms with exponential backoff
timeout_config: Configuration for service-specific request timeouts
max_concurrent_requests: Maximum number of concurrent translation requests (default: 5)
"""
retry_config: RetryConfig = field(default_factory=RetryConfig)
timeout_config: TimeoutConfig = field(default_factory=TimeoutConfig)
max_concurrent_requests: int = 5
@classmethod
def from_dict(cls, config_dict: Dict[str, Any]) -> "TranslationConfig":
"""Create TranslationConfig from a dictionary.
Args:
config_dict: Dictionary with keys 'retry', 'timeout', 'max_concurrent_requests'
Returns:
TranslationConfig instance with settings from the dictionary
"""
retry_config = RetryConfig(**config_dict.get("retry", {}))
timeout_config = TimeoutConfig(**config_dict.get("timeout", {}))
max_concurrent = config_dict.get("max_concurrent_requests", 5)
return cls(retry_config, timeout_config, max_concurrent)
@dataclass
class TranslationCache:
"""In-memory cache for translation results to avoid redundant API calls.
Implements a simple hash-based cache to store successful translations.
Reduces API calls and costs by reusing previously translated strings.
Cache is session-scoped and cleared between runs.
Attributes:
_cache: Internal dictionary storing cached translations
_cache_file: Optional file path for persistent cache (future feature)
"""
_cache: Dict[str, str] = field(default_factory=dict)
_cache_file: Optional[Path] = None
def _get_cache_key(
self, text: str, target_lang: str, source_lang: str, service: str
) -> str:
"""Generate a unique cache key from translation parameters.
Uses SHA256 hash to create a compact, deterministic key from the
text and language/service combination.
Args:
text: The text to translate
target_lang: Target language code
source_lang: Source language code
service: Translation service name
Returns:
SHA256 hex digest as cache key
"""
# Create a unique key by combining all parameters with delimiter
# Using SHA256 ensures: deterministic output, fixed length (64 chars),
# and minimal collision probability for different translations
key_str = f"{text}:{target_lang}:{source_lang}:{service}"
return hashlib.sha256(key_str.encode()).hexdigest()
def get(
self, text: str, target_lang: str, source_lang: str, service: str
) -> Optional[str]:
"""Retrieve a translation from cache if available.
Args:
text: The text to look up
target_lang: Target language code
source_lang: Source language code
service: Translation service name
Returns:
Cached translation if found, None otherwise
"""
key = self._get_cache_key(text, target_lang, source_lang, service)
return self._cache.get(key)
def set(
self,
text: str,
target_lang: str,
source_lang: str,
service: str,
translation: str,
) -> None:
"""Store a translation in cache.
Args:
text: The text that was translated
target_lang: Target language code
source_lang: Source language code
service: Translation service name
translation: The translated text to cache
"""
key = self._get_cache_key(text, target_lang, source_lang, service)
self._cache[key] = translation
def clear(self) -> None:
"""Clear all cached translations."""
self._cache.clear()
def size(self) -> int:
"""Get the number of cached translations.
Returns:
Number of entries in the cache
"""
return len(self._cache)
# Global configuration instance
_translation_config = TranslationConfig()
_translation_cache = TranslationCache()
def get_translation_config() -> TranslationConfig:
"""Get the global translation configuration."""
return _translation_config
def set_translation_config(config: TranslationConfig) -> None:
"""Set the global translation configuration."""
global _translation_config
_translation_config = config
def get_translation_cache() -> TranslationCache:
"""Get the global translation cache."""
return _translation_cache
def clear_translation_cache() -> None:
"""Clear the global translation cache."""
_translation_cache.clear()
# === Input Validation ===
def validate_language_code(language: Optional[str]) -> Optional[str]:
"""Validate and normalize a language code.
Ensures the language code is in the supported list and properly formatted.
Args:
language: Language code to validate (e.g., 'zh_CN'). If None, returns None.
Returns:
Normalized language code if valid, None if language is None
Raises:
ValueError: If language is not in the supported language map
"""
if language is None:
return None
if language not in LANG_MAP:
supported = ", ".join(sorted(LANG_MAP.keys()))
raise ValueError(
f"Unsupported language: {language}\nSupported languages: {supported}"
)
return language
def validate_file_path(file_path: Path) -> Path:
"""Validate that a file path exists and is readable.
Ensures the file is accessible and not a directory.
Args:
file_path: Path to validate
Returns:
The validated path
Raises:
FileNotFoundError: If file does not exist
IsADirectoryError: If path points to a directory
PermissionError: If file is not readable
"""
if not file_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
if file_path.is_dir():
raise IsADirectoryError(f"Path is a directory, not a file: {file_path}")
if not file_path.is_file():
raise ValueError(f"Path is not a regular file: {file_path}")
# Check if file is readable
if not file_path.stat().st_mode & 0o400:
raise PermissionError(f"File is not readable: {file_path}")
return file_path
def validate_directory_path(dir_path: Path) -> Path:
"""Validate that a directory path exists and is accessible.
Ensures the directory exists and is writable (for file operations).
Args:
dir_path: Directory path to validate
Returns:
The validated path
Raises:
FileNotFoundError: If directory does not exist
NotADirectoryError: If path is not a directory
PermissionError: If directory is not writable
"""
if not dir_path.exists():
raise FileNotFoundError(f"Directory not found: {dir_path}")
if not dir_path.is_dir():
raise NotADirectoryError(f"Path is not a directory: {dir_path}")
# Check if directory is writable
if not dir_path.stat().st_mode & 0o200:
raise PermissionError(f"Directory is not writable: {dir_path}")
return dir_path
def validate_api_key(api_key: Optional[str], service: str) -> str:
"""Validate API key for a translation service.
Ensures API key is provided and meets minimum format requirements.
Args:
api_key: The API key to validate
service: Name of the service (for error messages)
Returns:
The validated API key
Raises:
ValueError: If API key is missing or invalid
"""
if not api_key:
raise ValueError(f"{service} requires a valid API key")
if not isinstance(api_key, str):
raise TypeError(f"API key must be a string, got {type(api_key)}")
api_key = api_key.strip()
if len(api_key) < 5:
raise ValueError(f"{service} API key appears invalid (too short)")
return api_key
def validate_model_name(model: Optional[str]) -> str:
"""Validate OpenAI model name.
Ensures model name is provided and properly formatted.
Args:
model: Model name to validate (e.g., 'gpt-3.5-turbo')
Returns:
The validated model name
Raises:
ValueError: If model name is invalid
"""
if model is None:
return "gpt-3.5-turbo" # Default
if not isinstance(model, str):
raise TypeError(f"Model name must be a string, got {type(model)}")
model = model.strip()
if not model:
raise ValueError("Model name cannot be empty")
if not re.match(r"^[a-zA-Z0-9\-_.]+$", model):
raise ValueError(f"Invalid model name format: {model}")
return model
def validate_timeout(timeout: float) -> float:
"""Validate timeout value in seconds.
Ensures timeout is a positive number within reasonable bounds.
Args:
timeout: Timeout in seconds
Returns:
The validated timeout value
Raises:
ValueError: If timeout is invalid
TypeError: If timeout is not a number
"""
if not isinstance(timeout, (int, float)):
raise TypeError(f"Timeout must be a number, got {type(timeout)}")
if timeout <= 0:
raise ValueError(f"Timeout must be positive, got {timeout}")
if timeout > 300:
raise ValueError(f"Timeout is very large ({timeout}s), max recommended is 300s")
return float(timeout)
def validate_retry_count(max_retries: int) -> int:
"""Validate maximum retry count.
Ensures retry count is non-negative and within reasonable bounds.
Args:
max_retries: Maximum number of retries
Returns:
The validated retry count
Raises:
ValueError: If retry count is invalid
TypeError: If retry count is not an integer
"""
if not isinstance(max_retries, int):
raise TypeError(f"Retry count must be an integer, got {type(max_retries)}")
if max_retries < 0:
raise ValueError(f"Retry count cannot be negative, got {max_retries}")
if max_retries > 10:
raise ValueError(
f"Retry count is very high ({max_retries}), max recommended is 10"
)
return max_retries
def validate_concurrent_requests(max_concurrent: int) -> int:
"""Validate maximum concurrent requests setting.
Ensures concurrency is a positive integer within reasonable bounds.
Args:
max_concurrent: Maximum number of concurrent requests
Returns:
The validated concurrency value
Raises:
ValueError: If value is invalid
TypeError: If value is not an integer
"""
if not isinstance(max_concurrent, int):
raise TypeError(
f"Concurrent requests must be an integer, got {type(max_concurrent)}"
)
if max_concurrent <= 0:
raise ValueError(f"Concurrent requests must be positive, got {max_concurrent}")
if max_concurrent > 100:
raise ValueError(
f"Concurrent requests is very high ({max_concurrent}), max recommended is 100"
)
return max_concurrent
class LangMapEntry(TypedDict, total=False):
google: Optional[str]
deepl: Optional[str]
openai: Optional[str]
# Global language map for all supported languages
LANG_MAP: Dict[str, LangMapEntry] = {
"zh_CN": {"google": "zh-cn", "deepl": "ZH", "openai": "Simplified Chinese"},
"zh_TW": {"google": "zh-tw", "deepl": "ZH", "openai": "Traditional Chinese"},
"en_US": {"google": "en", "deepl": "EN", "openai": "English"},
"ja_JP": {"google": "ja", "deepl": "JA", "openai": "Japanese"},
"ko_KR": {"google": "ko", "deepl": "KO", "openai": "Korean"},
"fr_FR": {"google": "fr", "deepl": "FR", "openai": "French"},
"de_DE": {"google": "de", "deepl": "DE", "openai": "German"},
"es_ES": {"google": "es", "deepl": "ES", "openai": "Spanish"},
"ru_RU": {"google": "ru", "deepl": None, "openai": None},
"tr_TR": {"google": "tr", "deepl": None, "openai": None},
"pt_BR": {"google": "pt", "deepl": None, "openai": None},
}
def get_language_code(lang_code: str, service: str) -> str:
"""Get the appropriate language code for a specific translation service."""
entry: Optional[LangMapEntry] = LANG_MAP.get(lang_code)
if entry and isinstance(entry, dict):
code = cast(Optional[str], entry.get(service))
if isinstance(code, str):
return code
# Fallback: convert underscores to hyphens for Google, uppercase for DeepL, or use as-is
if service == "google":
return lang_code.lower().replace("_", "-")
elif service == "deepl":
return lang_code.upper()
else:
return lang_code
async def retry_with_backoff(
async_func: Any, *args: Any, config: Optional[RetryConfig] = None, **kwargs: Any
) -> Optional[Any]:
"""
Retry an async function with exponential backoff.
Args:
async_func: The async function to call
*args: Positional arguments for the function
config: RetryConfig instance (uses global config if None)
**kwargs: Keyword arguments for the function
Returns:
Result from the function or None if all retries failed
"""
# Use provided config or fall back to global configuration
if config is None:
config = get_translation_config().retry_config
# Attempt execution up to max_retries times
for attempt in range(config.max_retries):
try:
# Try to execute the async function with provided arguments
return await async_func(*args, **kwargs)
except Exception as e:
# Check if we have more retries available
if attempt < config.max_retries - 1:
# Calculate exponential backoff delay
delay = config.get_delay(attempt)
print(
f"⚠️ Attempt {attempt + 1} failed, retrying in {delay:.1f}s: {str(e)[:100]}"
)
# Wait before next attempt (prevents API rate limiting)
await asyncio.sleep(delay)
else:
# All retries exhausted, log final failure
print(f"❌ All {config.max_retries} retry attempts failed")
# Return None if all attempts failed
return None
def print_dry_run_summary(title: str) -> None:
"""Print a formatted dry-run summary header."""
print(f"\n{'=' * 60}")
print(f"📋 DRY-RUN PREVIEW: {title}")
print(f"{'=' * 60}")
# === Translation Services ===
class TranslationService:
"""Abstract base class for translation service implementations.
Defines the interface that all translation service adapters must implement.
Subclasses provide concrete implementations for specific translation APIs
(Google Translate, DeepL, OpenAI, etc.).
"""
async def translate(
self, text: str, target_lang: str, source_lang: str = "en_US"
) -> Optional[str]:
"""Translate text from source language to target language.
Args:
text: The text to translate
target_lang: Target language code (e.g., 'zh_CN', 'fr_FR')
source_lang: Source language code (default: 'en_US')
Returns:
Translated text if successful, None if translation failed
"""
raise NotImplementedError
class GoogleTranslateService(TranslationService):
"""Google Translate service implementation with exponential backoff retry.
Uses the free googletrans library to provide translation capabilities.
Includes automatic retry logic with exponential backoff for handling
transient failures and rate limiting.
Attributes:
translator: The googletrans Translator instance
config: Global translation configuration with retry settings
"""
def __init__(self) -> None:
"""Initialize Google Translate service.
Raises:
ImportError: If googletrans library is not installed
"""
if GoogleTranslator is None:
raise ImportError("googletrans library not available")
assert GoogleTranslator is not None
self.translator = GoogleTranslator()
self.config = get_translation_config()
self._setup_translator()
def _setup_translator(self) -> None:
"""Configure translator session properties (e.g., SSL verification)."""
# This is a workaround for a common issue with googletrans library where
# SSL verification fails. By accessing the internal session and setting
# verify to False, we can bypass these errors.
try:
session = getattr(self.translator, "_session", None)
if session:
session.verify = False
except AttributeError:
# If the session object doesn't exist, we can't configure it.
# This is not a critical error, so we can safely ignore it.
pass
async def translate(
self, text: str, target_lang: str, source_lang: str = "en_US"
) -> Optional[str]:
# First, check if the translation is already in the cache.
cache = get_translation_cache()
cached = cache.get(text, target_lang, source_lang, "google")
if cached is not None:
# If found, return the cached translation.
return cached
# Get the language code for the target language from the LANG_MAP.
target_entry: Optional[LangMapEntry] = LANG_MAP.get(target_lang)
target: Optional[str] = None
if target_entry is not None:
target = target_entry.get("google")
if not target:
# If the language code is not in the map, use a fallback.
target = target_lang.lower().replace("_", "-")
# Get the language code for the source language from the LANG_MAP.
source_entry: Optional[LangMapEntry] = LANG_MAP.get(source_lang)
source: Optional[str] = None
if source_entry is not None:
source = source_entry.get("google")
if not source:
# If the language code is not in the map, use a fallback.
source = source_lang.lower().replace("_", "-")
# Get the current asyncio event loop.
loop = asyncio.get_event_loop()
async def do_translate_with_retry() -> Optional[str]:
# Retry the translation up to the configured number of times.
for attempt in range(self.config.retry_config.max_retries):
try:
# Run the translation in a separate thread to avoid blocking.
result: Any = await loop.run_in_executor(
None,
lambda: self.translator.translate(
text, dest=target, src=source
),
)
# The result object has a 'text' attribute with the translation.
if hasattr(result, "text"):
return result.text
else:
# If the result object doesn't have a 'text' attribute,
# it might be a string itself.
return str(result)
except Exception as e:
error_str = str(e)
# If the attempt fails, check if we should retry.
if attempt < self.config.retry_config.max_retries - 1:
# If the error is an SSL error, reinstantiate the
# translator to fix it.
if (
"SSL" in error_str
or "TLS" in error_str
or "sslv3" in error_str.lower()
):
assert GoogleTranslator is not None
self.translator = GoogleTranslator()
self._setup_translator()
# Calculate the delay for the next retry.
delay = self.config.retry_config.get_delay(attempt)
print(
f"⚠️ Google translate attempt {attempt + 1} failed, retrying in {delay:.1f}s"
)
# Wait for the calculated delay.
await asyncio.sleep(delay)
else:
# If all retries fail, raise the exception.
raise
return None
try:
# Run the translation with retry logic.
result = await do_translate_with_retry()
if result:
# If the translation is successful, cache it.
cache.set(text, target_lang, source_lang, "google", result)
return result
except Exception as e:
# If the translation fails, print an error message.
print(f"❌ Google translate failed: {e}")
return None
class DeepLService(TranslationService):
"""DeepL translation service with configurable timeouts and retry logic.
Provides high-quality neural machine translation using DeepL's API.
Supports both synchronous and asynchronous translation with configurable
timeouts and automatic retry logic on transient failures.
Attributes:
api_key: DeepL API key for authentication
base_url: DeepL API endpoint URL (free tier)
config: Global translation configuration with timeout settings
"""
def __init__(self, api_key: str) -> None:
"""Initialize DeepL service.
Args:
api_key: Your DeepL API key (required for authentication)
"""
self.api_key = api_key
self.base_url = "https://api-free.deepl.com/v2/translate"
self.config = get_translation_config()
async def translate(
self, text: str, target_lang: str, source_lang: str = "en_US"
) -> Optional[str]:
# First, check if the translation is already in the cache.
cache = get_translation_cache()
cached = cache.get(text, target_lang, source_lang, "deepl")
if cached is not None:
# If found, return the cached translation.
return cached
# If aiohttp is not available, use the synchronous version of the
# translate method.
if aiohttp is None:
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
None, self._sync_translate, text, target_lang, source_lang
)
# Get the language code for the target language from the LANG_MAP.
target_entry: Optional[LangMapEntry] = LANG_MAP.get(target_lang)
target: Optional[str] = None
if target_entry is not None:
target = target_entry.get("deepl")
if not target:
# If the language code is not in the map, use a fallback.
target = target_lang.upper()
# Get the language code for the source language from the LANG_MAP.
source_entry: Optional[LangMapEntry] = LANG_MAP.get(source_lang)
source: Optional[str] = None
if source_entry is not None:
source = source_entry.get("deepl")
if not source:
# If the language code is not in the map, use a fallback.
source = source_lang.upper()
# The data to be sent to the DeepL API.
data = {
"auth_key": self.api_key,
"text": text,
"target_lang": target,
"source_lang": source,
}
# Retry the translation up to the configured number of times.
for attempt in range(self.config.retry_config.max_retries):
try:
# Set the timeout for the request.
timeout = aiohttp.ClientTimeout(
total=self.config.timeout_config.deepl_timeout
)
# Create a new aiohttp session for each request.
async with aiohttp.ClientSession() as session:
# Send the request to the DeepL API.
async with session.post(
self.base_url, data=data, timeout=timeout
) as response:
# Raise an exception if the request fails.
response.raise_for_status()
# Get the JSON response.
result = await response.json()
# The translation is in the 'translations' list.
translation = result["translations"][0]["text"]
# Cache the translation.
cache.set(text, target_lang, source_lang, "deepl", translation)
return translation
except asyncio.TimeoutError:
# If the request times out, check if we should retry.
if attempt < self.config.retry_config.max_retries - 1:
# Calculate the delay for the next retry.
delay = self.config.retry_config.get_delay(attempt)
print(
f"⚠️ DeepL timeout, retrying in {delay:.1f}s: Request {text[:50]}..."
)
# Wait for the calculated delay.
await asyncio.sleep(delay)
else:
# If all retries fail, print an error message.
print(
f"❌ DeepL translation timed out after {self.config.retry_config.max_retries} attempts"
)
return None
except Exception as e:
# If the request fails, check if we should retry.
if attempt < self.config.retry_config.max_retries - 1:
# Calculate the delay for the next retry.
delay = self.config.retry_config.get_delay(attempt)
print(
f"⚠️ DeepL attempt {attempt + 1} failed, retrying in {delay:.1f}s"
)
# Wait for the calculated delay.
await asyncio.sleep(delay)
else:
# If all retries fail, print an error message.
print(f"❌ DeepL translation failed: {e}")
return None
# If the translation fails, return None.
return None
def _sync_translate(
self, text: str, target_lang: str, source_lang: str = "en_US"
) -> Optional[str]:
# This is the synchronous version of the translate method. It is used
# when aiohttp is not available.
# The logic is the same as the async version, but it uses the
# requests library instead of aiohttp.
try:
target_entry: Optional[LangMapEntry] = LANG_MAP.get(target_lang)
target: Optional[str] = None
if target_entry is not None:
target = target_entry.get("deepl")
if not target:
target = target_lang.upper()
source_entry: Optional[LangMapEntry] = LANG_MAP.get(source_lang)
source: Optional[str] = None
if source_entry is not None:
source = source_entry.get("deepl")
if not source:
source = source_lang.upper()
data = {
"auth_key": self.api_key,
"text": text,
"target_lang": target,
"source_lang": source,
}
for attempt in range(self.config.retry_config.max_retries):
try:
response = requests.post(
self.base_url,
data=data,
timeout=self.config.timeout_config.deepl_timeout,
)
response.raise_for_status()
result = response.json()
return result["translations"][0]["text"]
except requests.exceptions.Timeout:
if attempt < self.config.retry_config.max_retries - 1:
delay = self.config.retry_config.get_delay(attempt)
print(
f"⚠️ DeepL timeout, retrying in {delay:.1f}s: Request {text[:50]}..."
)
time.sleep(delay)
else:
print(
f"❌ DeepL translation timed out after {self.config.retry_config.max_retries} attempts"
)
return None
except Exception as e:
if attempt < self.config.retry_config.max_retries - 1:
delay = self.config.retry_config.get_delay(attempt)
print(
f"⚠️ DeepL attempt {attempt + 1} failed, retrying in {delay:.1f}s"
)
time.sleep(delay)
else:
print(f"❌ DeepL translation failed: {e}")
return None
return None
except Exception as e:
print(f"❌ DeepL translation failed: {e}")
return None
class OpenAIService(TranslationService):
"""OpenAI GPT translation service with configurable timeouts and retry logic.
Uses OpenAI's language models (GPT-3.5-turbo or better) to provide context-aware
translations. Ideal for UI text where quality and naturalness are important.
Supports configurable models and automatic retry with exponential backoff.
Attributes:
client: OpenAI API client instance
model: The model to use for translation (default: 'gpt-3.5-turbo')
config: Global translation configuration with timeout settings
"""
def __init__(self, api_key: str, model: str = "gpt-3.5-turbo") -> None:
"""Initialize OpenAI translation service.
Args:
api_key: Your OpenAI API key (required for authentication)
model: The model to use for translation. Defaults to 'gpt-3.5-turbo'.
Other options: 'gpt-4', 'gpt-4-turbo-preview', etc.
Raises:
ImportError: If OpenAI library is not installed
"""
if openai_module is None:
raise ImportError("openai library not available")
self.config = get_translation_config()
self.client = openai_module.OpenAI(
api_key=api_key,
timeout=self.config.timeout_config.openai_timeout,
)
self.model = model
async def translate(
self, text: str, target_lang: str, source_lang: str = "en_US"
) -> Optional[str]:
assert openai_module is not None
# First, check if the translation is already in the cache.
cache = get_translation_cache()
cached = cache.get(text, target_lang, source_lang, "openai")
if cached is not None:
# If found, return the cached translation.
return cached
# Get the language name for the target language from the LANG_MAP.
target_entry: Optional[LangMapEntry] = LANG_MAP.get(target_lang)
target_name: Optional[str] = None
if target_entry is not None:
target_name = target_entry.get("openai")
if not target_name:
# If the language name is not in the map, use the language code.