File size: 2,054 Bytes
7db96fe
 
 
 
aed8eed
7db96fe
aed8eed
7db96fe
aed8eed
7db96fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aed8eed
7db96fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import json
from transformers import pipeline

# Initialize the pipeline with the model
try:
    text_translator = pipeline("translation", model="facebook/nllb-200-distilled-600M")
except Exception as e:
    raise ValueError(f"Error initializing the model: {e}")

# Load the JSON data for language codes
try:
    with open('language.json', 'r') as file:
        language_data = json.load(file)
except FileNotFoundError:
    raise FileNotFoundError("The language.json file was not found at the specified path.")
except json.JSONDecodeError:
    raise ValueError("Error decoding the JSON file. Ensure it is formatted correctly.")

# Create a function to get the FLORES-200 code for a given language
def get_FLORES_code_from_language(language):
    for entry in language_data:
        if entry['Language'].lower() == language.lower():
            return entry['FLORES-200 code']
    return None

# Translation function
def translate_text(text, destination_language):
    if not text.strip():
        return "Input text cannot be empty."

    dest_code = get_FLORES_code_from_language(destination_language)
    if not dest_code:
        return f"Language '{destination_language}' is not supported."

    try:
        # Perform translation
        translation = text_translator(text, src_lang="eng_Latn", tgt_lang=dest_code)
        return translation[0]["translation_text"]
    except Exception as e:
        return f"Error during translation: {e}"

# Extract available languages from JSON
available_languages = [entry['Language'] for entry in language_data]

# Create the Gradio interface
demo = gr.Interface(
    fn=translate_text,
    inputs=[
        gr.Textbox(label="Input text to translate", lines=6),
        gr.Dropdown(available_languages, label="Select language to translate to")
    ],
    outputs=gr.Textbox(label="Translated text", lines=6),
    title="Project 03: Multi Language Translator",
    description="Translate English text into multiple languages using the NLLB-200 model."
)

# Launch the interface
demo.launch()