【模型部署】使用Flask部署算法模型

Flask介绍

Flask是一个非常轻量级的Python Web框架。使用Flask可以很容易地部署算法服务,通过HTTP方式对外提供API响应接口。
敏感词检测算法为例。 如果要部署其他算法,代码对应做一些修改既可。

部署代码

from flask import Flask, request
from sensitive_word_detect import SensitiveWordDetect

app = Flask(__name__)

# 此处做一些文件读取、类实例化、计算图加载等预处理的工作
sensitive_words_path = './word_files/senti_words.txt' # 敏感词列表
stopWords_path = './word_files/stop_words.txt' # 特殊符号列表
detector = SensitiveWordDetect(sensitive_words_path, stopWords_path)

@app.route('/sentiwords', methods=("POST",))
def sentiwords():
    line = request.form['line']
    
    sensitive_words = ''
    if line.strip() != '':
        _, sensitive_lst = detector.replace_sensitive_word(line)
        for word in sensitive_lst:
            sensitive_words += word + ','
    
    if sensitive_words.strip() == '':
        rst = {
                "legal":"通过",
                "body":[]
        }
    else:
        rst_lst = []
        if sensitive_words.strip() != '':
            rst_lst.append({
                       "type":"包含敏感词",
                       "content":sensitive_words
                    })
        rst = {
            "legal":"不通过",
            "body":rst_lst
        }
    return rst

if __name__ == '__main__':
    app.config['JSON_AS_ASCII'] = False
    app.run(host='0.0.0.0', port=8000)

调用测试

# coding=UTF-8
from datetime import datetime
import requests

starttime = datetime.now()

text_path = "./test_files/000.txt"  # 文本路径

content = [] # 临时存储文本
with open(text_path, 'r', encoding='utf-8') as f:
    content = f.readlines()

line = ''.join(content)
data = {"line": line}
headers = {
    'Connection': 'close',
    }
r = requests.post('http://0.0.0.0:8000/sentiwords', data=data, headers=headers)

if str(r.status_code) != '200':
    print("status_code: ", str(r.status_code))
    print(r.text)
    
elif r.json()['legal'] == '不通过':
    for temp in r.json()['body']:
        if temp['type'] == '包含敏感词':
            sensitive_word_result = temp['content']
    print(sensitive_word_result)
        
endtime = datetime.now()
time_consume = endtime - starttime
print('敏感词检测完成,共用时{}'.format(time_consume))
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值