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

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

相关推荐
薛定e的猫咪3 分钟前
【调试技巧】vscode 四种断点调试,快速定位 bug
ide·vscode·python·bug
CadeCode3 分钟前
Python 开发环境与包管理
python
only-code3 分钟前
Fast-DetectGPT:用“条件概率曲率”拆穿 AI 伪装的文本
人工智能·深度学习·机器学习·ai大模型·论文解读·ai检测·文本检测
爱写代码的小朋友18 分钟前
Python局域网远程监控电脑屏幕实现
python·flask·python监控电脑屏幕
岚天start18 分钟前
Java程序生成Heap Dump堆内存快照文件的多种方法
开发语言·python·pycharm
兆。21 分钟前
python全栈-人工智能基础-机器学习
人工智能·python·机器学习
魔镜前的帅比30 分钟前
Few-shot / Chain-of-Thought 提示技巧
人工智能·chatgpt
深度学习lover40 分钟前
<项目代码>yolo遥感航拍船舶识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·遥感船舶识别
Coovally AI模型快速验证44 分钟前
基于SimCLR的自监督 YOLO:YOLOv5/8也能在低标注场景目标检测性能飙升
人工智能·科技·yolo·目标检测·机器学习·计算机视觉
不老刘1 小时前
新一代图像生成工具:Nano Banana Pro 带来更自然的创作体验
人工智能·google·gemini·nano banana pro