File size: 1,423 Bytes
ac29556 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | import base64
import io
import sys
from pathlib import Path
import numpy as np
import torch
from flask import Flask, jsonify, render_template, request
from PIL import Image
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
from model import CNN # noqa: E402
from preprocess import preprocess # noqa: E402
app = Flask(__name__)
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
_model = CNN(depth=5, use_residual=False).to(DEVICE)
_model.load_state_dict(torch.load(
Path(__file__).resolve().parent.parent / "runs/depth5/model.pt",
map_location=DEVICE, weights_only=True))
_model.eval()
@app.route("/")
def index():
return render_template("index.html")
@app.route("/predict", methods=["POST"])
def predict():
data = request.json.get("image", "")
png = base64.b64decode(data.split(",", 1)[-1])
img = Image.open(io.BytesIO(png)).convert("L")
arr = np.array(img, dtype=np.float32) / 255.0
arr = preprocess(arr)
with torch.no_grad():
x = torch.from_numpy(arr)[None, None].to(DEVICE)
probs = torch.softmax(_model(x), dim=1)[0].cpu().numpy()
top = probs.argsort()[::-1][:3]
return jsonify({
"digit": int(top[0]),
"confidence": float(probs[top[0]]),
"top3": [{"digit": int(d), "prob": float(probs[d])} for d in top],
})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5000, debug=False)
|