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

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

相关推荐
烟袅1 分钟前
使用 OpenAI SDK 调用 Tools 实现外部工具集成
python·openai·agent
青瓷程序设计14 分钟前
果蔬识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
川石课堂软件测试22 分钟前
自动化过程中验证码的解决思路
数据库·python·功能测试·测试工具·单元测试·tomcat·自动化
沫儿笙31 分钟前
镀锌板焊接中库卡机器人是如何省气的
网络·人工智能·机器人
2301_7644413339 分钟前
新能源汽车电磁辐射高级预测
python·算法·数学建模·汽车
Keep_Trying_Go1 小时前
论文Leveraging Unlabeled Data for Crowd Counting by Learning to Rank算法详解
人工智能·pytorch·深度学习·算法·人群计数
爱吃泡芙的小白白1 小时前
使用某云超算平台Jupyterlab的使用方法(自用)
运维·服务器·python·学习记录
qq_203769491 小时前
在conda环境中使用jupyter
python·jupyter·conda
趣浪吧1 小时前
AI在手机上真没用吗?
人工智能·智能手机·aigc·音视频·媒体
IT考试认证1 小时前
华为人工智能认证 HCIA-AI Solution H13-313 题库
人工智能·华为·题库·hcia-ai·h13-313