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

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

相关推荐
searchforAI几秒前
2026国产AI笔记工具横评:Get笔记、Ai好记、通义听悟、BiBiGPT各有什么特色?
人工智能·笔记·学习·ai·音视频·知识图谱·知识库
学术小白人几秒前
【早鸟优惠】第二届AI赋能图像处理与计算机视觉技术国际学术研讨会(AIPCVT 2026)
大数据·人工智能·医学·数字能源·学术会议参会
咕咕AI学堂2 分钟前
AI 任务调度算法:从优先级队列到公平调度的推理服务资源分配
人工智能
LaughingZhu4 分钟前
Product Hunt 每日热榜 | 2026-06-16
前端·人工智能·经验分享·chatgpt·html
guygg884 分钟前
二维弹塑性有限元分析(von Mises 等向硬化)— MATLAB 实现
开发语言·人工智能·matlab
三千花灯10 分钟前
【Playwright】 自动化测试之参数化登录(Excel/CSV 数据源)
人工智能·机器学习·excel
johnny23313 分钟前
Agent记忆框架:MemPalace、Cognee、Hindsight、memories.ai
人工智能
YOLO数据集集合14 分钟前
无人机风电设备智能巡检 风机叶片缺陷目标检测数据集实战 | 表面腐蚀漏油识别 工业视觉质检 深度学习模型训练落地10337期
人工智能·深度学习·目标检测·计算机视觉·无人机
zhenlai201214 分钟前
Vue3 + SpringBoot + AI:我做了一个股票分析工具(第1周复盘)
人工智能·spring boot·后端
装不满的克莱因瓶15 分钟前
【工业领域】了解目标检测基本流程——从数据到部署的完整工程化思路
人工智能·python·深度学习·机器学习·计算机视觉·目标跟踪·工业领域