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

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

相关推荐
机器之心3 分钟前
三百年几何猜想被推翻,数学家首次发现「穿不过去」的多面体
人工智能·openai
技术闲聊DD31 分钟前
深度学习(15)-PyTorch torch.nn 参考手册
人工智能·pytorch·深度学习
缘友一世34 分钟前
LLama 3分组查询注意力与KV缓存机制
人工智能·深度学习·缓存·transformer·llama·gqa·kv缓存
说私域43 分钟前
开源AI智能客服、AI智能名片与S2B2C商城小程序融合下的商家客服能力提升策略研究
人工智能·小程序
IT古董1 小时前
【第五章:计算机视觉-项目实战之推荐/广告系统】2.粗排算法-(2)理解粗排模型之离线部分:双塔模型结构精讲及实现
人工智能·算法·计算机视觉
AI小云1 小时前
【Python高级编程】类属性与类方法
人工智能·python
Chef_Chen1 小时前
数据科学每日总结--Day4--数据挖掘
人工智能·数据挖掘
lxmyzzs1 小时前
【图像算法 - 31】基于深度学习的太阳能板缺陷检测系统:YOLOv12 + UI界面 + 数据集实现
人工智能·深度学习·算法·yolo·缺陷检测
上官胡闹1 小时前
基于vLLM的PaddleOCR-VL部署指南
人工智能·百度飞桨
B站计算机毕业设计之家1 小时前
深度学习:YOLOv8人体行为动作识别检测系统 行为识别检测识系统 act-dataset数据集 pyqt5 机器学习✅
人工智能·python·深度学习·qt·yolo·机器学习·计算机视觉