-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslator.py
More file actions
2451 lines (2015 loc) · 99.5 KB
/
translator.py
File metadata and controls
2451 lines (2015 loc) · 99.5 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
#!/usr/bin/env python3
import argparse
import asyncio
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple, Any
from enum import Enum
import requests
from tqdm import tqdm
# --- Core Library Diagnostics ---
print("🔍 System Check...")
def check_library(name, modules):
"""Probe importability of a list of module names without exec()."""
import importlib
if isinstance(modules, str):
modules = [modules]
try:
for mod in modules:
importlib.import_module(mod)
print(f" ✓ {name}")
return True
except ImportError:
print(f" ⊘ {name} (optional)")
return False
except Exception as e:
print(f" ✗ {name} error: {e}")
return False
HAS_DOCX = check_library("python-docx", ["docx", "docx.shared", "docx.text.paragraph", "docx.oxml.shared", "docx.oxml.ns"])
HAS_PPTX = check_library("python-pptx", ["pptx", "pptx.util", "pptx.enum.text", "pptx.dml.color"])
HAS_TORCH = check_library("torch", ["torch"])
HAS_CT2 = check_library("CTranslate2", ["ctranslate2", "huggingface_hub"])
HAS_TRANSFORMERS = check_library("Transformers", ["transformers"])
try:
import ctranslate2 # type: ignore[import-untyped]
from huggingface_hub import snapshot_download # type: ignore[import-untyped]
except ImportError:
ctranslate2 = None # type: ignore[assignment]
snapshot_download = None # type: ignore[assignment]
try:
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM # type: ignore[import-untyped]
HFTokenizer = AutoTokenizer
except ImportError:
AutoTokenizer = None # type: ignore[assignment, misc]
AutoModelForSeq2SeqLM = None # type: ignore[assignment, misc]
HFTokenizer = None # type: ignore[assignment, misc]
HAS_OPENAI = check_library("OpenAI", "from openai import AsyncOpenAI")
HAS_ANTHROPIC = check_library("Anthropic", "from anthropic import AsyncAnthropic")
HAS_SIMALIGN = check_library("simalign", "from simalign import SentenceAligner")
HAS_LXML = check_library("lxml", "from lxml import etree")
try:
from openai import AsyncOpenAI # type: ignore[import-untyped]
except ImportError:
AsyncOpenAI = None # type: ignore[assignment, misc]
try:
from anthropic import AsyncAnthropic # type: ignore[import-untyped]
except ImportError:
AsyncAnthropic = None # type: ignore[assignment, misc]
try:
from docx import Document # type: ignore[import-untyped]
from docx.document import Document as DocxDocument # type: ignore[import-untyped]
from docx.text.paragraph import Paragraph # type: ignore[import-untyped]
except ImportError:
Document = None # type: ignore[assignment, misc]
DocxDocument = None # type: ignore[assignment, misc]
Paragraph = None # type: ignore[assignment, misc]
try:
from gradio_client import Client
HAS_GRADIO_CLIENT = True
except ImportError:
HAS_GRADIO_CLIENT = False
try:
from llama_cpp import Llama
HAS_LLAMA_CPP = True
except ImportError:
HAS_LLAMA_CPP = False
# --- Device & Backend Configuration ---
def get_torch_device():
if not HAS_TORCH: return "cpu"
import torch
if torch.cuda.is_available(): return torch.device("cuda")
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
def get_ct2_settings():
"""Optimized for M1 Mac (Accelerate CPU) vs NVIDIA (CUDA)."""
if HAS_TORCH:
import torch
if torch.cuda.is_available(): return "cuda", "float16"
# Mac M1/M2/M3: MUST use 'cpu' for CT2 and 'int8' for peak ARM64 optimization
return "cpu", "int8"
def check_fast_align():
script_dir = Path(__file__).parent
binary_locations = ["../fast_align/build/fast_align", "./fast_align/build/fast_align", "fast_align"]
for loc in binary_locations:
path = script_dir / loc if not loc.startswith('/') else Path(loc)
if os.path.isfile(path) and os.access(path, os.X_OK): return True
return False
HAS_FAST_ALIGN = check_fast_align()
print(f" {'✓' if HAS_FAST_ALIGN else '⊘'} fast_align")
print("-" * 60)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# ============================================================================
# ENUMS FOR CONFIGURATION
# ============================================================================
class TranslationBackend(Enum):
"""Available translation backends"""
CT2 = "ct2"
NLLB = "nllb"
OPENAI = "openai"
ANTHROPIC = "anthropic"
OLLAMA = "ollama"
SAUERKRAUT_API = "sauerkraut-api"
SAUERKRAUT_LOCAL = "sauerkraut-local"
AUTO = "auto"
class AlignerBackend(Enum):
"""Available alignment backends"""
LINDAT = "lindat"
FAST_ALIGN = "fast_align"
SIMALIGN = "simalign"
HEURISTIC = "heuristic"
AUTO = "auto"
class TranslationMode(Enum):
"""Translation modes"""
NMT_ONLY = "nmt"
LLM_WITH_ALIGN = "llm-align"
LLM_WITHOUT_ALIGN = "llm-plain"
HYBRID = "hybrid"
# ============================================================================
# DATA STRUCTURES
# ============================================================================
@dataclass
class FormatRun:
"""A run of text with formatting"""
text: str
bold: Optional[bool] = None
italic: Optional[bool] = None
underline: Optional[bool] = None
font_name: Optional[str] = None
font_size: Optional[float] = None
font_color: Optional[Tuple[int, int, int]] = None
@dataclass
class TranslatableParagraph:
"""Paragraph with formatting and metadata"""
runs: List[FormatRun] = field(default_factory=list)
metadata: Dict[str, Any] = field(default_factory=dict)
def get_text(self) -> str:
return ''.join(run.text for run in self.runs)
def get_words(self) -> List[str]:
"""Clean tokenization for the ALIGNER only: strips punctuation."""
import re
text = self.get_text()
# Extracts only alphanumeric sequences (e.g., "Theology" from "Theology:")
return re.findall(r"\w+", text)
def get_formatted_word_indices(self) -> Dict[str, Set[int]]:
"""Maps formatting to clean alphanumeric word indices."""
formatted: Dict[str, set] = {'italic': set(), 'bold': set(), 'italic_bold': set()}
text = self.get_text()
words = self.get_words() # Uses the same list the aligner sees
if not words:
return formatted
char_to_word = {}
last_found = 0
for word_idx, word in enumerate(words):
# Find the word in the text, starting search after the previous word
start = text.find(word, last_found)
if start != -1:
for i in range(start, start + len(word)):
char_to_word[i] = word_idx
last_found = start + len(word)
char_pos = 0
for run in self.runs:
if not run.text:
continue
for char in run.text:
if char_pos in char_to_word:
word_idx = char_to_word[char_pos]
if not char.isspace():
if run.bold and run.italic:
formatted['italic_bold'].add(word_idx)
elif run.italic:
formatted['italic'].add(word_idx)
elif run.bold:
formatted['bold'].add(word_idx)
char_pos += 1
return formatted
# ============================================================================
# TRANSLATION BACKENDS (keeping previous implementations)
# ============================================================================
class SauerkrautAPITranslator:
"""External API: SauerkrautLM via VAGOsolutions Demo"""
def __init__(self, tgt_lang: str):
self.tgt_lang = tgt_lang
self.available = False
if HAS_GRADIO_CLIENT:
try:
self.client = Client("VAGOsolutions/SauerkrautLM-Translator-LFM2.5-1.2b-Demo")
self.available = True
logger.info("✓ NMT | Sauerkraut API Connected")
except Exception as e:
logger.error(f"Sauerkraut API init failed: {e}")
def translate_batch(self, texts: List[str]) -> List[str]:
results = []
for text in texts:
try:
res = self.client.predict(text=text, target_lang=self.tgt_lang, api_name="/translate")
results.append(res[2]) # result[2] is the clean translation string
except:
results.append(text)
return results
class SauerkrautLocalTranslator:
"""Local GGUF: Sauerkraut/LFM 1.2B via llama-cpp-python (CPU Optimized)"""
def __init__(self, src_lang: str, tgt_lang: str):
self.src_lang, self.tgt_lang = src_lang, tgt_lang
self.available = False
if HAS_LLAMA_CPP:
try:
logger.info("NMT | Loading Local Sauerkraut 1.2B (LFM) GGUF...")
# This downloads the model to ~/.cache/huggingface/hub on first run
self.llm = Llama.from_pretrained(
repo_id="LiquidAI/LFM2.5-1.2B-Instruct-GGUF",
filename="LFM2.5-1.2B-Instruct-Q4_K_M.gguf",
n_ctx=2048,
n_threads=4, # Optimize for Hetzner vCPU count
verbose=False
)
self.available = True
logger.info("✓ NMT | Local Sauerkraut (LFM) ready on CPU")
except Exception as e:
logger.error(f"Local Sauerkraut init failed: {e}")
def translate_batch(self, texts: List[str]) -> List[str]:
results = []
for text in texts:
prompt = f"Translate from {self.src_lang} to {self.tgt_lang}. Return only the translation: {text}"
try:
response = self.llm.create_chat_completion(
messages=[{"role": "user", "content": prompt}],
temperature=0.1
)
results.append(response['choices'][0]['message']['content'].strip()) # type: ignore[index, union-attr]
except Exception: # noqa: BLE001
results.append(text)
return results
class CTranslate2Translator:
"""WMT21 Backend: High-quality dense model."""
MODELS = {
'en_to_x': 'cstr/wmt21ct2_int8',
'x_to_en': 'cstr/wmt21-ct2-x-en-int8',
}
SUPPORTED_LANGS = ['de', 'es', 'fr', 'it', 'ja', 'zh', 'ru', 'pt', 'nl', 'cs', 'uk']
def __init__(self, src_lang: str, tgt_lang: str):
self.src_lang, self.tgt_lang = src_lang, tgt_lang
self.available = False
self.ct2_dev, self.ct2_compute = get_ct2_settings()
if not HAS_CT2: return
if src_lang == 'en' and tgt_lang in self.SUPPORTED_LANGS:
self.direction, self.tokenizer_name = 'en_to_x', "facebook/wmt21-dense-24-wide-en-x"
elif tgt_lang == 'en' and src_lang in self.SUPPORTED_LANGS:
self.direction, self.tokenizer_name = 'x_to_en', "facebook/wmt21-dense-24-wide-x-en"
else: return
try:
logger.info(f"Loading WMT21-CT2 ({self.direction})...")
model_path = self._get_or_download_model()
self.translator = ctranslate2.Translator(
model_path, device=self.ct2_dev, compute_type=self.ct2_compute
)
self.tokenizer = AutoTokenizer.from_pretrained(self.tokenizer_name)
self.available = True
logger.info(f"✓ WMT21 CT2 ready on {self.ct2_dev}")
except Exception as e:
logger.error(f"WMT21 initialization failure: {e}")
def _get_or_download_model(self) -> str:
cache_base = Path.home() / '.cache' / 'huggingface' / 'hub'
model_repo = self.MODELS[self.direction]
model_dir = cache_base / f"models--{model_repo.replace('/', '--')}"
ref_path = model_dir / 'refs' / 'main'
if ref_path.exists():
with open(ref_path) as f:
commit_hash = f.read().strip()
snapshot_path = model_dir / 'snapshots' / commit_hash
if (snapshot_path / 'model.bin').exists():
return str(snapshot_path)
logger.info("Downloading CT2 model...")
return snapshot_download(repo_id=model_repo)
def translate_batch(self, texts: List[str]) -> List[str]:
if not self.available or not texts:
return texts
try:
# 1. Ensure language tokens are correctly formatted
# WMT21 models expect the target lang as a prefix
target_prefix = [[self.tokenizer.lang_code_to_token[self.tgt_lang]]] * len(texts)
# 2. Tokenize with specific padding/truncation
source_tokens = [self.tokenizer.convert_ids_to_tokens(self.tokenizer.encode(t)) for t in texts]
# 3. Translate with proper beam search and repetition penalty
results = self.translator.translate_batch(
source_tokens,
target_prefix=target_prefix,
beam_size=5,
max_batch_size=16,
repetition_penalty=1.2,
# Prevent the model from just 'copying' the source if it gets confused
disable_unk=True
)
translated = []
for i, res in enumerate(results):
# Strip the language token from the start of the result
tokens = res.hypotheses[0]
if self.tokenizer.lang_code_to_token[self.tgt_lang] in tokens:
tokens = tokens[tokens.index(self.tokenizer.lang_code_to_token[self.tgt_lang]) + 1:]
decoded = self.tokenizer.decode(self.tokenizer.convert_tokens_to_ids(tokens), skip_special_tokens=True)
translated.append(decoded.strip()) # type: ignore[union-attr]
return translated
except Exception as e:
logger.error(f"CT2 Critical Error: {e}")
return texts
class OpusMTTranslator:
"""Opus-MT Backend: Tiny, specialized bilingual models. Standalone logic."""
def __init__(self, src_lang: str, tgt_lang: str):
self.src_lang, self.tgt_lang = src_lang, tgt_lang
self.available = False
self.ct2_dev, self.ct2_compute = get_ct2_settings()
# The standard name format for Opus-MT
original_repo = f"Helsinki-NLP/opus-mt-{src_lang}-{tgt_lang}"
# Your custom optimized repo
self.custom_repo = f"cstr/opus-mt-{src_lang}-{tgt_lang}-ct2-int8"
try:
logger.info(f"NMT | Loading weights from {self.custom_repo}...")
model_path = snapshot_download(repo_id=self.custom_repo)
self.translator = ctranslate2.Translator(model_path, device=self.ct2_dev, compute_type=self.ct2_compute)
# FIXED: Load tokenizer from the ORIGINAL repo name to get the correct Marian model_type
# Transformers library will use the tiny cached JSON files from the original.
self.tokenizer = AutoTokenizer.from_pretrained(original_repo)
self.available = True
logger.info("✓ NMT | Opus-MT ready (Weights: cstr / Tokenizer: original)")
except Exception as e:
logger.warning(f"NMT | Opus-MT primary load failed: {e}. Trying michaelfeil fallback...")
try:
fallback = f"michaelfeil/ct2fast-opus-mt-{src_lang}-{tgt_lang}"
model_path = snapshot_download(repo_id=fallback)
self.translator = ctranslate2.Translator(model_path, device=self.ct2_dev, compute_type=self.ct2_compute)
self.tokenizer = AutoTokenizer.from_pretrained(original_repo)
self.available = True
logger.info(f"✓ NMT | Opus-MT ready using {fallback}")
except:
logger.error("NMT | All Opus-MT paths failed.")
def translate_batch(self, texts: List[str]) -> List[str]:
if not self.available or not texts: return texts
source_tokens = [self.tokenizer.convert_ids_to_tokens(self.tokenizer.encode(t)) for t in texts]
results = self.translator.translate_batch(source_tokens, beam_size=5)
return [self.tokenizer.decode(self.tokenizer.convert_tokens_to_ids(r.hypotheses[0]), skip_special_tokens=True) for r in results] # type: ignore[misc]
class Madlad400Translator:
"""Madlad-400 Backend: Google's 3B powerhouse. Optimized for your cstr/ repo."""
def __init__(self, src_lang: str, tgt_lang: str, model_size: str = "3b"):
self.src_lang, self.tgt_lang = src_lang, tgt_lang
self.available = False
self.ct2_dev, self.ct2_compute = get_ct2_settings()
original_repo = f"google/madlad400-{model_size}-mt"
self.custom_repo = f"cstr/madlad400-{model_size}-ct2-int8"
self.tgt_prefix = f"<2{tgt_lang}>"
try:
logger.info(f"NMT | Loading Madlad-400 from {self.custom_repo}...")
model_path = snapshot_download(repo_id=self.custom_repo)
self.translator = ctranslate2.Translator(model_path, device=self.ct2_dev, compute_type=self.ct2_compute)
# FIXED: Point tokenizer to Google's repo to resolve the T5 architecture correctly
self.tokenizer = AutoTokenizer.from_pretrained(original_repo)
self.available = True
logger.info("✓ NMT | Madlad-400 ready.")
except Exception as e:
logger.error(f"NMT | Madlad-400 load failed: {e}")
def translate_batch(self, texts: List[str]) -> List[str]:
if not self.available or not texts: return texts
# Prepends <2de> (or similar) to every sentence in the batch
source_tokens = [self.tokenizer.convert_ids_to_tokens(self.tokenizer.encode(f"{self.tgt_prefix} {t}")) for t in texts]
results = self.translator.translate_batch(source_tokens, beam_size=1, repetition_penalty=2.0)
return [self.tokenizer.decode(self.tokenizer.convert_tokens_to_ids(r.hypotheses[0]), skip_special_tokens=True) for r in results] # type: ignore[misc]
class NLLBTranslator:
"""NLLB-200 translator using CTranslate2 for 4x speedup and low memory"""
# Map sizes to specific CTranslate2 optimized repositories
REPOS = {
"600M": "JustFrederik/nllb-200-distilled-600M-ct2-int8",
"1.3B": "OpenNMT/nllb-200-distilled-1.3B-ct2-int8",
"3.3B": "OpenNMT/nllb-200-3.3B-ct2-int8"
}
LANG_CODES = {
'en': 'eng_Latn', 'de': 'deu_Latn', 'fr': 'fra_Latn',
'es': 'spa_Latn', 'it': 'ita_Latn', 'pt': 'por_Latn',
'ru': 'rus_Cyrl', 'zh': 'zho_Hans', 'ja': 'jpn_Jpan',
'ko': 'kor_Hang', 'ar': 'arb_Arab', 'hi': 'hin_Deva',
'nl': 'nld_Latn', 'pl': 'pol_Latn', 'tr': 'tur_Latn',
'cs': 'ces_Latn', 'uk': 'ukr_Cyrl', 'vi': 'vie_Latn',
}
def __init__(self, src_lang: str, tgt_lang: str, model_size: str = "600M"):
self.src_lang, self.tgt_lang = src_lang, tgt_lang
self.available = False
self.mode = None
self.device = get_torch_device()
self.ct2_dev, self.ct2_compute = get_ct2_settings()
self.src_code = self.LANG_CODES.get(src_lang)
self.tgt_code = self.LANG_CODES.get(tgt_lang)
if not self.src_code or not self.tgt_code: return
ct2_repo = self.REPOS.get(model_size, self.REPOS["600M"])
standard_repo = f"facebook/nllb-200-distilled-{model_size}"
if HAS_CT2:
try:
logger.info(f"Loading NLLB-CT2 from {ct2_repo}...")
model_path = snapshot_download(repo_id=ct2_repo)
try:
self.translator = ctranslate2.Translator(
model_path, device=self.ct2_dev, compute_type=self.ct2_compute
)
except Exception:
# Specific fallback for Mac CPU optimization mismatch
self.translator = ctranslate2.Translator(
model_path, device="cpu", compute_type="int8"
)
self.tokenizer = AutoTokenizer.from_pretrained(standard_repo, src_lang=self.src_code)
self.mode, self.available = "ct2", True
logger.info(f"✓ NLLB-{model_size} CT2 ready.")
return
except Exception as e:
logger.warning(f"NLLB-CT2 failed: {e}")
if HAS_TRANSFORMERS and HAS_TORCH:
try:
logger.info("Fallback: Loading standard PyTorch NLLB...")
self.model = AutoModelForSeq2SeqLM.from_pretrained(standard_repo)
self.tokenizer = HFTokenizer.from_pretrained(standard_repo, src_lang=self.src_code)
if self.device.type == "mps": self.model = self.model.half()
self.model.to(self.device).eval()
self.mode, self.available = "torch", True
logger.info(f"✓ NLLB PyTorch ready on {self.device}")
except Exception as e:
logger.error(f"Critical: All NLLB paths failed: {e}")
def translate_batch(self, texts: List[str], batch_size: int = 16) -> List[str]:
"""Translate batch using CT2 efficient beam search"""
if not self.available or not texts:
return texts
try:
results = []
# NLLB requires the target language code as the first token (target prefix)
target_prefix = [self.tgt_code]
for i in range(0, len(texts), batch_size):
batch = texts[i:i + batch_size]
# Tokenize
source_tokens = [
self.tokenizer.convert_ids_to_tokens(self.tokenizer.encode(t))
for t in batch
]
# Translate
step_results = self.translator.translate_batch(
source_tokens,
target_prefix=[target_prefix] * len(batch),
beam_size=4,
max_batch_size=batch_size,
repetition_penalty=1.1
)
# Decode (skipping the lang code prefix in the output)
for res in step_results:
tokens = res.hypotheses[0]
# The first token is usually the target lang code
if tokens[0] == self.tgt_code:
tokens = tokens[1:]
decoded = self.tokenizer.decode(
self.tokenizer.convert_tokens_to_ids(tokens),
skip_special_tokens=True
)
results.append(decoded.strip()) # type: ignore[union-attr]
return results
except Exception as e:
logger.error(f"NLLB-CT2 translation failed: {e}")
return texts
class LLMTranslator:
"""LLM translator (OpenAI/Anthropic/Ollama)"""
def __init__(self, src_lang: str, tgt_lang: str, preferred_provider: Optional[str] = None):
self.src_lang = src_lang
self.tgt_lang = tgt_lang
# Ensure we have access to the classes if they were imported via exec
self.OpenAIClass = globals().get('AsyncOpenAI')
self.AnthropicClass = globals().get('AsyncAnthropic')
self.providers = self._init_providers(preferred_provider)
if self.providers:
logger.info(f"✓ LLM available ({list(self.providers.keys())})")
def _init_providers(self, preferred: Optional[str] = None) -> Dict[str, Any]:
providers = {}
if HAS_OPENAI and os.getenv("OPENAI_API_KEY"):
providers["openai"] = {
"client": AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY")),
"model": os.getenv("OPENAI_MODEL", "gpt-4o-mini")
}
if HAS_ANTHROPIC and os.getenv("ANTHROPIC_API_KEY"):
providers["anthropic"] = {
"client": AsyncAnthropic(api_key=os.getenv("ANTHROPIC_API_KEY")),
"model": os.getenv("ANTHROPIC_MODEL", "claude-3-5-sonnet-20241022")
}
if self._check_ollama():
providers["ollama"] = {
"url": "http://localhost:11434/api/generate",
"model": self._get_ollama_model()
}
if preferred and preferred in providers:
return {preferred: providers[preferred]}
return providers
def _check_ollama(self) -> bool:
try:
r = requests.get("http://localhost:11434/api/tags", timeout=2)
return r.status_code == 200 and len(r.json().get("models", [])) > 0
except:
return False
def _get_ollama_model(self) -> str:
try:
r = requests.get("http://localhost:11434/api/tags", timeout=2)
models = r.json().get("models", [])
return models[0]["name"] if models else "llama3.2"
except:
return "llama3.2"
async def translate_text(self, text: str, use_alignment: bool = True) -> Optional[str]:
"""Translate single text"""
if not text.strip() or not self.providers:
return None
if use_alignment:
prompt = (
f"Translate the following text from {self.src_lang} to {self.tgt_lang}. "
f"Preserve the word order as much as possible for alignment purposes. "
f"Return ONLY the translation:\n\n{text}"
)
else:
prompt = (
f"Translate the following text from {self.src_lang} to {self.tgt_lang}. "
f"Provide a natural, fluent translation. "
f"Return ONLY the translation:\n\n{text}"
)
for provider_name, provider in self.providers.items():
try:
if provider_name == "openai":
response = await provider["client"].chat.completions.create(
model=provider["model"],
messages=[{"role": "user", "content": prompt}],
temperature=0.3,
max_tokens=4000
)
return response.choices[0].message.content.strip()
elif provider_name == "anthropic":
response = await provider["client"].messages.create(
model=provider["model"],
messages=[{"role": "user", "content": prompt}],
temperature=0.3,
max_tokens=4000
)
return response.content[0].text.strip()
elif provider_name == "ollama":
r = requests.post(
provider["url"],
json={"model": provider["model"], "prompt": prompt, "stream": False},
timeout=120
)
if r.status_code == 200:
return r.json().get("response", "").strip()
except Exception as e:
logger.debug(f"{provider_name} failed: {e}")
continue
return None
async def translate_batch(self, texts: List[str], use_alignment: bool = True) -> List[str]:
"""Translate batch"""
tasks = [self.translate_text(text, use_alignment) for text in texts]
results = await asyncio.gather(*tasks)
return [res if res else text for res, text in zip(results, texts)]
# ============================================================================
# WORD ALIGNERS
# ============================================================================
class LindatAligner:
"""Lindat word alignment API: Zero RAM usage fallback."""
def __init__(self, src_lang: str, tgt_lang: str):
self.src_lang, self.tgt_lang = src_lang, tgt_lang
self.available = self._check_available()
if self.available:
logger.info(f"✓ ALIGN | Lindat API available ({src_lang}-{tgt_lang})")
def _check_available(self) -> bool:
try:
r = requests.get(f"https://lindat.cz/services/text-aligner/align/{self.src_lang}-{self.tgt_lang}", timeout=3)
return r.status_code in [200, 405]
except: return False
def align(self, src_words: List[str], tgt_words: List[str]) -> List[Tuple[int, int]]:
if not self.available or not src_words or not tgt_words: return []
try:
r = requests.post(
f"https://lindat.cz/services/text-aligner/align/{self.src_lang}-{self.tgt_lang}",
headers={'Content-Type': 'application/json'},
json={'src_tokens': [src_words], 'trg_tokens': [tgt_words]},
timeout=15
)
if r.status_code == 200:
alignment = r.json()["alignment"][0]
return [(int(a[0]), int(a[1])) for a in alignment]
except Exception as e:
logger.debug(f"ALIGN | Lindat request failed: {e}")
return []
class AwesomeAlignAligner:
"""BERT Aligner: Uses custom CT2-INT8 model from HuggingFace."""
def __init__(self):
self.available = False
self.mode = None
self.device = get_torch_device()
self.ct2_dev, self.ct2_compute = get_ct2_settings()
self.ct2_repo = "cstr/bert-base-multilingual-cased-ct2-int8"
self.standard_repo = "bert-base-multilingual-cased"
if HAS_CT2:
try:
logger.info(f"Loading CT2 Aligner from {self.ct2_repo}...")
model_path = snapshot_download(repo_id=self.ct2_repo)
self.encoder = ctranslate2.Encoder(
model_path, device=self.ct2_dev, compute_type=self.ct2_compute,
intra_threads=1
)
# Load tokenizer from string to avoid local JSON collision
self.tokenizer = AutoTokenizer.from_pretrained(self.standard_repo)
self.mode, self.available = "ct2", True
logger.info("✓ Awesome-Align CT2 ready.")
return
except Exception as e:
logger.warning(f"CT2 Aligner load failed: {e}")
if HAS_TRANSFORMERS and HAS_TORCH:
try:
from transformers import BertModel, BertTokenizer
self.model = BertModel.from_pretrained(self.standard_repo)
self.tokenizer = BertTokenizer.from_pretrained(self.standard_repo)
if self.device.type == "mps": self.model = self.model.half()
self.model.to(self.device).eval()
self.mode, self.available = "torch", True
logger.info(f"✓ Awesome-Align PyTorch ready on {self.device}")
except Exception as e:
logger.error(f"Critical: Aligner fallback failed: {e}")
def align(self, src_words: List[str], tgt_words: List[str]) -> List[Tuple[int, int]]:
"""
Extracts high-precision word alignments using BERT embeddings.
Uses Mutual Argmax (Intersection) logic for 1-to-1 precision.
Compatible with Mac CTranslate2 (no return_all_layers).
"""
if not self.available or not src_words or not tgt_words:
return []
import numpy as np
src_out, tgt_out = None, None
try:
# 1. PRE-PROCESSING: Subword tokenization
def get_tokens_and_map(words):
subtokens, word_map = [], []
for i, w in enumerate(words):
tokens = self.tokenizer.tokenize(w) or [self.tokenizer.unk_token]
subtokens.extend(tokens)
word_map.extend([i] * len(tokens))
return subtokens, word_map
src_subtokens, src_word_map = get_tokens_and_map(src_words)
tgt_subtokens, tgt_word_map = get_tokens_and_map(tgt_words)
# 2. EMBEDDING EXTRACTION
if self.mode == "ct2":
src_input = [["[CLS]"] + src_subtokens + ["[SEP]"]]
tgt_input = [["[CLS]"] + tgt_subtokens + ["[SEP]"]]
# Use standard batch forward for cross-version compatibility
res_src = self.encoder.forward_batch(src_input)
res_tgt = self.encoder.forward_batch(tgt_input)
# Extract Layer 12 (last_hidden_state)
src_out = np.array(res_src.last_hidden_state)[0, 1:-1]
tgt_out = np.array(res_tgt.last_hidden_state)[0, 1:-1]
else: # PyTorch Mode
import torch
def to_ids(tokens):
ids = self.tokenizer.convert_tokens_to_ids(tokens)
return torch.tensor([self.tokenizer.cls_token_id] + ids + [self.tokenizer.sep_token_id]).to(self.device)
with torch.no_grad():
# PyTorch uses Layer 8 (sweet spot)
out_s = self.model(to_ids(src_subtokens).unsqueeze(0), output_hidden_states=True)[2][8][0, 1:-1]
out_t = self.model(to_ids(tgt_subtokens).unsqueeze(0), output_hidden_states=True)[2][8][0, 1:-1]
src_out = out_s.detach().cpu().float().numpy()
tgt_out = out_t.detach().cpu().float().numpy()
# 3. STABLE ALIGNMENT LOGIC: Mutual Argmax
# Normalize vectors for cosine similarity
src_norm = src_out / np.linalg.norm(src_out, axis=-1, keepdims=True)
tgt_norm = tgt_out / np.linalg.norm(tgt_out, axis=-1, keepdims=True)
similarity = np.dot(src_norm, tgt_norm.T)
# Find best matches in both directions
best_tgt_for_src = np.argmax(similarity, axis=1) # Shape: (src_len,)
best_src_for_tgt = np.argmax(similarity, axis=0) # Shape: (tgt_len,)
threshold = 1e-3
align_words = set()
# Mutual Agreement (The standard working method)
for i, j in enumerate(best_tgt_for_src):
# If source i picked target j, AND target j picked source i...
if best_src_for_tgt[j] == i and similarity[i, j] > threshold:
# Map subword indices back to word indices
align_words.add((src_word_map[i], tgt_word_map[j]))
final_alignments = sorted(list(align_words))
# VERBOSE CLI LOG
logger.debug(f"TRACE | Awesome-Align | Mode: {self.mode.upper()} | Links: {len(final_alignments)}")
return final_alignments
except Exception as e:
logger.error(f"ALIGN | Logic failure: {e}")
return []
def align_old(self, src_words: List[str], tgt_words: List[str]) -> List[Tuple[int, int]]:
if not self.available or not src_words or not tgt_words:
return []
try:
import numpy as np
# 1. Tokenize
def get_tokens_and_map(words):
tokens = []
word_map = []
for i, w in enumerate(words):
subwords = self.tokenizer.tokenize(w)
tokens.extend(subwords)
word_map.extend([i] * len(subwords))
return tokens, word_map
src_tokens, src_map = get_tokens_and_map(src_words)
tgt_tokens, tgt_map = get_tokens_and_map(tgt_words)
# 2. Extract Embeddings using CTranslate2
# We add [CLS] and [SEP] just like BERT expects
src_input = [["[CLS]"] + src_tokens + ["[SEP]"]]
tgt_input = [["[CLS]"] + tgt_tokens + ["[SEP]"]]
# forward_batch returns a StorageView; we convert to numpy for easy math
src_out = np.array(self.encoder.forward_batch(src_input).last_hidden_state)[0, 1:-1]
tgt_out = np.array(self.encoder.forward_batch(tgt_input).last_hidden_state)[0, 1:-1]
# 3. Compute Similarity (Dot Product)
# Normalizing vectors first ensures we are doing Cosine Similarity
src_out /= np.linalg.norm(src_out, axis=-1, keepdims=True)
tgt_out /= np.linalg.norm(tgt_out, axis=-1, keepdims=True)
similarity = np.dot(src_out, tgt_out.T)
# 4. Extract Alignments (Mutual Argmax / Threshold)
threshold = 1e-3
best_src = np.argmax(similarity, axis=1)
best_tgt = np.argmax(similarity, axis=0)
align_words = set()
for i, j in enumerate(best_src):
if best_tgt[j] == i and similarity[i, j] > threshold:
align_words.add((src_map[i], tgt_map[j]))
return sorted(list(align_words))
except Exception as e:
logger.debug(f"CT2 Alignment failed: {e}")
return []
class FastAlignAligner:
"""fast_align local aligner - uses temp file for binary"""
def __init__(self):
self.available = False
self.mode = None
self.binary_path = None
self.atools_path = None
# Check for Python package first
try:
import fast_align
self.available = True
self.mode = "python"
return
except ImportError:
pass
# Binary search logic
script_dir = Path(__file__).parent
search_dirs = [script_dir / "../fast_align/build", script_dir / "./fast_align/build"]
for d in search_dirs:
fa = d / "fast_align"
at = d / "atools"
if fa.exists() and os.access(fa, os.X_OK):
self.binary_path = str(fa)
self.atools_path = str(at) if at.exists() else None
self.available = True
self.mode = "binary"
return
def align(self, src_words: List[str], tgt_words: List[str]) -> List[Tuple[int, int]]:
if not self.available or not src_words or not tgt_words:
return []
try:
if self.mode == "python":
from fast_align import align
src_text = ' '.join(src_words)
tgt_text = ' '.join(tgt_words)
result = align([f"{src_text} ||| {tgt_text}"], forward=True)
return [tuple(map(int, p.split('-'))) for p in result[0].split()] # type: ignore[misc]
elif self.mode == "binary":
import subprocess # nosec B404
import tempfile
input_str = f"{' '.join(src_words)} ||| {' '.join(tgt_words)}\n"
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
f.write(input_str)
temp_path = f.name
try:
# -d: diagonal, -o: optimize tension, -v: variational bayes
# -I 1: single pass is enough for alignment of a known translation
cmd = [self.binary_path, '-i', temp_path, '-d', '-o', '-v', '-I', '1']
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10) # nosec B603
if result.returncode != 0:
return []
# fast_align binary outputs to stdout in Pharaoh format (i-j)
alignments = []
output = result.stdout.strip()
if output:
for pair in output.split():
if '-' in pair:
i, j = map(int, pair.split('-'))
alignments.append((i, j))
return alignments
finally:
if os.path.exists(temp_path): os.unlink(temp_path)
except Exception as e:
logger.debug(f"fast_align execution failed: {e}")
return []
class SimAlignAligner:
"""SimAlign Aligner: Heavy PyTorch BERT (1.2GB RAM)."""
def __init__(self):
self.available = globals().get('HAS_SIMALIGN', False)
if self.available:
try:
from simalign import SentenceAligner
# FIXED: matching_methods must be a short string mapping code
# "m" maps to "mwmf" internally in simalign.simalign.py
self.aligner = SentenceAligner(model="bert", token_type="bpe", matching_methods="m", device="cpu")
logger.info("✓ ALIGN | SimAlign (Standard BERT) ready.")
except Exception as e:
logger.error(f"ALIGN | SimAlign init failed: {e}")
self.available = False
def align(self, src_words: List[str], tgt_words: List[str]) -> List[Tuple[int, int]]:
if not self.available or not src_words or not tgt_words: return []
try:
# returns dict of lists: {'mwmf': [(0,0), ...]}
result = self.aligner.get_word_aligns(src_words, tgt_words)
alignments = result.get('mwmf', [])
return [(int(a[0]), int(a[1])) for a in alignments]
except Exception as e:
logger.error(f"ALIGN | SimAlign failed: {e}")
return []
class HeuristicAligner:
"""Heuristic fallback - align words that appear in both"""
def __init__(self):
logger.info("✓ Heuristic aligner (fallback)")
def align(self, src_words: List[str], tgt_words: List[str]) -> List[Tuple[int, int]]:
"""Simple heuristic alignment"""
alignments = []
src_lower = [w.lower().strip('.,!?;:') for w in src_words]
tgt_lower = [w.lower().strip('.,!?;:') for w in tgt_words]
for i, src_word in enumerate(src_lower):