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

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

相关推荐
shchojj几秒前
Generative AI applications - Tips for Prompting
人工智能
深度学习lover2 分钟前
<数据集>yolo 白天鹅识别<目标检测>
人工智能·yolo·目标检测·数据集·白天鹅识别
@蔓蔓喜欢你3 分钟前
Web性能优化完全指南:从加载到渲染的全方位优化
人工智能·ai
互联科技报3 分钟前
2026年4K投影仪画质横评:明基W系列“色彩科学”解析
人工智能
步步为营DotNet3 分钟前
洞悉.NET 11:Blazor 与 Microsoft.Extensions.AI 的融合创新实践
人工智能·microsoft·.net
甲维斯3 分钟前
谷歌Antigravity 还活着啊!全新系列四个产品覆盖所有人群!
人工智能
xingyuzhisuan3 分钟前
Jupyter Notebook 云GPU配置全解析(含实操+选型指南)
ide·python·jupyter·gpu算力
ITIRONMAN10 分钟前
开源data-compare:轻量级数据对比工具
人工智能·python
财经资讯数据_灵砚智能13 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年5月18日
人工智能·信息可视化·自然语言处理
江苏赛融科技18 分钟前
打破传统管理壁垒,智慧园区重构楼宇资产管理模式
大数据·人工智能·智慧园区·楼宇资产管理·楼宇智能化