一、通过Helsinki-NLP模型实现离线翻译接口
参考文档:https://blog.csdn.net/mzl87/article/details/127123445
1.1、开发环境配置
系统环境:WIN10
开发环境:pycharm
开发语言环境:
Python3.8.10-64bit
pip 21.1.1 (pip降级:python -m pip install pip==21.1.1)
常用命令:
查看python版本:python
查看pip版本:pip -V
查看当前安装的包:pip list
安装依赖包:pip install xx包
删除依赖包:pip uninstall xx包
1.2、安装依赖包
打开pycharm——创建项目——终端——执行安装包的命令:
可使用镜像地址提速:https://pypi.tuna.tsinghua.edu.cn/simple
1、pytorch包: pip install torch -i https://pypi.tuna.tsinghua.edu.cn/simple (如果本地已设置好镜像,则只输入“ pip install torch”即可)
2、flask包:pip install flask
3、gevent包: pip install gevent
4、transformers包:pip install transformers (自然语言框架)
5、sentencepiece包:pip install sentencepiece
6、pyinstaller包:pip install pyinstaller (打包为exe)
1.3、下载离线翻译模型
方式一:登录国外的网站:https://huggingface.co/Helsinki-NLP
登录上面网站的国内镜像网站(上面登录不了时):https://hf-mirror.com/
查找2个模型:‘Helsinki-NLP/opus-mt-zh-en’ 和 ‘Helsinki-NLP/opus-mt-en-zh’;
(说明:zh-en 表示中文转英文,en-zh 表示英文转中文)
方式二:
通过python脚本下载,创建ModelDownnload.py文件,代码如下:
import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' # 设置为hf的国内镜像网站
from huggingface_hub import snapshot_download
model_name = "Helsinki-NLP/opus-mt-en-zh"
# while True 是为了防止断联
while True:
try:
snapshot_download(
repo_id=model_name,
local_dir_use_symlinks=True, # 在local-dir指定的目录中都是一些“链接文件”
# ignore_patterns=["*.bin"], # 忽略下载哪些文件
local_dir=model_name,
# token="*************", # huggingface的token
resume_download=True
)
print("下载成功!")
break
except:
print("下载失败,未知原因!")
pass
默认下载到当前项目的根目录下。
1.4、搭建web翻译服务
创建MyTranslate.py文件,写入以下内容:
# -*- coding: utf-8 -*-
#离线翻译服务代码
import os
from flask import Flask, request
from gevent import pywsgi
from transformers import pipeline, AutoModelWithLMHead, AutoTokenizer
import warnings, requests
warnings.filterwarnings('ignore')
try:
print('\n\n 翻译服务 Designed by:Wesky \n\n\n')
print('正在加载【汉语-英语】翻译模型。。。 。。。')
model = AutoModelWithLMHead.from_pretrained('./Helsinki-NLP/opus-mt-zh-en', trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained('./Helsinki-NLP/opus-mt-zh-en', trust_remote_code=True)
translation = pipeline('translation_zh_to_en',model=model, tokenizer=tokenizer)
print('正在加载【英语-汉语】翻译模型。。。 。。。')
model_en2zh = AutoModelWithLMHead.from_pretrained('./Helsinki-NLP/opus-mt-en-zh', trust_remote_code=True)
tokenizer_en2zh = AutoTokenizer.from_pretrained('./Helsinki-NLP/opus-mt-en-zh', trust_remote_code=True)
translation_en2zh = pipeline('translation_en_to_zh', model=model_en2zh, tokenizer=tokenizer_en2zh)
app = Flask(__name__)
@app.route('/wesky-translater', methods=['POST'])
def translate():
mod = request.form['mod'] #定义路由、参数、以及根据翻译模式,选择指定的语言版本进行翻译
text = request.form['text']
if mod == 'zh2en':
result = translation(text, max_length=10240)[0]['translation_text']
return result
if mod == 'en2zh':
result = translation_en2zh(text, max_length=10240)[0]['tra