python - 为什么我的 fastapi 或 uvicorn 会关闭?

标签 python fastapi multilabel-classification uvicorn simpletransformers

我正在尝试运行使用简单转换器 Roberta 模型进行分类的服务。推理脚本/函数本身在测试时按预期工作。当我将它包含在快速 api 中时,它会关闭服务器。

uvicorn==0.11.8
fastapi==0.61.1
simpletransformers==0.51.6
cmd : uvicorn --host 0.0.0.0 --port 5000 src.main:app
@app.get("/article_classify")
def classification(text:str):
    """function to classify article using a deep learning model.
    Returns:
        [type]: [description]
    """

    _,_,result = inference(text)
    return result
错误 :
INFO:     Started server process [8262]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:5000 (Press CTRL+C to quit)
INFO:     127.0.0.1:36454 - "GET / HTTP/1.1" 200 OK
INFO:     127.0.0.1:36454 - "GET /favicon.ico HTTP/1.1" 404 Not Found
INFO:     127.0.0.1:36454 - "GET /docs HTTP/1.1" 200 OK
INFO:     127.0.0.1:36454 - "GET /openapi.json HTTP/1.1" 200 OK
before
100%|████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 17.85it/s]
INFO:     Shutting down
INFO:     Finished server process [8262]
推理脚本:
model_name = "checkpoint-3380-epoch-20"
model = MultiLabelClassificationModel("roberta","src/outputs/"+model_name)
def inference(input_text,model_name="checkpoint-3380-epoch-20"):
    """Function to run inverence on one sample text"""
    #model = MultiLabelClassificationModel("roberta","src/outputs/"+model_name)
    all_tags =[]
    if isinstance(input_text,str):
        print("before")
        result ,output = model.predict([input_text])
        print(result)
        tags=[]
        for idx,each in enumerate(result[0]):
            if each==1:
                tags.append(classes[idx])
        all_tags.append(tags)
    elif isinstance(input_text,list):
        result ,output = model.predict(input_text)
        tags=[]
        for res in result : 
            for idx,each in enumerate(res):
                if each==1:
                    tags.append(classes[idx])
            all_tags.append(tags)

    return result,output,all_tags
更新:尝试使用 flask 并且服务正在运行,但是当在 flask 顶部添加 uvicorn 时,它陷入了重启循环。

最佳答案

我已经通过显式使用多处理启动进程池解决了这个问题。

from multiprocessing import set_start_method
from multiprocessing import Process, Manager
try:
    set_start_method('spawn')
except RuntimeError:
    pass
@app.get("/article_classify")
def classification(text:str):
    """function to classify article using a deep learning model.
    Returns:
        [type]: [description]
    """
    manager = Manager()

    return_result = manager.dict()
    # as the inference is failing 
    p = Process(target = inference,args=(text,return_result,))
    p.start()
    p.join()
    # print(return_result)
    result = return_result['all_tags']
    return result

关于python - 为什么我的 fastapi 或 uvicorn 会关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65505710/

相关文章:

python - 从数组末尾取消填充全零行

graphql - FastAPI + GraphQL 在引发异常时出现错误 NoneType 是可调用的

machine-learning - Keras 如何更新多标签学习中的权重(实现方面)

python - 出现错误 "AttributeError: ' numpy.ndarray' 对象没有属性 'lower'“在单词标记器中

python - "is"和 "=="有什么区别?

在 macOS High Sierra 上找不到 Python 调试器 pdb

python - GRU加载模型错误,ValueError : GRU(reset_after=False) is not compatible with GRU(reset_after=True)

python - 动态设置可选端点参数

python - 使用标签传播/传播对具有多个标签的数据帧训练缺失标签