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

​

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

相关推荐
IT_陈寒2 分钟前
用Vue时这个响应式陷阱坑了我一整天
前端·人工智能·后端
alphaTao3 分钟前
LeetCode 每日一题 2026/9/21-2026/9/27
python·算法·leetcode
bing.shao4 分钟前
不点鼠标的AI:GPT-6 Astra 推开「软件操作层时代」
人工智能·gpt
围炉聊科技4 分钟前
你从IDE切到ADE了吗?智能体开发环境赛道地图——智能体基建系列
ide·人工智能
jeffsonfu5 分钟前
生成对抗网络(GAN)原理:生成器与判别器的“猫鼠游戏”
人工智能·游戏·生成对抗网络
TK泰妞14 分钟前
爆款视频怎么改成TikTok带货内容?
人工智能·prompt·音视频
TechEdu20260616 分钟前
[人工智能]Python06:NumPy 数组操作详解
人工智能·numpy
愚公搬代码17 分钟前
【愚公系列】《微信小程序项目实战(AI编程+视频图解)》002-一张新地图:AI创业的核心分析框架
人工智能·微信小程序·ai编程
TAN-90°-19 分钟前
Deep Learning for Computer Vision——Vision and Language
人工智能·深度学习·神经网络·算法·目标检测·机器学习·计算机视觉
东坡肘子19 分钟前
iPhone Duo 留给开发者的一个月 -- 肘子的 Swift 周报 #155
人工智能·swiftui·swift