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

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

相关推荐
geneculture8 分钟前
亚符号:人机互助中被忽视的根基——一种认知哲学分析
人工智能·融智学的重要应用·人机间性·符号与规则·亚符号与权重·融智时代杂志
aisifang008 分钟前
PDF转Word神器:Gemini3.1Pro一键搞定文档处理
人工智能·pdf·word
东坡肘子9 分钟前
让 AI 从称手到称心 -- 肘子的 Swift 周报 #134
人工智能·swiftui·swift
la_vie_est_belle10 分钟前
Pygame Studio——用Python自制的一款可视化游戏编辑器
python·游戏·编辑器·游戏引擎·pygame·pyside6·pygame-ce
潘祖记11 分钟前
# 一行命令让 AI 接管全屋智能:FeyaGate Skill 保姆级接入教程,小米/涂鸦/美的/易微联全搞定
人工智能·后端·asp.net
joshchen21516 分钟前
强化学习基础(赵世钰)第二章 贝尔曼方程
人工智能·python·机器学习·强化学习
魔术师Grace17 分钟前
普通人学 AI,不要一上来就学提示词
前端·人工智能·程序员
小妖同学学AI18 分钟前
架构图即代码:GitHub星标41.9k的Diagrams,用Python解放你的画图生产力
开发语言·python·github
数字化转型202520 分钟前
10年之后的未来:AI + 机器人成为主要价值创造者
人工智能
ZhengEnCi21 分钟前
01d-前馈神经网络代码实现 💻
人工智能·深度学习·神经网络