-
Notifications
You must be signed in to change notification settings - Fork 0
/
iTrace-Visualize.py
1534 lines (1251 loc) · 68.6 KB
/
iTrace-Visualize.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
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This Python file uses the following encoding: utf-8
import sys
import cv2
import time
import numpy as np
import math
import re
import random
import colorsys
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from PIL import Image, ImageFont, ImageDraw
from lxml import etree as ET
from iTraceDB import iTraceDB
from EyeDataTypes import Gaze, Fixation
from TextDetector import get_text_boxes, highlight_frame
from PySide6 import QtCore, QtWidgets, QtGui
import ctypes
myappid = 'mycompany.myproduct.subproduct.version' # arbitrary string
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
WIN_WIDTH, WIN_HEIGHT = 950, 465
DEFAULT_ROLLING_WIN_SIZE = 1000 # Size of rolling window in miliseconds
DEFAULT_GAZE_RADIUS = 5
DEFAULT_FIXATION_RADIUS = 5
DEFAULT_VID_SCALE = 1 # INCREASING THIS CAUSES THE VIDEO TO BECOME MUCH LONGER, AND HAVE MUCH MORE DETAIL
DEFAULT_NUM_OF_COLORS = 5
fontTitle = {'family':'serif','color':'black','size':20}
fontTitle2 = {'family':'serif','color':'black','size':15}
fontLabelX = {'family':'serif','color':'black','size':15}
fontLabelY = {'family':'serif','color':'black','size':15}
# Converts color string (rgb) to color tuple (bgr)
def ConvertColorStringToTuple(color: "#XXXXXX") -> tuple[int]:
color = color[1:]
b = int(color[4:6],base=16)
g = int(color[2:4],base=16)
r = int(color[0:2],base=16)
return (b,g,r)
# converts color tuple (bgr) to color string (rgb)
def ConvertColorTupleToString(color: tuple[int]) -> "#XXXXXX":
return "#"+str(hex(color[2]))[2:].zfill(2)+str(hex(color[1]))[2:].zfill(2)+str(hex(color[0]))[2:].zfill(2)
# Converts windows time to Unix time
def ConvertWindowsTime(t) -> int:
return ((t / 10000000) - 11644473600) * 1000
# Takes the list of Fixations and Gazes and figures out the saccades
# Saccades are defined as the group of gazes between two consecutive fixations
def GetSaccadesOfGazesAndFixationGazes(idb,gazes,fixation_gazes) -> list[list[Gaze]]:
fix_gaze_times = []
for fix_id in fixation_gazes:
for fixation_gaze in fixation_gazes[fix_id]:
fix_gaze_times.append(Gaze(idb.GetGazeFromEventTime(fixation_gaze[1])).system_time)
saccades = []
add = []
for gaze in gazes:
if gaze.system_time in fix_gaze_times and len(add) == 0: #Do nothing, looking for next saccade
pass
elif gaze.system_time in fix_gaze_times and len(add) != 0: #End current saccade, start new one
saccades.append(add)
add = []
elif gaze.system_time not in fix_gaze_times and not gaze.isNaN():
add.append(gaze)
if len(add) != 0:
saccades.append(add)
return saccades
def FindMatchingPath(all_files,target_file):
target_file.replace("\\","/")
target_file = target_file.lower()
file_split = target_file.split("/")
check = file_split[-1]
possible = []
for file in all_files:
if file.lower().endswith(check):
possible.append(file.split("/"))
if len(possible) == 0:
return None
elif len(possible) == 1:
return "/".join(possible[0])
shortest = ""
passes = 1
while len(possible) != 1:
candidates = []
if passes > len(file_split):
return shortest
for unit_path in possible:
if passes > len(unit_path):
if shortest == "":
shortest = "/".join(unit_path)
continue
unit_check = unit_path[len(unit_path) - passes].lower()
file_check = file_split[len(file_split) - passes]
if unit_check == file_check:
candidates.append(unit_path)
possible = candidates
passes += 1
if len(possible) == 0:
return None;
return "/".join(possible[0])
def GetLineAndCol(element):
try:
return (int(element.attrib["{http://www.srcML.org/srcML/position}start"].split(":")[0]),
int(element.attrib["{http://www.srcML.org/srcML/position}start"].split(":")[1]),
int(element.attrib["{http://www.srcML.org/srcML/position}end"].split(":")[0]),
int(element.attrib["{http://www.srcML.org/srcML/position}end"].split(":")[1]))
except:
xml_remover = re.compile("<.*?>")
text = xml_remover.sub('',ET.tostring(element).decode()).replace(">",">").replace("<","<").replace("&","&")
return (1,1,len(text.split("\n")),max([len(x.rstrip()) for x in text.split("\n")]))
def GetTokenStartPoint(line_start,col_start,elements):
xml_remover = re.compile("<.*?>")
for element in elements:
if type(element) == str:
s = element
else:
s = xml_remover.sub('',ET.tostring(element).decode())
s = s.replace(">",">").replace("<","<").replace("&","&")
lines = s.split('\n')
if len(lines) > 1:
line_start += len(lines) - 1
col_start = 0
col_start += len(lines[-1])
return line_start, col_start
SINGLE_CHAR_TOKENS = ["{","}","[","]","(",")","'",'"',".",",",";"]
def FindTokenInElement(line,col,element):
xml_remover = re.compile("<.*?>")
text = xml_remover.sub('',ET.tostring(element).decode()).replace(">",">").replace("<","<").replace("&","&")
lines = text.split("\n")
token_line = lines[line - 1]
if col > len(token_line):
#return ((line,col),(line,col))
return
char = token_line[col - 1]
if char.isspace():
return
elif char in SINGLE_CHAR_TOKENS:
return ((line,col),(line,col))
elif char.isalnum():
mode = "word"
else:
mode = "op"
start = col - 1
end = col - 1
while token_line[start].isalnum() if mode == "word" else ((not token_line[start].isalnum()) and (not token_line[start].isspace()) and (token_line[start] not in SINGLE_CHAR_TOKENS)):
start -= 1
if start < 0:
start = -1
break
while token_line[end].isalnum() if mode == "word" else ((not token_line[end].isalnum()) and (not token_line[end].isspace()) and (token_line[end] not in SINGLE_CHAR_TOKENS)):
end += 1
if end > len(token_line) - 1:
end = len(token_line)
break
return ((line,start+2),(line,end))
class ConfirmDialog(QtWidgets.QDialog):
def __init__(self, parent=None, title="Dialog", msg="Warning"):
super().__init__(parent)
self.setWindowTitle(title)
QBtn = QtWidgets.QDialogButtonBox.Yes | QtWidgets.QDialogButtonBox.No
self.buttonBox = QtWidgets.QDialogButtonBox(QBtn)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
self.layout = QtWidgets.QVBoxLayout()
message = QtWidgets.QLabel(msg)
self.layout.addWidget(message)
self.layout.addWidget(self.buttonBox)
self.setLayout(self.layout)
# class EntryDialog(QtWidgets.QDialog):
# def __init__(self,parent=None,title="Dialog"):
# super().__init__(parent)
# self.setWindowTitle(title)
# QBtn = QtWidgets.QDialogButtonBox.Apply | QtWidgets.QDialogButtonBox.Cancel
# self.buttonBox = QtWidgets.QDialogButtonBox(QBtn)
# self.buttonBox.accepted.connect(self.accept)
# self.buttonBox.rejected.connect(self.reject)
# self.layout = QtWidgets.QVBoxLayout()
# message = QtWidgets.QLabel(msg)
# self.layout.addWidget(message)
# self.layout.addWidget(self.buttonBox)
# self.setLayout(self.layout)
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.ROLLING_WIN_SIZE = DEFAULT_ROLLING_WIN_SIZE
self.GAZE_RADIUS = DEFAULT_GAZE_RADIUS
self.FIXATION_RADIUS = DEFAULT_FIXATION_RADIUS
self.VID_SCALE = DEFAULT_VID_SCALE
self.setWindowTitle("iTrace Visualize")
self.setMinimumHeight(WIN_HEIGHT)
self.setMinimumWidth(WIN_WIDTH)
self.setWindowIcon(QtGui.QIcon("Visualize.png"))
# Major File Data
self.video_idb = None
self.code_idb = None
self.graph_idb = None
self.video = None
self.dejavu = None
self.code_srcml = None
# self.graph_srcml = None
# Time variables
self.selected_session_time = 0
self.loaded_video_time = 0
self.session_start_time = 0
self.video_fps = 0
self.video_frames = 0
# Size variables
self.video_width = 0
self.video_height = 0
# Color variables
self.gazeColor = (255,255,0)
self.saccadeColor = (255,255,255)
self.fixationColor = (0,0,255)
self.highlightColor = (255,0,0)
self.startColor = (0,0,255)
self.endColor = (0,255,0)
# Tabs
self.tab_widget = QtWidgets.QTabWidget(self)
self.video_tab = QtWidgets.QWidget()
self.video_layout = QtWidgets.QGridLayout()
self.video_tab.setLayout(self.video_layout)
self.code_tab = QtWidgets.QWidget()
self.code_layout = QtWidgets.QGridLayout()
self.code_tab.setLayout(self.code_layout)
self.graph_tab = QtWidgets.QWidget()
self.graph_layout = QtWidgets.QGridLayout()
self.graph_tab.setLayout(self.graph_layout)
# Inner File Tabs
self.file_tabs = {}
# Video Tab
############################################################################
# Load DB Button
self.video_db_load_button = QtWidgets.QPushButton("Select Database", self)
self.video_db_load_button.clicked.connect(self.videoDatabaseButtonClicked)
self.video_db_loaded_text = QtWidgets.QLabel("No Database Loaded", self)
self.video_layout.addWidget(self.video_db_load_button,1,0)
self.video_layout.addWidget(self.video_db_loaded_text,0,0)
self.video_layout.setColumnMinimumWidth(1,23)
self.video_layout.setColumnMinimumWidth(2,10)
# Session List
self.video_session_list = QtWidgets.QListWidget(self)
self.video_session_list.itemClicked.connect(self.videoSessionLoadClicked)
self.video_layout.addWidget(self.video_session_list,1,3,10,10)
self.video_session_list_text = QtWidgets.QLabel("Sessions", self)
self.video_layout.addWidget(self.video_session_list_text,0,3)
self.video_layout.setColumnMinimumWidth(9,250)
# Fixation Run List
self.video_fixation_runs_list = QtWidgets.QListWidget(self)
self.video_fixation_runs_list.itemClicked.connect(self.videoFixationRunClicked)
self.video_layout.addWidget(self.video_fixation_runs_list,1,13,10,10)
self.video_fixation_runs_list_text = QtWidgets.QLabel("Fixation Runs", self)
self.video_layout.addWidget(self.video_fixation_runs_list_text,0,13)
# Colors
## Gaze Color Picker Button
self.color_picker_button_gaze = QtWidgets.QPushButton("Gaze color", self)
self.color_picker_button_gaze.clicked.connect(self.gazePickerClicked)
self.video_layout.addWidget(self.color_picker_button_gaze,3,0)
self.color_picker_text_gaze = QtWidgets.QLabel("", self)
self.color_picker_text_gaze.setStyleSheet(f"QLabel {{ background-color : {ConvertColorTupleToString(self.gazeColor)}; }}")
self.color_picker_text_gaze.setGeometry(115, 175, 23, 23)
self.video_layout.addWidget(self.color_picker_text_gaze,3,1)
# Saccade Color Picker Button
self.color_picker_button_saccade = QtWidgets.QPushButton("Saccade color", self)
self.color_picker_button_saccade.clicked.connect(self.saccadePickerClicked)
self.video_layout.addWidget(self.color_picker_button_saccade,4,0)
self.color_picker_text_saccade = QtWidgets.QLabel("", self)
self.color_picker_text_saccade.setStyleSheet(f"QLabel {{ background-color : {ConvertColorTupleToString(self.saccadeColor)}; }}")
self.color_picker_text_saccade.setGeometry(115, 200, 23, 23)
self.video_layout.addWidget(self.color_picker_text_saccade,4,1)
## Fixation Color Picker Button
self.color_picker_button_fixation = QtWidgets.QPushButton("Fixation color", self)
self.color_picker_button_fixation.clicked.connect(self.fixationPickerClicked)
self.video_layout.addWidget(self.color_picker_button_fixation,5,0)
self.color_picker_text_fixation = QtWidgets.QLabel("", self)
self.color_picker_text_fixation.setStyleSheet(f"QLabel {{ background-color : {ConvertColorTupleToString(self.fixationColor)}; }}")
self.color_picker_text_fixation.setGeometry(115, 225, 23, 23)
self.video_layout.addWidget(self.color_picker_text_fixation,5,1)
## Highlighting Color Picker Button
self.color_picker_button_highlight = QtWidgets.QPushButton("Highlight color", self)
self.color_picker_button_highlight.clicked.connect(self.highlightPickerClicked)
self.video_layout.addWidget(self.color_picker_button_highlight,6,0)
self.color_picker_text_highlight = QtWidgets.QLabel("", self)
self.color_picker_text_highlight.setStyleSheet(f"QLabel {{ background-color : {ConvertColorTupleToString(self.highlightColor)}; }}")
self.color_picker_text_highlight.setGeometry(115, 250, 23, 23)
self.video_layout.addWidget(self.color_picker_text_highlight,6,1)
# Draw Fixation Gazes Checkbox
# self.draw_fixation_gazes_box = QtWidgets.QCheckBox("Mark Gaze Fixations",self)
# self.draw_fixation_gazes_box.move(620, 300)
# self.draw_fixation_gazes_box.setChecked(True)
# Load Video Button
self.video_load_button = QtWidgets.QPushButton("Select Video", self)
self.video_load_button.clicked.connect(self.videoLoadClicked)
self.video_layout.addWidget(self.video_load_button,11,0)
self.video_loaded_text = QtWidgets.QLabel("No Video Loaded", self)
self.video_layout.addWidget(self.video_loaded_text,12,0)
# # Select DejaVu Button
# self.dejavu_load_button = QtWidgets.QPushButton("Select Replay Data", self)
# self.dejavu_load_button.move(150,300)
# self.dejavu_load_button.clicked.connect(self.dejavuLoadClicked)
# self.dejavu_loaded_text = QtWidgets.QLabel("No Data Loaded", self)
# self.dejavu_loaded_text.move(150, 325)
# Options
## Label
self.options_text = QtWidgets.QLabel("Options",self)
self.options_text.setStyleSheet("font-weight: bold")
self.video_layout.addWidget(self.options_text,11,22)
## Highlighting Checkbox
self.highlight_box = QtWidgets.QCheckBox("Highlight Lines",self)
self.highlight_box.setChecked(True)
self.video_layout.addWidget(self.highlight_box,12,22)
## Draw Saccade Checkbox
self.draw_saccade_box = QtWidgets.QCheckBox("Mark Saccades",self)
self.draw_saccade_box.setChecked(True)
self.video_layout.addWidget(self.draw_saccade_box,13,22)
## Fade Delay
self.fade_delay_box = QtWidgets.QLineEdit(self)
self.fade_delay_box.setGeometry(620,350,25,20)
self.fade_delay_box.setValidator(QtGui.QIntValidator())
self.fade_delay_box.setText(str(DEFAULT_ROLLING_WIN_SIZE//1000))
self.video_layout.addWidget(self.fade_delay_box,14,21)
self.fade_delay_text = QtWidgets.QLabel("Fade Delay (seconds)",self)
self.video_layout.addWidget(self.fade_delay_text,14,22)
## Video Stretch
self.video_stretch_box = QtWidgets.QLineEdit(self)
self.video_stretch_box.setGeometry(620,375,25,20)
self.video_stretch_box.setValidator(QtGui.QIntValidator())
self.video_stretch_box.setText(str(DEFAULT_VID_SCALE))
self.video_layout.addWidget(self.video_stretch_box,15,21)
self.video_stretch_text = QtWidgets.QLabel("Video Stretch Factor",self)
self.video_layout.addWidget(self.video_stretch_text,15,22)
## Gaze Radius
self.gaze_radius_box = QtWidgets.QLineEdit(self)
self.gaze_radius_box.setGeometry(620,400,25,20)
self.gaze_radius_box.setValidator(QtGui.QIntValidator())
self.gaze_radius_box.setText(str(DEFAULT_GAZE_RADIUS))
self.video_layout.addWidget(self.gaze_radius_box,16,21)
self.gaze_radius_text = QtWidgets.QLabel("Gaze Radius (pixels)",self)
self.video_layout.addWidget(self.gaze_radius_text,16,22)
## Base Fixation Radius
self.base_fixation_radius_box = QtWidgets.QLineEdit(self)
self.base_fixation_radius_box.setGeometry(620,425,25,20)
self.base_fixation_radius_box.setValidator(QtGui.QIntValidator())
self.base_fixation_radius_box.setText(str(DEFAULT_FIXATION_RADIUS))
self.video_layout.addWidget(self.base_fixation_radius_box,17,21)
self.base_fixation_radius_text = QtWidgets.QLabel("Base Fixation Radius (pixels)",self)
self.video_layout.addWidget(self.base_fixation_radius_text,17,22)
# Start Video Calculation Button
self.start_video_button = QtWidgets.QPushButton("Start Visualization", self)
self.start_video_button.clicked.connect(self.startVideoClicked)
self.video_layout.addWidget(self.start_video_button,16,0)
# Progress Bar
self.progress_bar = QtWidgets.QProgressBar(self)
# self.progress_bar.setGeometry(25,450,200,25)
self.video_layout.addWidget(self.progress_bar,17,0,1,4)
self.elapsed_time_text = QtWidgets.QLabel("00:00:00",self)
self.video_layout.addWidget(self.elapsed_time_text,16,1,1,3)
# Heatmap Tab
############################################################################
# DB Button
self.code_db_load_button = QtWidgets.QPushButton("Select Database", self)
self.code_db_load_button.clicked.connect(self.codeDatabaseButtonClicked)
self.code_db_loaded_text = QtWidgets.QLabel("No Database Loaded", self)
self.code_layout.addWidget(self.code_db_load_button,1,0)
self.code_layout.addWidget(self.code_db_loaded_text,0,0)
self.code_layout.setRowMinimumHeight(2,10)
# self.code_layout.setColumnMinimumWidth(0,150)
# Time Checkbox
self.time_process_box = QtWidgets.QCheckBox("Process Time",self)
self.time_process_box.setChecked(False)
self.code_layout.addWidget(self.time_process_box,2,0)
# Average Checkbox
self.average_runs = QtWidgets.QCheckBox("Average the Runs",self)
self.average_runs.setChecked(False)
self.average_runs.stateChanged.connect(self.averageCheckBoxToggle)
self.code_layout.addWidget(self.average_runs,3,0)
# Normalize Average Checkbox
self.normalize_average_runs = QtWidgets.QCheckBox("Normalize the Runs",self)
self.normalize_average_runs.setChecked(False)
self.code_layout.addWidget(self.normalize_average_runs,4,0)
self.normalize_average_runs.setVisible(False)
self.code_layout.setColumnMinimumWidth(0,130)
self.code_layout.setRowMinimumHeight(4,25)
# srcML Button
self.code_srcml_load_button = QtWidgets.QPushButton("Select srcML Archive", self)
self.code_srcml_load_button.clicked.connect(self.codeSrcmlButtonClicked)
self.code_srcml_loaded_text = QtWidgets.QLabel("No srcML Loaded",self)
self.code_layout.addWidget(self.code_srcml_load_button,6,0)
self.code_layout.addWidget(self.code_srcml_loaded_text,5,0)
# Number of colors
self.color_number_box = QtWidgets.QLineEdit(self)
self.color_number_box.setMaximumWidth(23)
self.color_number_box.setGeometry(620,400,25,20)
self.color_number_box.setValidator(QtGui.QIntValidator())
self.color_number_box.setText(str(DEFAULT_NUM_OF_COLORS))
self.code_layout.addWidget(self.color_number_box,8,1)
self.color_number_text = QtWidgets.QLabel("# of colors",self)
self.code_layout.addWidget(self.color_number_text,8,0)
self.code_layout.setRowMinimumHeight(9,10)
# Process Button
self.process_code_button = QtWidgets.QPushButton("Process Image",self)
self.process_code_button.clicked.connect(self.generateCodeHeatmap)
self.code_layout.addWidget(self.process_code_button,10,0)
# Session List
self.code_session_list = QtWidgets.QListWidget(self)
self.code_session_list.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.MultiSelection)
self.code_session_list.itemClicked.connect(self.codeSessionLoadClicked)
self.code_layout.addWidget(self.code_session_list,1,3,10,10)
self.code_session_list_text = QtWidgets.QLabel("Sessions", self)
self.code_layout.addWidget(self.code_session_list_text,0,3)
# Session Select All
self.code_session_select_all_button = QtWidgets.QPushButton("Select All",self)
self.code_session_select_all_button.clicked.connect(self.codeSelectAllSessions)
self.code_layout.addWidget(self.code_session_select_all_button,0,4)
# Fixation Run List
self.code_fixation_runs_list = QtWidgets.QListWidget(self)
self.code_fixation_runs_list.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.MultiSelection)
self.code_fixation_runs_list.itemClicked.connect(self.codeFixationRunClicked)
self.code_layout.addWidget(self.code_fixation_runs_list,1,13,10,10)
self.code_fixation_runs_list_text = QtWidgets.QLabel("Fixation Runs", self)
self.code_layout.addWidget(self.code_fixation_runs_list_text,0,13)
# Fixation Run Select All
self.code_fixation_run_select_all_button = QtWidgets.QPushButton("Select All",self)
self.code_fixation_run_select_all_button.clicked.connect(self.codeSelectAllFixationRuns)
self.code_layout.addWidget(self.code_fixation_run_select_all_button,0,14)
# Graph Tab
############################################################################
# DB Button
self.graph_db_load_button = QtWidgets.QPushButton("Select Database", self)
self.graph_db_load_button.clicked.connect(self.graphDatabaseButtonClicked)
self.graph_db_loaded_text = QtWidgets.QLabel("No Database Loaded", self)
self.graph_layout.addWidget(self.graph_db_load_button,1,0)
self.graph_layout.addWidget(self.graph_db_loaded_text,0,0)
# # srcML Button
# self.graph_srcml_load_button = QtWidgets.QPushButton("Select srcML Archive", self)
# self.graph_srcml_load_button.clicked.connect(self.graphSrcmlButtonClicked)
# self.graph_srcml_loaded_text = QtWidgets.QLabel("No srcML Loaded",self)
# self.graph_layout.addWidget(self.graph_srcml_load_button,5,0)
# self.graph_layout.addWidget(self.graph_srcml_loaded_text,4,0)
# Session List
self.graph_session_list = QtWidgets.QListWidget(self)
self.graph_session_list.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.MultiSelection)
self.graph_session_list.itemClicked.connect(self.graphSessionLoadClicked)
self.graph_layout.addWidget(self.graph_session_list,1,3,10,10)
self.graph_session_list_text = QtWidgets.QLabel("Sessions", self)
self.graph_layout.addWidget(self.graph_session_list_text,0,3)
# Session Select All
self.graph_session_select_all_button = QtWidgets.QPushButton("Select All",self)
self.graph_session_select_all_button.clicked.connect(self.graphSelectAllSessions)
self.graph_layout.addWidget(self.graph_session_select_all_button,0,4)
# Fixation Run List
self.graph_fixation_runs_list = QtWidgets.QListWidget(self)
self.graph_fixation_runs_list.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.MultiSelection)
self.graph_fixation_runs_list.itemClicked.connect(self.graphFixationRunClicked)
self.graph_layout.addWidget(self.graph_fixation_runs_list,1,13,10,10)
self.graph_fixation_runs_list_text = QtWidgets.QLabel("Fixation Runs", self)
self.graph_layout.addWidget(self.graph_fixation_runs_list_text,0,13)
# Fixation Run Select All
self.graph_fixation_run_select_all_button = QtWidgets.QPushButton("Select All",self)
self.graph_fixation_run_select_all_button.clicked.connect(self.graphSelectAllFixationRuns)
self.graph_layout.addWidget(self.graph_fixation_run_select_all_button,0,14)
# ROI Tab Box
self.graph_roi_list = QtWidgets.QTabWidget(self)
self.graph_roi_list.setTabsClosable(True)
self.graph_roi_list.tabCloseRequested.connect(self.closeFileTab)
self.graph_layout.addWidget(self.graph_roi_list,2,26,9,10)
self.graph_roi_list_text = QtWidgets.QLabel("File ROIs", self)
self.graph_layout.addWidget(self.graph_roi_list_text,0,26,2,1)
# ROI Add File Button
self.graph_file_add_button = QtWidgets.QPushButton("Add File")
self.graph_file_add_button.clicked.connect(self.addFileTab)
self.graph_layout.addWidget(self.graph_file_add_button,0,27)
# ROI Add ROI Button
self.graph_roi_add_button = QtWidgets.QPushButton("Add ROI")
self.graph_roi_add_button.clicked.connect(self.addROI)
self.graph_layout.addWidget(self.graph_roi_add_button,0,28)
# ROI Load ROIs Button
self.graph_roi_load_button = QtWidgets.QPushButton("Load ROIs")
self.graph_roi_load_button.clicked.connect(self.loadROI)
self.graph_layout.addWidget(self.graph_roi_load_button,1,27)
# ROI Load ROIs Button
self.graph_roi_export_button = QtWidgets.QPushButton("Export ROIs")
self.graph_roi_export_button.clicked.connect(self.exportROI)
self.graph_layout.addWidget(self.graph_roi_export_button,1,28)
# Make Graphs Button
self.graph_make_graphs_button = QtWidgets.QPushButton("Generate Graphs")
self.graph_make_graphs_button.clicked.connect(self.generateGraphs)
self.graph_layout.addWidget(self.graph_make_graphs_button)
self.tab_widget.addTab(self.video_tab,'Gaze Cloud Video')
self.tab_widget.addTab(self.code_tab,'Tokenized Heatmap')
self.tab_widget.addTab(self.graph_tab,'Graphs')
def videoDatabaseButtonClicked(self): # Load Database
db_file_path = QtWidgets.QFileDialog.getOpenFileName(self, "Open Database", "", "SQLite Files (*.db3 *.db *.sqlite *sqlite3)")[0]
if(db_file_path == ''):
return
try:
self.video_idb = iTraceDB(db_file_path)
except Exception as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
return
display_name = db_file_path.split("/")[-1]
if len(display_name) > 20:
display_name = display_name[:20]
self.video_db_loaded_text.setText(display_name)
self.video_session_list.clear()
self.video_fixation_runs_list.clear()
sessions = self.video_idb.GetSessions()
self.video_session_list.addItems(sessions)
def codeDatabaseButtonClicked(self): # Load Database
db_file_path = QtWidgets.QFileDialog.getOpenFileName(self, "Open Database", "", "SQLite Files (*.db3 *.db *.sqlite *sqlite3)")[0]
if(db_file_path == ''):
return
try:
self.code_idb = iTraceDB(db_file_path)
except Exception as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
return
display_name = db_file_path.split("/")[-1]
if len(display_name) > 20:
display_name = display_name[:20]
self.code_db_loaded_text.setText(display_name)
self.code_session_list.clear()
self.code_fixation_runs_list.clear()
sessions = self.code_idb.GetSessionsWithParticipantID()
self.code_session_list.addItems(sessions)
def graphDatabaseButtonClicked(self): # Load Database
db_file_path = QtWidgets.QFileDialog.getOpenFileName(self, "Open Database", "", "SQLite Files (*.db3 *.db *.sqlite *sqlite3)")[0]
if(db_file_path == ''):
return
try:
self.graph_idb = iTraceDB(db_file_path)
except Exception as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
return
display_name = db_file_path.split("/")[-1]
if len(display_name) > 20:
display_name = display_name[:20]
self.graph_db_loaded_text.setText(display_name)
self.graph_session_list.clear()
self.graph_fixation_runs_list.clear()
sessions = self.graph_idb.GetSessionsWithParticipantID()
self.graph_session_list.addItems(sessions)
def codeSrcmlButtonClicked(self): # Load srcML
srcml_file_path = QtWidgets.QFileDialog.getOpenFileName(self, "Open srcML Archive","","srcML Files (*.xml *.srcml)")[0]
if(srcml_file_path == ''):
return
try:
self.code_srcml = ET.parse(srcml_file_path)
except Exception as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
return
if("filename" in self.code_srcml.getroot().attrib):
QtWidgets.QMessageBox.critical(self, "srcML Error", "The provided srcML file is not an archive file")
self.video = None
return
display_name = srcml_file_path.split("/")[-1]
if len(display_name) > 20:
display_name = display_name[:20]
self.code_srcml_loaded_text.setText(display_name)
def videoSessionLoadClicked(self, item): # Select Session
session_id = int(item.text().split(" - ")[1])
self.video_fixation_runs_list.clear()
self.video_fixation_runs_list.addItems(self.video_idb.GetFixationRuns(session_id))
self.selected_session_time = self.video_idb.GetSessionTimeLength(session_id)
self.session_start_time = self.video_idb.GetSessionStartTime(session_id)
def codeSessionLoadClicked(self, item): # Select Session
particpant_id = item.text().split(" - ")[0]
task_name = item.text().split(" - ")[1]
session_id = int(item.text().split(" - ")[2])
selected = self.code_session_list.selectedItems()
fixation_runs = self.code_idb.GetFixationRunsWithSession(session_id)
list_id = f"----------- {particpant_id} - {task_name} -----------"
if item not in selected:
self.code_fixation_runs_list.takeItem(self.code_fixation_runs_list.row(self.code_fixation_runs_list.findItems(list_id,QtCore.Qt.MatchExactly)[0]))
for run in fixation_runs:
self.code_fixation_runs_list.takeItem(self.code_fixation_runs_list.row(self.code_fixation_runs_list.findItems(run,QtCore.Qt.MatchExactly)[0]))
else:
# self.code_fixation_runs_list.clear()
self.code_fixation_runs_list.addItem(list_id)
self.code_fixation_runs_list.addItems(fixation_runs)
def codeSelectAllSessions(self):
for item in [self.code_session_list.item(i) for i in range(self.code_session_list.count())]:
if not item.isSelected():
item.setSelected(True)
self.codeSessionLoadClicked(item)
def codeSelectAllFixationRuns(self):
for item in [self.code_fixation_runs_list.item(i) for i in range(self.code_fixation_runs_list.count())]:
if not item.isSelected():
item.setSelected(True)
self.codeFixationRunClicked(item)
def graphSelectAllSessions(self):
for item in [self.graph_session_list.item(i) for i in range(self.graph_session_list.count())]:
if not item.isSelected():
item.setSelected(True)
self.graphSessionLoadClicked(item)
def graphSelectAllFixationRuns(self):
for item in [self.graph_fixation_runs_list.item(i) for i in range(self.graph_fixation_runs_list.count())]:
if not item.isSelected():
item.setSelected(True)
self.graphFixationRunClicked(item)
def graphSessionLoadClicked(self, item): # Select Session
particpant_id = item.text().split(" - ")[0]
task_name = item.text().split(" - ")[1]
session_id = int(item.text().split(" - ")[2])
selected = self.graph_session_list.selectedItems()
fixation_runs = self.graph_idb.GetFixationRunsWithSession(session_id)
list_id = f"----------- {particpant_id} - {task_name} -----------"
if item not in selected:
self.graph_fixation_runs_list.takeItem(self.graph_fixation_runs_list.row(self.graph_fixation_runs_list.findItems(list_id,QtCore.Qt.MatchExactly)[0]))
for run in fixation_runs:
self.graph_fixation_runs_list.takeItem(self.graph_fixation_runs_list.row(self.graph_fixation_runs_list.findItems(run,QtCore.Qt.MatchExactly)[0]))
else:
# self.code_fixation_runs_list.clear()
self.graph_fixation_runs_list.addItem(list_id)
self.graph_fixation_runs_list.addItems(fixation_runs)
def videoFixationRunClicked(self, item): # Select Fixation Run (Doesn't currently do anything extra)
pass
def codeFixationRunClicked(self, item):
if item.text().startswith("-----------") and item in self.code_fixation_runs_list.selectedItems():
item.setSelected(False)
def averageCheckBoxToggle(self):
self.normalize_average_runs.setVisible(self.average_runs.isChecked())
def graphFixationRunClicked(self, item):
if item.text().startswith("-----------") and item in self.graph_fixation_runs_list.selectedItems():
item.setSelected(False)
def addFileTab(self,file):
if file == False:
file, ok = QtWidgets.QInputDialog.getText(self, "Add File for ROIs", "Enter file name", QtWidgets.QLineEdit.Normal, "")
if not ok:
return
if "." not in file:
dlg = ConfirmDialog(self, "Unusual File Name", "The supplied name does not resemble a file. Continue anyway?")
if dlg.exec():
pass
else:
return
tab = QtWidgets.QWidget()
roi_list = QtWidgets.QListWidget(tab)
removeItem = lambda item : roi_list.takeItem(roi_list.row(item))
roi_list.itemDoubleClicked.connect(removeItem)
self.graph_roi_list.addTab(tab,file)
self.file_tabs[file] = {"tab":tab,"rois":roi_list}
self.graph_roi_list.setCurrentWidget(tab)
def closeFileTab(self,index):
del self.file_tabs[self.graph_roi_list.tabText(index)]
self.graph_roi_list.removeTab(index)
def addROI(self, lines):
if lines == False:
lines, ok = QtWidgets.QInputDialog.getText(self, "Add Region of Interest", "Enter start and end line numbers (inclusive):", QtWidgets.QLineEdit.Normal, "START,END")
if not ok:
return
try:
vals = [int(num) for num in lines.split(",")]
if len(vals) != 2:
QtWidgets.QMessageBox.critical(self, "Input Error", "Number of inputs must be 2")
return
elif vals[0] > vals[1]:
QtWidgets.QMessageBox.critical(self, "Input Error", "Start line must be less than or equal to end line")
return
elif vals[0] <= 0 or vals[1] <= 0:
QtWidgets.QMessageBox.critical(self, "Input Error", "Entered lines cannot be 0 or less")
return
except Exception as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
return
if self.graph_roi_list.currentWidget() == None:
QtWidgets.QMessageBox.critical(self, "Input Error", "No Files Added")
return
# print(self.graph_roi_list.currentWidget())
# print(self.file_tabs)
rois = self.file_tabs[self.graph_roi_list.tabText(self.graph_roi_list.currentIndex())]["rois"]
insert = 0
for item in [rois.item(i) for i in range(rois.count())]:
start,end = [int(num) for num in item.text().split(",")]
if (vals[0] >= start and vals[0] <= end) or (vals[1] >= start and vals[1] <= end):
QtWidgets.QMessageBox.critical(self, "Input Error", "Entered lines cannot be within another ROI")
return
if vals[0] > start:
insert = rois.row(item)+1
print(insert)
rois.insertItem(insert,f"{vals[0]},{vals[1]}")
# rois.addItem(f"{vals[0]},{vals[1]}")
def loadROI(self):
roi_json_file_path = QtWidgets.QFileDialog.getOpenFileName(self, "Load ROIs","","JSON(*.json)")[0]
if roi_json_file_path == "":
return
try:
with open(roi_json_file_path,'r') as in_file:
data = eval(in_file.read())
print(data)
except Exception as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
return
self.file_tabs = {}
self.graph_roi_list.clear()
for file in data:
self.addFileTab(file)
self.graph_roi_list.setCurrentIndex(self.graph_roi_list.count()-1)
for lines in data[file]:
self.addROI(lines)
def exportROI(self):
output_file_name, _ = QtWidgets.QFileDialog.getSaveFileName(self,"Export ROIs","","JSON(*.json)")
if output_file_name == "":
return
try:
with open(output_file_name,'w') as out_file:
out_file.write("{\n")
for file in self.file_tabs:
out_file.write(f" \"{file}\": [\n")
rois_list = self.file_tabs[file]["rois"]
for item in [rois_list.item(i) for i in range(rois_list.count())]:
out_file.write(f" \"{item.text()}\",\n")
out_file.write(" ],\n")
out_file.write("}")
except Exception as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
return
def generateGraphs(self):
output_folder_name = QtWidgets.QFileDialog.getExistingDirectory(self,"Open Directory")
if not output_folder_name:
return
rois = {}
timelines = {}
colors = {}
for file in self.file_tabs:
roi_list = self.file_tabs[file]["rois"]
rois[file] = {f"ROI_{i+1}":tuple([int(l) for l in roi_list.item(i).text().split(",")]) for i in range(roi_list.count())}
timelines[file] = {}
colors[file] = {"otherLine":"#D3E1E8","noROI":"#6D7477"}
for i in range(len(rois[file])):
rgb = colorsys.hsv_to_rgb(((i / (len(rois[file]) - 1)) if len(rois[file]) > 1 else 0) * (0.75),1,1)
colors[file][f"ROI_{i+1}"] = f"#{str(hex(int(rgb[0]*255)))[2:].zfill(2)}{str(hex(int(rgb[1]*255)))[2:].zfill(2)}{str(hex(int(rgb[2]*255)))[2:].zfill(2)}"
for fixation_run in self.graph_fixation_runs_list.selectedItems():
fixation_run_id = int(fixation_run.text().split(" - ")[1])
session_id = int(fixation_run.text().split(" - ")[2])
particpant_id = self.graph_idb.GetParticipantFromSessionID(session_id)
task_name = self.graph_idb.GetTaskFromSessionID(session_id)
dict_id = f"{particpant_id}-{task_name}-{fixation_run_id}"
print(dict_id)
for file in timelines:
timelines[file][dict_id] = []
fixations = [Fixation(tup) for tup in self.graph_idb.GetAllRunFixations(fixation_run_id)]
# print(1,set([file[0] for file in self.graph_idb.GetFilesLookedAtBySession(session_id)]))
# print(2,set([file for file in timelines]))
target_files = set([file[0] for file in self.graph_idb.GetFilesLookedAtBySession(session_id)]) & set([file for file in timelines])
print(f"\t{target_files}")
# print(3,target_files)
for i in range(len(fixations)):
fixation = fixations[i]
looked_file = fixation.fixation_target
for target_file in target_files:
if looked_file == target_file:
for roi_id in rois[target_file]:
roi = rois[target_file][roi_id]
line = fixation.source_file_line
if line >= roi[0] and line <= roi[1]:
region = roi_id
break
else:
region = "otherLine"
else:
region = "noROI"
duration = fixation.duration
if len(timelines[target_file][dict_id]) == 0:
timelines[target_file][dict_id].append({region:duration})
elif list(timelines[target_file][dict_id][-1].keys())[0] == region:
diff = ConvertWindowsTime(fixation.fixation_start_event_time) - (ConvertWindowsTime(fixations[i-1].fixation_start_event_time) + fixations[i-1].duration)
timelines[target_file][dict_id][-1][region] += diff + duration
elif region == "noROI" and list(timelines[target_file][dict_id][-1].keys())[0] != "noROI":
diff = ConvertWindowsTime(fixation.fixation_start_event_time) - (ConvertWindowsTime(fixations[i-1].fixation_start_event_time) + fixations[i-1].duration)
timelines[target_file][dict_id].append({region:diff+duration})
elif region != "noROI" and list(timelines[target_file][dict_id][-1].keys())[0] == "noROI":
diff = ConvertWindowsTime(fixation.fixation_start_event_time) - (ConvertWindowsTime(fixations[i-1].fixation_start_event_time) + fixations[i-1].duration)
timelines[target_file][dict_id][-1]["noROI"] += diff
timelines[target_file][dict_id].append({region:duration})
elif region != "noROI" and list(timelines[target_file][dict_id][-1].keys())[0] != "noROI":
diff = ConvertWindowsTime(fixation.fixation_start_event_time) - (ConvertWindowsTime(fixations[i-1].fixation_start_event_time) + fixations[i-1].duration)
timelines[target_file][dict_id].append({"noROI":diff})
timelines[target_file][dict_id].append({region:duration})
for file in timelines:
plt.clf()
plt.close()
plt.figure(figsize=(25,10))
for run_id in timelines[file]:
y = [run_id]
barList = []
barColorsList = []
totalTime = 0
if len(timelines[file][run_id]) == 0:
continue
for zone in timelines[file][run_id]:
region = list(zone.keys())[0]
barList.append(zone[region])
barColorsList.append(region)
totalTime += zone[region]
if len(barList) > 0:
plt.barh(y,barList[0],color = colors[file][barColorsList[0]],height = 0.5)
leftStackValue = barList[0]
for i in range(1, len(barList)):
plt.barh(y,barList[i], left = leftStackValue ,color = colors[file][barColorsList[i]],height = 0.5, label=barColorsList[i])
leftStackValue += barList[i]
plt.title("Session Timeline", fontdict = fontTitle, loc="center")
plt.title(f"File: {file}", fontdict = fontTitle, loc="left")
plt.ylabel("Run ID", fontdict = fontLabelY)
plt.xlabel("Time in milliseconds", fontdict = fontLabelX)
plt.grid(axis='x',alpha=1)
legends = []
for region in rois[file]:
if len(rois[file][region]) > 0:
legends.append(mpatches.Patch(color = colors[file][region], label=f"{region}: {rois[file][region][0]}-{rois[file][region][1]}"))
legends.append(mpatches.Patch(color = colors[file]["noROI"], label="Off-screen/In Other File"))
legends.append(mpatches.Patch(color = colors[file]["otherLine"], label="Non-ROI Line"))
plt.legend(handles=legends)
plt.savefig(f"{output_folder_name}/graphTimeline-{file}.png")
plt.close()
print("Done!")
def videoLoadClicked(self): # Load Video
video_file_path = QtWidgets.QFileDialog.getOpenFileName(self, "Open Database", "", "Video Files (*.flv *.mp4 *.mov *.mkv);;All Files (*.*)")[0]
if(video_file_path == ''):
return
if(self.video):
self.video.release()
self.video = cv2.VideoCapture(video_file_path)
if(not self.video.isOpened()): # Starts to draw on the video
QtWidgets.QMessageBox.critical(self, "Error", "Error loading video file")
self.video = None
return
display_name = video_file_path.split("/")[-1]
if len(display_name) > 20:
display_name = display_name[:20]
self.video_loaded_text.setText(display_name)
self.video_fps = int(self.video.get(cv2.CAP_PROP_FPS))
self.video_height = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.video_width = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))
self.video_frames = int(self.video.get(cv2.CAP_PROP_FRAME_COUNT))
self.loaded_video_time = self.video_frames / self.video_fps