Translation helps convert text from one language to another so people can understand each other better.
0
0
Translation with Hugging Face in NLP
Introduction
You want to read a website written in a language you don't know.
You need to translate a message from a friend who speaks a different language.
You want to build an app that supports multiple languages.
You want to understand foreign news articles quickly.
You want to help travelers communicate in a new country.
Syntax
NLP
from transformers import pipeline translator = pipeline('translation_en_to_fr', model='Helsinki-NLP/opus-mt-en-fr') result = translator('Hello, how are you?') print(result[0]['translation_text'])
Use pipeline('translation_en_to_fr', model='model-name') to create a translator.
Call the translator with the text you want to translate.
Examples
This example translates English to French using a shortcut pipeline name.
NLP
translator = pipeline('translation_en_to_fr') result = translator('Good morning') print(result[0]['translation_text'])
This example translates French to English by specifying a different model.
NLP
translator = pipeline('translation_fr_to_en', model='Helsinki-NLP/opus-mt-fr-en') result = translator('Bonjour') print(result[0]['translation_text'])
Sample Model
This program translates a simple English sentence into French using Hugging Face's translation pipeline.
NLP
from transformers import pipeline # Create a translator from English to French translator = pipeline('translation_en_to_fr', model='Helsinki-NLP/opus-mt-en-fr') # Text to translate text = 'Machine learning is fun and useful.' # Translate the text result = translator(text) # Print the translated text print(result[0]['translation_text'])
OutputSuccess
Important Notes
Make sure you have the transformers library installed with pip install transformers.
Translation models can be large, so expect some download time the first time you run.
You can change the model name to translate between other languages supported by Hugging Face.
Summary
Translation converts text from one language to another automatically.
Hugging Face provides easy-to-use translation pipelines with pre-trained models.
Just create a translator pipeline and call it with your text to get translations.