使用 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设计·bim正向设计·国产二三维设计软件·飞扬集成设计系统
自律懒人2 分钟前
当AI智能体学会了操控浏览器:Chrome CDP + 自动化Agent实战
人工智能·chrome·自动化
用户5191495848452 分钟前
WP NssUser Register 权限提升漏洞利用工具 (CVE-2024-54363)
人工智能·aigc
Elastic 中国社区官方博客5 分钟前
Elasticsearch:使用预计算上下文降低 agent 成本
大数据·人工智能·elasticsearch·搜索引擎·ai·全文检索
Lumos_yuan5 分钟前
What is data ?
人工智能
码以致用8 分钟前
OpenFoundry 开源数据操作系统:架构解析与实战指南
人工智能·ai·架构·开源
m0_715674438 分钟前
技术创新突破·可管可控·对标行标 医疗API安全解决方案实践指南
大数据·人工智能·安全
SelectDB技术团队12 分钟前
97% 召回率、900 QPS:Apache Doris 4.1 生产级向量检索的工程实践
数据库·人工智能·数据分析·apache doris·selectdb
skywalk816319 分钟前
python run.py “请讨论一下中文编程语言的设计“ --max-rounds 4
开发语言·人工智能