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

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

相关推荐
明月_清风2 分钟前
AI 时代,为什么架构师又开始谈"本体论"?
人工智能·后端·agent
千里码aicood8 分钟前
Flask-基于图神经网络的谣言检测研究
人工智能·神经网络·flask
ocean210315 分钟前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
触底反弹26 分钟前
面试被问到 Text2SQL,我用 DeepSeek 自己实现了一个
python·sqlite
妙码生花34 分钟前
使用git更新ai-go-admin框架
前端·人工智能·git·golang·typescript·php
Claire_8834 分钟前
企业网盘文件防泄露方案分析:权限管控、加密存储与AI检索能力对比
人工智能
2601_9622955836 分钟前
python+selenium实现自动化测试
自动化测试·python·selenium·学习心得·web端测试
室内定位小白38 分钟前
2026 年的大模型战争:GPT、Claude、Gemini、Grok 与中国模型,究竟谁更强?
人工智能·gpt
azhou的代码园38 分钟前
基于RFM模型的中小型企业客户管理系统
java·人工智能·spring boot·毕业设计
米小虾39 分钟前
AI 没有证明费马大定理:1300 万行 Lean 代码背后,是"可验证 AI"的新范式
人工智能