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

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

相关推荐
之歆12 分钟前
Python-封装和解构-set及操作-字典及操作-解析式生成器-内建函数迭代器-学习笔记
笔记·python·学习
麻雀无能为力29 分钟前
CAU数据挖掘 支持向量机
人工智能·支持向量机·数据挖掘·中国农业大学计算机
智能汽车人43 分钟前
Robot---能打羽毛球的机器人
人工智能·机器人·强化学习
埃菲尔铁塔_CV算法43 分钟前
基于 TOF 图像高频信息恢复 RGB 图像的原理、应用与实现
人工智能·深度学习·数码相机·算法·目标检测·计算机视觉
ζั͡山 ั͡有扶苏 ั͡✾1 小时前
AI辅助编程工具对比分析:Cursor、Copilot及其他主流选择
人工智能·copilot·cursor
东临碣石821 小时前
【AI论文】数学推理能否提升大型语言模型(LLM)的通用能力?——探究大型语言模型推理能力的可迁移性
人工智能·语言模型·自然语言处理
天天爱吃肉82181 小时前
ZigBee通信技术全解析:从协议栈到底层实现,全方位解读物联网核心无线技术
python·嵌入式硬件·物联网·servlet
未来智慧谷1 小时前
微软医疗AI诊断系统发布 多智能体协作实现疑难病例分析
人工智能·microsoft·医疗ai
野生技术架构师1 小时前
简述MCP的原理-AI时代的USB接口
人工智能·microsoft
Allen_LVyingbo2 小时前
Python常用医疗AI库以及案例解析(2025年版、上)
开发语言·人工智能·python·学习·健康医疗