-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
68 lines (48 loc) · 1.62 KB
/
Copy pathapp.py
File metadata and controls
68 lines (48 loc) · 1.62 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
66
67
68
import numpy as np
import PIL.Image
import io
from contextlib import asynccontextmanager
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from tensorflow.keras.applications.efficientnet import EfficientNetB0
from tensorflow.keras.applications.efficientnet import preprocess_input, decode_predictions
model_dict = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
## --------startup tasks--------
# 1. Load the ML model
model_dict['model'] = EfficientNetB0()
yield
## --------shutdown tasks--------
app = FastAPI(lifespan = lifespan,
title = "Image Classifiction API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def convert_to_output(preds):
decoded_preds = decode_predictions(preds, top=5)[0]
out = ''
for p in decoded_preds:
out += str(p[1])
out += ': '
out += str(p[2])
out += '; '
out += '<br>'
return out
@app.get("/")
async def root():
return {"healthCheck": "OK"}
@app.post('/predict-image/')
async def predict_image(file: UploadFile = File(...)):
contents = await file.read()
img_pil = PIL.Image.open(io.BytesIO(contents))
img_pil = img_pil.resize((224, 224), PIL.Image.LANCZOS)
img_arr = np.array(img_pil)[:, :, :3] # take first 3 channels (without transparency)
img_arr = np.expand_dims(img_arr, axis=0)
img_arr = preprocess_input(img_arr)
preds = model_dict['model'].predict(img_arr)
return {'predictions' : convert_to_output(preds)}