首页 > 解决方案 > 在 Python 中使用 Flask 创建 ML 模型的 API

问题描述

我想使用烧瓶创建我的 ML 模型的 API。该模型只是获取图像并对其进行分类。我想上传我的模型的泡菜文件,并希望用户在运行时动态上传图像文件作为我的功能运行的参数。

以下是我尝试过的代码片段,但存在一些问题,因为我无法从硬盘中检索文件:

from flask import Flask, request
import requests
import os
from tensorflow import keras as tfk
import matplotlib.pyplot as plt
from PIL import Image
from numpy import asarray
import pickle

app = Flask(__name__)


@app.route("/")
def hello():
    return "Image Classifier!"

@app.route('/', defaults={'path': ''})
@app.route('/image_reader/<path:image_path>/<pickle_file>', methods=['GET', 'POST'])
def image_classification(image_path):
    if request.json:
        data = request.get_json(image_path)

        image_path = data.get("image_path")
        print(image_path)
        r = requests.get(image_path, timeout=60)

        # save the image to disk
        temp_file = 'tmp/temp.jpg'
        f = open(temp_file, "wb")
        f.write(r.content)
        f.close()

        model = pickle.load(pickle_file)

        return image_path
    else:
        return "no json received"


if __name__ == '__main__':
    app.run(debug=True)

最初,我只是尝试采用上述两个参数,即上传pickle_file 并将用户的动态文件路径作为参数。

标签: pythonjsonapiflask

解决方案


当您上传文件时,它会存储在request.files字典中。

相反,你应该做的是这样的:

from flask import Flask, request
import requests
import os
from tensorflow import keras as tfk
import matplotlib.pyplot as plt
from PIL import Image
from numpy import asarray
import pickle

app = Flask(__name__)


@app.route("/")
def hello():
    return "Image Classifier!"

@app.route('/', defaults={'path': ''})
@app.route('/image_reader', methods=['POST'])
def image_classification():
    if request.method == 'POST':
        image_file = request.file.get('image_path')        
        pickle_file = request.file.get('pickle_file')

        # save the image to disk
        temp_file = 'tmp/temp.jpg'
        image_file.save(temp_file)

        # Save the pickle file to disk
        temp_picke_file = 'tmp/model.pickle'
        pickle_file.save(temp_pickle_file)

        # Load the model using the pickle file
        model = pickle.load(open(temp_pickle_file,'w'))

        return "Image saved to " + temp_file


if __name__ == '__main__':
    app.run(debug=True)

推荐阅读