Spaces:
Running
Running
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""app.py
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1UBKp9Q5WTAiaXvsRK_6KupUXBI3i05wH
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 11 |
+
import gradio as gr
|
| 12 |
+
|
| 13 |
+
# Dictionary mapping target languages to Helsinki models
|
| 14 |
+
LANG_MODELS = {
|
| 15 |
+
"German": "Helsinki-NLP/opus-mt-en-de",
|
| 16 |
+
"French": "Helsinki-NLP/opus-mt-en-fr",
|
| 17 |
+
"Spanish": "Helsinki-NLP/opus-mt-en-es",
|
| 18 |
+
"Italian": "Helsinki-NLP/opus-mt-en-it",
|
| 19 |
+
"Japanese": "Helsinki-NLP/opus-mt-en-jap",
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
# Preload models for speed (optional, you can also load on demand)
|
| 23 |
+
model_cache = {}
|
| 24 |
+
tokenizer_cache = {}
|
| 25 |
+
|
| 26 |
+
def translate_text_multi(text, target_lang):
|
| 27 |
+
model_name = LANG_MODELS.get(target_lang)
|
| 28 |
+
if not model_name:
|
| 29 |
+
return "Error: language not supported."
|
| 30 |
+
|
| 31 |
+
# Load model/tokenizer if not already loaded
|
| 32 |
+
if model_name not in model_cache:
|
| 33 |
+
tokenizer_cache[model_name] = AutoTokenizer.from_pretrained(model_name)
|
| 34 |
+
model_cache[model_name] = AutoModelForSeq2SeqLM.from_pretrained(model_name)
|
| 35 |
+
|
| 36 |
+
tokenizer = tokenizer_cache[model_name]
|
| 37 |
+
model = model_cache[model_name]
|
| 38 |
+
|
| 39 |
+
inputs = tokenizer(text, return_tensors="pt")
|
| 40 |
+
outputs = model.generate(**inputs)
|
| 41 |
+
translated = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 42 |
+
return translated
|
| 43 |
+
|
| 44 |
+
# Gradio UI
|
| 45 |
+
with gr.Blocks() as demo:
|
| 46 |
+
gr.Markdown("## 🌐 Multi-language Translator")
|
| 47 |
+
input_text = gr.Textbox(label="Enter English text", lines=4)
|
| 48 |
+
target_language = gr.Dropdown(choices=list(LANG_MODELS.keys()), value="German", label="Target Language")
|
| 49 |
+
output_text = gr.Textbox(label="Translation", lines=4)
|
| 50 |
+
|
| 51 |
+
translate_btn = gr.Button("Translate")
|
| 52 |
+
translate_btn.click(fn=translate_text_multi, inputs=[input_text, target_language], outputs=output_text)
|
| 53 |
+
|
| 54 |
+
demo.launch()
|