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

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

相关推荐
lqjun08274 分钟前
无分类器引导的条件生成模型
人工智能
美狐美颜sdk12 分钟前
从API到UI:直播美颜SDK中的滤镜与贴纸功能开发与落地方案详解
人工智能·ui·音视频·美颜sdk·视频美颜sdk·美颜api
菜只因C12 分钟前
嵌入式系统:技术演进、应用领域发展趋势全面解析
人工智能·软件工程
半青年23 分钟前
Qt读取Excel文件的技术实现与最佳实践
c语言·c++·python·qt·c#·excel
上海云盾商务经理杨杨24 分钟前
2025年AI与网络安全的终极博弈:冲击、重构与生存法则
人工智能·安全·web安全·网络安全·重构
AI360labs_atyun27 分钟前
谷歌前CEO TED演讲解析:AI 红利的三年窗口期与行业重构
人工智能·科技·ai·重构·llama·教育
无闻墨客29 分钟前
数据分析与应用---数据可视化基础
python·信息可视化·数据挖掘·数据分析·matplotlib
Jamence34 分钟前
多模态大语言模型arxiv论文略读(八十)
论文阅读·人工智能·语言模型·自然语言处理·论文笔记
xiaohanbao0935 分钟前
day30 python 模块、包与库的高效使用指南
人工智能·python·学习·算法
Q_Q196328847538 分钟前
python动漫论坛管理系统
开发语言·spring boot·python·django·flask·node.js·php