Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

interact.py 17 KB

You have to be logged in to leave a comment. Sign In
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
  1. import multiprocessing
  2. import os
  3. import sys
  4. import threading
  5. import time
  6. import types
  7. import colorama
  8. import cv2
  9. from tqdm import tqdm
  10. from core import stdex
  11. try:
  12. import IPython #if success we are in colab
  13. from IPython.display import display, clear_output
  14. import PIL
  15. import matplotlib.pyplot as plt
  16. is_colab = True
  17. except:
  18. is_colab = False
  19. yn_str = {True:'y',False:'n'}
  20. class InteractBase(object):
  21. EVENT_LBUTTONDOWN = 1
  22. EVENT_LBUTTONUP = 2
  23. EVENT_MBUTTONDOWN = 3
  24. EVENT_MBUTTONUP = 4
  25. EVENT_RBUTTONDOWN = 5
  26. EVENT_RBUTTONUP = 6
  27. EVENT_MOUSEWHEEL = 10
  28. def __init__(self):
  29. self.named_windows = {}
  30. self.capture_mouse_windows = {}
  31. self.capture_keys_windows = {}
  32. self.mouse_events = {}
  33. self.key_events = {}
  34. self.pg_bar = None
  35. self.focus_wnd_name = None
  36. self.error_log_line_prefix = '/!\\ '
  37. self.process_messages_callbacks = {}
  38. def is_support_windows(self):
  39. return False
  40. def is_colab(self):
  41. return False
  42. def on_destroy_all_windows(self):
  43. raise NotImplemented
  44. def on_create_window (self, wnd_name):
  45. raise NotImplemented
  46. def on_destroy_window (self, wnd_name):
  47. raise NotImplemented
  48. def on_show_image (self, wnd_name, img):
  49. raise NotImplemented
  50. def on_capture_mouse (self, wnd_name):
  51. raise NotImplemented
  52. def on_capture_keys (self, wnd_name):
  53. raise NotImplemented
  54. def on_process_messages(self, sleep_time=0):
  55. raise NotImplemented
  56. def on_wait_any_key(self):
  57. raise NotImplemented
  58. def log_info(self, msg, end='\n'):
  59. if self.pg_bar is not None:
  60. print ("\n")
  61. print (msg, end=end)
  62. def log_err(self, msg, end='\n'):
  63. if self.pg_bar is not None:
  64. print ("\n")
  65. print (f'{self.error_log_line_prefix}{msg}', end=end)
  66. def named_window(self, wnd_name):
  67. if wnd_name not in self.named_windows:
  68. #we will show window only on first show_image
  69. self.named_windows[wnd_name] = 0
  70. self.focus_wnd_name = wnd_name
  71. else: print("named_window: ", wnd_name, " already created.")
  72. def destroy_all_windows(self):
  73. if len( self.named_windows ) != 0:
  74. self.on_destroy_all_windows()
  75. self.named_windows = {}
  76. self.capture_mouse_windows = {}
  77. self.capture_keys_windows = {}
  78. self.mouse_events = {}
  79. self.key_events = {}
  80. self.focus_wnd_name = None
  81. def destroy_window(self, wnd_name):
  82. if wnd_name in self.named_windows:
  83. self.on_destroy_window(wnd_name)
  84. self.named_windows.pop(wnd_name)
  85. if wnd_name == self.focus_wnd_name:
  86. self.focus_wnd_name = list(self.named_windows.keys())[-1] if len( self.named_windows ) != 0 else None
  87. if wnd_name in self.capture_mouse_windows:
  88. self.capture_mouse_windows.pop(wnd_name)
  89. if wnd_name in self.capture_keys_windows:
  90. self.capture_keys_windows.pop(wnd_name)
  91. if wnd_name in self.mouse_events:
  92. self.mouse_events.pop(wnd_name)
  93. if wnd_name in self.key_events:
  94. self.key_events.pop(wnd_name)
  95. def show_image(self, wnd_name, img):
  96. if wnd_name in self.named_windows:
  97. if self.named_windows[wnd_name] == 0:
  98. self.named_windows[wnd_name] = 1
  99. self.on_create_window(wnd_name)
  100. if wnd_name in self.capture_mouse_windows:
  101. self.capture_mouse(wnd_name)
  102. self.on_show_image(wnd_name,img)
  103. else: print("show_image: named_window ", wnd_name, " not found.")
  104. def capture_mouse(self, wnd_name):
  105. if wnd_name in self.named_windows:
  106. self.capture_mouse_windows[wnd_name] = True
  107. if self.named_windows[wnd_name] == 1:
  108. self.on_capture_mouse(wnd_name)
  109. else: print("capture_mouse: named_window ", wnd_name, " not found.")
  110. def capture_keys(self, wnd_name):
  111. if wnd_name in self.named_windows:
  112. if wnd_name not in self.capture_keys_windows:
  113. self.capture_keys_windows[wnd_name] = True
  114. self.on_capture_keys(wnd_name)
  115. else: print("capture_keys: already set for window ", wnd_name)
  116. else: print("capture_keys: named_window ", wnd_name, " not found.")
  117. def progress_bar(self, desc, total, leave=True, initial=0):
  118. if self.pg_bar is None:
  119. self.pg_bar = tqdm( total=total, desc=desc, leave=leave, ascii=True, initial=initial )
  120. else: print("progress_bar: already set.")
  121. def progress_bar_inc(self, c):
  122. if self.pg_bar is not None:
  123. self.pg_bar.n += c
  124. self.pg_bar.refresh()
  125. else: print("progress_bar not set.")
  126. def progress_bar_close(self):
  127. if self.pg_bar is not None:
  128. self.pg_bar.close()
  129. self.pg_bar = None
  130. else: print("progress_bar not set.")
  131. def progress_bar_generator(self, data, desc=None, leave=True, initial=0):
  132. self.pg_bar = tqdm( data, desc=desc, leave=leave, ascii=True, initial=initial )
  133. for x in self.pg_bar:
  134. yield x
  135. self.pg_bar.close()
  136. self.pg_bar = None
  137. def add_process_messages_callback(self, func ):
  138. tid = threading.get_ident()
  139. callbacks = self.process_messages_callbacks.get(tid, None)
  140. if callbacks is None:
  141. callbacks = []
  142. self.process_messages_callbacks[tid] = callbacks
  143. callbacks.append ( func )
  144. def process_messages(self, sleep_time=0):
  145. callbacks = self.process_messages_callbacks.get(threading.get_ident(), None)
  146. if callbacks is not None:
  147. for func in callbacks:
  148. func()
  149. self.on_process_messages(sleep_time)
  150. def wait_any_key(self):
  151. self.on_wait_any_key()
  152. def add_mouse_event(self, wnd_name, x, y, ev, flags):
  153. if wnd_name not in self.mouse_events:
  154. self.mouse_events[wnd_name] = []
  155. self.mouse_events[wnd_name] += [ (x, y, ev, flags) ]
  156. def add_key_event(self, wnd_name, ord_key, ctrl_pressed, alt_pressed, shift_pressed):
  157. if wnd_name not in self.key_events:
  158. self.key_events[wnd_name] = []
  159. self.key_events[wnd_name] += [ (ord_key, chr(ord_key), ctrl_pressed, alt_pressed, shift_pressed) ]
  160. def get_mouse_events(self, wnd_name):
  161. ar = self.mouse_events.get(wnd_name, [])
  162. self.mouse_events[wnd_name] = []
  163. return ar
  164. def get_key_events(self, wnd_name):
  165. ar = self.key_events.get(wnd_name, [])
  166. self.key_events[wnd_name] = []
  167. return ar
  168. def input(self, s):
  169. return input(s)
  170. def input_number(self, s, default_value, valid_list=None, show_default_value=True, add_info=None, help_message=None):
  171. if show_default_value and default_value is not None:
  172. s = f"[{default_value}] {s}"
  173. if add_info is not None or \
  174. help_message is not None:
  175. s += " ("
  176. if add_info is not None:
  177. s += f" {add_info}"
  178. if help_message is not None:
  179. s += " ?:help"
  180. if add_info is not None or \
  181. help_message is not None:
  182. s += " )"
  183. s += " : "
  184. while True:
  185. try:
  186. inp = input(s)
  187. if len(inp) == 0:
  188. result = default_value
  189. break
  190. if help_message is not None and inp == '?':
  191. print (help_message)
  192. continue
  193. i = float(inp)
  194. if (valid_list is not None) and (i not in valid_list):
  195. result = default_value
  196. break
  197. result = i
  198. break
  199. except:
  200. result = default_value
  201. break
  202. print(result)
  203. return result
  204. def input_int(self, s, default_value, valid_list=None, add_info=None, show_default_value=True, help_message=None):
  205. if show_default_value:
  206. if len(s) != 0:
  207. s = f"[{default_value}] {s}"
  208. else:
  209. s = f"[{default_value}]"
  210. if add_info is not None or \
  211. help_message is not None:
  212. s += " ("
  213. if add_info is not None:
  214. s += f" {add_info}"
  215. if help_message is not None:
  216. s += " ?:help"
  217. if add_info is not None or \
  218. help_message is not None:
  219. s += " )"
  220. s += " : "
  221. while True:
  222. try:
  223. inp = input(s)
  224. if len(inp) == 0:
  225. raise ValueError("")
  226. if help_message is not None and inp == '?':
  227. print (help_message)
  228. continue
  229. i = int(inp)
  230. if (valid_list is not None) and (i not in valid_list):
  231. result = default_value
  232. break
  233. result = i
  234. break
  235. except:
  236. result = default_value
  237. break
  238. print (result)
  239. return result
  240. def input_bool(self, s, default_value, help_message=None):
  241. s = f"[{yn_str[default_value]}] {s} ( y/n"
  242. if help_message is not None:
  243. s += " ?:help"
  244. s += " ) : "
  245. while True:
  246. try:
  247. inp = input(s)
  248. if len(inp) == 0:
  249. raise ValueError("")
  250. if help_message is not None and inp == '?':
  251. print (help_message)
  252. continue
  253. return bool ( {"y":True,"n":False}.get(inp.lower(), default_value) )
  254. except:
  255. print ( "y" if default_value else "n" )
  256. return default_value
  257. def input_str(self, s, default_value=None, valid_list=None, show_default_value=True, help_message=None):
  258. if show_default_value and default_value is not None:
  259. s = f"[{default_value}] {s}"
  260. if valid_list is not None or \
  261. help_message is not None:
  262. s += " ("
  263. if valid_list is not None:
  264. s += " " + "/".join(valid_list)
  265. if help_message is not None:
  266. s += " ?:help"
  267. if valid_list is not None or \
  268. help_message is not None:
  269. s += " )"
  270. s += " : "
  271. while True:
  272. try:
  273. inp = input(s)
  274. if len(inp) == 0:
  275. if default_value is None:
  276. print("")
  277. return None
  278. result = default_value
  279. break
  280. if help_message is not None and inp == '?':
  281. print(help_message)
  282. continue
  283. if valid_list is not None:
  284. if inp.lower() in valid_list:
  285. result = inp.lower()
  286. break
  287. if inp in valid_list:
  288. result = inp
  289. break
  290. continue
  291. result = inp
  292. break
  293. except:
  294. result = default_value
  295. break
  296. print(result)
  297. return result
  298. def input_process(self, stdin_fd, sq, str):
  299. sys.stdin = os.fdopen(stdin_fd)
  300. try:
  301. inp = input (str)
  302. sq.put (True)
  303. except:
  304. sq.put (False)
  305. def input_in_time (self, str, max_time_sec):
  306. sq = multiprocessing.Queue()
  307. p = multiprocessing.Process(target=self.input_process, args=( sys.stdin.fileno(), sq, str))
  308. p.daemon = True
  309. p.start()
  310. t = time.time()
  311. inp = False
  312. while True:
  313. if not sq.empty():
  314. inp = sq.get()
  315. break
  316. if time.time() - t > max_time_sec:
  317. break
  318. p.terminate()
  319. p.join()
  320. old_stdin = sys.stdin
  321. sys.stdin = os.fdopen( os.dup(sys.stdin.fileno()) )
  322. old_stdin.close()
  323. return inp
  324. def input_process_skip_pending(self, stdin_fd):
  325. sys.stdin = os.fdopen(stdin_fd)
  326. while True:
  327. try:
  328. if sys.stdin.isatty():
  329. sys.stdin.read()
  330. except:
  331. pass
  332. def input_skip_pending(self):
  333. if is_colab:
  334. # currently it does not work on Colab
  335. return
  336. """
  337. skips unnecessary inputs between the dialogs
  338. """
  339. p = multiprocessing.Process(target=self.input_process_skip_pending, args=( sys.stdin.fileno(), ))
  340. p.daemon = True
  341. p.start()
  342. time.sleep(0.5)
  343. p.terminate()
  344. sys.stdin = os.fdopen( sys.stdin.fileno() )
  345. class InteractDesktop(InteractBase):
  346. def __init__(self):
  347. colorama.init()
  348. super().__init__()
  349. def color_red(self):
  350. pass
  351. def is_support_windows(self):
  352. return True
  353. def on_destroy_all_windows(self):
  354. cv2.destroyAllWindows()
  355. def on_create_window (self, wnd_name):
  356. cv2.namedWindow(wnd_name)
  357. def on_destroy_window (self, wnd_name):
  358. cv2.destroyWindow(wnd_name)
  359. def on_show_image (self, wnd_name, img):
  360. cv2.imshow (wnd_name, img)
  361. def on_capture_mouse (self, wnd_name):
  362. self.last_xy = (0,0)
  363. def onMouse(event, x, y, flags, param):
  364. (inst, wnd_name) = param
  365. if event == cv2.EVENT_LBUTTONDOWN: ev = InteractBase.EVENT_LBUTTONDOWN
  366. elif event == cv2.EVENT_LBUTTONUP: ev = InteractBase.EVENT_LBUTTONUP
  367. elif event == cv2.EVENT_RBUTTONDOWN: ev = InteractBase.EVENT_RBUTTONDOWN
  368. elif event == cv2.EVENT_RBUTTONUP: ev = InteractBase.EVENT_RBUTTONUP
  369. elif event == cv2.EVENT_MBUTTONDOWN: ev = InteractBase.EVENT_MBUTTONDOWN
  370. elif event == cv2.EVENT_MBUTTONUP: ev = InteractBase.EVENT_MBUTTONUP
  371. elif event == cv2.EVENT_MOUSEWHEEL:
  372. ev = InteractBase.EVENT_MOUSEWHEEL
  373. x,y = self.last_xy #fix opencv bug when window size more than screen size
  374. else: ev = 0
  375. self.last_xy = (x,y)
  376. inst.add_mouse_event (wnd_name, x, y, ev, flags)
  377. cv2.setMouseCallback(wnd_name, onMouse, (self,wnd_name) )
  378. def on_capture_keys (self, wnd_name):
  379. pass
  380. def on_process_messages(self, sleep_time=0):
  381. has_windows = False
  382. has_capture_keys = False
  383. if len(self.named_windows) != 0:
  384. has_windows = True
  385. if len(self.capture_keys_windows) != 0:
  386. has_capture_keys = True
  387. if has_windows or has_capture_keys:
  388. wait_key_time = max(1, int(sleep_time*1000) )
  389. ord_key = cv2.waitKey(wait_key_time)
  390. shift_pressed = False
  391. if ord_key != -1:
  392. chr_key = chr(ord_key)
  393. if chr_key >= 'A' and chr_key <= 'Z':
  394. shift_pressed = True
  395. ord_key += 32
  396. elif chr_key == '?':
  397. shift_pressed = True
  398. ord_key = ord('/')
  399. elif chr_key == '<':
  400. shift_pressed = True
  401. ord_key = ord(',')
  402. elif chr_key == '>':
  403. shift_pressed = True
  404. ord_key = ord('.')
  405. else:
  406. if sleep_time != 0:
  407. time.sleep(sleep_time)
  408. if has_capture_keys and ord_key != -1:
  409. self.add_key_event ( self.focus_wnd_name, ord_key, False, False, shift_pressed)
  410. def on_wait_any_key(self):
  411. cv2.waitKey(0)
  412. class InteractColab(InteractBase):
  413. def is_support_windows(self):
  414. return False
  415. def is_colab(self):
  416. return True
  417. def on_destroy_all_windows(self):
  418. pass
  419. #clear_output()
  420. def on_create_window (self, wnd_name):
  421. pass
  422. #clear_output()
  423. def on_destroy_window (self, wnd_name):
  424. pass
  425. def on_show_image (self, wnd_name, img):
  426. pass
  427. # # cv2 stores colors as BGR; convert to RGB
  428. # if img.ndim == 3:
  429. # if img.shape[2] == 4:
  430. # img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA)
  431. # else:
  432. # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  433. # img = PIL.Image.fromarray(img)
  434. # plt.imshow(img)
  435. # plt.show()
  436. def on_capture_mouse (self, wnd_name):
  437. pass
  438. #print("on_capture_mouse(): Colab does not support")
  439. def on_capture_keys (self, wnd_name):
  440. pass
  441. #print("on_capture_keys(): Colab does not support")
  442. def on_process_messages(self, sleep_time=0):
  443. time.sleep(sleep_time)
  444. def on_wait_any_key(self):
  445. pass
  446. #print("on_wait_any_key(): Colab does not support")
  447. if is_colab:
  448. interact = InteractColab()
  449. else:
  450. interact = InteractDesktop()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...