forked from robmarkcole/tensorflow-lite-rest-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtflite-server.py
More file actions
161 lines (137 loc) · 6.11 KB
/
tflite-server.py
File metadata and controls
161 lines (137 loc) · 6.11 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
"""
Expose tflite models via a rest API.
"""
import io
import sys
import numpy as np
import tflite_runtime.interpreter as tflite
from fastapi import FastAPI, File, HTTPException, UploadFile
from PIL import Image
from helpers import classify_image, read_labels, set_input_tensor
app = FastAPI()
# Settings
MIN_CONFIDENCE = 0.1 # The absolute lowest confidence for a detection.
# URL
FACE_DETECTION_URL = "/v1/vision/face"
OBJ_DETECTION_URL = "/v1/vision/detection"
SCENE_URL = "/v1/vision/scene"
# Models and labels
FACE_MODEL = "models/face_detection/mobilenet_ssd_v2_face/mobilenet_ssd_v2_face_quant_postprocess.tflite"
OBJ_MODEL = "models/object_detection/ssd_mobilenet_v2_coco_quant_postprocess_edgetpu.tflite"
OBJ_LABELS = "models/object_detection/mobilenet_ssd_v2_coco/coco_labels.txt"
SCENE_MODEL = "models/classification/dogs-vs-cats/model.tflite"
SCENE_LABELS = "models/classification/dogs-vs-cats/labels.txt"
# Setup object detection
obj_interpreter = tflite.Interpreter(model_path=OBJ_MODEL, experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
obj_interpreter.allocate_tensors()
obj_input_details = obj_interpreter.get_input_details()
obj_output_details = obj_interpreter.get_output_details()
obj_input_height = obj_input_details[0]["shape"][1]
obj_input_width = obj_input_details[0]["shape"][2]
obj_labels = read_labels(OBJ_LABELS)
# Setup face detection
face_interpreter = tflite.Interpreter(model_path=FACE_MODEL)
face_interpreter.allocate_tensors()
face_input_details = face_interpreter.get_input_details()
face_output_details = face_interpreter.get_output_details()
face_input_height = face_input_details[0]["shape"][1]
face_input_width = face_input_details[0]["shape"][2]
# Setup face detection
scene_interpreter = tflite.Interpreter(model_path=SCENE_MODEL)
scene_interpreter.allocate_tensors()
scene_input_details = scene_interpreter.get_input_details()
scene_output_details = scene_interpreter.get_output_details()
scene_input_height = scene_input_details[0]["shape"][1]
scene_input_width = scene_input_details[0]["shape"][2]
scene_labels = read_labels(SCENE_LABELS)
@app.get("/")
async def info():
return """tflite-server docs at ip:port/docs"""
@app.post(FACE_DETECTION_URL)
async def predict_face(image: UploadFile = File(...)):
try:
contents = await image.read()
image = Image.open(io.BytesIO(contents))
image_width = image.size[0]
image_height = image.size[1]
# Format data and send to interpreter
resized_image = image.resize((face_input_width, face_input_height), Image.ANTIALIAS)
input_data = np.expand_dims(resized_image, axis=0)
face_interpreter.set_tensor(face_input_details[0]["index"], input_data)
# Process image and get predictions
face_interpreter.invoke()
boxes = face_interpreter.get_tensor(face_output_details[0]["index"])[0]
classes = face_interpreter.get_tensor(face_output_details[1]["index"])[0]
scores = face_interpreter.get_tensor(face_output_details[2]["index"])[0]
data = {}
faces = []
for i in range(len(scores)):
if not classes[i] == 0: # Face
continue
single_face = {}
single_face["userid"] = "unknown"
single_face["confidence"] = float(scores[i])
single_face["y_min"] = int(float(boxes[i][0]) * image_height)
single_face["x_min"] = int(float(boxes[i][1]) * image_width)
single_face["y_max"] = int(float(boxes[i][2]) * image_height)
single_face["x_max"] = int(float(boxes[i][3]) * image_width)
if single_face["confidence"] < MIN_CONFIDENCE:
continue
faces.append(single_face)
data["predictions"] = faces
data["success"] = True
return data
except:
e = sys.exc_info()[1]
raise HTTPException(status_code=500, detail=str(e))
@app.post(OBJ_DETECTION_URL)
async def predict_object(image: UploadFile = File(...)):
try:
contents = await image.read()
image = Image.open(io.BytesIO(contents))
image_width = image.size[0]
image_height = image.size[1]
# Format data and send to interpreter
resized_image = image.resize((obj_input_width, obj_input_height), Image.ANTIALIAS)
input_data = np.expand_dims(resized_image, axis=0)
obj_interpreter.set_tensor(obj_input_details[0]["index"], input_data)
# Process image and get predictions
obj_interpreter.invoke()
boxes = obj_interpreter.get_tensor(obj_output_details[0]["index"])[0]
classes = obj_interpreter.get_tensor(obj_output_details[1]["index"])[0]
scores = obj_interpreter.get_tensor(obj_output_details[2]["index"])[0]
data = {}
objects = []
for i in range(len(scores)):
single_object = {}
single_object["label"] = obj_labels[int(classes[i])]
single_object["confidence"] = float(scores[i])
single_object["y_min"] = int(float(boxes[i][0]) * image_height)
single_object["x_min"] = int(float(boxes[i][1]) * image_width)
single_object["y_max"] = int(float(boxes[i][2]) * image_height)
single_object["x_max"] = int(float(boxes[i][3]) * image_width)
if single_object["confidence"] < MIN_CONFIDENCE:
continue
objects.append(single_object)
data["predictions"] = objects
data["success"] = True
return data
except:
e = sys.exc_info()[1]
raise HTTPException(status_code=500, detail=str(e))
@app.post(SCENE_URL)
async def predict_scene(image: UploadFile = File(...)):
try:
contents = await image.read()
image = Image.open(io.BytesIO(contents))
resized_image = image.resize((scene_input_width, scene_input_height), Image.ANTIALIAS)
results = classify_image(scene_interpreter, image=resized_image)
label_id, prob = results[0]
data = {}
data["label"] = scene_labels[label_id]
data["confidence"] = prob
data["success"] = True
return data
except:
e = sys.exc_info()[1]
raise HTTPException(status_code=500, detail=str(e))