-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
43 lines (33 loc) · 1.03 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
## To run:
## uvicorn main:app --reload
## And then open the index.html
## pip install fastapi
## pip install uvicorn
## pip install pillow
## pip install scikit-learn
import io
import pickle
import numpy as np
import PIL.Image
import PIL.ImageOps
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
with open('mnist_model.pkl', 'rb') as f:
model = pickle.load(f)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)
@app.post("/predict-image/")
async def predict_image(file: UploadFile = File(...)):
contents = await file.read()
pil_image = PIL.Image.open(io.BytesIO(contents)).convert('L')
pil_image = PIL.ImageOps.invert(pil_image)
pil_image = pil_image.resize((28,28), PIL.Image.LANCZOS)
img_array = np.array(pil_image).reshape(1, -1)
prediction = model.predict(img_array)
return {"prediction": int(prediction[0])}