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

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

相关推荐
简简单单OnlineZuozuo1 分钟前
设计共情:面向真实系统的人本AI模式
人工智能·microsoft·架构·图像识别·banana·the stanford ai
高洁011 分钟前
【无标题】
人工智能·深度学习·算法·机器学习·transformer
大千AI助手10 分钟前
Dockerfile中pip镜像源的优雅配置:告别重复,拥抱高效
python·docker·pip·镜像源·pypi·大千ai助手
Coder_Boy_11 分钟前
基于SpringAI企业级智能教学考试平台全流程图示化总结:架构、协同与逻辑闭环
人工智能·spring boot·spring cloud
我命由我1234513 分钟前
PyCharm - Install Plugin from Disk 从本地磁盘加载插件
服务器·开发语言·python·学习·pycharm·学习方法·python3.11
DeepVis Research13 分钟前
【NLP/Microservices】2026年度语义逻辑编译与分布式微服务架构基准索引 (Benchmark Index)
算法·微服务·自然语言处理·架构·数据集·编译原理
许泽宇的技术分享14 分钟前
打破AI调用壁垒:Antigravity Tools如何用Rust+Tauri重构你的AI工作流
人工智能·重构·rust
、BeYourself17 分钟前
Spring AI ETL Pipeline Transformers 详细指南
人工智能·spring·etl·springai
fawubio_A1 小时前
毕业设计项目 车道线检测(自动驾驶 机器视觉)
python·毕业设计·毕设
郭wes代码1 小时前
Pygame--谷歌小恐龙游戏(附彩蛋+保姆级教程)
python·游戏