forked from norc-heal/heal-data-pkg-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlayout_scrollannotateresourcewidget.py
More file actions
2374 lines (1885 loc) · 151 KB
/
Copy pathlayout_scrollannotateresourcewidget.py
File metadata and controls
2374 lines (1885 loc) · 151 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
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
import sys
import os
from json import dumps, loads, load
from qtpy import QtWidgets
#from qt_jsonschema_form import WidgetBuilder
from pyqtschema.builder import WidgetBuilder
#from schema_resource_tracker import schema_resource_tracker
#from form_schema_resource_tracker import form_schema_resource_tracker
#from schema_resource_tracker import form_schema_resource_tracker, schema_resource_tracker
from schema_resource_tracker import schema_resource_tracker
from dsc_pkg_utils import qt_object_properties, get_multi_like_file_descriptions
import pandas as pd
import dsc_pkg_utils
from PyQt5.QtWidgets import (QWidget, QSlider, QLineEdit, QLabel, QPushButton, QScrollArea,QApplication,
QHBoxLayout, QVBoxLayout, QMainWindow, QGroupBox)
from PyQt5.QtCore import Qt, QSize
from PyQt5 import QtWidgets, QtCore, uic
from PyQt5.QtGui import QTextCursor
import sys
from pathlib import Path
from layout_fileurladdwidget import ListboxWidget
import re
from copy import deepcopy
import json
import datetime
import jsonschema
from jsonschema import validate
from healdata_utils.validators.jsonschema import validate_against_jsonschema
class ScrollAnnotateResourceWindow(QtWidgets.QMainWindow):
def __init__(self, workingDataPkgDirDisplay, workingDataPkgDir, filesCheckList = [], mode = "add", formSetState = {}, annotationMode = "standard", *args, **kwargs):
super().__init__(*args, **kwargs)
#self.setWindowTitle("Annotate Resource")
self.workingDataPkgDirDisplay = workingDataPkgDirDisplay
self.workingDataPkgDir = workingDataPkgDir
self.filesCheckList = filesCheckList
self.mode = mode
self.formSetState = formSetState
if self.formSetState:
self.resetForFormSetState = True
else:
self.resetForFormSetState = False
self.annotationMode = annotationMode
self.schemaVersion = schema_resource_tracker["version"]
self.loadingFormDataFromFile = False
self.itemsDescriptionList = []
self.initUI()
#self.load_file()
def initUI(self):
self.scroll = QtWidgets.QScrollArea() # Scroll Area which contains the widgets, set as the centralWidget
self.widget = QtWidgets.QWidget() # Widget that contains the collection of Vertical Box
self.vbox = QtWidgets.QVBoxLayout() # The Vertical Box that contains the Horizontal Boxes of labels and buttons
self.mfilehbox = QtWidgets.QHBoxLayout()
self.saveFolderPath = None
self.saveFilePath = None
self.priorityContentList = None
################################## Create component widgets - form, save button, status message box
# create the form widget
#self.schema = form_schema_resource_tracker
self.schema = schema_resource_tracker
self.experimentNameList = []
self.experimentNameList, _ = dsc_pkg_utils.get_exp_names(self=self, perResource=False) # gets self.experimentNameList
print("self.experimentNameList: ",self.experimentNameList)
if self.experimentNameList:
#self.schema = self.add_exp_names_to_schema() # uses self.experimentNameList and self.schema to update schema property experimentNameBelongs to be an enum with values equal to experimentNameList
self.schema = dsc_pkg_utils.add_exp_names_to_schema(self=self) # uses self.experimentNameList and self.schema to update schema property experimentNameBelongs to be an enum with values equal to experimentNameList
self.ui_schema = {}
self.builder = WidgetBuilder(self.schema)
self.form = self.builder.create_form(self.ui_schema)
self.formDefaultState = {
"schemaVersion": self.schemaVersion,
"resourceId": "resource-1",
"experimentNameBelongsTo": "default-experiment-name",
#"expBelongsTo": "exp-999",
"accessDate": "2099-01-01"
}
print(self.formDefaultState)
# by default self.formSetState will be an empty dict, also equal to None, so this will not be enacted
# if a dict is passed in the formSetState param to scroll annotate resource widge, this will be enacted
# it will merge the dict passes as param with the hard coded default dict, overwriting key value
# pairs in the hard coded default dict with dict passed as param if there are overlapping keys
if self.formSetState:
print(self.formSetState)
self.formDefaultState = {**self.formDefaultState, **self.formSetState}
print(self.formDefaultState)
self.form.widget.state = deepcopy(self.formDefaultState)
# # create 'add dsc data pkg directory' button
# self.buttonAddDir = QtWidgets.QPushButton(text="Add DSC Package Directory",parent=self)
# self.buttonAddDir.clicked.connect(self.add_dir)
# self.buttonAddDir.setSizePolicy(
# QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding
# )
# self.buttonAddDir.setStyleSheet("QPushButton{background-color:rgba(10,105,33,100);} QPushButton:hover{background-color:rgba(0,125,0,50);}");
# create save button
self.buttonSaveResource = QtWidgets.QPushButton(text="Save resource",parent=self)
self.buttonSaveResource.clicked.connect(self.save_resource)
self.buttonSaveResource.setSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding
)
self.buttonSaveResource.setStyleSheet("QPushButton{background-color:rgba(10,105,33,100);} QPushButton:hover{background-color:rgba(0,125,0,50);}");
# create clear form button
self.buttonClearForm = QtWidgets.QPushButton(text="Clear form",parent=self)
self.buttonClearForm.clicked.connect(self.clear_form)
self.buttonClearForm.setSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding
)
self.buttonClearForm.setStyleSheet("QPushButton{background-color:rgba(196,77,86,100);} QPushButton:hover{background-color:rgba(196,30,58,50);}");
# create status message box
self.userMessageBox = QtWidgets.QTextEdit(parent=self)
self.userMessageBox.setReadOnly(True)
self.messageText = ""
self.userMessageBox.setText(self.messageText)
self.labelUserMessageBox = QtWidgets.QLabel(text = "User Status Message Box:", parent=self)
# create button to add multiple like resources
self.buttonAddMultiResource = QtWidgets.QPushButton(text="Add Multiple \'like\' Resources",parent=self)
self.buttonAddMultiResource.clicked.connect(self.add_multi_resource)
self.labelAddMultiResource = QtWidgets.QLabel(text="To add multiple 'like' resources, <b>drag and drop file paths right here</b>. If you are annotating a single file, you can drag and drop it here or browse to the file using the Resource File Path field in the form below.",parent=self)
self.labelApplyNameConvention = QtWidgets.QLabel(text="To apply a naming convention when adding multiple 'like' resources that share a naming convention, <b>add your naming convention in the Name Convention field in the form below</b>, then come back and <b>click the Apply Name Convention button right here</b> to apply. This will autogenerate a minimal description based on the naming convention for each of your 'like' files." + "\n\n" + "e.g." + "\n" + "Name Convention: subject_{subject ID}_day_{date of data collection in YYYYMMDD})" + "\n" + "Example File Name: subject_A1_day_20230607)" + "\n" + "Autogenerated File Description: subject ID: A1, date of data collection in YYYYMMDD: 20230607)",parent=self)
self.labelAddMultiResource.setSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding
)
self.labelApplyNameConvention.setSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding
)
self.labelAddMultiResource.setWordWrap(True)
self.labelApplyNameConvention.setWordWrap(True)
# create button to apply naming convention for multiple like resources
self.buttonApplyNameConvention = QtWidgets.QPushButton(text="Apply Name Convention",parent=self)
self.buttonApplyNameConvention.clicked.connect(self.apply_name_convention)
# create drag and drop window for multiple like file addition
self.lstbox_view = ListboxWidget(self)
self.lwModel = self.lstbox_view.model()
self.items = []
self.programmaticListUpdate = False
self.lwModel.rowsInserted.connect(self.get_items_list)
self.lwModel.rowsRemoved.connect(self.get_items_list)
# create button to add multiple file dependencies addition
self.buttonAddMultiDepend = QtWidgets.QPushButton(text="Add Multiple Resource Dependencies",parent=self)
self.buttonAddMultiDepend.clicked.connect(self.add_multi_depend)
self.labelAddMultiDepend = QtWidgets.QLabel(text="To add multiple file dependencies for your resource, <b>drag and drop file paths right here</b>. If your resource has one or just a few dependencies, you can drag and drop them here or browse to each dependency (one dependency at a time) using the Associated Files/Dependencies field in the form below.",parent=self)
self.labelAddMultiDepend.setSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding
)
self.labelAddMultiDepend.setWordWrap(True)
# create drag and drop window for multiple file dependencies addition
self.lstbox_view2 = ListboxWidget(self)
self.lwModel2 = self.lstbox_view2.model()
self.items2 = [] # this will hold the values in the listbox widget
self.programmaticListUpdate2 = False
self.lwModel2.rowsInserted.connect(self.get_items_list2)
self.lwModel2.rowsRemoved.connect(self.get_items_list2)
################################## Apply some initializing and maintenance functions
# initialize tool tip for each form field based on the description text for the corresponding schema property
self.add_tooltip()
self.add_priority_highlight_and_hide()
self.add_dir()
if not self.resetForFormSetState:
if self.mode == "add":
self.get_id()
#self.add_priority_highlight()
#self.initial_hide()
self.popFormField = []
self.editSingle = False
# check for emptyp tooltip content whenever form changes and replace empty tooltip with original tooltip content
# (only relevant for fields with in situ validation - i.e. string must conform to a pattern - as pyqtschema will replace the
# tooltip content with some error content, then replace the content with empty string once the error is cleared - this check will
# restore the original tooltip content - for efficiency, may want to only run this when a widget that can have validation
# errors changes - #TODO)
self.form.widget.on_changed.connect(self.check_tooltip)
self.formWidgetList[self.formWidgetNameList.index("category")].on_changed.connect(self.conditional_fields)
self.formWidgetList[self.formWidgetNameList.index("access")].on_changed.connect(self.conditional_fields)
self.formWidgetList[self.formWidgetNameList.index("descriptionFileNameConvention")].on_changed.connect(self.conditional_highlight_apply_convention)
self.formWidgetList[self.formWidgetNameList.index("categorySubMetadata")].on_changed.connect(self.conditional_fields)
self.formWidgetList[self.formWidgetNameList.index("path")].on_changed.connect(self.conditional_fields)
#self.form.widget.on_changed.connect(self.check_priority_highlight)
################################## Finished creating component widgets
#self.mfilehbox.addWidget(self.buttonAddMultiResource)
#self.mfilehbox.addWidget(self.buttonApplyNameConvention)
#self.vbox.addWidget(self.buttonAddDir)
self.vbox.addWidget(self.buttonSaveResource)
self.vbox.addWidget(self.buttonClearForm)
self.vbox.addWidget(self.labelUserMessageBox)
self.vbox.addWidget(self.userMessageBox)
self.vbox.addWidget(self.buttonAddMultiResource)
#self.vbox.addLayout(self.mfilehbox)
self.vbox.addWidget(self.labelAddMultiResource)
self.vbox.addWidget(self.lstbox_view)
self.vbox.addWidget(self.labelApplyNameConvention)
self.vbox.addWidget(self.buttonApplyNameConvention)
self.vbox.addWidget(self.buttonAddMultiDepend)
self.vbox.addWidget(self.labelAddMultiDepend)
self.vbox.addWidget(self.lstbox_view2)
self.vbox.addWidget(self.form)
self.widget.setLayout(self.vbox)
#Scroll Area Properties
self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scroll.setWidgetResizable(True)
self.scroll.setWidget(self.widget)
self.setCentralWidget(self.scroll)
self.setGeometry(600, 100, 1000, 900)
self.setWindowTitle("Annotate Resource")
#self.show()
#if self.editState:
# self.load_file
if self.resetForFormSetState:
self.clear_form(resetForFormSetState=self.resetForFormSetState)
# this will engage the connected functions for fields and so will
# hide/show appropriate fields (was not doing this before because form set state
# values were added before functions for fields were connected)
# this will also get the resource id (don't get it above if a formsetstate param has been passed
# so that we don't run get id fx twice and print the message twice which is inefficient and
# confusing for users)
return
def scrollScrollArea (self, topOrBottom, minVal=None, maxVal=None):
# Additional params 'minVal' and 'maxVal' are declared because
# rangeChanged signal sends them, but we set it to optional
# because we may need to call it separately (if you need).
if topOrBottom == "bottom":
self.scroll.verticalScrollBar().setValue(
self.scroll.verticalScrollBar().maximum()
)
if topOrBottom == "top":
self.scroll.verticalScrollBar().setValue(
self.scroll.verticalScrollBar().minimum()
)
def add_tooltip(self):
self.toolTipContentList = []
self.formWidgetNameList = []
self.formWidgetList = []
for key, value in self.form.widget.widgets.items():
name = key
print(name)
widget = value
print(widget)
print(type(widget))
#print(widget.items())
toolTipContent = self.schema["properties"][name]["description"]
#if self.schema["properties"][name]["priority"] == "all, high":
# p = widget.palette()
# p.setColor(widget.backgroundRole(), Qt.red)
# widget.setPalette(p)
print(toolTipContent)
widget.setToolTip(toolTipContent)
self.toolTipContentList.append(toolTipContent)
self.formWidgetNameList.append(name)
self.formWidgetList.append(widget)
def add_priority_highlight_and_hide(self):
self.labelAddMultiResource.hide()
self.lstbox_view.hide()
self.labelApplyNameConvention.hide()
self.buttonApplyNameConvention.hide()
self.labelAddMultiDepend.hide()
self.lstbox_view2.hide()
print(self.form.widget.layout())
self.formLabelWidgetList = []
self.formLabelWidgetTextList = []
self.formLabelWidgetTypeList = []
l = self.form.widget.layout() # get form widget layout (it's a qgridlayout)
wList = (l.itemAt(i).widget() for i in range(l.count())) # get a list of the widgets in the layout
for idx, w in enumerate(wList): # collect all the qlabel widgets in the layout (for array widgets you have to collect the title instead)
#print(w.text)
print("widget: %s - %s" %(w.objectName(), type(w)))
if isinstance(w, QLabel):
print("label: %s" %(w.text()))
self.formLabelWidgetList.append(w)
self.formLabelWidgetTextList.append(w.text())
self.formLabelWidgetTypeList.append("label")
if isinstance(w, QGroupBox):
print("gbtitle: %s" %(w.title()))
self.formLabelWidgetList.append(w)
self.formLabelWidgetTextList.append(w.title())
self.formLabelWidgetTypeList.append("groupbox")
newList = None
if not self.priorityContentList:
newList = True
self.priorityContentList = []
for key, value in self.form.widget.widgets.items():
fColor = None
name = key
widget = value
titleContent = self.schema["properties"][name]["title"]
priorityContent = self.schema["properties"][name]["priority"]
if newList:
self.priorityContentList.append(priorityContent)
if titleContent in self.formLabelWidgetTextList:
labelWidgetIdx = self.formLabelWidgetTextList.index(titleContent)
labelWidget = self.formLabelWidgetList[labelWidgetIdx]
labelWidgetType = self.formLabelWidgetTypeList[labelWidgetIdx]
if ", high" in priorityContent:
fColor = "green"
if ", auto" in priorityContent:
fColor = "blue"
if fColor:
if (labelWidgetType == "label"):
labelWidget.setText('<font color = ' + fColor + '>' + labelWidget.text() + '</font>')
if (labelWidgetType == "groupbox"):
#labelWidget.setTitle('<font color = ' + fColor + '>' + labelWidget.title() + '</font>')
labelWidget.setStyleSheet('QGroupBox {color: ' + fColor + ';}')
if not priorityContent.startswith("all, "):
labelWidget.hide()
widget.hide()
# if annotationMode is minimal and hide-minimal in priority text content then hide the widget and its label
if self.annotationMode == "minimal":
if "hide-minimal" in priorityContent:
labelWidget.hide()
widget.hide()
def check_tooltip(self):
i = 0
for key, value in self.form.widget.widgets.items():
name = key
#print(name)
widget = value
#print(widget)
#print(type(widget))
toolTipContent = widget.toolTip() # get current tool tip content
#print(toolTipContent)
if not toolTipContent: # check if the tool tip string is empty (this will occur if a validation error happened and error message was displayed and then the error was resolved as tooltip will be set to empty by pyqtschema pkg upon clearing the error)
widget.setToolTip(self.toolTipContentList[i]) # if empty then set it to the tooltip content from schema description that was stored on initialization
i+=1 # increment
def toggle_widgets(self, keyText, desiredToggleState):
indices = [i for i, x in enumerate(self.priorityContentList) if keyText in x.split(", ")]
print(indices)
for i in indices:
labelW = self.formLabelWidgetList[i]
print(labelW)
labelWType = self.formLabelWidgetTypeList[i]
print(labelWType)
labelWText = self.formLabelWidgetTextList[i]
print(labelWText)
fieldW = self.formWidgetList[i]
print(fieldW)
fieldWName = self.formWidgetNameList[i]
print(fieldWName)
if desiredToggleState == "show":
if self.annotationMode == "standard":
labelW.show()
fieldW.show()
elif self.annotationMode == "minimal":
if "hide-minimal" not in self.priorityContentList[i]:
labelW.show()
fieldW.show()
if desiredToggleState == "hide":
labelW.hide()
fieldW.hide()
def conditional_fields(self, changedFieldName):
#if changedFieldName == "category":
# reminder to add dd if tabular data; reminder to add result tracker if publication
# if results tracker, read in and try to get result dependencies
# DO NOT do these items if loading from file (i.e. user is editing an existing annotation or adding a new annotation based on existing)
if not self.loadingFormDataFromFile:
if self.form.widget.state["category"] == "tabular-data":
messageText = "<br>You have indicated your resource is a tabular data resource. Please ensure that you add a data dictionary for this tabular data resource in the Associated Data Dictionary field in the form below. A HEAL formatted data dictionary is highly preferred. If you don't already have a HEAL formatted data dictionary, you can easily create one directly from your tabular data file by visiting the Data Dictionary tab of the DSC Packaging Desktop application. You can leave this form open, visit the Data Dictionary tab to create and save your HEAL formatted data dictionary, and then return to this form to add the data dictionary you created."
errorFormat = '<span style="color:blue;">{}</span>'
self.userMessageBox.append(errorFormat.format(messageText))
if self.form.widget.state["category"] == "publication":
messageText = "<br>You have indicated your resource is a publication resource. Please ensure that you add a results tracker for this publication resource in the Associated Results Tracker field in the form below. A results tracker is a HEAL formatted standard data package metadata file to track all results in a publication, along with the data and other supporting files that underly each result. If you don't already have a HEAL formatted results tracker, you can easily create one by visiting the Results Tracker tab of the DSC Data Packaging Desktop Tool. You can leave this form open, visit the Results Tracker tab to create and save your HEAL formatted results tracker, and then return to this form to add the results tracker you created."
errorFormat = '<span style="color:blue;">{}</span>'
self.userMessageBox.append(errorFormat.format(messageText))
if self.form.widget.state["category"] == "metadata":
if self.form.widget.state["categorySubMetadata"] == "heal-formatted-results-tracker":
messageText = "<br>You have indicated your resource is a HEAL formatted Results Tracker. The Associated Files/Dependencies field in this form has been hidden from view because this field cannot be used to add file dependencies for a Results Tracker file. If your Result Tracker is correctly formatted, and you have provided file dependencies for each result listed in the results tracker, file dependencies will be pulled in directly from the Results Tracker."
errorFormat = '<span style="color:blue;">{}</span>'
self.userMessageBox.append(errorFormat.format(messageText))
if not self.form.widget.state["path"]:
messageText = "<br>Please use the Resource File Path field in the form to browse to your Results Tracker file."
errorFormat = '<span style="color:blue;">{}</span>'
self.userMessageBox.append(errorFormat.format(messageText))
if self.form.widget.state["path"]:
pathStem = Path(self.form.widget.state["path"]).stem
if not pathStem.startswith("heal-csv-results-tracker"):
messageText = "<br>The resource file path you have added to the Resource File Path field in the form does not appear to be a HEAL formatted results tracker, or the tracker has been re-named. Please ensure that you have added a HEAL formatted Results Tracker to the Resource File Path field in the form, and that the Results tracker name follows the naming convention: heal-csv-results-tracker-(name of publication file with which the results tracker is associated)."
errorFormat = '<span style="color:red;">{}</span>'
self.userMessageBox.append(errorFormat.format(messageText))
else:
# formally validate the results tracker here?
self.popFormField = []
messageText = "<br>The resource file path you have added to the Resource File Path field in the form appears to be a HEAL formatted results tracker. Attempting to extract file dependencies for each result in the results tracker now."
errorFormat = '<span style="color:green;">{}</span>'
self.userMessageBox.append(errorFormat.format(messageText))
resultsTrk = pd.read_csv(self.form.widget.state["path"])
resultIds = resultsTrk["resultId"].tolist()
if resultIds:
# for each result id if multiple entries (due to editing the result entry) only keep the entry with the latest mod date
print("de-duping result ids if necessary")
resultsTrk["annotationModDateTime"] = pd.to_datetime(resultsTrk["annotationModDateTime"])
#print(resultsTrk)
print("start resultsTrk.columns: ",resultsTrk.columns)
print("start resultsTrk.shape: ",resultsTrk.shape)
resultsTrk = resultsTrk[resultsTrk["annotationModDateTime"] == (resultsTrk.groupby("resultId")["annotationModDateTime"].transform("max"))]
print("finished de-duping result ids if necessary")
#print(resultsTrk)
print("end resultsTrk.columns: ",resultsTrk.columns)
print("end resultsTrk.shape: ",resultsTrk.shape)
resultIds = resultsTrk["resultId"].tolist()
resultIdDependencies = resultsTrk["associatedFileDependsOn"].tolist()
popFormField = [{"resultId": rId, "resultIdDependsOn": rIdD.strip("][").split(", ")} for rId,rIdD in zip(resultIds,resultIdDependencies)]
print("popFormField: ", popFormField)
messageText = "<br>Extracted file dependencies for each result in the results tracker are as follows:<br><br>"
#errorFormat = '<span style="color:green;">{}</span>'
#self.userMessageBox.append(errorFormat.format(messageText))
self.userMessageBox.append(messageText)
emptyDependencies = []
formatDependencies = []
for i, list_item in enumerate(popFormField):
self.userMessageBox.append(f"{i + 1}. ")
for j, key in enumerate(list_item.keys()):
self.userMessageBox.append(f"{key}:{list_item[key]}{'' if j == len(list_item) - 1 else ', '}")
if key == "resultId":
resultId = list_item[key]
if key == "resultIdDependsOn":
if not list_item[key]:
emptyDependencies.append(resultId)
print("emptyDependencies: ",emptyDependencies)
formatDependencies.append([])
else:
formatDependencies.append([item.replace("'", '') for item in list_item[key]])
self.userMessageBox.append("")
self.popFormField = [{"resultId": rId, "resultIdDependsOn": rIdD} for rId,rIdD in zip(resultIds,formatDependencies)]
print("popFormField_format: ", self.popFormField)
if emptyDependencies:
messageText = "<br>The following result IDs listed in the Results Tracker did not have any file dependencies listed:<br>" + ", ".join(emptyDependencies) + "<br><br>Please review your results tracker and add file dependencies for each result as appropriate, then come back and re-add the results tracker as a resource.<br><br>"
errorFormat = '<span style="color:red;">{}</span>'
self.userMessageBox.append(errorFormat.format(messageText))
#self.form.widget.state = {
# "associatedFileResultsDependOn": popFormField
#}
else:
messageText = "<br>There do not appear to be any results listed in the Results Tracker. Please add at least one result to your Results Tracker by navigating to the Add Results sub-tab of the Results Tracker tab. If you have already annotated your result(s), use the Add result or Auto-add result button to add your result files to your Result Tracker. If you need to annotate your result(s), start by clicking the Annotate Result button, fill out the brief form that appears to annotate your result(s), use the Add or Auto-add Result button(s) to add your result file(s) to your Results Tracker, then come back here to re-add your Results Tracker as a resource.<br>"
errorFormat = '<span style="color:red;">{}</span>'
self.userMessageBox.append(errorFormat.format(messageText))
# this is an inefficient way to make sure previously unhidden fields get hidden again if user changes the category
# should really save the last chosen state and be selective about re-hiding the ones that were revealed due to the
# previous selection
################### hide fields that were revealed due to previous selection
if self.form.widget.state["category"] != "tabular-data":
self.toggle_widgets(keyText = "data", desiredToggleState = "hide")
self.toggle_widgets(keyText = "tabular data", desiredToggleState = "hide")
# delete contents of conditional fields if any added
# DO NOT do these items if loading from file (i.e. user is editing an existing annotation or adding a new annotation based on existing)
if not self.loadingFormDataFromFile:
self.form.widget.state = {
"descriptionRow": "",
"associatedFileDataDict": []
}
if self.form.widget.state["category"] != "non-tabular-data":
self.toggle_widgets(keyText = "data", desiredToggleState = "hide")
if self.form.widget.state["category"] not in ["tabular-data","non-tabular-data"]:
# delete contents of conditional fields if any added
# DO NOT do these items if loading from file (i.e. user is editing an existing annotation or adding a new annotation based on existing)
if not self.loadingFormDataFromFile:
self.form.widget.state = {
"categorySubData": "",
"associatedFileProtocol": []
}
if self.form.widget.state["category"] != "metadata":
self.toggle_widgets(keyText = "metadata", desiredToggleState = "hide")
# delete contents of conditional fields if any added
# DO NOT do these items if loading from file (i.e. user is editing an existing annotation or adding a new annotation based on existing)
if not self.loadingFormDataFromFile:
self.form.widget.state = {
"categorySubMetadata": ""
}
# if self.form.widget.state["category"] not in ["single-result","multi-result"]:
# self.toggle_widgets(keyText = "results", desiredToggleState = "hide")
# # delete contents of conditional fields if any added
# self.form.widget.state = {
# "categorySubResults": ""
# }
if self.form.widget.state["category"] != "result":
self.toggle_widgets(keyText = "result", desiredToggleState = "hide")
# delete contents of conditional fields if any added
# DO NOT do these items if loading from file (i.e. user is editing an existing annotation or adding a new annotation based on existing)
if not self.loadingFormDataFromFile:
self.form.widget.state = {
"categorySubResult": ""
}
if self.form.widget.state["category"] != "publication":
self.toggle_widgets(keyText = "publication", desiredToggleState = "hide")
# delete contents of conditional fields if any added
# DO NOT do these items if loading from file (i.e. user is editing an existing annotation or adding a new annotation based on existing)
if not self.loadingFormDataFromFile:
self.form.widget.state = {
"categorySubPublication": ""
}
if self.form.widget.state["category"] != "publication":
self.toggle_widgets(keyText = "publication", desiredToggleState = "hide")
self.toggle_widgets(keyText = "not publication", desiredToggleState = "show")
# DO NOT do these items if loading from file (i.e. user is editing an existing annotation or adding a new annotation based on existing)
if not self.loadingFormDataFromFile:
self.form.widget.state = {
"associatedFileResultsTracker": []
}
if self.form.widget.state["category"] == "metadata":
if self.form.widget.state["categorySubMetadata"] != "heal-formatted-results-tracker":
self.toggle_widgets(keyText = "not results-tracker", desiredToggleState = "show")
# clear associatedFileResultsDependOn field (not sure the format for this, is it a list of lists?)
# DO NOT do these items if loading from file (i.e. user is editing an existing annotation or adding a new annotation based on existing)
if not self.loadingFormDataFromFile:
self.popFormField = []
if self.form.widget.state["categorySubMetadata"] != "other":
self.toggle_widgets(keyText = "subMetadataOther", desiredToggleState = "hide")
# DO NOT do these items if loading from file (i.e. user is editing an existing annotation or adding a new annotation based on existing)
if not self.loadingFormDataFromFile:
self.form.widget.state = {
"categorySubMetadataOther": ""
}
if self.form.widget.state["category"] != "metadata":
#if self.form.widget.state["categorySubMetadata"] == "heal-formatted-results-tracker":
self.toggle_widgets(keyText = "not results-tracker", desiredToggleState = "show")
# DO NOT do these items if loading from file (i.e. user is editing an existing annotation or adding a new annotation based on existing)
if not self.loadingFormDataFromFile:
self.form.widget.state = {
"categorySubMetadata": ""
}
self.popFormField = []
self.toggle_widgets(keyText = "subMetadataOther", desiredToggleState = "hide")
# DO NOT do these items if loading from file (i.e. user is editing an existing annotation or adding a new annotation based on existing)
if not self.loadingFormDataFromFile:
self.form.widget.state = {
"categorySubMetadataOther": ""
}
################### show field appropriate to current selection
if self.form.widget.state["category"] == "tabular-data":
self.toggle_widgets(keyText = "data", desiredToggleState = "show")
self.toggle_widgets(keyText = "tabular data", desiredToggleState = "show")
if self.form.widget.state["category"] == "non-tabular-data":
self.toggle_widgets(keyText = "data", desiredToggleState = "show")
if self.form.widget.state["category"] == "metadata":
self.toggle_widgets(keyText = "metadata", desiredToggleState = "show")
# if self.form.widget.state["category"] in ["single-result","multi-result"]:
# self.toggle_widgets(keyText = "results", desiredToggleState = "show")
if self.form.widget.state["category"] == "result":
self.toggle_widgets(keyText = "result", desiredToggleState = "show")
if self.form.widget.state["category"] == "publication":
self.toggle_widgets(keyText = "publication", desiredToggleState = "show")
if self.form.widget.state["category"] == "publication":
self.toggle_widgets(keyText = "publication", desiredToggleState = "show")
self.toggle_widgets(keyText = "not publication", desiredToggleState = "hide")
if self.form.widget.state["category"] == "metadata":
if self.form.widget.state["categorySubMetadata"] == "heal-formatted-results-tracker":
self.toggle_widgets(keyText = "not results-tracker", desiredToggleState = "hide")
if self.form.widget.state["categorySubMetadata"] == "other":
self.toggle_widgets(keyText = "subMetadataOther", desiredToggleState = "show")
#if changedFieldName == "access":
if "temporary-private" in self.form.widget.state["access"]:
self.toggle_widgets(keyText = "temporary private", desiredToggleState = "show")
messageText = "<br>You have indicated your resource will be temporarily held as private. Please 1) use the Access field to indicate the access level at which you'll set this resource once the temporary private access setting expires (either open-access access, or managed-access), and 2) use the Access Date field to indicate the date at which the temporary private access level is expected to expire (You will not be held to this date - Estimated dates are appreciated)."
errorFormat = '<span style="color:blue;">{}</span>'
self.userMessageBox.append(errorFormat.format(messageText))
else:
self.toggle_widgets(keyText = "temporary private", desiredToggleState = "hide")
self.form.widget.state = {
"accessDate": self.formDefaultState["accessDate"]
}
def conditional_highlight_apply_convention(self):
if self.form.widget.state["descriptionFileNameConvention"]:
self.buttonApplyNameConvention.setStyleSheet("background-color : rgba(0,125,0,50)")
else:
self.buttonApplyNameConvention.setStyleSheet("")
self.form.widget.state = {
"descriptionFile": ""
}
self.itemsDescriptionList = []
def add_dir(self):
#self.saveFolderPath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select Your DSC Data Package Directory - Your new resource will be saved there!')
self.saveFolderPath = self.workingDataPkgDir
def get_id(self):
if self.saveFolderPath:
# get new resource ID for new resource file - get the max id num used for existing resource files and add 1; if no resource files yet, set id num to 1
resFileList = [filename for filename in os.listdir(self.saveFolderPath) if filename.startswith("resource-trk-resource-")]
print(resFileList)
if resFileList: # if the list is not empty
resFileStemList = [Path(filename).stem for filename in resFileList]
print(resFileStemList)
resIdNumList = [int(filename.rsplit('-',1)[1]) for filename in resFileStemList]
print(resIdNumList)
resIdNum = max(resIdNumList) + 1
print(max(resIdNumList),resIdNum)
else:
resIdNum = 1
self.resIdNum = resIdNum
self.form.widget.state = {
"resourceIdNumber": self.resIdNum
}
self.resource_id = 'resource-'+ str(self.resIdNum)
self.resourceFileName = 'resource-trk-'+ self.resource_id + '.txt'
self.saveFilePath = os.path.join(self.saveFolderPath,self.resourceFileName)
messageText = "<br>Based on other resources already saved in your DSC Package directory, your new resource will be saved with the unique ID: " + self.resource_id + "<br>Resource ID has been added to the resource form."
messageText = messageText + "<br>Your new resource file will be saved in your DSC Package directory as: " + self.saveFilePath + "<br><br>"
self.userMessageBox.append(messageText)
#self.userMessageBox.moveCursor(QTextCursor.End)
# if there's not a resource tracker template already in the directory they added
# let them proceed but provide an informative warning
if not os.path.isfile(os.path.join(self.saveFolderPath,"heal-csv-resource-tracker.csv")):
messageText = "<br>Warning: It looks like there is no HEAL formatted resource tracker in the directory you selected. Are you sure you selected a directory that is a DSC package directory? If you have not already created a DSC package directory, you can do so now by navigating to the DSC Package tab in the application, and clicking on the Create sub-tab. This will create a directory called \n'dsc-pkg\n' which will have a HEAL formatted resource tracker file inside. Once you've done that please return here and add this directory before proceeding to annotate your resource files."
errorFormat = '<span style="color:red;">{}</span>'
self.userMessageBox.append(errorFormat.format(messageText))
self.form.widget.state = {
"resourceId": self.resource_id
}
else:
messageText = "<br>Please set your working DSC Data Package Directory to proceed."
errorFormat = '<span style="color:red;">{}</span>'
self.userMessageBox.append(errorFormat.format(messageText))
return
def get_items_list(self):
#item = QListWidgetItem(self.lstbox_view.currentItem())
#print(item.text())
if self.programmaticListUpdate:
self.programmaticListUpdate = False
return
lw = self.lstbox_view
oldLength = None
if self.items:
oldLength = len(self.items)
oldItems = self.items
self.items = [os.path.normpath(lw.item(x).text()) for x in range(lw.count())]
print(self.items)
refactorItems = []
for i in self.items:
print(i)
if os.path.isdir(i):
#self.programmaticListUpdate = True
myFiles = [os.path.normpath(os.path.join(i,f)) for f in os.listdir(i) if os.path.isfile(os.path.join(i,f))]
print(myFiles)
refactorItems.extend(myFiles)
else:
refactorItems.append(i)
if self.items != refactorItems:
self.programmaticListUpdate = True
self.items = refactorItems
self.lstbox_view.clear()
self.lstbox_view.addItems(self.items)
newLength = len(self.items)
print(self.items)
#print(type(self.items))
print(len(self.items))
if self.items:
updatePath = self.items[0]
updateAssocFileMultiLike = self.items
else:
updatePath = ""
updateAssocFileMultiLike = []
self.form.widget.state = {
"path": updatePath,
"associatedFileMultiLikeFiles": updateAssocFileMultiLike
}
if len(self.items) > 1:
print("show")
indices = [i for i, x in enumerate(self.priorityContentList) if ("multiple like resource" in x) and ("permanent hide" not in x)]
print(indices)
for i in indices:
labelW = self.formLabelWidgetList[i]
print(labelW)
labelWType = self.formLabelWidgetTypeList[i]
print(labelWType)
labelWText = self.formLabelWidgetTextList[i]
print(labelWText)
fieldW = self.formWidgetList[i]
print(fieldW)
fieldWName = self.formWidgetNameList[i]
print(fieldWName)
labelW.show()
fieldW.show()
self.labelApplyNameConvention.show()
self.buttonApplyNameConvention.show()
if oldLength:
if ((oldLength > 1) and (newLength <= 1)):
print("hide")
indices = [i for i, x in enumerate(self.priorityContentList) if "multiple like resource" in x]
print(indices)
for i in indices:
labelW = self.formLabelWidgetList[i]
print(labelW)
labelWType = self.formLabelWidgetTypeList[i]
print(labelWType)
labelWText = self.formLabelWidgetTextList[i]
print(labelWText)
fieldW = self.formWidgetList[i]
print(fieldW)
fieldWName = self.formWidgetNameList[i]
print(fieldWName)
labelW.hide()
fieldW.hide()
# should also probably delete the contents of these folders?
self.labelApplyNameConvention.hide()
self.buttonApplyNameConvention.hide()
def get_items_list2(self):
#item = QListWidgetItem(self.lstbox_view.currentItem())
#print(item.text())
if self.programmaticListUpdate2:
self.programmaticListUpdate2 = False
return
lw = self.lstbox_view2
oldLength = None
if self.items2:
oldLength = len(self.items2)
oldItems = self.items2
self.items2 = [lw.item(x).text() for x in range(lw.count())]
print(self.items2)
refactorItems = []
for i in self.items2:
print(i)
if os.path.isdir(i):
#self.programmaticListUpdate = True
myFiles = [os.path.join(i,f) for f in os.listdir(i) if os.path.isfile(os.path.join(i,f))]
print(myFiles)
refactorItems.extend(myFiles)
else:
refactorItems.append(i)
if self.items2 != refactorItems:
self.programmaticListUpdate2 = True
self.items2 = refactorItems
self.lstbox_view2.clear()
self.lstbox_view2.addItems(self.items2)
newLength = len(self.items2)
print(self.items2)
#print(type(self.items))
print(len(self.items2))
if self.items2:
updateAssocFileMultiDepend = self.items2
# if self.form.widget.state["associatedFileDependsOn"]:
# updateAssocFileMultiDepend = self.items2 +
# else:
# updateAssocFileMultiDepend = self.items2
else:
updateAssocFileMultiDepend = []
#list(pd.unique(students))
self.form.widget.state = {
#"path": updatePath,
"associatedFileDependsOn": updateAssocFileMultiDepend
}
if oldLength:
if ((oldLength > 0) and (newLength == 0)):
print("hide")
self.labelAddMultiDepend.hide()
self.lstbox_view2.hide()
def conditional_priority_highlight(self, priorityText, fontColor):
# not in use? confirm and delete
indices = [i for i, x in enumerate(self.priorityContentList) if x == priorityText]
for i in indices:
labelW = self.formLabelWidgetList[i]
labelWType = self.formLabelWidgetTypeList[i]
labelWText = self.formLabelWidgetTextList[i]
fColor = fontColor
if (labelWType == "label"):
labelW.setText('<font color = ' + fColor + '>' + labelW.text() + '</font>')
if (labelWType == "groupbox"):
labelW.setStyleSheet('QGroupBox {color: ' + fColor + ';}')
def add_multi_resource(self):
if ((self.lstbox_view.isHidden()) and (self.labelAddMultiResource.isHidden())):
self.lstbox_view.show()
self.labelAddMultiResource.show()
else:
self.lstbox_view.hide()
self.labelAddMultiResource.hide()
def add_multi_depend(self):
if ((self.lstbox_view2.isHidden()) and (self.labelAddMultiDepend.isHidden())):
self.lstbox_view2.show()
self.labelAddMultiDepend.show()
else:
self.lstbox_view2.hide()
self.labelAddMultiDepend.hide()
def apply_name_convention(self):
print("applying name convention")
# have to do this after add_tooltip because these items are defined in that function - may want to change that at some point
# get the name convention widget
# if the contents of the name convention widget
self.nameConventionWidgetIdx = self.formWidgetNameList.index("descriptionFileNameConvention")
self.nameConventionWidget = self.formWidgetList[self.nameConventionWidgetIdx]
print("my state: ", self.nameConventionWidget.state)
self.nameConvention = self.nameConventionWidget.state