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

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

相关推荐
盘古开天16662 分钟前
通俗易懂:YOLO模型原理详解,从零开始理解目标检测
人工智能·yolo·目标检测
OpenBuild.xyz3 分钟前
x402 生态系统:Web3 与 AI 融合的支付新基建
人工智能·web3
王哈哈^_^9 分钟前
【完整源码+数据集】高空作业数据集,yolo高空作业检测数据集 2076 张,人员高空作业数据集,目标检测高空作业识别系统实战教程
人工智能·算法·yolo·目标检测·计算机视觉·目标跟踪·视觉检测
猿小猴子12 分钟前
主流 AI IDE 之一的 Comate IDE 介绍
ide·人工智能·comate
scala舔狗汪14 分钟前
双层跳动爱心❤️❤️💕💕
python
Rolei_zl22 分钟前
AIGC(生成式AI)试用 40 -- 程序(Python + OCR)-2
python·aigc
可触的未来,发芽的智生27 分钟前
触摸未来2025-11-09:万有力,图论革命
javascript·人工智能·python·程序人生·自然语言处理
悟乙己28 分钟前
超越文本:利用大型语言模型进行时间序列预测(第1部分)
人工智能·语言模型·自然语言处理
ZEERO~33 分钟前
夏普比率和最大回撤公式推导及代码实现
大数据·人工智能·机器学习·金融
飞哥数智坊34 分钟前
11月12日,TRAE SOLO 正式版发布
人工智能·ai编程·solo