joshuaberkowitzus's picture
updated html
9176961 verified
# app.py (for Helsinki-NLP/opus-mt-en-fr translation)
import gradio as gr
from transformers import pipeline
import os
# Model ID for the English-to-French translation model
model_id = "Helsinki-NLP/opus-mt-en-fr"
task = "translation_en_to_fr" # Define the specific task for the pipeline
# Load the translation pipeline
print(f"Loading {task} pipeline for model {model_id}...")
try:
translation_pipeline = pipeline(task, model=model_id)
print(f"{task} pipeline loaded successfully.")
except Exception as e:
# Fallback if the specific task pipeline isn't found, try generic translation
try:
print(f"Could not load specific task '{task}'. Trying generic 'translation'...")
# Note: Generic translation might require specifying src/tgt languages at inference
translation_pipeline = pipeline("translation", model=model_id)
print("Generic translation pipeline loaded.")
except Exception as e_generic:
print(f"Error loading translation pipeline: {e_generic}")
translation_pipeline = None
def translate_text(english_text):
"""Translates English text to French using the loaded pipeline."""
if translation_pipeline is None:
return "Error: Translation model pipeline could not be loaded."
if not english_text:
return "Please enter some English text to translate."
try:
# Perform translation
# The pipeline returns a list of dictionaries, e.g., [{'translation_text': '...'}]
result = translation_pipeline(english_text)
# Extract the translated text
french_text = result[0]['translation_text']
return french_text
except Exception as e:
print(f"Error during translation: {e}")
return f"Error during translation: {str(e)}"
# --- Use gr.Blocks for layout control ---
with gr.Blocks() as demo:
# 1. Add Title and Description
gr.Markdown(f"# English to French Translation")
gr.Markdown(f"Translate English text to French using the `{model_id}` model via the Hugging Face `transformers` pipeline.")
# 2. Define the main interface components
with gr.Row():
input_english = gr.Textbox(
lines=5,
placeholder="Enter English text here...",
label="English Input")
output_french = gr.Textbox(
lines=5,
label="French Translation")
# 3. Add a Submit Button
translate_button = gr.Button("Translate to French")
# 4. Add Examples
gr.Examples(
examples=["Hello, how are you?"],
inputs=input_english,
outputs=output_french,
fn=translate_text
)
# 5. --- Add your custom HTML section below ---
gr.HTML("""
<div style='border: 1px solid #eee; padding: 15px; margin-top: 20px; border-radius: 5px;'>
<h2 style='color: #555;'>About This Demo</h2>
<p><b>Description:</b> This model is part of the extensive OPUS-MT project developed by the Language Technology Research Group at the University of Helsinki (Helsinki-NLP). It is specifically trained for machine translation from English to French. These models are based on the Transformer architecture and utilize SentencePiece for tokenization, making them efficient and effective for translation tasks across numerous language pairs</p>
<p><b>Architecture:</b> The model employs a standard Transformer encoder-decoder architecture, specifically the MarianMT implementation within the transformers library, which is highly optimized for neural machine translation.</p>
<p><b>Intended Uses & Scope:</b> The sole purpose of this model is to translate text from English into French. It is one instance within the larger OPUS-MT collection, which provides pre-trained models for a vast number of language directions.</p>
<p><b>Popularity Context:</b> The high download counts associated with Helsinki-NLP/opus-mt-en-fr and other OPUS-MT models reflect their widespread adoption for translation tasks. The Helsinki-NLP group's work is highly regarded, and their models are known for quality and comprehensive language coverage, making them a standard choice for many translation applications built using the Hugging Face ecosystem.</p>
<p><b>Functionality:</b> A user enters English text. The application utilizes a transformers translation pipeline, pre-configured for English-to-French translation using the specified Helsinki-NLP model, to generate the French equivalent, which is then displayed.</p>
</div>
""")
# 6. Connect the button to the function
translate_button.click(
fn=translate_text,
inputs=input_english,
outputs=output_french
)
# Launch the interface defined by gr.Blocks
if __name__ == "__main__":
demo.launch()