CoolFace
Apppublic

Razzaqi3143/MultiLanguage_Model

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py57 linesDownload Raw Back to root
1import gradio as gr2from transformers import AutoTokenizer, AutoModelForSeq2SeqLM3 4# Dictionary to hold models and tokenizers for each language5models = {}6tokenizers = {}7 8# List of language pairs9language_pairs = {10    "English to French": "Helsinki-NLP/opus-mt-en-fr",11    "English to Chinese": "Helsinki-NLP/opus-mt-en-zh",12    "English to German": "Helsinki-NLP/opus-mt-en-de",13    "English to Urdu": "Helsinki-NLP/opus-mt-en-ur"14}15 16# Load models and tokenizers for each language pair17for lang, model_name in language_pairs.items():18    tokenizers[lang] = AutoTokenizer.from_pretrained(model_name)19    models[lang] = AutoModelForSeq2SeqLM.from_pretrained(model_name)20 21# Function to perform translation22def translate_text(text, language_choice):23    # Select the appropriate tokenizer and model based on the chosen language24    tokenizer = tokenizers[language_choice]25    model = models[language_choice]26    27    # Tokenize the input text28    inputs = tokenizer(text, return_tensors="pt", truncation=True)29    30    # Generate the translation31    outputs = model.generate(**inputs)32    33    # Decode the translated text34    translated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)35    36    return translated_text37 38# Define the Gradio interface39def gradio_interface(text, language_choice):40    translated_text = translate_text(text, language_choice)41    return translated_text42 43# Create a list of language choices for the dropdown44language_choices = list(language_pairs.keys())45 46# Set up the Gradio app47interface = gr.Interface(48    fn=gradio_interface,49    inputs=[gr.Textbox(lines=2, placeholder="Enter text here..."), 50            gr.Dropdown(choices=language_choices, label="Select Target Language")],51    outputs=gr.Textbox(label="Translated Text"),52    title="Multi-Language Translation App"53)54 55# Launch the app56interface.launch()57