File size: 2,214 Bytes
3d5fb4c
5f23c2f
 
d3b7dd0
 
 
 
 
 
3d5fb4c
 
d3b7dd0
 
 
 
 
 
 
 
3d5fb4c
d3b7dd0
3d5fb4c
 
 
d3b7dd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d5fb4c
d3b7dd0
3d5fb4c
 
 
d3b7dd0
3d5fb4c
 
 
 
 
 
d3b7dd0
3d5fb4c
 
d3b7dd0
3d5fb4c
 
 
d3b7dd0
3d5fb4c
d3b7dd0
3d5fb4c
 
 
 
 
 
d3b7dd0
3d5fb4c
5f23c2f
3d5fb4c
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
import gradio as gr
from transformers import pipeline

MODEL_SPECS = {
    "Spanish":   ("translation_en_to_es", "Helsinki-NLP/opus-mt-en-es"),
    "German":    ("translation_en_to_de", "Helsinki-NLP/opus-mt-en-de"),
    "Japanese":  ("translation_en_to_ja", "staka/fugumt-en-ja"),
    "Ukrainian": ("translation_en_to_uk", "Helsinki-NLP/opus-mt-en-uk"),
    "Russian":   ("translation_en_to_ru", "Helsinki-NLP/opus-mt-en-ru"),
}

CACHED_MODELS = {}

def get_model(language: str):
    if language not in CACHED_MODELS:
        task, model_name = MODEL_SPECS[language]
        CACHED_MODELS[language] = pipeline(task, model=model_name)
    return CACHED_MODELS[language]

def translate(text, language):
    text = (text or "").strip()
    if not text:
        return "Please enter an English sentence."

    model = get_model(language)
    result = model(text)
    return result[0]["translation_text"]

CSS = """
#output-box textarea {
    background-color: #800000 !important;
    color: white !important;
    font-size: 1.2em !important;
    font-weight: bold !important;
    text-align: center !important;
}
"""

with gr.Blocks(title="Short Translation Web App", css=CSS) as demo:
    gr.Markdown("# Short Translation")

    with gr.Row():
        with gr.Column(scale=2):
            input_text = gr.Textbox(
                label="English Sentence",
                placeholder="Type your English sentence here...",
                lines=2
            )
            with gr.Row():
                translate_btn = gr.Button("Translate", variant="primary")
                clear_btn = gr.Button("Clear")

        with gr.Column(scale=1):
            lang_radio = gr.Radio(
                choices=list(MODEL_SPECS.keys()),
                label="Translation Language",
                value="Spanish"
            )

    output_text = gr.Textbox(
        label="Translation",
        interactive=False,
        container=True,
        elem_id="output-box"
    )

    translate_btn.click(fn=translate, inputs=[input_text, lang_radio], outputs=output_text)
    clear_btn.click(fn=lambda: ("", "Spanish", ""), inputs=None, outputs=[input_text, lang_radio, output_text])

if __name__ == "__main__":
    demo.launch()