File size: 6,899 Bytes
e2922eb 1d31c06 4f48525 e2922eb 1d31c06 4f48525 1d31c06 e2922eb 4f48525 e2922eb 1d31c06 e2922eb 1d31c06 47f5afd 1d31c06 47f5afd 1d31c06 47f5afd 1d31c06 ad762c9 1d31c06 4f48525 1d31c06 623666e 1d31c06 e2922eb 1d31c06 aef09aa 1d31c06 aef09aa 1d31c06 aef09aa 1d31c06 2292d74 | 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 | import gradio as gr
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
import torch
# Load the NLLB model and tokenizer
MODEL_NAME = "facebook/nllb-200-distilled-600M"
print("Loading model and tokenizer...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
# Language codes for NLLB-200
# This is a subset of the most common languages
LANGUAGES = {
"Afrikaans": "afr_Latn",
"Arabic": "arb_Arab",
"Bengali": "ben_Beng",
"Bulgarian": "bul_Cyrl",
"Catalan": "cat_Latn",
"Chinese (Simplified)": "zho_Hans",
"Chinese (Traditional)": "zho_Hant",
"Croatian": "hrv_Latn",
"Czech": "ces_Latn",
"Danish": "dan_Latn",
"Dutch": "nld_Latn",
"English": "eng_Latn",
"Estonian": "est_Latn",
"Finnish": "fin_Latn",
"French": "fra_Latn",
"German": "deu_Latn",
"Greek": "ell_Grek",
"Hebrew": "heb_Hebr",
"Hindi": "hin_Deva",
"Hungarian": "hun_Latn",
"Indonesian": "ind_Latn",
"Italian": "ita_Latn",
"Japanese": "jpn_Jpan",
"Korean": "kor_Hang",
"Latvian": "lvs_Latn",
"Lithuanian": "lit_Latn",
"Malay": "zsm_Latn",
"Norwegian": "nob_Latn",
"Persian": "pes_Arab",
"Polish": "pol_Latn",
"Portuguese": "por_Latn",
"Romanian": "ron_Latn",
"Russian": "rus_Cyrl",
"Serbian": "srp_Cyrl",
"Slovak": "slk_Latn",
"Slovenian": "slv_Latn",
"Spanish": "spa_Latn",
"Swahili": "swh_Latn",
"Swedish": "swe_Latn",
"Tamil": "tam_Taml",
"Telugu": "tel_Telu",
"Thai": "tha_Thai",
"Turkish": "tur_Latn",
"Ukrainian": "ukr_Cyrl",
"Urdu": "urd_Arab",
"Vietnamese": "vie_Latn",
}
def detect_language(text):
"""
Simple language detection using the model's ability to identify language.
This is a basic implementation - for production, consider using langdetect or similar.
"""
# For simplicity, we'll use a heuristic approach
# In a real implementation, you might want to use a dedicated language detection library
# Check for common scripts
if any('\u0600' <= c <= '\u06FF' for c in text): # Arabic script
return "arb_Arab"
elif any('\u0980' <= c <= '\u09FF' for c in text): # Bengali script
return "ben_Beng"
elif any('\u4E00' <= c <= '\u9FFF' for c in text): # Chinese characters
return "zho_Hans"
elif any('\u0400' <= c <= '\u04FF' for c in text): # Cyrillic
# Could be Russian, Ukrainian, Bulgarian, etc.
return "rus_Cyrl"
elif any('\u0900' <= c <= '\u097F' for c in text): # Devanagari (Hindi)
return "hin_Deva"
elif any('\u3040' <= c <= '\u309F' or '\u30A0' <= c <= '\u30FF' for c in text): # Japanese
return "jpn_Jpan"
elif any('\uAC00' <= c <= '\uD7AF' for c in text): # Korean
return "kor_Hang"
elif any('\u0E00' <= c <= '\u0E7F' for c in text): # Thai
return "tha_Thai"
else:
# Default to English for Latin script
return "eng_Latn"
def translate_text(text, target_language):
"""
Translate text from auto-detected language to target language.
"""
if not text.strip():
return "Please enter some text to translate.", "Unknown"
# Detect source language
source_lang_code = detect_language(text)
# Get the target language code
target_lang_code = LANGUAGES.get(target_language, "eng_Latn")
# If source and target are the same, return the original text
if source_lang_code == target_lang_code:
source_lang_name = [k for k, v in LANGUAGES.items() if v == source_lang_code]
source_lang_name = source_lang_name[0] if source_lang_name else "Unknown"
return text, source_lang_name
# Set the tokenizer's source language
tokenizer.src_lang = source_lang_code
# Tokenize the input text
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
# Generate translation
translated_tokens = model.generate(
**inputs,
forced_bos_token_id=tokenizer.convert_tokens_to_ids(target_lang_code),
max_length=512,
num_beams=5,
early_stopping=True
)
# Decode the translation
translation = tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)[0]
# Get the source language name for display
source_lang_name = [k for k, v in LANGUAGES.items() if v == source_lang_code]
source_lang_name = source_lang_name[0] if source_lang_name else "Unknown"
return translation, source_lang_name
# Create Gradio interface
with gr.Blocks(title="NLLB-200 Translator", theme=gr.themes.Soft()) as demo:
gr.Markdown(
"""
# 🌍 Universal Language Translator
Translate text between 200+ languages using Meta's NLLB-200 model.
The source language is automatically detected!
**Powered by:** `facebook/nllb-200-distilled-600M`
"""
)
with gr.Row():
with gr.Column():
input_text = gr.Textbox(
label="Input Text",
placeholder="Enter text in any language...",
lines=5
)
target_language = gr.Dropdown(
choices=list(LANGUAGES.keys()),
label="Target Language",
value="English"
)
translate_btn = gr.Button("Translate", variant="primary")
with gr.Column():
detected_lang = gr.Textbox(
label="Detected Source Language",
interactive=False
)
output_text = gr.Textbox(
label="Translation",
lines=5,
interactive=False
)
# Examples
gr.Examples(
examples=[
["Hello, how are you?", "Spanish"],
["আমি ভালো আছি", "English"],
["こんにちは", "English"],
["Bonjour le monde", "German"],
["مرحبا بك", "English"],
],
inputs=[input_text, target_language],
)
# Set up the translation action
translate_btn.click(
fn=translate_text,
inputs=[input_text, target_language],
outputs=[output_text, detected_lang]
)
gr.Markdown(
"""
---
### About NLLB-200
The No Language Left Behind (NLLB) project aims to build a single AI model that can translate across 200 languages.
This model supports high-quality translations for low-resource languages.
**Note:** Language detection is based on script analysis. For best results, ensure your input text is clear and properly formatted.
"""
)
# Launch the app
if __name__ == "__main__":
demo.launch(share=True, show_error=True)
|