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

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

相关推荐
xcLeigh1 分钟前
AI写作的前世今生:从规则模板到大语言模型的演进之路
人工智能·ai·ai写作
前端.火鸡1 分钟前
AI取代互联网开发者:冲击、优势与行业重构的深度分析
人工智能
DogDaoDao5 分钟前
HYPERmotion 深度解析:当人形机器人学会“自己想招“——LLM 规划 + RL 技能库 + 全身优化的混合行为规划框架
人工智能·机器人·人形机器人·运动轨迹·自由度·运动估计·hypermotion
常山云栈8 分钟前
axios和restful的区别是什么?
人工智能
wshzd12 分钟前
LLM之Agent(六十九)|PI(八)发布流程与供应链安全
人工智能
罗西的思考14 分钟前
[Agent Memory / 强化学习] MemPO源码学习笔记 — (2)— 训练
人工智能·深度学习
Forerror202626 分钟前
大模型网关解决什么问题?MAI Gateway(魔芋企业级AI网关)给出企业级答案
人工智能·ai工具·ai安全·maigateway·企业ai网关·企业级大模型治理网关·大模型财务治理
Gu0Qiang26 分钟前
从 0 到 1 打造 AI 提示流编排器:条件分支路由、Kahn 图剪枝与 HTTP 节点实战(开源系列 06)
人工智能·github
驭风少年君27 分钟前
Codex 从入门到进阶
人工智能·aigc·codex
JAI科研29 分钟前
YOLO 完全指南(七):YOLO识别工程化 (上)
人工智能·深度学习·神经网络·yolo·目标检测·计算机视觉·transformer