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

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

相关推荐
蓝星空2000几秒前
GPT-Image-2 实战教程:一段提示词生成专业分镜图(含 9 格脚本模板,附一键同款)
人工智能·gpt·image2·imagen
用户337922545682 分钟前
从字节跳动 DeerFlow 源码看 Agent 平台设计(二):工具系统设计 — 从全量绑定到按需加载
人工智能
IT 行者9 分钟前
GitHub Spec Kit 实战(四):读懂和干预 /speckit.plan——AI 最自由发挥的一步
java·人工智能·github·ai编程·claude
城事漫游Molly10 分钟前
AI辅助实验设计的标准工作流
人工智能·提示词·ai for science·科研论文·实验设计
tianxingjian201911 分钟前
科技创新核心工具,TRIZ理论助力技术难题高效突破
大数据·人工智能·科技
极客老王说Agent15 分钟前
自动化架构演进:2026年有比RPA更加稳定的技术吗?
人工智能·ai·chatgpt·架构·自动化·rpa
tsfy200322 分钟前
Python批量调整Excel格式,并排版导出PDF
python·pdf·excel
静Yu26 分钟前
从“生成一篇知识点”到“面对面讲清一道题”:我用魔珐星云改造 AI 教育助手的实践
人工智能
陈天伟教授27 分钟前
图解人工智能(60)人工智能应用-AI游戏
人工智能·游戏
deephub30 分钟前
AI Agent的三重记忆机制:打造高可用的多维记忆系统
人工智能·大语言模型·agent·记忆