-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
374 lines (295 loc) · 10 KB
/
utils.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import json
import queue
from collections import deque
from datetime import datetime, timedelta
from threading import Event
def format_sse(data, event=None):
"""
Format `data` as a server-sent Event on the topic `event`.
Returns
-------
message : str
"""
message = f"data: {data}\n\n"
if event is not None:
message = f"event: {event}\n{message}"
return message
class SSEMessenger:
"""
Messenger object that allows sending server-sent events to subscribed clients.
"""
def __init__(self):
self.subscribers = []
def subscribe(self):
"""
Subscribe to events sent by this messenger.
Returns
-------
: generator
Generator that yields server-sent events when they are sent.
"""
q = queue.Queue(maxsize=5)
self.subscribers.append(q)
def generator():
while True:
message = q.get() # Blocks when queue is empty
yield message
return generator()
def send(self, event, data):
"""
Send `data` to subscribers on the `event` topic.
"""
if isinstance(data, dict):
data = json.dumps(data)
message = format_sse(data, event=event)
for i in reversed(range(len(self.subscribers))):
try:
self.subscribers[i].put_nowait(message)
except queue.Full:
del self.subscribers[i]
class BaseCallback:
"""
Base class of callbacks for `FilmScanner` objects. Inherit from this class and
overwrite one of its methods to react to the corresponding event. Access the
`FilmScanner` class a callback is connected to via `self.scanner`.
"""
def __init__(self):
self.scanner = None
def setup(self, scanner):
self.scanner = scanner
def on_advance_start(self):
"""
Called before the scanner advances a frame.
"""
pass
def on_advance_end(self):
"""
Called after the scanner has advances a frame.
"""
pass
def on_fast_forward_start(self):
"""
Called before the scanner starts fast-forwarding.
"""
pass
def on_fast_forward_end(self):
"""
Called after the scanner finished fast-forwarding.
"""
pass
def on_frame_capture(self):
"""
Called after a frame was captured during a scan.
"""
pass
def on_last_scan_end_info_change(self):
"""
Called when the info on how the last scan ended changed.
"""
def on_light_on(self):
"""
Called after the scanner's light is turned on.
"""
pass
def on_light_off(self):
"""
Called after the scanner's light is turned off.
"""
pass
def on_scan_start(self):
"""
Called after a scan starts.
"""
pass
def on_scan_end(self):
"""
Called after a scan ended.
"""
pass
def on_zoom_in(self):
"""
Called after the camera zoomed in.
"""
pass
def on_zoom_out(self):
"""
Called after the camera zoomed out.
"""
pass
class CallbackList(BaseCallback):
"""
Helper class to accumulate multiple callbacks for `FilmScanner` in one object.
Parameters
----------
callbacks : list
List of callbacks, each of which is called when the callback events occur.
"""
def __init__(self, callbacks):
super().__init__()
self.callbacks = callbacks
self.scanner = None
def setup(self, scanner):
for callback in self.callbacks:
callback.setup(scanner)
def on_advance_start(self):
for callback in self.callbacks:
callback.on_advance_start()
def on_advance_end(self):
for callback in self.callbacks:
callback.on_advance_end()
def on_fast_forward_start(self):
for callback in self.callbacks:
callback.on_fast_forward_start()
def on_fast_forward_end(self):
for callback in self.callbacks:
callback.on_fast_forward_end()
def on_frame_capture(self):
for callback in self.callbacks:
callback.on_frame_capture()
def on_last_scan_end_info_change(self):
for callback in self.callbacks:
callback.on_last_scan_end_info_change()
def on_light_on(self):
for callback in self.callbacks:
callback.on_light_on()
def on_light_off(self):
for callback in self.callbacks:
callback.on_light_off()
def on_scan_start(self):
for callback in self.callbacks:
callback.on_scan_start()
def on_scan_end(self):
for callback in self.callbacks:
callback.on_scan_end()
def on_zoom_in(self):
for callback in self.callbacks:
callback.on_zoom_in()
def on_zoom_out(self):
for callback in self.callbacks:
callback.on_zoom_out()
class SSESendingCallback(BaseCallback):
"""
Callback that reacts to events on the `FilmScanner` object by sending server-sent
events which can be subscribed to.
"""
def __init__(self):
super().__init__()
self.messenger = SSEMessenger()
def subscribe_to_sse(self):
"""
Subsribed to the server-sent events sent by this callback.
"""
return self.messenger.subscribe()
class DashboardCallback(SSESendingCallback):
"""
Callback to send state information to the displays on the web dashboard.
"""
def __init__(self):
super().__init__()
# Scan controls
self.time_remaining = timedelta(0)
self.str_time_remaining = "-"
self.is_time_remaining_first_update = False
def on_advance_start(self):
self.messenger.send("state", self.scanner_state_dict)
def on_advance_end(self):
self.messenger.send("state", self.scanner_state_dict)
def on_fast_forward_start(self):
self.messenger.send("state", self.scanner_state_dict)
def on_fast_forward_end(self):
self.messenger.send("state", self.scanner_state_dict)
def on_frame_capture(self):
self.update_time_remaining()
self.messenger.send("state", self.scanner_state_dict)
def on_last_scan_end_info_change(self):
self.messenger.send("state", self.scanner_state_dict)
def on_light_on(self):
self.messenger.send("state", self.scanner_state_dict)
def on_light_off(self):
self.messenger.send("state", self.scanner_state_dict)
def on_scan_start(self):
self.init_time_remaining_estimation()
self.messenger.send("state", self.scanner_state_dict)
scan_setup = {
"n_frames": self.scanner.n_frames,
"output_directory": self.scanner.output_directory,
}
self.messenger.send("scan_setup", scan_setup)
def on_scan_end(self):
self.messenger.send("state", self.scanner_state_dict)
def on_zoom_in(self):
self.messenger.send("state", self.scanner_state_dict)
def on_zoom_out(self):
self.messenger.send("state", self.scanner_state_dict)
@property
def scanner_state_dict(self):
return {
"advance_toggle": {
"active": self.scanner.is_advancing
and not self.scanner.is_fast_forwarding,
"enabled": self.scanner.is_advance_allowed,
},
"current_frame_index": self.scanner.current_frame_index,
"fast_forward_toggle": {
"active": self.scanner.is_fast_forwarding,
"enabled": self.scanner.is_fast_forward_allowed
or self.scanner.is_fast_forwarding,
},
"is_scanning": self.scanner.is_scanning,
"is_scan_button_enabled": self.scanner.is_scanning_allowed
or self.scanner.is_scanning,
"last_scan_end_info": self.scanner.last_scan_end_info,
"light_toggle": {
"active": self.scanner.is_light_on,
"enabled": self.scanner.is_light_toggle_allowed,
},
"time_remaining": self.str_time_remaining,
"zoom_toggle": {
"active": self.scanner.is_zoomed,
"enabled": self.scanner.is_zoom_toggle_allowed,
},
}
def init_time_remaining_estimation(self):
self.t_last = datetime.now()
self.dts = deque([], maxlen=100)
self.time_remaining = timedelta(0)
self.str_time_remaining = "-"
self.is_time_remaining_first_update = True
def update_time_remaining(self):
t_now = datetime.now()
dt = t_now - self.t_last
self.t_last = t_now
# On the first update of time remaining don't add dt to dts because it measures
# the duration of the scan initialisation and therefore throws off the time
# remaining estimate.
if self.is_time_remaining_first_update:
self.is_time_remaining_first_update = False
return
self.dts.append(dt)
dt_mean = sum(self.dts, timedelta(0)) / len(self.dts)
frames_remaining = self.scanner.n_frames - self.scanner.current_frame_index
self.time_remaining = dt_mean * frames_remaining
self.str_time_remaining = str(self.time_remaining).split(".")[0]
class Viewer:
"""
Helper class to pass frames to a previewing client when they become available.
"""
def __init__(self, scanner):
self.scanner = scanner
self.event = Event()
self.last_access = datetime.now()
def notify(self):
"""
Notify this viewer that a new frame is available.
"""
self.event.set()
def view(self):
"""
Generator that yields preview frames when this viewer is notified (that a new
one is available).
"""
while True:
self.event.wait()
yield self.scanner.preview_frame
self.event.clear()
self.last_access = datetime.now()