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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Smart Multilingual Text Translator
|
| 4 |
+
==================================
|
| 5 |
+
Smart translation application with automatic language detection
|
| 6 |
+
Based on Hugging Face models and Gradio
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import warnings
|
| 12 |
+
from typing import Dict, List, Tuple, Optional
|
| 13 |
+
import logging
|
| 14 |
+
|
| 15 |
+
# Configure logging
|
| 16 |
+
logging.basicConfig(level=logging.INFO)
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
# Suppress unnecessary warnings
|
| 20 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
| 21 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
import gradio as gr
|
| 25 |
+
import torch
|
| 26 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
|
| 27 |
+
from langdetect import detect, detect_langs
|
| 28 |
+
import numpy as np
|
| 29 |
+
except ImportError as e:
|
| 30 |
+
print(f"❌ Import error: {e}")
|
| 31 |
+
print("💡 Install required packages: pip install gradio torch transformers langdetect")
|
| 32 |
+
exit(1)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class SmartTranslator:
|
| 36 |
+
"""Main class for the smart translation application"""
|
| 37 |
+
|
| 38 |
+
def __init__(self, config_file: str = "map_model_lang.json"):
|
| 39 |
+
"""Initialize the smart translator"""
|
| 40 |
+
self.config = self._load_config(config_file)
|
| 41 |
+
self.models_cache = {} # Cache for loaded models
|
| 42 |
+
self.pipelines_cache = {} # Cache for pipelines
|
| 43 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 44 |
+
logger.info(f"🚀 Initializing translator on {self.device}")
|
| 45 |
+
|
| 46 |
+
# Default target languages
|
| 47 |
+
self.target_languages = self.config.get("target_languages", {}).get("primary", ["en", "fr", "es"])
|
| 48 |
+
|
| 49 |
+
def _load_config(self, config_file: str) -> Dict:
|
| 50 |
+
"""Load configuration file"""
|
| 51 |
+
try:
|
| 52 |
+
if os.path.exists(config_file):
|
| 53 |
+
with open(config_file, 'r', encoding='utf-8') as f:
|
| 54 |
+
return json.load(f)
|
| 55 |
+
else:
|
| 56 |
+
logger.warning(f"⚠️ Config file {config_file} not found, using default settings")
|
| 57 |
+
return self._get_default_config()
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logger.error(f"❌ Error loading configuration: {e}")
|
| 60 |
+
return self._get_default_config()
|
| 61 |
+
|
| 62 |
+
def _get_default_config(self) -> Dict:
|
| 63 |
+
"""Default configuration in case file is not found"""
|
| 64 |
+
return {
|
| 65 |
+
"translation_models": {
|
| 66 |
+
"to_english": {
|
| 67 |
+
"he": "Helsinki-NLP/opus-mt-he-en",
|
| 68 |
+
"ar": "Helsinki-NLP/opus-mt-ar-en",
|
| 69 |
+
"fr": "Helsinki-NLP/opus-mt-fr-en",
|
| 70 |
+
"es": "Helsinki-NLP/opus-mt-es-en",
|
| 71 |
+
"de": "Helsinki-NLP/opus-mt-de-en"
|
| 72 |
+
},
|
| 73 |
+
"from_english": {
|
| 74 |
+
"he": "Helsinki-NLP/opus-mt-en-he",
|
| 75 |
+
"ar": "Helsinki-NLP/opus-mt-en-ar",
|
| 76 |
+
"fr": "Helsinki-NLP/opus-mt-en-fr",
|
| 77 |
+
"es": "Helsinki-NLP/opus-mt-en-es",
|
| 78 |
+
"de": "Helsinki-NLP/opus-mt-en-de"
|
| 79 |
+
}
|
| 80 |
+
},
|
| 81 |
+
"language_names": {
|
| 82 |
+
"he": "Hebrew", "en": "English", "ar": "Arabic",
|
| 83 |
+
"fr": "French", "es": "Spanish", "de": "German"
|
| 84 |
+
},
|
| 85 |
+
"target_languages": {"primary": ["he", "fr", "es"]},
|
| 86 |
+
"configuration": {
|
| 87 |
+
"max_length": 512, "num_beams": 4, "temperature": 1.0,
|
| 88 |
+
"do_sample": False, "early_stopping": True
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
def detect_language(self, text: str) -> Tuple[str, float]:
|
| 93 |
+
"""Detect text language"""
|
| 94 |
+
if not text.strip():
|
| 95 |
+
return "unknown", 0.0
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
# Basic detection
|
| 99 |
+
detected = detect(text)
|
| 100 |
+
|
| 101 |
+
# Detailed detection with confidence level
|
| 102 |
+
detailed = detect_langs(text)
|
| 103 |
+
confidence = detailed[0].prob if detailed else 0.0
|
| 104 |
+
|
| 105 |
+
return detected, confidence
|
| 106 |
+
|
| 107 |
+
except Exception as e:
|
| 108 |
+
logger.warning(f"⚠️ Language detection error: {e}")
|
| 109 |
+
return "en", 0.5 # Default fallback
|
| 110 |
+
|
| 111 |
+
def _get_model_name(self, source_lang: str, target_lang: str) -> Optional[str]:
|
| 112 |
+
"""Get appropriate model name for language pair"""
|
| 113 |
+
models = self.config["translation_models"]
|
| 114 |
+
|
| 115 |
+
# Check for direct model
|
| 116 |
+
direct_key = f"{source_lang}_{target_lang}"
|
| 117 |
+
if "direct_pairs" in models and direct_key in models["direct_pairs"]:
|
| 118 |
+
return models["direct_pairs"][direct_key]
|
| 119 |
+
|
| 120 |
+
# Translation to English
|
| 121 |
+
if target_lang == "en" and source_lang in models["to_english"]:
|
| 122 |
+
return models["to_english"][source_lang]
|
| 123 |
+
|
| 124 |
+
# Translation from English
|
| 125 |
+
if source_lang == "en" and target_lang in models["from_english"]:
|
| 126 |
+
return models["from_english"][target_lang]
|
| 127 |
+
|
| 128 |
+
return None
|
| 129 |
+
|
| 130 |
+
def _load_translation_pipeline(self, model_name: str) -> Optional[object]:
|
| 131 |
+
"""Load translation pipeline"""
|
| 132 |
+
if model_name in self.pipelines_cache:
|
| 133 |
+
return self.pipelines_cache[model_name]
|
| 134 |
+
|
| 135 |
+
try:
|
| 136 |
+
logger.info(f"📥 Loading model: {model_name}")
|
| 137 |
+
|
| 138 |
+
# Create pipeline with better error handling
|
| 139 |
+
translator = pipeline(
|
| 140 |
+
"translation",
|
| 141 |
+
model=model_name,
|
| 142 |
+
device=0 if self.device == "cuda" else -1,
|
| 143 |
+
max_length=512,
|
| 144 |
+
clean_up_tokenization_spaces=True
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# Save to cache
|
| 148 |
+
self.pipelines_cache[model_name] = translator
|
| 149 |
+
logger.info(f"✅ Model {model_name} loaded successfully")
|
| 150 |
+
|
| 151 |
+
return translator
|
| 152 |
+
|
| 153 |
+
except Exception as e:
|
| 154 |
+
logger.error(f"❌ Error loading model {model_name}: {e}")
|
| 155 |
+
print(f"❌ Failed to load model {model_name}: {str(e)}")
|
| 156 |
+
return None
|
| 157 |
+
|
| 158 |
+
def translate_via_english(self, text: str, source_lang: str, target_lang: str) -> Optional[str]:
|
| 159 |
+
"""Translate via English as intermediate language"""
|
| 160 |
+
try:
|
| 161 |
+
# Translate to English
|
| 162 |
+
to_en_model = self._get_model_name(source_lang, "en")
|
| 163 |
+
if not to_en_model:
|
| 164 |
+
return None
|
| 165 |
+
|
| 166 |
+
to_en_pipeline = self._load_translation_pipeline(to_en_model)
|
| 167 |
+
if not to_en_pipeline:
|
| 168 |
+
return None
|
| 169 |
+
|
| 170 |
+
english_text = to_en_pipeline(text)[0]['translation_text']
|
| 171 |
+
|
| 172 |
+
# Translate from English to target language
|
| 173 |
+
from_en_model = self._get_model_name("en", target_lang)
|
| 174 |
+
if not from_en_model:
|
| 175 |
+
return None
|
| 176 |
+
|
| 177 |
+
from_en_pipeline = self._load_translation_pipeline(from_en_model)
|
| 178 |
+
if not from_en_pipeline:
|
| 179 |
+
return None
|
| 180 |
+
|
| 181 |
+
final_translation = from_en_pipeline(english_text)[0]['translation_text']
|
| 182 |
+
return final_translation
|
| 183 |
+
|
| 184 |
+
except Exception as e:
|
| 185 |
+
logger.error(f"❌ Error in English pivot translation: {e}")
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
def translate_text(self, text: str, source_lang: str, target_lang: str) -> Optional[str]:
|
| 189 |
+
"""Translate text between languages"""
|
| 190 |
+
if not text.strip():
|
| 191 |
+
return ""
|
| 192 |
+
|
| 193 |
+
if source_lang == target_lang:
|
| 194 |
+
return text
|
| 195 |
+
|
| 196 |
+
try:
|
| 197 |
+
# Try direct translation
|
| 198 |
+
model_name = self._get_model_name(source_lang, target_lang)
|
| 199 |
+
|
| 200 |
+
if model_name:
|
| 201 |
+
pipeline_obj = self._load_translation_pipeline(model_name)
|
| 202 |
+
if pipeline_obj:
|
| 203 |
+
result = pipeline_obj(text)
|
| 204 |
+
return result[0]['translation_text']
|
| 205 |
+
|
| 206 |
+
# If no direct model, try via English
|
| 207 |
+
if source_lang != "en" and target_lang != "en":
|
| 208 |
+
logger.info(f"🔄 Translating {source_lang}→{target_lang} via English")
|
| 209 |
+
return self.translate_via_english(text, source_lang, target_lang)
|
| 210 |
+
|
| 211 |
+
return f"❌ No translation model found for {source_lang}→{target_lang}"
|
| 212 |
+
|
| 213 |
+
except Exception as e:
|
| 214 |
+
logger.error(f"❌ Translation error: {e}")
|
| 215 |
+
return f"❌ Translation error: {str(e)}"
|
| 216 |
+
|
| 217 |
+
def get_language_name(self, lang_code: str) -> str:
|
| 218 |
+
"""Get language name in local language"""
|
| 219 |
+
return self.config.get("language_names", {}).get(lang_code, lang_code.upper())
|
| 220 |
+
|
| 221 |
+
def process_translation_request(self, input_text: str) -> Tuple[str, str, Dict[str, str]]:
|
| 222 |
+
"""Process complete translation request"""
|
| 223 |
+
if not input_text.strip():
|
| 224 |
+
return "", "❌ Please enter text to translate", {}
|
| 225 |
+
|
| 226 |
+
# Language detection
|
| 227 |
+
detected_lang, confidence = self.detect_language(input_text)
|
| 228 |
+
lang_name = self.get_language_name(detected_lang)
|
| 229 |
+
|
| 230 |
+
# Prepare detected language info
|
| 231 |
+
language_info = f"{lang_name} ({detected_lang}) - Confidence: {confidence:.2%}"
|
| 232 |
+
|
| 233 |
+
# Translate to all target languages
|
| 234 |
+
translations = {}
|
| 235 |
+
|
| 236 |
+
for target_lang in self.target_languages:
|
| 237 |
+
if target_lang != detected_lang: # Don't translate to same language
|
| 238 |
+
target_name = self.get_language_name(target_lang)
|
| 239 |
+
translation = self.translate_text(input_text, detected_lang, target_lang)
|
| 240 |
+
|
| 241 |
+
if translation:
|
| 242 |
+
translations[f"{target_name} ({target_lang})"] = translation
|
| 243 |
+
else:
|
| 244 |
+
translations[f"{target_name} ({target_lang})"] = "❌ Translation not available"
|
| 245 |
+
|
| 246 |
+
return detected_lang, language_info, translations
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def create_gradio_interface():
|
| 250 |
+
"""Create Gradio interface"""
|
| 251 |
+
|
| 252 |
+
# Initialize translator
|
| 253 |
+
translator = SmartTranslator()
|
| 254 |
+
|
| 255 |
+
def translate_interface(input_text: str) -> Tuple[str, str]:
|
| 256 |
+
"""Interface function for translation"""
|
| 257 |
+
if not input_text.strip():
|
| 258 |
+
return "❌ Please enter text to translate", ""
|
| 259 |
+
|
| 260 |
+
try:
|
| 261 |
+
detected_lang, language_info, translations = translator.process_translation_request(input_text)
|
| 262 |
+
|
| 263 |
+
# Format results
|
| 264 |
+
result_html = f"""
|
| 265 |
+
<div style="font-family: Arial, sans-serif; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white;">
|
| 266 |
+
<h3 style="margin-top: 0; color: #fff;">🎯 Translation Results</h3>
|
| 267 |
+
|
| 268 |
+
<div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px; margin: 10px 0;">
|
| 269 |
+
<strong>📝 Original Text:</strong><br>
|
| 270 |
+
<div style="background: rgba(255,255,255,0.2); padding: 10px; border-radius: 5px; margin: 5px 0;">
|
| 271 |
+
{input_text}
|
| 272 |
+
</div>
|
| 273 |
+
</div>
|
| 274 |
+
|
| 275 |
+
<div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px; margin: 10px 0;">
|
| 276 |
+
<strong>🌍 Detected Language:</strong><br>
|
| 277 |
+
<div style="color: #FFD700; font-size: 1.1em; margin: 5px 0;">
|
| 278 |
+
{language_info}
|
| 279 |
+
</div>
|
| 280 |
+
</div>
|
| 281 |
+
"""
|
| 282 |
+
|
| 283 |
+
if translations:
|
| 284 |
+
result_html += '<div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px; margin: 10px 0;"><strong>🔄 Translations:</strong><br>'
|
| 285 |
+
|
| 286 |
+
for lang_name, translation in translations.items():
|
| 287 |
+
result_html += f"""
|
| 288 |
+
<div style="background: rgba(255,255,255,0.2); padding: 10px; border-radius: 5px; margin: 8px 0;">
|
| 289 |
+
<strong style="color: #FFD700;">{lang_name}:</strong><br>
|
| 290 |
+
<div style="margin-top: 5px; font-size: 1.05em;">
|
| 291 |
+
{translation}
|
| 292 |
+
</div>
|
| 293 |
+
</div>
|
| 294 |
+
"""
|
| 295 |
+
result_html += '</div>'
|
| 296 |
+
else:
|
| 297 |
+
result_html += '<div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px; margin: 10px 0; color: #FFB6C1;">❌ No translations available</div>'
|
| 298 |
+
|
| 299 |
+
result_html += '</div>'
|
| 300 |
+
|
| 301 |
+
# Simple text for second tab
|
| 302 |
+
simple_result = f"""
|
| 303 |
+
Detected Language: {language_info}
|
| 304 |
+
|
| 305 |
+
Translations:
|
| 306 |
+
{chr(10).join([f"{lang}: {trans}" for lang, trans in translations.items()])}
|
| 307 |
+
"""
|
| 308 |
+
|
| 309 |
+
return result_html, simple_result
|
| 310 |
+
|
| 311 |
+
except Exception as e:
|
| 312 |
+
error_msg = f"❌ Processing error: {str(e)}"
|
| 313 |
+
return error_msg, error_msg
|
| 314 |
+
|
| 315 |
+
# Interface styling
|
| 316 |
+
css = """
|
| 317 |
+
.gradio-container {
|
| 318 |
+
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
|
| 319 |
+
color: white;
|
| 320 |
+
}
|
| 321 |
+
.gr-button {
|
| 322 |
+
background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
|
| 323 |
+
border: none;
|
| 324 |
+
color: white;
|
| 325 |
+
font-weight: bold;
|
| 326 |
+
}
|
| 327 |
+
.gr-button:hover {
|
| 328 |
+
background: linear-gradient(45deg, #764ba2 0%, #667eea 100%);
|
| 329 |
+
transform: translateY(-2px);
|
| 330 |
+
box-shadow: 0 5px 15px rgba(0,0,0,0.3);
|
| 331 |
+
}
|
| 332 |
+
"""
|
| 333 |
+
|
| 334 |
+
# Create interface
|
| 335 |
+
with gr.Blocks(css=css, title="🌍 Smart Multilingual Translator", theme=gr.themes.Soft()) as app:
|
| 336 |
+
|
| 337 |
+
gr.Markdown(
|
| 338 |
+
"""
|
| 339 |
+
# 🌍 Smart Multilingual Translator
|
| 340 |
+
### Automatic Language Detection and Multi-Language Translation
|
| 341 |
+
**Powered by Advanced Hugging Face Models**
|
| 342 |
+
""",
|
| 343 |
+
elem_id="header"
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
with gr.Row():
|
| 347 |
+
with gr.Column(scale=1):
|
| 348 |
+
input_text = gr.Textbox(
|
| 349 |
+
label="📝 Enter Text to Translate",
|
| 350 |
+
placeholder="Type or paste text in any language here...",
|
| 351 |
+
lines=5,
|
| 352 |
+
max_lines=10
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
translate_btn = gr.Button(
|
| 356 |
+
"🚀 Translate Now",
|
| 357 |
+
variant="primary",
|
| 358 |
+
size="lg"
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
gr.Examples(
|
| 362 |
+
examples=[
|
| 363 |
+
["Hello world! How are you?"],
|
| 364 |
+
["שלום עולם! איך הולך?"],
|
| 365 |
+
["مرحبا بالعالم! كيف حالك؟"],
|
| 366 |
+
["Bonjour le monde! Comment allez-vous?"],
|
| 367 |
+
["¡Hola mundo! ¿Cómo estás?"],
|
| 368 |
+
["Artificial Intelligence is transforming our world"],
|
| 369 |
+
["Machine learning enables computers to learn patterns"]
|
| 370 |
+
],
|
| 371 |
+
inputs=input_text,
|
| 372 |
+
label="💡 Example Texts"
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
with gr.Row():
|
| 376 |
+
with gr.Column():
|
| 377 |
+
with gr.Tabs():
|
| 378 |
+
with gr.TabItem("🎨 Styled View"):
|
| 379 |
+
styled_output = gr.HTML(
|
| 380 |
+
label="Translation Results",
|
| 381 |
+
elem_id="styled_output"
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
with gr.TabItem("📄 Plain Text View"):
|
| 385 |
+
simple_output = gr.Textbox(
|
| 386 |
+
label="Results in Plain Text",
|
| 387 |
+
lines=10,
|
| 388 |
+
max_lines=20,
|
| 389 |
+
interactive=False
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
# Connect functions
|
| 393 |
+
translate_btn.click(
|
| 394 |
+
fn=translate_interface,
|
| 395 |
+
inputs=[input_text],
|
| 396 |
+
outputs=[styled_output, simple_output]
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
# Additional information
|
| 400 |
+
gr.Markdown(
|
| 401 |
+
"""
|
| 402 |
+
---
|
| 403 |
+
### 📊 Technical Information
|
| 404 |
+
- **Supported Languages**: Hebrew, English, Arabic, French, Spanish, German and more
|
| 405 |
+
- **Translation Models**: Helsinki-NLP MarianMT
|
| 406 |
+
- **Language Detection**: Google langdetect
|
| 407 |
+
- **Built with**: Hugging Face Transformers + Gradio
|
| 408 |
+
|
| 409 |
+
💡 **Tip**: The system automatically detects language and translates to predefined target languages
|
| 410 |
+
"""
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
return app
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def main():
|
| 417 |
+
"""Run the main application"""
|
| 418 |
+
print("🚀 Starting Smart Translation Application...")
|
| 419 |
+
|
| 420 |
+
try:
|
| 421 |
+
app = create_gradio_interface()
|
| 422 |
+
|
| 423 |
+
# Launch application
|
| 424 |
+
app.launch(
|
| 425 |
+
server_name="0.0.0.0", # Access from anywhere
|
| 426 |
+
server_port=7860, # Standard port
|
| 427 |
+
share=True, # Public link
|
| 428 |
+
debug=False, # No debug in production
|
| 429 |
+
show_error=True, # Show errors
|
| 430 |
+
inbrowser=True # Auto-open in browser
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
except Exception as e:
|
| 434 |
+
logger.error(f"❌ Error launching application: {e}")
|
| 435 |
+
print(f"❌ Error: {e}")
|
| 436 |
+
print("💡 Install required packages: pip install gradio torch transformers langdetect")
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
if __name__ == "__main__":
|
| 440 |
+
main()
|
map_model_lang.json
ADDED
|
@@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t-pt-en",
|
| 11 |
+
"ru": "Helsinki-NLP/opus-mt-ru-en",
|
| 12 |
+
"zh": "Helsinki-NLP/opus-mt-zh-en",
|
| 13 |
+
"ja": "Helsinki-NLP/opus-mt-ja-en"
|
| 14 |
+
},
|
| 15 |
+
"from_english": {
|
| 16 |
+
"he": "Helsinki-NLP/opus-mt-en-he",
|
| 17 |
+
"ar": "Helsinki-NLP/opus-mt-en-ar",
|
| 18 |
+
"fr": "Helsinki-NLP/opus-mt-en-fr",
|
| 19 |
+
"es": "Helsinki-NLP/opus-mt-en-es",
|
| 20 |
+
"de": "Helsinki-NLP/opus-mt-en-de",
|
| 21 |
+
"it": "Helsinki-NLP/opus-mt-en-it",
|
| 22 |
+
"pt": "Helsinki-NLP/opus-mt-en-pt",
|
| 23 |
+
"ru": "Helsinki-NLP/opus-mt-en-ru"
|
| 24 |
+
},
|
| 25 |
+
"direct_pairs": {
|
| 26 |
+
"he_ar": "Helsinki-NLP/opus-mt-he-ar",
|
| 27 |
+
"ar_he": "Helsinki-NLP/opus-mt-ar-he",
|
| 28 |
+
"fr_es": "Helsinki-NLP/opus-mt-fr-es",
|
| 29 |
+
"es_fr": "Helsinki-NLP/opus-mt-es-fr",
|
| 30 |
+
"de_fr": "Helsinki-NLP/opus-mt-de-fr",
|
| 31 |
+
"fr_de": "Helsinki-NLP/opus-mt-fr-de"
|
| 32 |
+
}
|
| 33 |
+
},
|
| 34 |
+
"language_codes": {
|
| 35 |
+
"hebrew": "he",
|
| 36 |
+
"english": "en",
|
| 37 |
+
"arabic": "ar",
|
| 38 |
+
"french": "fr",
|
| 39 |
+
"spanish": "es",
|
| 40 |
+
"german": "de",
|
| 41 |
+
"italian": "it",
|
| 42 |
+
"portuguese": "pt",
|
| 43 |
+
"russian": "ru",
|
| 44 |
+
"chinese": "zh",
|
| 45 |
+
"japanese": "ja"
|
| 46 |
+
},
|
| 47 |
+
"language_names": {
|
| 48 |
+
"he": "עברית",
|
| 49 |
+
"en": "English",
|
| 50 |
+
"ar": "العربية",
|
| 51 |
+
"fr": "Français",
|
| 52 |
+
"es": "Español",
|
| 53 |
+
"de": "Deutsch",
|
| 54 |
+
"it": "Italiano",
|
| 55 |
+
"pt": "Português",
|
| 56 |
+
"ru": "Русский",
|
| 57 |
+
"zh": "中文",
|
| 58 |
+
"ja": "日本語"
|
| 59 |
+
},
|
| 60 |
+
"target_languages": {
|
| 61 |
+
"primary": ["he", "fr", "es"],
|
| 62 |
+
"secondary": ["ar", "de", "it"],
|
| 63 |
+
"extended": ["pt", "ru"]
|
| 64 |
+
},
|
| 65 |
+
"model_priorities": {
|
| 66 |
+
"high_quality": [
|
| 67 |
+
"Helsinki-NLP/opus-mt-he-en",
|
| 68 |
+
"Helsinki-NLP/opus-mt-en-he",
|
| 69 |
+
"Helsinki-NLP/opus-mt-ar-en",
|
| 70 |
+
"Helsinki-NLP/opus-mt-en-ar",
|
| 71 |
+
"Helsinki-NLP/opus-mt-fr-en",
|
| 72 |
+
"Helsinki-NLP/opus-mt-en-fr"
|
| 73 |
+
],
|
| 74 |
+
"fast_loading": [
|
| 75 |
+
"Helsinki-NLP/opus-mt-es-en",
|
| 76 |
+
"Helsinki-NLP/opus-mt-en-es",
|
| 77 |
+
"Helsinki-NLP/opus-mt-de-en",
|
| 78 |
+
"Helsinki-NLP/opus-mt-en-de"
|
| 79 |
+
]
|
| 80 |
+
},
|
| 81 |
+
"fallback_strategy": {
|
| 82 |
+
"use_english_pivot": true,
|
| 83 |
+
"description": "If direct translation model not available, translate via English",
|
| 84 |
+
"example": "he->fr becomes he->en->fr"
|
| 85 |
+
},
|
| 86 |
+
"model_info": {
|
| 87 |
+
"Helsinki-NLP/opus-mt-he-en": {
|
| 88 |
+
"description": "Hebrew to English translation",
|
| 89 |
+
"quality": "high",
|
| 90 |
+
"size": "small",
|
| 91 |
+
"domain": "general"
|
| 92 |
+
},
|
| 93 |
+
"Helsinki-NLP/opus-mt-en-he": {
|
| 94 |
+
"description": "English to Hebrew translation",
|
| 95 |
+
"quality": "high",
|
| 96 |
+
"size": "small",
|
| 97 |
+
"domain": "general"
|
| 98 |
+
},
|
| 99 |
+
"Helsinki-NLP/opus-mt-ar-en": {
|
| 100 |
+
"description": "Arabic to English translation",
|
| 101 |
+
"quality": "high",
|
| 102 |
+
"size": "medium",
|
| 103 |
+
"domain": "general"
|
| 104 |
+
},
|
| 105 |
+
"Helsinki-NLP/opus-mt-en-ar": {
|
| 106 |
+
"description": "English to Arabic translation",
|
| 107 |
+
"quality": "high",
|
| 108 |
+
"size": "medium",
|
| 109 |
+
"domain": "general"
|
| 110 |
+
}
|
| 111 |
+
},
|
| 112 |
+
"configuration": {
|
| 113 |
+
"max_length": 512,
|
| 114 |
+
"num_beams": 4,
|
| 115 |
+
"temperature": 1.0,
|
| 116 |
+
"do_sample": false,
|
| 117 |
+
"early_stopping": true
|
| 118 |
+
}
|
| 119 |
+
}
|