【问题标题】:Creating an API of ML model using Flask in Python在 Python 中使用 Flask 创建 ML 模型的 API
【发布时间】:2020-05-18 18:24:43
【问题描述】:

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

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

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 并将用户的动态文件路径作为参数。

【问题讨论】:

    标签: python json api flask


    【解决方案1】:

    当您上传文件时,它会存储在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)
    

    【讨论】:

    • 这里是关于上传文件的官方flask文档:flask.palletsprojects.com/en/1.1.x/patterns/fileuploads>
    • 我不确定如何在点击 url 时提供 image_path 作为输入:“localhost:5000/image_reader”。我应该在 URL 本身中提供路径吗?类似“localhost:5000/image_reader/C:\\Users\\Desktop\\file.png”?我应该如何提供 file_path 来编程?
    • 你用什么来提出请求?您只是在使用网络浏览器吗?
    猜你喜欢
    • 2019-01-21
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2021-02-20
    • 2017-01-12
    • 2020-06-09
    相关资源
    最近更新 更多