使用 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.

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

相关推荐
147API1 分钟前
OpenAI新增工作区Admin keys,管理自动化怎么拆权限
运维·人工智能·自动化·openai·api
触底反弹2 分钟前
🧠 别再让 AI 裸奔了!用 Skills 让 AI 秒变专属员工
人工智能
科技新芯7 分钟前
蚂蚁集团发布三层AI布局,智能体商业落地提速
人工智能
人工干智能26 分钟前
科普:Pandas 索引器 loc 与 iloc 的编程思维
java·人工智能·pandas
ddshub_cc30 分钟前
理解 Loop Engineering 与 AI 编程成本优化
大数据·人工智能·gpt·prompt·ai编程
喵喵喵~~~~41 分钟前
2026 指挥控制台源头工厂深度测评:按行业项目落地能力择优采购指南
大数据·运维·人工智能·智能家居
喵喵喵~~~~43 分钟前
2026 调度操作台厂商横向实测:多行业落地案例拆解,指挥中心控制台怎么选
大数据·人工智能
GuWen_yue1 小时前
告别LLM无本地文件能力!30行Node手写MCP文件读取服务,AI自由读写本地代码
人工智能
Xuantong_901 小时前
AI概念与企业落地实用指南
人工智能
美狐美颜SDK开放平台1 小时前
从采集到渲染:直播APP开发中视频美颜SDK工作原理详解
人工智能·音视频·实时音视频·美颜sdk·视频美颜sdk·美颜api