|
import gradio as gr |
|
import json |
|
from transformers import pipeline |
|
|
|
|
|
try: |
|
text_translator = pipeline("translation", model="facebook/nllb-200-distilled-600M") |
|
except Exception as e: |
|
raise ValueError(f"Error initializing the model: {e}") |
|
|
|
|
|
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.") |
|
|
|
|
|
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 |
|
|
|
|
|
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: |
|
|
|
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}" |
|
|
|
|
|
available_languages = [entry['Language'] for entry in language_data] |
|
|
|
|
|
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." |
|
) |
|
|
|
|
|
demo.launch() |
|
|