Elffuss BraidHub

kikocis/online-translator public

main · 43.6 KiBRawPermalink
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4"""
5Translation Module
6-----------------
7Handles text translation functionality for the Online-Translator application.
8Provides translation services using MLX models and manages translation context.
9
10Copyright (c) 2025 Kiko Cisneros
11Licensed under the MIT License (see LICENSE file for details)
12"""
13
14import time
15import re
16from collections import deque
17from mlx_lm import load, generate
18import mlx.core as mx
19from . import config
20
21
22class TextTranslator:
23 """Handles text translation using MLX models"""
24
25 def __init__(self):
26 self.translation_model = None
27 self.translation_tokenizer = None
28
29 # Translation history for context
30 self.translation_history = deque(maxlen=10) # Keep last 10 translations for context
31
32 # Timing statistics
33 self.translation_times = deque(maxlen=20) # Keep last 20 translation times
34 self.model_load_times = deque(maxlen=5) # Keep last 5 model load times
35 self.total_translations = 0
36 self.total_characters_translated = 0
37
38 # MLX device info
39 self.device = mx.default_device()
40 print(f"🔧 MLX Translation using device: {self.device}")
41
42 self.load_translation_model()
43
44 def load_translation_model(self):
45 """Load MLX translation model (Qwen) with GPU optimization"""
46 try:
47 print(f"🔄 Loading translation model: {config.TRANSLATION_MODEL}")
48 print(f"🔧 Target device: {self.device}")
49 load_start_time = time.time()
50
51 # Clear MLX cache before loading
52 mx.clear_cache()
53
54 self.translation_model, self.translation_tokenizer = load(config.TRANSLATION_MODEL)
55
56 load_time = time.time() - load_start_time
57 self.model_load_times.append(load_time)
58
59 # Check memory usage after loading
60 try:
61 peak_memory = mx.get_peak_memory() / 1024 / 1024 # Convert to MB
62 cache_memory = mx.metal.get_cache_memory() / 1024 / 1024 if hasattr(mx.metal, 'get_cache_memory') else 0
63 print(f"✅ Translation model loaded successfully in {load_time:.2f}s")
64 print(f"🔧 GPU Memory - Peak: {peak_memory:.1f} MB, Cache: {cache_memory:.1f} MB")
65 except Exception as e:
66 print(f"✅ Translation model loaded successfully in {load_time:.2f}s")
67 if config.ENABLE_DEBUG_LOGGING:
68 print(f"Memory info not available: {e}")
69
70 if config.ENABLE_DEBUG_LOGGING:
71 print(f"Model details: {config.TRANSLATION_MODEL}")
72 print(f"Model device: {self.device}")
73
74 except Exception as e:
75 print(f"❌ Error loading translation model: {e}")
76 print("🔄 Falling back to simple translation...")
77
78 def translate_text(self, text, target_language="es", previous_text=None):
79 """Translate text using MLX model with GPU optimization and optional context"""
80 if not text.strip():
81 return ""
82
83 try:
84 if self.translation_model is None:
85 print(f"⚠️ Translation model not loaded, using fallback for: '{text[:30]}...'")
86 return f"[{target_language.upper()}] {text}"
87
88 # Start timing
89 start_time = time.time()
90
91 # Log translation request with context info
92 context_info = f" (with context)" if previous_text else ""
93 print(f"🌐 Starting translation{context_info}: '{text[:50]}{'...' if len(text) > 50 else ''}' -> {target_language.upper()}")
94
95 # Comprehensive language code mapping
96 language_names = {
97 # Major languages
98 "es": "Spanish", "en": "English", "fr": "French", "de": "German",
99 "it": "Italian", "pt": "Portuguese", "ru": "Russian", "zh": "Chinese",
100 "ja": "Japanese", "ko": "Korean", "ar": "Arabic", "hi": "Hindi",
101
102 # European languages
103 "nl": "Dutch", "sv": "Swedish", "da": "Danish", "no": "Norwegian",
104 "fi": "Finnish", "pl": "Polish", "cs": "Czech", "hu": "Hungarian",
105 "ro": "Romanian", "bg": "Bulgarian", "hr": "Croatian", "sk": "Slovak",
106 "sl": "Slovenian", "et": "Estonian", "lv": "Latvian", "lt": "Lithuanian",
107 "mt": "Maltese", "cy": "Welsh", "ga": "Irish", "is": "Icelandic",
108
109 # Regional Spanish/European languages
110 "ca": "Catalan", "eu": "Basque", "gl": "Galician",
111
112 # Slavic languages
113 "mk": "Macedonian", "sq": "Albanian", "sr": "Serbian",
114 "uk": "Ukrainian", "be": "Belarusian",
115
116 # Central Asian languages
117 "kk": "Kazakh", "ky": "Kyrgyz", "uz": "Uzbek", "tg": "Tajik", "mn": "Mongolian",
118
119 # South Asian languages
120 "bn": "Bengali", "te": "Telugu", "ta": "Tamil", "ml": "Malayalam",
121 "kn": "Kannada", "gu": "Gujarati", "pa": "Punjabi", "ne": "Nepali",
122 "si": "Sinhala",
123
124 # Southeast Asian languages
125 "th": "Thai", "vi": "Vietnamese", "my": "Burmese", "km": "Khmer",
126 "lo": "Lao", "tr": "Turkish",
127
128 # Middle Eastern languages
129 "fa": "Persian", "he": "Hebrew", "ka": "Georgian", "am": "Amharic",
130
131 "auto": "auto-detected language"
132 }
133
134 target_lang_name = language_names.get(target_language, target_language.capitalize())
135
136 # Try to detect source language from text features (simple heuristic)
137 # This will be enhanced in future with proper language detection
138 def detect_source_language(text):
139 # Simple character set based detection for common languages
140 # This is a basic heuristic and should be replaced with proper language detection
141 text = text.lower()
142
143 # Check for specific character sets
144 if re.search(r'[а-яА-Я]', text): # Cyrillic
145 return "ru" # Russian as default for Cyrillic
146 elif re.search(r'[一-龯]', text) or re.search(r'[\u4e00-\u9fff]', text): # Chinese characters
147 return "zh"
148 elif re.search(r'[ぁ-んァ-ン]', text): # Japanese kana
149 return "ja"
150 elif re.search(r'[가-힣]', text): # Korean
151 return "ko"
152 elif re.search(r'[א-ת]', text): # Hebrew
153 return "he"
154 elif re.search(r'[ا-ي]', text): # Arabic
155 return "ar"
156 elif re.search(r'[ก-๙]', text): # Thai
157 return "th"
158 # European languages
159 elif re.search(r'[áàâäãåāăąèéêëēėęîïíīįìôöòóœøōõùúûüūğçćčñńňşšßžźż]', text):
160 # Check for specific European language markers
161 if re.search(r'[ñ]', text) and re.search(r'[áéíóú]', text):
162 return "es" # Spanish
163 elif re.search(r'[àâçéèêëîïôùûüÿ]', text):
164 return "fr" # French
165 elif re.search(r'[äöüß]', text):
166 return "de" # German
167 elif re.search(r'[àèéìíîòóù]', text):
168 return "it" # Italian
169 elif re.search(r'[ãõáéíóúçà]', text):
170 return "pt" # Portuguese
171 else:
172 return "en" # Default to English for Latin script
173 else:
174 return "en" # Default to English
175
176 # Get source language
177 source_lang = detect_source_language(text)
178 source_lang_name = language_names.get(source_lang, "unknown language")
179
180 # Build context-aware prompts
181 def build_context_prompt(source_lang, target_lang, text, previous_text=None):
182 """Build explicit prompts for all languages to avoid AI explanations"""
183
184 # ✅ CONTEXTO MEJORADO - Incluir mensaje anterior pero traducir solo el segundo
185 context_section = ""
186 if previous_text and previous_text.strip():
187 context_section = f"""Contexto (mensaje anterior): "{previous_text.strip()}"
188
189IMPORTANTE: El contexto anterior es SOLO para ayudarte a entender mejor el tema. ÚNICAMENTE traduce el texto que aparece después de "Texto a traducir:".
190
191"""
192
193 # ✅ PROMPTS ESPECÍFICOS PARA EVITAR EXPLICACIONES DE IA
194 # Definir instrucciones estrictas por idioma de destino
195 strict_instructions = {
196 "es": "SOLO traduce el texto marcado. NO agregues explicaciones, NOTAS, comentarios, aclaraciones, o cualquier texto adicional. NUNCA pongas NOTAS. ÚNICAMENTE la traducción.",
197 "en": "ONLY translate the marked text. DO NOT add explanations, NOTES, comments, clarifications, or any additional text. NEVER add NOTES. ONLY the translation.",
198 "fr": "SEULEMENT traduisez le texte marqué. N'ajoutez PAS d'explications, de NOTES, de commentaires, de clarifications ou de texte supplémentaire. JAMAIS de NOTES. SEULEMENT la traduction.",
199 "de": "NUR den markierten Text übersetzen. Fügen Sie KEINE Erklärungen, NOTIZEN, Kommentare, Erläuterungen oder zusätzlichen Text hinzu. NIEMALS NOTIZEN. NUR die Übersetzung.",
200 "it": "SOLO traduci il testo contrassegnato. NON aggiungere spiegazioni, NOTE, commenti, chiarimenti o testo aggiuntivo. MAI NOTE. SOLO la traduzione.",
201 "pt": "APENAS traduza o texto marcado. NÃO adicione explicações, NOTAS, comentários, esclarecimentos ou texto adicional. NUNCA NOTAS. APENAS a tradução.",
202 "ru": "ТОЛЬКО переведите отмеченный текст. НЕ добавляйте объяснений, ПРИМЕЧАНИЙ, комментариев, разъяснений или дополнительного текста. НИКОГДА ПРИМЕЧАНИЙ. ТОЛЬКО перевод.",
203 "zh": "仅翻译标记的文本。不要添加解释、注释、评论、说明或任何额外文本。绝不添加注释。仅翻译。",
204 "ja": "マークされたテキストのみを翻訳してください。説明、注釈、コメント、解説、追加テキストは一切追加しないでください。絶対に注釈を追加しないでください。翻訳のみ。",
205 "ko": "표시된 텍스트만 번역하세요. 설명, 메모, 댓글, 해설 또는 추가 텍스트를 추가하지 마세요. 절대 메모를 추가하지 마세요. 번역만.",
206 "ar": "ترجم النص المحدد فقط. لا تضيف تفسيرات أو ملاحظات أو تعليقات أو توضيحات أو أي نص إضافي. لا تضيف ملاحظات أبداً. الترجمة فقط.",
207 "hi": "केवल चिह्नित पाठ का अनुवाद करें। कोई स्पष्टीकरण, नोट्स, टिप्पणी, स्पष्टीकरण या अतिरिक्त पाठ न जोड़ें। कभी भी नोट्स न जोड़ें। केवल अनुवाद।",
208 "nl": "Vertaal ALLEEN de gemarkeerde tekst. Voeg GEEN uitleg, NOTITIES, commentaar, toelichtingen of extra tekst toe. NOOIT NOTITIES. ALLEEN de vertaling.",
209 "sv": "Översätt ENDAST den markerade texten. Lägg INTE till förklaringar, ANTECKNINGAR, kommentarer, förtydliganden eller extra text. ALDRIG ANTECKNINGAR. ENDAST översättningen.",
210 "da": "Oversæt KUN den markerede tekst. Tilføj IKKE forklaringer, NOTER, kommentarer, præciseringer eller ekstra tekst. ALDRIG NOTER. KUN oversættelsen.",
211 "no": "Oversett KUN den merkede teksten. Ikke legg til forklaringer, NOTATER, kommentarer, avklaringer eller ekstra tekst. ALDRI NOTATER. KUN oversettelsen.",
212 "fi": "Käännä VAIN merkitty teksti. Älä lisää selityksiä, MUISTIINPANOJA, kommentteja, selvennyksiä tai ylimääräistä tekstiä. EI KOSKAAN MUISTIINPANOJA. VAIN käännös.",
213 "pl": "Przetłumacz TYLKO oznaczony tekst. NIE dodawaj wyjaśnień, NOTATEK, komentarzy, wyjaśnień ani dodatkowego tekstu. NIGDY NOTATEK. TYLKO tłumaczenie.",
214 "cs": "Přeložte POUZE označený text. NEPŘIDÁVEJTE vysvětlení, POZNÁMKY, komentáře, objasnění nebo další text. NIKDY POZNÁMKY. POUZE překlad.",
215 "hu": "CSAK a megjelölt szöveget fordítsd le. NE adj hozzá magyarázatokat, JEGYZETEKET, megjegyzéseket, magyarázatokat vagy további szöveget. SOHA JEGYZETEKET. CSAK a fordítás.",
216 "ro": "Traduceți DOAR textul marcat. NU adăugați explicații, NOTE, comentarii, clarificări sau text suplimentar. NICIODATĂ NOTE. DOAR traducerea.",
217 "tr": "SADECE işaretli metni çevirin. Açıklama, NOTLAR, yorumlar, açıklamalar veya ek metin eklemeyin. ASLA NOT EKLEMEYİN. SADECE çeviri."
218 }
219
220 # Obtener instrucción estricta
221 instruction = strict_instructions.get(target_lang, "ONLY translate the marked text. DO NOT add explanations, notes, comments, clarifications, or any additional text. ONLY the translation.")
222
223 # ✅ PROMPTS ESPECÍFICOS POR PAR DE IDIOMAS CON CONTEXTO MEJORADO
224 # Inglés -> Español
225 if source_lang == "en" and target_lang == "es":
226 return f"""{context_section}Instrucciones: {instruction}
227
228Texto a traducir (inglés): "{text}"
229
230Traducción al español:"""
231
232 # Español -> Inglés
233 elif source_lang == "es" and target_lang == "en":
234 return f"""{context_section}Instructions: {instruction}
235
236Text to translate (Spanish): "{text}"
237
238English translation:"""
239
240 # Inglés -> Francés
241 elif source_lang == "en" and target_lang == "fr":
242 return f"""{context_section}Instructions: {instruction}
243
244Text to translate (English): "{text}"
245
246French translation:"""
247
248 # Francés -> Inglés
249 elif source_lang == "fr" and target_lang == "en":
250 return f"""{context_section}Instructions: {instruction}
251
252Texte à traduire (français): "{text}"
253
254English translation:"""
255
256 # Inglés -> Alemán
257 elif source_lang == "en" and target_lang == "de":
258 return f"""{context_section}Instructions: {instruction}
259
260Text to translate (English): "{text}"
261
262German translation:"""
263
264 # Alemán -> Inglés
265 elif source_lang == "de" and target_lang == "en":
266 return f"""{context_section}Instructions: {instruction}
267
268Zu übersetzender Text (Deutsch): "{text}"
269
270English translation:"""
271
272 # Inglés -> Italiano
273 elif source_lang == "en" and target_lang == "it":
274 return f"""{context_section}Instructions: {instruction}
275
276Text to translate (English): "{text}"
277
278Italian translation:"""
279
280 # Italiano -> Inglés
281 elif source_lang == "it" and target_lang == "en":
282 return f"""{context_section}Instructions: {instruction}
283
284Testo da tradurre (italiano): "{text}"
285
286English translation:"""
287
288 # Inglés -> Portugués
289 elif source_lang == "en" and target_lang == "pt":
290 return f"""{context_section}Instructions: {instruction}
291
292Text to translate (English): "{text}"
293
294Portuguese translation:"""
295
296 # Portugués -> Inglés
297 elif source_lang == "pt" and target_lang == "en":
298 return f"""{context_section}Instructions: {instruction}
299
300Texto para traduzir (português): "{text}"
301
302English translation:"""
303
304 # Inglés -> Ruso
305 elif source_lang == "en" and target_lang == "ru":
306 return f"""{context_section}Instructions: {instruction}
307
308Text to translate (English): "{text}"
309
310Russian translation:"""
311
312 # Ruso -> Inglés
313 elif source_lang == "ru" and target_lang == "en":
314 return f"""{context_section}Instructions: {instruction}
315
316Текст для перевода (русский): "{text}"
317
318English translation:"""
319
320 # Inglés -> Chino
321 elif source_lang == "en" and target_lang == "zh":
322 return f"""{context_section}Instructions: {instruction}
323
324Text to translate (English): "{text}"
325
326Chinese translation:"""
327
328 # Chino -> Inglés
329 elif source_lang == "zh" and target_lang == "en":
330 return f"""{context_section}Instructions: {instruction}
331
332要翻译的文本 (中文): "{text}"
333
334English translation:"""
335
336 # Inglés -> Japonés
337 elif source_lang == "en" and target_lang == "ja":
338 return f"""{context_section}Instructions: {instruction}
339
340Text to translate (English): "{text}"
341
342Japanese translation:"""
343
344 # Japonés -> Inglés
345 elif source_lang == "ja" and target_lang == "en":
346 return f"""{context_section}Instructions: {instruction}
347
348翻訳するテキスト (日本語): "{text}"
349
350English translation:"""
351
352 # Inglés -> Coreano
353 elif source_lang == "en" and target_lang == "ko":
354 return f"""{context_section}Instructions: {instruction}
355
356Text to translate (English): "{text}"
357
358Korean translation:"""
359
360 # Coreano -> Inglés
361 elif source_lang == "ko" and target_lang == "en":
362 return f"""{context_section}Instructions: {instruction}
363
364번역할 텍스트 (한국어): "{text}"
365
366English translation:"""
367
368 # Inglés -> Árabe
369 elif source_lang == "en" and target_lang == "ar":
370 return f"""{context_section}Instructions: {instruction}
371
372Text to translate (English): "{text}"
373
374Arabic translation:"""
375
376 # Árabe -> Inglés
377 elif source_lang == "ar" and target_lang == "en":
378 return f"""{context_section}Instructions: {instruction}
379
380النص المراد ترجمته (العربية): "{text}"
381
382English translation:"""
383
384 # Inglés -> Hindi
385 elif source_lang == "en" and target_lang == "hi":
386 return f"""{context_section}Instructions: {instruction}
387
388Text to translate (English): "{text}"
389
390Hindi translation:"""
391
392 # Hindi -> Inglés
393 elif source_lang == "hi" and target_lang == "en":
394 return f"""{context_section}Instructions: {instruction}
395
396अनुवाद करने के लिए पाठ (हिंदी): "{text}"
397
398English translation:"""
399
400 # Inglés -> Holandés
401 elif source_lang == "en" and target_lang == "nl":
402 return f"""{context_section}Instructions: {instruction}
403
404Text to translate (English): "{text}"
405
406Dutch translation:"""
407
408 # Holandés -> Inglés
409 elif source_lang == "nl" and target_lang == "en":
410 return f"""{context_section}Instructions: {instruction}
411
412Te vertalen tekst (Nederlands): "{text}"
413
414English translation:"""
415
416 # Inglés -> Sueco
417 elif source_lang == "en" and target_lang == "sv":
418 return f"""{context_section}Instructions: {instruction}
419
420Text to translate (English): "{text}"
421
422Swedish translation:"""
423
424 # Sueco -> Inglés
425 elif source_lang == "sv" and target_lang == "en":
426 return f"""{context_section}Instructions: {instruction}
427
428Text att översätta (svenska): "{text}"
429
430English translation:"""
431
432 # Inglés -> Turco
433 elif source_lang == "en" and target_lang == "tr":
434 return f"""{context_section}Instructions: {instruction}
435
436Text to translate (English): "{text}"
437
438Turkish translation:"""
439
440 # Turco -> Inglés
441 elif source_lang == "tr" and target_lang == "en":
442 return f"""{context_section}Instructions: {instruction}
443
444Çevrilecek metin (Türkçe): "{text}"
445
446English translation:"""
447
448 # Español -> otros idiomas
449 elif source_lang == "es" and target_lang != "en":
450 return f"""{context_section}Instructions: {instruction}
451
452Texto a traducir (español): "{text}"
453
454Traducción al {target_lang_name}:"""
455
456 # Otros idiomas -> Español
457 elif target_lang == "es" and source_lang != "en":
458 return f"""{context_section}Instrucciones: {instruction}
459
460Texto a traducir ({source_lang_name}): "{text}"
461
462Traducción al español:"""
463
464 # Caso genérico con instrucciones estrictas
465 else:
466 return f"""{context_section}Instructions: {instruction}
467
468Text to translate ({source_lang_name}): "{text}"
469
470Translation to {target_lang_name}:"""
471
472 # Build the prompt with context
473 prompt = build_context_prompt(source_lang, target_language, text, previous_text)
474
475 if config.ENABLE_DEBUG_LOGGING:
476 print(f"Using context-aware prompt for {source_lang}->{target_language}")
477 if previous_text:
478 print(f"Context: '{previous_text[:30]}...'")
479
480 # Measure prompt preparation time
481 prompt_time = time.time() - start_time
482
483 # Optimized generation parameters for GPU performance
484 try:
485 # Start model generation timing
486 generation_start_time = time.time()
487
488 # Generate translation with conservative parameters
489 response = generate(
490 self.translation_model,
491 self.translation_tokenizer,
492 prompt=prompt,
493 max_tokens=min(200, len(text.split()) * 8), # ✅ Aumentado de 120 a 200 y de 6x a 8x
494 verbose=False
495 )
496
497 generation_time = time.time() - generation_start_time
498
499 if config.ENABLE_DEBUG_LOGGING:
500 print(f"Translation raw response: '{response}'")
501 print(f"🔧 Generation time: {generation_time:.3f}s on {self.device}")
502
503 # Start post-processing timing
504 postprocess_start_time = time.time()
505
506 # Enhanced cleanup for context-aware translations
507 translated = response.strip()
508
509 # Remove common end tokens and artifacts
510 end_tokens = ["<|endoftext|>", "</s>", "<|end|>", "<|im_end|>", "[INST]", "[/INST]"]
511 for token in end_tokens:
512 if token in translated:
513 translated = translated.split(token)[0].strip()
514
515 # ✅ DETECTAR Y REMOVER EXPLICACIONES DE IA
516 explanation_patterns = [
517 # Inglés
518 r"This translation conveys.*",
519 r"This conveys.*",
520 r"The translation.*",
521 r"This translates to.*",
522 r"This means.*",
523 r"In Spanish.*",
524 r"In English.*",
525 r"Note:.*",
526 r"Note that.*",
527 r"It should be noted.*",
528 r"Please note.*",
529 r"This phrase.*",
530 r"The phrase.*",
531 r"The meaning.*",
532 r"This expression.*",
533 r"In this context.*",
534 r"Here.*translation.*",
535 r"The above.*",
536 r"This captures.*",
537 r"This maintains.*",
538 r"This preserves.*",
539 r"This reflects.*",
540
541 # Español
542 r"Esta traducción.*",
543 r"Esta frase.*",
544 r"El significado.*",
545 r"En español.*",
546 r"En inglés.*",
547 r"Nota:.*",
548 r"Cabe señalar.*",
549 r"Es importante.*",
550 r"La traducción.*",
551 r"Esto significa.*",
552 r"Esta expresión.*",
553 r"En este contexto.*",
554 r"La frase.*",
555 r"Esto transmite.*",
556 r"Esto mantiene.*",
557 r"Esto preserva.*",
558 r"Esto refleja.*",
559
560 # Francés
561 r"Cette traduction.*",
562 r"Cette phrase.*",
563 r"Le sens.*",
564 r"En français.*",
565 r"En anglais.*",
566 r"Note:.*",
567 r"Il convient.*",
568 r"La traduction.*",
569 r"Cela signifie.*",
570 r"Cette expression.*",
571
572 # Alemán
573 r"Diese Übersetzung.*",
574 r"Dieser Satz.*",
575 r"Die Bedeutung.*",
576 r"Auf Deutsch.*",
577 r"Auf Englisch.*",
578 r"Hinweis:.*",
579 r"Es ist wichtig.*",
580 r"Die Übersetzung.*",
581
582 # Italiano
583 r"Questa traduzione.*",
584 r"Questa frase.*",
585 r"Il significato.*",
586 r"In italiano.*",
587 r"In inglese.*",
588 r"Nota:.*",
589 r"È importante.*",
590 r"La traduzione.*",
591
592 # Portugués
593 r"Esta tradução.*",
594 r"Esta frase.*",
595 r"O significado.*",
596 r"Em português.*",
597 r"Em inglês.*",
598 r"Nota:.*",
599 r"É importante.*",
600 r"A tradução.*",
601
602 # Patrones genéricos
603 r"\(.*explains.*\)",
604 r"\(.*explanation.*\)",
605 r"\(.*translation.*\)",
606 r"\(.*note.*\)",
607 r"\(.*nota.*\)",
608 r"\".*translation.*\"$",
609 r"\".*explains.*\"$",
610 r"\".*conveys.*\"$",
611 r"\".*transmite.*\"$",
612 r"\".*significa.*\"$",
613 r"^(This|Esta|Cette|Diese|Questa|Esta)\s+(translation|traducción|traduction|Übersetzung|traduzione|tradução).*",
614
615 # Patrones de fin de explicación
616 r"\..*This is.*$",
617 r"\..*Esto es.*$",
618 r"\..*C'est.*$",
619 r"\..*Das ist.*$",
620 r"\..*Questo è.*$",
621 r"\..*Isto é.*$"
622 ]
623
624 for pattern in explanation_patterns:
625 # Buscar y remover explicaciones al final
626 match = re.search(pattern, translated, re.IGNORECASE | re.DOTALL)
627 if match:
628 translated = translated[:match.start()].strip()
629 print(f"🧹 Removed AI explanation: '{match.group()[:30]}...'")
630 break
631
632 # ✅ DETECTAR Y LIMPIAR REPETICIONES EXCESIVAS MEJORADO
633 # Detectar repeticiones de signos de puntuación
634 punct_repetition = r'([!?.,;:\-_=+])\1{10,}'
635 if re.search(punct_repetition, translated):
636 translated = re.sub(punct_repetition, r'\1', translated)
637 print(f"🧹 Removed excessive punctuation repetition")
638
639 # Detectar repeticiones de palabras/frases
640 word_repetition = r'\b(\w+(?:\s+\w+){0,2})\s+(?:\1\s+){3,}'
641 if re.search(word_repetition, translated, re.IGNORECASE):
642 # Tomar solo la primera ocurrencia antes de la repetición
643 match = re.search(word_repetition, translated, re.IGNORECASE)
644 if match:
645 translated = translated[:match.start()].strip()
646 print(f"🧹 Removed excessive word repetition pattern")
647
648 # Remove training artifacts and prompts that sometimes leak through
649 cleanup_prefixes = [
650 "Human:", "Assistant:", "Translation:", "Traducción:", "Traduction:",
651 "Übersetzung:", "Traduzione:", "Tradução:", "Перевод:", "翻译:",
652 "To translate", "Para traducir", "Pour traduire", "Um zu übersetzen",
653 "I'll translate", "Voy a traducir", "Je vais traduire",
654 "The translation", "La traducción", "La traduction"
655 ]
656
657 for prefix in cleanup_prefixes:
658 if prefix in translated:
659 translated = translated.split(prefix)[0].strip()
660
661 # Language-specific cleanup - remove prompt markers
662 lang_markers = {
663 "Spanish:": "", "English:": "", "French:": "", "German:": "",
664 "Italian:": "", "Portuguese:": "", "Russian:": "", "Chinese:": "",
665 "Japanese:": "", "Korean:": "", "Arabic:": "", "Hindi:": "",
666 "Español:": "", "Inglés:": "", "Francés:": "", "Alemán:": "",
667 "Italiano:": "", "Portugués:": "", "Ruso:": "", "Chino:": ""
668 }
669
670 for marker in lang_markers:
671 if translated.startswith(marker):
672 translated = translated[len(marker):].strip()
673 break
674 # Also check for lowercase versions
675 if translated.startswith(marker.lower()):
676 translated = translated[len(marker):].strip()
677 break
678
679 # Remove quotes if the entire translation is wrapped in them
680 if ((translated.startswith('"') and translated.endswith('"')) or
681 (translated.startswith("'") and translated.endswith("'"))):
682 translated = translated[1:-1].strip()
683
684 # ✅ MANEJO MEJORADO DE ORACIONES MÚLTIPLES - MENOS AGRESIVO
685 # Solo cortar si hay evidencia clara de que es un error (muchas oraciones muy cortas)
686 sentences = re.split(r'[.!?]+\s+', translated)
687 if len(sentences) > 4: # Más de 4 oraciones, revisar
688 # Contar oraciones sustanciales (más de 5 palabras)
689 substantial_sentences = [s for s in sentences if len(s.split()) > 5]
690 short_sentences = [s for s in sentences if len(s.split()) <= 5]
691
692 # Si hay muchas oraciones cortas vs sustanciales, posible error
693 if len(short_sentences) > len(substantial_sentences) and len(short_sentences) > 2:
694 # Tomar solo las primeras 2-3 oraciones sustanciales
695 if substantial_sentences:
696 translated = '. '.join(substantial_sentences[:3])
697 if not translated.endswith(('.', '!', '?')):
698 translated += '.'
699 print(f"🧹 Trimmed excessive short sentences")
700
701 # ✅ DETECTAR Y ELIMINAR "NOTA:" O "NOTE:" AL FINAL ESPECÍFICAMENTE
702 # Eliminar patrones específicos de notas al final de la traducción
703 note_patterns_at_end = [
704 r'\s*NOTA\s*[:.].*$', # NOTA: o NOTA. al final
705 r'\s*NOTE\s*[:.].*$', # NOTE: o NOTE. al final
706 r'\s*Nota\s*[:.].*$', # Nota: o Nota. al final
707 r'\s*Note\s*[:.].*$', # Note: o Note. al final
708 r'\s*NOTES\s*[:.].*$', # NOTES: o NOTES. al final
709 r'\s*Notes\s*[:.].*$', # Notes: o Notes. al final
710 r'\s*NOTAS\s*[:.].*$', # NOTAS: o NOTAS. al final
711 r'\s*Notas\s*[:.].*$', # Notas: o Notas. al final
712 r'\s*\(NOTA\).*$', # (NOTA) al final
713 r'\s*\(NOTE\).*$', # (NOTE) al final
714 r'\s*\(Nota\).*$', # (Nota) al final
715 r'\s*\(Note\).*$', # (Note) al final
716 ]
717
718 for pattern in note_patterns_at_end:
719 before_cleanup = translated
720 translated = re.sub(pattern, '', translated, flags=re.IGNORECASE).strip()
721 if before_cleanup != translated:
722 print(f"🧹 Removed NOTE pattern at end: '{before_cleanup[len(translated):].strip()}'")
723 break # Solo eliminar el primer patrón encontrado
724
725 # Final cleanup
726 translated = translated.strip(' "\'`.,:-*()[]{}')
727
728 # ✅ AGREGAR PUNTO FINAL SI ES NECESARIO
729 if len(translated) > 10 and not translated.endswith(('.', '!', '?', ':')):
730 translated += '.'
731
732 postprocess_time = time.time() - postprocess_start_time
733
734 # Enhanced validation
735 if not translated or len(translated) < 2:
736 total_time = time.time() - start_time
737 print(f"⚠️ Translation too short: '{translated}' (Total: {total_time:.2f}s)")
738 if config.ENABLE_DEBUG_LOGGING:
739 print(f"Translation too short: '{translated}'")
740 return f"[{target_language.upper()}] {text}"
741
742 # ✅ VALIDACIÓN MEJORADA PARA DETECTAR TRADUCCIONES SIN SENTIDO
743 if self._is_nonsensical_translation(translated, text):
744 total_time = time.time() - start_time
745 print(f"⚠️ Nonsensical translation detected: '{translated}' (Total: {total_time:.2f}s)")
746 return f"[{target_language.upper()}] {text}"
747
748 # Don't return if it's exactly the same as input (unless it's a proper noun or very short)
749 if (translated.lower().strip() == text.lower().strip() and
750 len(text.split()) > 1 and
751 not text[0].isupper()): # Allow proper nouns to remain the same
752 total_time = time.time() - start_time
753 print(f"⚠️ Translation same as original: '{translated}' (Total: {total_time:.2f}s)")
754 if config.ENABLE_DEBUG_LOGGING:
755 print(f"Translation same as original: '{translated}'")
756 return f"[{target_language.upper()}] {text}"
757
758 # Calculate final timing and statistics
759 total_time = time.time() - start_time
760 self.translation_times.append(total_time)
761 self.total_translations += 1
762 self.total_characters_translated += len(text)
763
764 # Calculate statistics
765 avg_time = sum(self.translation_times) / len(self.translation_times)
766 chars_per_second = len(text) / total_time if total_time > 0 else 0
767
768 # Enhanced timing logs with GPU info and context info
769 context_marker = " (+context)" if previous_text else ""
770 print(f"✅ Translation complete{context_marker}: '{translated[:50]}{'...' if len(translated) > 50 else ''}'")
771 print(f"⏱️ Timing - Prompt: {prompt_time:.3f}s | Generation: {generation_time:.3f}s | Post-proc: {postprocess_time:.3f}s | Total: {total_time:.2f}s")
772 print(f"🔧 Device: {self.device} | Performance: {chars_per_second:.1f} chars/sec")
773 print(f"📈 Stats - Avg: {avg_time:.2f}s | Count: {self.total_translations} | Total chars: {self.total_characters_translated}")
774
775 if config.ENABLE_DEBUG_LOGGING:
776 print(f"Final translation: '{text}' -> '{translated}'")
777
778 return translated
779
780 except Exception as gen_error:
781 total_time = time.time() - start_time
782 print(f"❌ Generation error after {total_time:.2f}s on {self.device}: {gen_error}")
783 if config.ENABLE_DEBUG_LOGGING:
784 print(f"Generation error: {gen_error}")
785 return f"[{target_language.upper()}] {text}"
786
787 except Exception as e:
788 total_time = time.time() - start_time if 'start_time' in locals() else 0
789 print(f"❌ Translation error after {total_time:.2f}s: {e}")
790 if config.ENABLE_DEBUG_LOGGING:
791 print(f"Translation error: {e}")
792 return f"[{target_language.upper()}] {text}"
793
794 finally:
795 # Optimize GPU memory after each translation if enabled
796 if hasattr(config, 'MLX_CACHE_OPTIMIZATION') and config.MLX_CACHE_OPTIMIZATION:
797 if self.total_translations % 10 == 0: # Clear cache every 10 translations
798 self.optimize_gpu_memory()
799
800 def translate_with_context(self, text, target_language="es", use_auto_context=False):
801 """Translate text with automatic context from previous translations"""
802
803 # Get previous translation for context if enabled
804 previous_text = None
805 if use_auto_context and self.translation_history:
806 # Use the most recent translation as context
807 previous_entry = self.translation_history[-1]
808 previous_text = previous_entry.get('original_text', '')
809
810 # ✅ SER MÁS CONSERVADOR CON EL CONTEXTO
811 # Solo usar contexto si es muy relevante y no muy largo
812 if len(previous_text.split()) > 2 and len(previous_text.split()) < 15:
813 # Verificar que el contexto anterior sea del mismo idioma aproximadamente
814 current_words = set(text.lower().split()[:5]) # Primeras 5 palabras
815 previous_words = set(previous_text.lower().split()[:5]) # Primeras 5 palabras
816
817 # Solo usar contexto si hay alguna palabra en común (mismo tema)
818 if current_words & previous_words: # Intersección no vacía
819 if config.ENABLE_DEBUG_LOGGING:
820 print(f"📝 Using automatic context: '{previous_text[:30]}...'")
821 else:
822 previous_text = None # No usar contexto si no hay relación
823 else:
824 previous_text = None # No usar contexto si es muy corto o muy largo
825
826 # Perform the translation
827 translated = self.translate_text(text, target_language, previous_text)
828
829 # Store in history
830 history_entry = {
831 'original_text': text,
832 'translated_text': translated,
833 'target_language': target_language,
834 'timestamp': time.time(),
835 'used_context': previous_text is not None
836 }
837 self.translation_history.append(history_entry)
838
839 return translated
840
841 def get_translation_history(self, limit=5):
842 """Get recent translation history"""
843 recent_history = list(self.translation_history)[-limit:]
844 return recent_history
845
846 def clear_translation_history(self):
847 """Clear translation history"""
848 self.translation_history.clear()
849 print("🗑️ Translation history cleared")
850
851 def get_gpu_performance_info(self):
852 """Get current GPU performance and memory information"""
853 try:
854 device_info = {
855 "device": str(self.device),
856 "peak_memory_mb": 0,
857 "cache_memory_mb": 0,
858 "is_gpu": str(self.device).startswith("Device(gpu")
859 }
860
861 try:
862 device_info["peak_memory_mb"] = mx.get_peak_memory() / 1024 / 1024
863 except:
864 pass
865
866 try:
867 # Use the non-deprecated function
868 device_info["cache_memory_mb"] = mx.get_cache_memory() / 1024 / 1024
869 except:
870 try:
871 # Fallback to deprecated function if new one doesn't exist
872 device_info["cache_memory_mb"] = mx.metal.get_cache_memory() / 1024 / 1024
873 except:
874 pass
875
876 return device_info
877 except Exception as e:
878 if config.ENABLE_DEBUG_LOGGING:
879 print(f"Error getting GPU info: {e}")
880 return {"device": str(self.device), "peak_memory_mb": 0, "cache_memory_mb": 0, "is_gpu": True}
881
882 def optimize_gpu_memory(self):
883 """Optimize GPU memory usage by clearing caches"""
884 try:
885 mx.clear_cache()
886 if config.ENABLE_DEBUG_LOGGING:
887 print("🔧 MLX cache cleared for memory optimization")
888 except Exception as e:
889 if config.ENABLE_DEBUG_LOGGING:
890 print(f"Error clearing MLX cache: {e}")
891
892 def _is_nonsensical_translation(self, translation, original):
893 # ✅ VALIDACIÓN MEJORADA PARA DETECTAR TRADUCCIONES SIN SENTIDO
894
895 # Detectar mezclas de idiomas obvias
896 mixed_language_patterns = [
897 r"c'è\s+la\s+", # Italiano mezclado con otro idioma
898 r"\w+\s+la\s+armi", # Patrones específicos sin sentido
899 r"[а-я]+\s+[a-z]+\s+[а-я]+", # Cirílico mezclado
900 r"[一-龯]\s+[a-z]+\s+[一-龯]", # Chino mezclado
901 ]
902
903 for pattern in mixed_language_patterns:
904 if re.search(pattern, translation.lower()):
905 return True
906
907 # ✅ VALIDACIÓN MEJORADA DE LONGITUD - ser menos estricto
908 original_words = len(original.split())
909 translated_words = len(translation.split())
910
911 # Solo marcar como sin sentido si es MUY corta (menos del 15%) Y el original es largo
912 if (translated_words < original_words * 0.15 and
913 original_words > 8 and
914 translated_words < 3): # Muy restrictivo
915 return True
916
917 # Detectar si solo hay puntuación o símbolos
918 clean_translation = re.sub(r'[^\w\s]', '', translation).strip()
919 if len(clean_translation) < 2:
920 return True
921
922 return False