python - 在 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 并将用户的动态文件路径作为参数。
解决方案
当您上传文件时,它会存储在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)
推荐阅读
- macos - 签署 Mac 安装程序 (.dmg) 的分步配方
- clickhouse - 多阵列 Clickhouse
- android - Android 应用程序可以正常运行,但会在调试器中崩溃
- html - 我可以将部分元素与字体大小同步吗?下图
- asp.net-core - 从 App.config 在 .NET Core 控制台应用程序中设置环境变量
- node.js - 我可以使用 Firebase 令牌 (JWT) 来识别过期日期 > 1 小时的用户吗?
- python - 为什么 PyCharm 调试器因“ImportError:无法导入名称‘heappush’”而崩溃
- powershell - Powershell:无法使用事件处理程序(按钮)打开串行端口
- c# - Ranorex 构建失败 9.4.1 未找到框架“.NETFramework,Version=v4.7.2”的参考程序集
- c# - C# Selenium WebDriver - 等待未完成的 HTTP 请求的解决方案