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

​

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

相关推荐
林伽一几秒前
GPU 调度栈开源与框架层精炼:AI 基础设施的两个新落点|2026年10月20日
人工智能·科技·安全·ai·开源
武子康1 分钟前
从预约改期看 Agent 工具粒度:把不变量留在权威服务
人工智能·后端·agent
Wanda12146 分钟前
机器人与机电一体化3D数字孪生机器-Day5
人工智能·unity·游戏引擎·数字孪生
Maya动画技术7 分钟前
pptx批量转png图片工具
python
frankzch8 分钟前
HybridAgent 拆解:在潜空间想,动手时才出字
人工智能·深度学习·语言模型
Martina_03219 分钟前
AI生成模型怎么做网页3D轻量化?用6步压缩Mesh、贴图与材质调用
图像处理·人工智能·3d·自然语言处理·aigc·游戏策划
张彦峰ZYF10 分钟前
用一个业务场景画出生产级 Agent 的全景架构
人工智能·生产级 agent·模型、工具、记忆·企业任务执行 agent·接入、会话与上下文·编排、模型访问、工具与集成·数据与状态、治理与观测
小李同学_LHY11 分钟前
大白话模型第三章:深度学习
人工智能·深度学习
Maynor99613 分钟前
TypeSafe Jev 1.14.0 使用教程:System One 决策 API 从入门到 box 定位
人工智能·api·jev·system one·决策模型·typesafe·jev-1.14.0