zoukankan      html  css  js  c++  java
  • 【模型部署】使用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))
    
  • 相关阅读:
    Windows下的SASS环境搭建
    cocos开发环境搭建
    cocos2d-x中描述精灵帧图片的plist和json文件各个key的含义
    seajs模块路径解析 简单总结
    【LESS系列】内置函数说明
    Zepto自定义模块打包构建
    【LESS系列】高级特性
    【LESS系列】三角形Mixins
    关于delete和对象复制
    vue使用技巧
  • 原文地址:https://www.cnblogs.com/yanqiang/p/13535161.html
Copyright © 2011-2022 走看看