Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
65 lines (44 loc) · 1.38 KB
/
Copy pathmain.py
File metadata and controls
65 lines (44 loc) · 1.38 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
import base64
import io
from typing import List
import torch.nn.functional as F
from PIL import Image
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.middleware.cors import CORSMiddleware
from torchvision.transforms.functional import to_tensor
import torch
app = FastAPI(debug=True)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class ImageData(BaseModel):
img_base_64: str
def to_pil(self):
decoded_image = base64.b64decode(self.img_base_64)
img = Image.open(io.BytesIO(decoded_image))
img = img.convert('RGB')
return img
class PredResponse(BaseModel):
prediction: int
import onnxruntime as ort
import numpy as np
ort_sess = ort.InferenceSession('/Users/kopcion/swm-ai/rtcon/resnet101.onnx')
@app.post("/api/mnist", response_model=PredResponse)
async def mnist_predict(img_data: ImageData):
img = img_data.to_pil()
img = img.resize((224, 224))
img = to_tensor(img).unsqueeze(0)
output = ort_sess.run(None, {'input': img.numpy()})[0]
output = torch.from_numpy(output)
prediction = torch.argmax(output, dim=1).item()
return {
"prediction": prediction,
}
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="localhost", port=8081, log_level="info", reload=True)