-
Notifications
You must be signed in to change notification settings - Fork 56
/
app.py
344 lines (295 loc) · 11.6 KB
/
app.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
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# WARNING: you are on the master branch, please refer to the examples on the branch that matches your `cortex version`
import signal, os, time, json, queue, socket, click, cv2, pandas as pd
import multiprocessing as mp
import threading as td
import logging
logger = logging.getLogger()
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_format = logging.Formatter(
"%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(message)s"
)
stream_handler.setFormatter(stream_format)
logger.addHandler(stream_handler)
logger.setLevel(logging.DEBUG)
disable_loggers = ["urllib3.connectionpool"]
for name, logger in logging.root.manager.loggerDict.items():
if name in disable_loggers:
logger.disabled = True
from gps import ReadGPSData
from workers import BroadcastReassembled, InferenceWorker, Flusher, session
from utils.image import resize_image, image_to_jpeg_bytes
from utils.queue import MPQueue
from requests_toolbelt.adapters.source import SourceAddressAdapter
class GracefullKiller:
"""
For killing the app gracefully.
"""
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self, signum, frame):
self.kill_now = True
class WorkerPool(mp.Process):
"""
Pool of threads running in a different process.
"""
def __init__(self, name, worker, pool_size, *args, **kwargs):
"""
name - Name of the process.
worker - Derived class of thread to execute.
pool_size - Number of workers to have.
"""
super(WorkerPool, self).__init__(name=name)
self.event_stopper = mp.Event()
self.Worker = worker
self.pool_size = pool_size
self.args = args
self.kwargs = kwargs
def run(self):
logger.info("spawning workers on separate process")
pool = [
self.Worker(
self.event_stopper,
*self.args,
**self.kwargs,
name="{}-Worker-{}".format(self.name, i),
)
for i in range(self.pool_size)
]
[worker.start() for worker in pool]
while not self.event_stopper.is_set():
time.sleep(0.001)
logger.info("stoppping workers on separate process")
[worker.join() for worker in pool]
def stop(self):
self.event_stopper.set()
class DistributeFramesAndInfer:
"""
Custom output class primarly built for the PiCamera class.
Has 3 process-safe queues: in_queue for the incoming frames from the source,
bc_queue for the frames with the predicted overlays heading off to the broadcaster,
predicts_queue for the predictions to be written off to the disk.
"""
def __init__(self, pool_cfg, worker_cfg):
"""
pool_cfg - Configuration dictionary for the pool manager.
worker_cfg - Configuration dictionary for the pool workers.
"""
self.frame_num = 0
self.in_queue = MPQueue()
self.bc_queue = MPQueue()
self.predicts_queue = MPQueue()
for key, value in pool_cfg.items():
setattr(self, key, value)
self.pool = WorkerPool(
"InferencePool",
InferenceWorker,
self.workers,
self.in_queue,
self.bc_queue,
self.predicts_queue,
worker_cfg,
)
self.pool.start()
def write(self, buf):
"""
Mandatory custom output method for the PiCamera class.
buf - Frame as a bytes object.
"""
if buf.startswith(b"\xff\xd8"):
# start of new frame; close the old one (if any) and
if self.frame_num % self.pick_every_nth_frame == 0:
self.in_queue.put({"frame_num": self.frame_num, "jpeg": buf})
self.frame_num += 1
def stop(self):
"""
Stop all workers and the process altogether.
"""
self.pool.stop()
self.pool.join()
qs = [self.in_queue, self.bc_queue]
[q.cancel_join_thread() for q in qs]
def get_queues(self):
"""
Retrieve all queues.
"""
return self.in_queue, self.bc_queue, self.predicts_queue
@click.command(
help=(
"Identify license plates from a given video source"
" while outsourcing the predictions using REST API endpoints."
)
)
@click.option("--config", "-c", required=True, type=str)
def main(config):
killer = GracefullKiller()
# open config file
try:
file = open(config)
cfg = json.load(file)
file.close()
except Exception as error:
logger.critical(str(error), exc_info=1)
return
# give meaningful names to each sub config
source_cfg = cfg["video_source"]
broadcast_cfg = cfg["broadcaster"]
pool_cfg = cfg["inferencing_pool"]
worker_cfg = cfg["inferencing_worker"]
flusher_cfg = cfg["flusher"]
gps_cfg = cfg["gps"]
gen_cfg = cfg["general"]
# bind requests module to use a given network interface
try:
socket.inet_aton(gen_cfg["bind_ip"])
session.mount("http://", SourceAddressAdapter(gen_cfg["bind_ip"]))
logger.info("binding requests module to {} IP".format(gen_cfg["bind_ip"]))
except OSError as e:
logger.error("bind IP is invalid, resorting to default interface", exc_info=True)
# start polling the GPS
if gps_cfg["use_gps"]:
wport = gps_cfg["write_port"]
rport = gps_cfg["read_port"]
br = gps_cfg["baudrate"]
gps = ReadGPSData(wport, rport, br)
gps.start()
else:
gps = None
# workers on a separate process to run inference on the data
logger.info("initializing pool w/ " + str(pool_cfg["workers"]) + " workers")
output = DistributeFramesAndInfer(pool_cfg, worker_cfg)
frames_queue, bc_queue, predicts_queue = output.get_queues()
logger.info("initialized worker pool")
# a single worker in a separate process to reassemble the data
reassembler = BroadcastReassembled(bc_queue, broadcast_cfg, name="BroadcastReassembled")
reassembler.start()
# a single thread to flush the producing queue
# when there are too many frames in the pipe
flusher = Flusher(frames_queue, threshold=flusher_cfg["frame_count_threshold"], name="Flusher")
flusher.start()
# data aggregator to write things to disk
def results_writer():
if len(gen_cfg["saved_data"]) > 0:
df = pd.DataFrame(columns=["Date", "License Plate", "Coordinates"])
while not killer.kill_now:
time.sleep(0.01)
try:
data = predicts_queue.get_nowait()
except queue.Empty:
continue
predicts = data["predicts"]
date = data["date"]
for lp in predicts:
if len(lp) > 0:
lp = " ".join(lp)
entry = {"Date": date, "License Plate": lp, "Coordinates": ""}
if gps:
entry["Coordinates"] = "{}, {}".format(
gps.latitude, gps.longitude
).upper()
df = df.append(entry, ignore_index=True)
logger.info("dumping results to csv file {}".format(gen_cfg["saved_data"]))
if os.path.isfile(gen_cfg["saved_data"]):
header = False
else:
header = True
with open(gen_cfg["saved_data"], "a") as f:
df.to_csv(f, header=header)
# data aggregator thread
results_thread = td.Thread(target=results_writer)
results_thread.start()
if source_cfg["type"] == "camera":
# import module
import picamera
# start the pi camera
with picamera.PiCamera() as camera:
# configure the camera
camera.sensor_mode = source_cfg["sensor_mode"]
camera.resolution = source_cfg["resolution"]
camera.framerate = source_cfg["framerate"]
logger.info(
"picamera initialized w/ mode={} resolution={} framerate={}".format(
camera.sensor_mode, camera.resolution, camera.framerate
)
)
# start recording both to disk and to the queue
camera.start_recording(
output=source_cfg["output_file"], format="h264", splitter_port=0, bitrate=10000000,
)
camera.start_recording(
output=output, format="mjpeg", splitter_port=1, bitrate=10000000, quality=95,
)
logger.info("started recording to file and to queue")
# wait until SIGINT is detected
while not killer.kill_now:
camera.wait_recording(timeout=0.5, splitter_port=0)
camera.wait_recording(timeout=0.5, splitter_port=1)
logger.info(
"frames qsize: {}, broadcast qsize: {}, predicts qsize: {}".format(
frames_queue.qsize(), bc_queue.qsize(), predicts_queue.qsize()
)
)
# stop recording
logger.info("gracefully exiting")
camera.stop_recording(splitter_port=0)
camera.stop_recording(splitter_port=1)
output.stop()
elif source_cfg["type"] == "file":
# open video file
video_reader = cv2.VideoCapture(source_cfg["input"])
video_reader.set(cv2.CAP_PROP_POS_FRAMES, source_cfg["frames_to_skip"])
# get # of frames and determine target width
nb_frames = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT))
frame_h = int(video_reader.get(cv2.CAP_PROP_FRAME_HEIGHT))
frame_w = int(video_reader.get(cv2.CAP_PROP_FRAME_WIDTH))
target_h = int(frame_h * source_cfg["scale_video"])
target_w = int(frame_w * source_cfg["scale_video"])
period = 1.0 / source_cfg["framerate"]
logger.info(
"file-based video stream initialized w/ resolution={} framerate={} and {} skipped frames".format(
(target_w, target_h), source_cfg["framerate"], source_cfg["frames_to_skip"],
)
)
# serve each frame to the workers iteratively
last_log = time.time()
for i in range(nb_frames):
start = time.time()
try:
# write frame to queue
_, frame = video_reader.read()
if target_w != frame_w:
frame = resize_image(frame, target_w)
jpeg = image_to_jpeg_bytes(frame)
output.write(jpeg)
except Exception as error:
logger.error("unexpected error occurred", exc_info=True)
break
end = time.time()
spent = end - start
left = period - spent
if left > 0:
# maintain framerate
time.sleep(period)
# check if SIGINT has been sent
if killer.kill_now:
break
# do logs every second
current = time.time()
if current - last_log >= 1.0:
logger.info(
"frames qsize: {}, broadcast qsize: {}, predicts qsize: {}".format(
frames_queue.qsize(), bc_queue.qsize(), predicts_queue.qsize()
)
)
last_log = current
logger.info("gracefully exiting")
video_reader.release()
output.stop()
if gps_cfg["use_gps"]:
gps.stop()
reassembler.stop()
flusher.stop()
if __name__ == "__main__":
main()