Download web/app.py from shyo2/cnn0: direct link, hf CLI and curl.
- Browser
- Download file 1.42 kB
-
https://huggingface.co/shyo2/cnn0/resolve/main/web/app.py
- Command line
-
hf download hf://shyo2/cnn0/web/app.py
-
curl -L -o app.py https://huggingface.co/shyo2/cnn0/resolve/main/web/app.py
1.42 kB
| 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() | |
| def index(): | |
| return render_template("index.html") | |
| 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) | |