How to use translation pipeline Hugging Face
Quick answer
Use the Hugging Face
transformers library's pipeline function with the task set to translation or a specific language pair like translation_en_to_fr. Initialize the pipeline and pass the text to translate, which returns the translated output.PREREQUISITES
Python 3.8+pip install transformers>=4.0.0Internet connection to download model weights
Setup
Install the transformers library from Hugging Face and ensure Python 3.8 or higher is installed. No API key is required for local translation pipelines.
pip install transformers Step by step
Use the pipeline function from transformers to create a translation pipeline. Specify the translation task or model name for the language pair. Pass the input text to get the translated result.
from transformers import pipeline
# Create a translation pipeline from English to French
translator = pipeline("translation_en_to_fr")
# Input text to translate
text = "Hello, how are you?"
# Perform translation
result = translator(text)
# Output the translated text
print(result[0]['translation_text']) output
Bonjour, comment ça va ?
Common variations
- Use different language pairs by changing the pipeline task, e.g.,
translation_en_to_defor German. - Specify a particular model by passing
model="Helsinki-NLP/opus-mt-en-fr"topipeline. - Use the pipeline asynchronously with
asynciofor batch translations.
from transformers import pipeline
# Specify a model explicitly
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-fr")
text = "Good morning"
result = translator(text)
print(result[0]['translation_text']) output
Bonjour
Troubleshooting
- If you see
OSError: Model name 'translation_en_to_fr' was not found, install the latesttransformersand check your internet connection. - For slow performance, consider using a smaller model or running on GPU.
- If translation output is empty or incorrect, verify the input text encoding and language pair.
Key Takeaways
- Use Hugging Face's
pipelinewith task names liketranslation_en_to_frfor quick translation. - You can specify any supported model for translation by passing the
modelparameter. - No API key is needed; models download automatically on first run.
- For better performance, run on GPU or choose smaller models.
- Handle errors by updating
transformersand checking model availability.