Download app.py from balaji4991512/MultiLanguageTranslator: direct link, hf CLI and curl.
- Browser
- Download file 2.13 kB
-
https://huggingface.co/spaces/balaji4991512/MultiLanguageTranslator/resolve/main/app.py
- Command line
-
hf download hf://spaces/balaji4991512/MultiLanguageTranslator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/balaji4991512/MultiLanguageTranslator/resolve/main/app.py
2.13 kB
| import torch | |
| import gradio as gr | |
| import json | |
| from transformers import pipeline | |
| # Initialize translation pipeline (online or offline) | |
| text_translator = pipeline("translation", model="facebook/nllb-200-distilled-600M", | |
| torch_dtype=torch.bfloat16) | |
| # Load the Flores-200 language codes from a JSON file | |
| with open('language.json', 'r') as file: | |
| language_data = json.load(file) | |
| # Helper function to get the Flores code from the full language name | |
| 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 used by the Gradio interface | |
| def translate_text(text, destination_language): | |
| dest_code = get_FLORES_code_from_language(destination_language) | |
| if not dest_code: | |
| return f"β Language code for '{destination_language}' not found." | |
| translation = text_translator(text, src_lang="eng_Latn", tgt_lang=dest_code) | |
| return translation[0]["translation_text"] | |
| # Build the dropdown list from the loaded language.json | |
| language_list = [entry["Language"] for entry in language_data] | |
| # Create a polished Gradio UI | |
| with gr.Blocks(theme=gr.themes.Default()) as demo: | |
| gr.Markdown( | |
| """ | |
| # π Multilingual Translator β Powered by Meta NLLB-200 | |
| Translate English text into 200+ languages using the FLORES-200 dataset. | |
| """ | |
| ) | |
| with gr.Row(): | |
| input_text = gr.Textbox(label="π English Input", lines=6, placeholder="Type your English sentence here...") | |
| output_lang = gr.Dropdown(choices=language_list, label="π Target Language") | |
| output_text = gr.Textbox(label="β Translated Output", lines=4) | |
| translate_btn = gr.Button("π Translate") | |
| translate_btn.click(fn=translate_text, inputs=[input_text, output_lang], outputs=output_text) | |
| gr.Markdown( | |
| """ | |
| --- | |
| π§ Model: `facebook/nllb-200-distilled-600M` | |
| π Language codes from [FLORES-200](https://github.com/facebookresearch/flores) | |
| """ | |
| ) | |
| demo.launch() |