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

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

相关推荐
江华森11 小时前
Gephi 可视化 + NetworkX 网络分析——《釜山行》人物关系(三)
数据库·python
环境栈笔记11 小时前
AI 浏览器任务失败怎么排查:Context、Session、Page State 和 Task Log 检查清单
前端·人工智能·后端·自动化
Be-real11 小时前
机器学习:欠拟合、过拟合、偏差方差超全详解
人工智能·机器学习·过拟合·欠拟合
饼干哥哥11 小时前
Lovart真的帮大忙了,一键直出品牌视觉套件和个人IP封面Skill
人工智能·代码规范·设计
私人珍藏库11 小时前
[Android] Npatch-免Root框架+可内置模块
android·人工智能·智能手机·工具·软件
147API11 小时前
Claude 的 Microsoft 365 connector 能写入了,技术接入别跳过权限验收
人工智能·microsoft·claude
进击切图仔11 小时前
基于千问的白盒蒸馏操作教学文档
服务器·人工智能·python
战族狼魂11 小时前
每日一课:算法系统学习路线
人工智能·算法·大模型·大语言模型
七牛云行业应用11 小时前
Codex Desktop 怎么安装:Windows、macOS 全平台完整教程
人工智能·windows·macos
Token炼金师11 小时前
提词的艺术:Few-shot、CoT、Function Calling、ReAct 与自洽性 —— Prompt 工程六技
人工智能·llm·prompt·react·function call·cot·few-show