我正在寻找一个将非常大的文本翻译成英语的 Python 库。我已经使用过
TextBlob
(在某些时候只是停止翻译,我想是API限制),googletrans
(在某些时候也只是停止翻译,它也不会翻译非常大的文本,我必须将它们分开成碎片然后合并)。我正在寻找一种解决方案,我可以确定它不会停止工作,因为我将定期对大约 100K 文本(平均字长为 10K)运行此代码。如果有人做过类似的事情,我将不胜感激!
Python 库 dl-translate 可以很好地完成工作。它基于 Huggingface 转换器,有 2 个可用的模型选项 - mBART-50 Large(50 种语言,我个人认为它非常准确)和 m2m100(100 种语言,但准确度略低)。 github链接:https://github.com/xhluca/dl-translate
Deepl API 允许你每个月获得 500k 字符,这够吗? https://www.deepl.com/en/docs-api/
可能不是,但我想确定
可以使用 mBART-50(paper,Hugging Face 上的预训练模型)。 Hugging Face 上的预训练模型已获得 MIT 许可。
请参阅下面的示例代码。我在带有 NVIDIA A100 40GB GPU 和 CUDA 12.0 的 Ubuntu 20.04.5 LTS 上使用的环境:
conda create --name mbart-python39 python=3.9
conda activate mbart-python39
pip install transformers==4.28.1
pip install chardet==5.1.0
pip install sentencepiece==0.1.99
pip install protobuf==3.20
代码(下面 95% 以上的代码来自 Hugging Face 文档):
from transformers import MBartForConditionalGeneration, MBart50TokenizerFast
article_fr = "Bonjour comment ca va?"
article_en = "What's going on?"
model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
# translate French to English
tokenizer.src_lang = "fr_XX"
encoded_fr = tokenizer(article_fr, return_tensors="pt")
generated_tokens = model.generate(**encoded_fr, forced_bos_token_id=tokenizer.lang_code_to_id["en_XX"])
translation =tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
print(translation)
# => "Hello, how are you?"
# translate English to French
tokenizer.src_lang = "en_XX"
encoded_en = tokenizer(article_en, return_tensors="pt")
generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id["fr_XX"])
translation = tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
print(translation)
# => "Qu'est-ce qui se passe?"