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

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

相关推荐
三川6983 分钟前
Tkinter库的学习记录08- 容器控件
python
新知图书6 分钟前
本书学习路径与前置知识要求
人工智能·多模态·ai agent·智能体
c_lb72887 分钟前
近期AI量化工具选择,学习开发执行要分开
人工智能·python
天天进步201513 分钟前
Python全栈项目--校园食堂点餐与推荐系统
开发语言·python
AI科技星13 分钟前
特征值与特征向量不是矩阵特殊解,是变换矩阵下不改变生长方向、仅缩放体量的固有主螺旋脉络 -《全域数学vs传统数学:人类文明进阶200讲》第73讲
人工智能·线性代数·矩阵·数据挖掘·回归·乖乖数学·全域数学
Ulyanov15 分钟前
雷达导引头体制演进、技术特点与数学模型
python·雷达电子对抗·导引头
科技发布15 分钟前
可出具正规收录回执广告平台推荐,朝闻通合规投放满足企业审计需求
大数据·人工智能·科技·媒体
Promise微笑27 分钟前
激光清障仪市场与技术深度分析:基于原理、应用及厂家格局的综述
大数据·人工智能·物联网
eybk30 分钟前
写一个可以编制pdf文件的python程序
开发语言·python·pdf
大郭鹏宇30 分钟前
LangChain Model I/O 完全指南:从模型调用到多平台实战
人工智能