This article is part of a tutorial series on txtai, an AI-powered search engine.
A Spanish language translation of this article is available. Thank you to Chema Bescós for providing this!
This article covers machine translation backed by Hugging Face models. The quality of machine translation via cloud services has come a very long way and produces high quality results. This article shows how the models from Hugging Face give developers a reasonable alternative for local machine translation.
txtai and all dependencies.
pip install txtai
The Translation instance is the main entrypoint for translating text between languages. The pipeline abstracts translating text into a one line call!
The pipeline has logic to detect the input language, load the relevant model that handles translating from source to target language and return results. The translation pipeline also has built-in logic to handle splitting large text blocks into smaller sections the models can handle.
from txtai.pipeline import Translation # Create translation model translate = Translation()
The example below shows how to translate text from English to Spanish. This text is then translated back to English.
translation = translate("This is a test translation into Spanish", "es") translation
Esta es una traducción de prueba al español
This is a test translation into Spanish
The section below translates a single English sentence into 5 different languages. The results are then passed to a single translation call to translate back into English. The pipeline detects each input language and is able to load the relevant translation models.
languages = ["fr", "es", "de", "hi", "ja"] translations = [translate("The sky is blue, the stars are far", language) for language in languages] english = translate(translations, "en") for x, text in enumerate(translations): print("Original Language: %s" % languages[x]) print("Translation: %s" % text) print("Back to English: %s" % english[x]) print()
Original Language: fr Translation: Le ciel est bleu, les étoiles sont loin Back to English: The sky is blue, the stars are far away Original Language: es Translation: El cielo es azul, las estrellas están lejos. Back to English: The sky is blue, the stars are far away. Original Language: de Translation: Der Himmel ist blau, die Sterne sind weit Back to English: The sky is blue, the stars are wide Original Language: hi Translation: आकाश नीला है, तारे दूर हैं Back to English: Sky is blue, stars are away Original Language: ja Translation: 天は青い、星は遠い。 Back to English: The heavens are blue and the stars are far away.
The translation quality overall is very high. Machine translation has made giant leaps and strides the last couple of years. These models give developers a solid alternative to cloud translation services if translating on local servers is preferred.