File size: 2,196 Bytes
145a35c
 
 
54473e1
145a35c
54473e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145a35c
 
54473e1
 
 
 
 
 
 
 
 
 
 
 
 
 
3daa2d3
a7cc277
0fde74b
 
 
 
a7cc277
 
 
 
 
 
0fde74b
a7cc277
 
 
0fde74b
a7cc277
0fde74b
 
 
 
145a35c
 
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
import gradio as gr
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, pipeline

# Define available languages with their corresponding model suffixes
languages = {
    "english": "en",
    "spanish": "es",
    "french": "fr",
    "german": "de",
    "chinese": "zh",
    "japanese": "ja",
    "korean": "ko",
    "italian": "it",
    "portuguese": "pt",
    "russian": "ru",
    "hindi": "hi",
    "arabic": "ar",
    "dutch": "nl",
    "turkish": "tr",
    "greek": "el",
    "urdu": "ur"
}

# Define the translation function
def translate_text(text, target_language):
    # Get the correct model name based on the target language
    target_language_code = languages.get(target_language.lower())
    
    if target_language_code:
        model_name = f"Helsinki-NLP/opus-mt-en-{target_language_code}"
        tokenizer = AutoTokenizer.from_pretrained(model_name)
        model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
        translator = pipeline("translation", model=model, tokenizer=tokenizer)
        translation = translator(text)[0]['translation_text']
        return translation
    else:
        return "Error: Language not supported or incorrect."

# Set up the Gradio interface with a submit button and side-by-side layout
with gr.Blocks() as iface:
    gr.Markdown("# Text Translator")
    gr.Markdown("Translate text into multiple languages using Hugging Face models.")

    # Create a row for input and output
    with gr.Row():
        # Input components on the left
        with gr.Column(scale=1):  # This column is smaller
            text_input = gr.Textbox(label="Enter text to translate")
            language_dropdown = gr.Dropdown(list(languages.keys()), label="Target Language", type="value")

        # Output components on the right
        with gr.Column(scale=1):  # This column is also smaller
            translation_output = gr.Textbox(label="Translation", interactive=False)

    # Button to submit the translation
    submit_button = gr.Button("Translate")

    # When button is clicked, trigger the translation
    submit_button.click(fn=translate_text, inputs=[text_input, language_dropdown], outputs=translation_output)

iface.launch()