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

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

相关推荐
vanchWanquan3 小时前
平置革新:RFID 地毯天线重构多行业数字化识别体系
人工智能·安全·重构·制造
m0_380167143 小时前
加密市场数据API 指南:价格、合约、期权与分析
人工智能·ai·区块链
数据仓库搬砖人3 小时前
CLI、MCP、Skill:构建 AI Agent 的三层基础设施,你真的分清楚了吗?
人工智能
70asunflower3 小时前
【Day1-2】部署&运行 Gemma4 大模型 - Datawhale AI学习
人工智能·学习·datawhale·amdev
wuhanzhanhui3 小时前
智能座舱技术新高地!2026武汉国际智能显示及智能座舱展览会
人工智能·物联网
学Linux的语莫3 小时前
OpenCV 视频处理入门教程
人工智能·opencv·音视频
砍材农夫3 小时前
python 如何一次性安装项目所有依赖包(pip和uv)
开发语言·python·pip·uv
yijianace3 小时前
Python爬虫项目实战:从 BeautifulSoup 到 XPath
爬虫·python·beautifulsoup
王小王-1234 小时前
基于机器学习的二手汽车交易价格分析与可视化
人工智能·机器学习·二手车价格预测·汽车销量分析·二手车分析·新能源汽车系统·汽车销量分析可视化系统
云水-禅心4 小时前
解决MacOS 安装Python之后默认版本指向不正确问题
开发语言·python·macos