【问题标题】:How to Upload audio file in fast API for the prediction如何在 fastAPI 中上传音频文件以进行预测
【发布时间】:2020-12-18 16:31:45
【问题描述】:

我在 fastAPI 中上传音频文件时遇到内部错误

您好,我是 FastAPI 的新手,我必须为我的深度学习音频分类模型构建 API。

我已经尝试过这样做:

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    y, sr = librosa.load(file.filename)
    print(file.filename)
    S = librosa.feature.melspectrogram(
        y, sr=sr, n_fft=2048, hop_length=512, n_mels=128)
    mfccs = librosa.feature.mfcc(S=librosa.power_to_db(S), n_mfcc=40)
    # mfccs = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40)
    return mfccs
    #return {"filename": file.filename}

if __name__ == "__main__":
    # load model
    model = load_model("trained_heartbeat_classifier.h5")

classify_file = sys.argv[1]
x_test = []
x_test.append(create_upload_file(classify_file, 0.5))
x_test = np.asarray(x_test)
x_test = x_test.reshape(x_test.shape[0], x_test.shape[1], x_test.shape[2], 1)
pred = model.predict(x_test, verbose=1)
# print(pred)

pred_class = model.predict_classes(x_test)
if pred_class[0]:
    print("\nNormal heartbeat")
    print("confidence:", pred[0][1])
else:
    print("\nAbnormal heartbeat")
    print("confidence:", pred[0][0])

但是当我上传音频文件时出现错误: Internal Server Error

在终端中显示找不到文件。

那么我们必须在任何临时文件夹中保存音频文件吗?

【问题讨论】:

  • 我相信你必须在打开文件之前保存它。否则,根据库的实现方式,您可以直接将文件内容提供给解析器。试试y, sr = librosa.load(file.file)

标签: fastapi


【解决方案1】:

UploadFile 具有以下属性:

  • 文件名:带有上传的原始文件名的字符串

  • file:一个 SpooledTemporaryFile(一个类似文件的对象)。这是您可以直接传递给需要“类文件”对象的其他函数或库的实际 Python 文件。

所以如果你调用file.file,你会得到文件内容。在路由器函数内部进行预测和预处理活动,因为路由器函数不能称为传统函数。该函数在router decorator下实例化(见源码)。

注意:如果您不想等到预测到来,您可以使用后台任务或工作队列,来自工作队列的确认(使用带有 redis/rabbitmq 的 Celery)将通知您任务完成。如果您可以使用多个工作人员,工作队列也会并行任务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2021-02-12
    • 2021-04-19
    相关资源
    最近更新 更多