Spaces:
Running
on
Zero
Running
on
Zero
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
| 4 |
+
from flores import code_mapping
|
| 5 |
+
import platform
|
| 6 |
+
|
| 7 |
+
device = "cpu" if platform.system() == "Darwin" else "cuda"
|
| 8 |
+
MODEL_NAME = "facebook/nllb-200-distilled-600M"
|
| 9 |
+
|
| 10 |
+
code_mapping = dict(sorted(code_mapping.items(), key=lambda item: item[1]))
|
| 11 |
+
flores_codes = list(code_mapping.keys())
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_model():
|
| 15 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME).to(device)
|
| 16 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 17 |
+
return model, tokenizer
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
model, tokenizer = load_model()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@spaces.GPU
|
| 24 |
+
def translate(text: str, src_lang: str, tgt_lang: str):
|
| 25 |
+
source = code_mapping[src_lang]
|
| 26 |
+
target = code_mapping[tgt_lang]
|
| 27 |
+
translator = pipeline(
|
| 28 |
+
"translation",
|
| 29 |
+
model=model,
|
| 30 |
+
tokenizer=tokenizer,
|
| 31 |
+
src_lang=source,
|
| 32 |
+
tgt_lang=target,
|
| 33 |
+
device=device,
|
| 34 |
+
)
|
| 35 |
+
output = translator(text, max_length=400)
|
| 36 |
+
return output[0]["translation_text"]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
description = """
|
| 40 |
+
No Language Left Behind (NLLB) is a series of open-source models aiming to provide high-quality translations between 200 language."""
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
with gr.Blocks() as demo:
|
| 44 |
+
gr.Markdown("# No Language Left Behind (NLLB) Translation Demo")
|
| 45 |
+
gr.Markdown(description)
|
| 46 |
+
with gr.Row():
|
| 47 |
+
src_lang = gr.Dropdown(label="Source Language", choices=flores_codes)
|
| 48 |
+
target_lang = gr.Dropdown(label="Target Language", choices=flores_codes)
|
| 49 |
+
with gr.Row():
|
| 50 |
+
input_text = gr.Textbox(label="Input Text", lines=6)
|
| 51 |
+
with gr.Row():
|
| 52 |
+
btn = gr.Button("Translate text")
|
| 53 |
+
with gr.Row():
|
| 54 |
+
output = gr.Textbox(label="Output Text", lines=6)
|
| 55 |
+
btn.click(
|
| 56 |
+
translate,
|
| 57 |
+
inputs=[input_text, src_lang, target_lang],
|
| 58 |
+
outputs=output,
|
| 59 |
+
)
|
| 60 |
+
demo.launch()
|