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

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

相关推荐
l1t6 小时前
我改写的二分法XML转CSV文件程序速度追上了张泽鹏先生的
xml·c语言·人工智能·算法·expat
roshy6 小时前
MCP(模型上下文协议)入门教程1
人工智能·大模型·agent
一碗白开水一6 小时前
【论文阅读】Far3D: Expanding the Horizon for Surround-view 3D Object Detection
论文阅读·人工智能·深度学习·算法·目标检测·计算机视觉·3d
nju_spy6 小时前
李沐深度学习论文精读(二)Transformer + GAN
人工智能·深度学习·机器学习·transformer·gan·注意力机制·南京大学
山烛6 小时前
OpenCV 银行卡号识别
人工智能·opencv·计算机视觉·图像识别·数字识别
用户5191495848456 小时前
强大的OSINT情报工具:Blackbird用户名与邮箱搜索分析平台
人工智能·aigc
非晓为骁6 小时前
【AI】AI 评测入门(二):Prompt 迭代实战从“能跑通”到“能落地”
人工智能·prompt·提示词工程·ai评测
张较瘦_6 小时前
[论文阅读] 人工智能 + 软件工程 | TDD痛点破解:LLM自动生成测试骨架靠谱吗?静态分析+专家评审给出答案
论文阅读·人工智能·软件工程
字节数据平台7 小时前
一客一策:Data Agent 如何重构大模型时代的智能营销
大数据·人工智能·重构
咖啡Beans7 小时前
Python工具DrissionPage推荐
后端·python