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

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

相关推荐
在水一缸6 分钟前
深度解析 GPT-5.6:大模型架构演进与复杂任务实战指南
大数据·人工智能·gpt·架构·大模型·架构演进·gpt-5.6
ltqvibe9 分钟前
企业AI应用开发框架到底解决什么问题
人工智能·深度学习
AI784021 分钟前
开源与闭源博弈:正在决定未来AI产业的生态走向
人工智能·开源
集芯微电科技有限公司22 分钟前
PC3100H 专为TFT-LCD面板偏置电源设计双输出100m电流
人工智能·单片机·嵌入式硬件·神经网络·生成对抗网络
无忧智库36 分钟前
智慧电厂:引领发电行业新革命(PPT)
大数据·人工智能
Oflycomm44 分钟前
物理AI时代的“连接底座”:Wi-Fi 7模组如何撑起具身智能的神经网络
人工智能·深度学习·神经网络·物联网·具身智能·wifi7
许彰午1 小时前
100_Python面试常见问题汇总
java·python·面试
皓悦编程记1 小时前
【YOLO26 系列】基于YOLO26的垃圾分类检测系统【python源码+Pyqt5界面/WEB+数据集+训练代码】
python·qt·分类
hughnz1 小时前
海上钻井平台的“绿色革命”:如何破解能源世界的“不可能三角”
人工智能
滴滴滴嘟嘟嘟.1 小时前
强化学习消融实验-batch_size / clip_range / gae_lambda / lr
python·机器学习