-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
53 lines (42 loc) · 1.38 KB
/
main.py
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
from model.classify_model import MNIST_Classify_Model, DataPreprocessing
import numpy as np
import torch
import base64
import cv2
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from fastapi import FastAPI
device = torch.device('mps')
SAVED_MODEL_PATH = "./model/model.pth"
CLASSIFY_MODEL = MNIST_Classify_Model().to(device)
CLASSIFY_MODEL.load_state_dict(torch.load(SAVED_MODEL_PATH))
IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNEL = 28, 28, 1
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
test_image = cv2.imread("./test.png", cv2.IMREAD_GRAYSCALE)
test_image = cv2.resize(test_image, (28, 28))
test_image = test_image.tobytes()
class RequestInput(BaseModel):
input: str
@app.get("/")
async def index():
return {"Message": ["Hello World"]}
@app.post("/predict")
async def predict(request: RequestInput):
print(request.input)
request_input = DataPreprocessing(
target_datatype=np.float32,
image_width=IMAGE_WIDTH,
image_height=IMAGE_HEIGHT,
image_channel=IMAGE_CHANNEL,
)(request.input)
prediction = CLASSIFY_MODEL(torch.tensor(request_input).to(device))
prediction = prediction.cpu().detach().numpy()
prediction = np.argmax(prediction, axis=1)
return {"prediction": prediction.tolist()}