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()