使用 Helsinki-NLP 中英文翻译本地部署 - python 实现

通过 Helsinki-NLP 本地部署中英文翻译功能。该开源模型性价比相对高,资源占用少,对于翻译要求不高的应用场景可以使用,比如单词,简单句式的中英文翻译。

该示例使用的模型下载地址:【免费】Helsinki-NLP中英文翻译本地部署-python实现模型资源-CSDN文库

模型也可以在hugging face 下载。

1、英文翻译为中文示例:

python 复制代码
# -*- coding: utf-8 -*-
# date:2024
# Author: DataBall
# function:英文翻译为中文
import os
import cv2
os.environ['CUDA_VISIBLE_DEVICES'] = "0"

from transformers import pipeline, AutoModelWithLMHead, AutoTokenizer

# 英文翻译成中文
model = AutoModelWithLMHead.from_pretrained("Helsinki-NLP/opus-mt-en-zh",cache_dir = "./ckpt-fy",local_files_only=True)
tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-zh",cache_dir = "./ckpt-fy",local_files_only=True)
translation = pipeline("translation_en_to_zh", model=model, tokenizer=tokenizer)

text = "Because of dreams, I will work hard."
translated_text = translation(text, max_length=256)[0]['translation_text']

print(" 原英文  : {}".format(text))
print(" 翻译中文: {}".format(translated_text))

对应的英文转中文log如下:

python 复制代码
原英文  : Because of dreams, I will work hard.
翻译中文: 因为梦想,我会努力工作

2、中文翻译为英文示例:

python 复制代码
# -*- coding: utf-8 -*-
# date:2024
# Author: DataBall
# function:中文翻译为英文
import os
os.environ['CUDA_VISIBLE_DEVICES'] = "0"
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from transformers import pipeline, AutoModelWithLMHead, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-zh-en",cache_dir = "./ckpt-fy",local_files_only=True)
model = AutoModelForSeq2SeqLM.from_pretrained("Helsinki-NLP/opus-mt-zh-en",cache_dir = "./ckpt-fy",local_files_only=True)
translation = pipeline("translation_zh_to_en", model=model, tokenizer=tokenizer)
text = "因为梦想,我会努力工作。"
translated_text = translation(text, max_length=256)[0]['translation_text']

print(" 原中文  : {}".format(text))
print(" 翻译英文: {}".format(translated_text))

对应的中文转英文log如下:

python 复制代码
原中文  : 因为梦想,我会努力工作。
翻译英文: Because of my dreams, I'll work hard.

助力快速掌握数据集的信息和使用方式。

相关推荐
mubei-123几秒前
TF-IDF / BM25:经典的传统信息检索算法
人工智能·检索算法
databook5 分钟前
回归分析全家桶(16种回归模型实现方式总结)
人工智能·python·机器学习
天竺鼠不该去劝架6 分钟前
传统财务管理瓶颈:财务机器人如何提升效率
大数据·数据库·人工智能
zhongerzixunshi12 分钟前
“首版次高端软件”:国产工业软件皇冠上的明珠
人工智能·云计算
猴子年华、13 分钟前
【每日一技】:GitHub 精确查询
开发语言·python·github
virtaitech17 分钟前
【免费申请】趋动科技OrionX社区版开放:GPU池化神器
人工智能·科技·gpu·池化技术·永久免费
WZGL123017 分钟前
“近邻+数智”:解码智慧养老的温情答案
大数据·人工智能·科技·生活·智能家居
elangyipi12318 分钟前
2025 搜索优化新革命:GEO 正在悄然取代 SEO?
前端·人工智能
Toky丶20 分钟前
QLoRA Efficient Finetuning of Quantized LLMs
人工智能·chatgpt
丝斯201121 分钟前
AI学习笔记整理(39)——自然语言处理算法之词向量 Word2vec
人工智能·学习·自然语言处理