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

​

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

相关推荐
howdoyoudo2026062 小时前
AI基建融资信用分层:谁被挤出GPU抵押市场?
大数据·人工智能·安全·microsoft·ai·语言模型
牛老师讲GIS2 小时前
透过 GeoLibre AI 助手,Agentic WebGIS 该如何架构与发展?
人工智能·geolibre ai 助手·agentic webgis
可信计算2 小时前
从单视口渲染到分支击穿:关于概率、脑神经与“创世启动器”的一些构想
人工智能·笔记
科技每日热闻2 小时前
大模型 API 调用遭遇限制时,推荐哪些支持弹性扩展和稳定调用的云平台?
大数据·网络·人工智能·ai
广州工博科技2 小时前
在咨询领域,AI 有哪些用途?
人工智能
AIHR数智引擎2 小时前
蚂蚁350亿换不来智能体飞轮?拆中台和流水线
人工智能·经验分享·职场和发展·ai-native·aihr
snakeshe10102 小时前
Python面向对象编程(OOP)与Lambda表达式入门实战
人工智能
silvercarp20262 小时前
Codex CLI / Claude Code 接自建网关:base_url 与协议踩坑记录
人工智能
坊钰2 小时前
【LangGraph框架入门级】4. 支持联网搜索的智能代理系统
python·ai编程·langgraph
xsd202411182 小时前
VoxCPM:砍掉语音分词器的开源TTS,连续潜空间实现3秒克隆与48kHz多语种
人工智能