前提・実現したいこと
pythonとVSCodeを用いて、自分で学習させたモデルを使用したWebアプリを作ろうとしています。
ローカルの環境でWebを動かそうとしたのですが、画像の入力を行うと、chrome上で "400 Bad Request" と表示されてしまいます。エラーメッセージで調べてみても、あまり有力な情報が得られなかったため、こちらで質問させていただきました。
実行したpredict.py
from flask import Flask, render_template, request, redirect, url_for import numpy as np from PIL import Image from datetime import datetime from torchvision import datasets, models, transforms from wtforms import Form, FloatField, SubmitField, validators, ValidationError import joblib import cv2 import torch import torch.nn as nn import tensorflow as tf app = Flask(__name__) @app.route('/', methods = ['GET', 'POST']) def upload_file(): if request.method == 'GET': return render_template('index.html') if request.method == 'POST': # アプロードされたファイルを保存する """ f = request.files['file'] filepath = "./static/" + datetime.now().strftime("%Y%m%d%H%M%S") + ".png" f.save(filepath) """ filepath = "./static/" + datetime.now().strftime("%Y%m%d%H%M%S") + ".png" img_dir = "static/" stream = request.files['img'].stream img_array = np.asarray(bytearray(stream.read()), dtype=np.uint8) img = cv2.imdecode(img_array, 1) #モデルの読み込み model = models.resnet18(pretrained=False).to(torch.device('cpu')) num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, 8) #出力クラス8 model.load_state_dict(torch.load('./ResNet.pkl')) #入力データ作成 cv2.imwrite(filepath, img) img = cv2.resize(img , (224, 224)) params = torch.Tensor(img) x = torch.tensor([img]) predict = model(x) return render_template('index.html', filepath = filepath , predict = torch.argmax(predict).numpy() ) #return render_template('result.html', filepath = filepath, irisName=torch.argmax(predict).numpy()) if __name__ == '__main__': app.run(host="0.0.0.0", port=int("5000"),debug=False)
index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>pHAI Protocol Header</title> </head> <body> {% if predict %} <IMG SRC="{{filepath}} " BORDER="1"> predict:{{predict}} <BR> <HR> {% endif %} 画像を選択して下さい<BR> <form action = "./" method = "POST" enctype = "multipart/form-data"> <input type = "file" name = "file" /> <input type = "submit"/> </form> </body> </html>
VSCode上のメッセージ
Use a production WSGI server instead. * Debug mode: off * Running on all addresses. WARNING: This is a development server. Do not use it in a production deployment. * Running on http://192.168.10.9:5000/ (Press CTRL+C to quit) 192.168.10.9 - - [25/Jul/2021 18:02:52] "GET / HTTP/1.1" 200 - 192.168.10.9 - - [25/Jul/2021 18:03:57] "POST / HTTP/1.1" 400 -
Chromeでのエラーメッセージ
Bad Request
The browser (or proxy) sent a request that this server could not understand.

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。