-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGUI.py
1667 lines (1392 loc) · 75 KB
/
GUI.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
import threading
from dictEditor import LineNumberArea, CodeEditor, DictEditor, JsonHighlighter
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QFileDialog, QListWidget, \
QSplitter, QTextEdit, QLabel, QLineEdit, QHBoxLayout, QStackedWidget, QAction, QComboBox, QScrollArea, \
QSpinBox, QFormLayout, QDoubleSpinBox, QCheckBox, QGridLayout, QMessageBox, QDialog, QLayout, QDialogButtonBox
from PyQt5.QtCore import Qt, QObject, pyqtSignal, QTimer
from PyQt5 import QtGui
from PyQt5.QtGui import QTextCursor, QColor, QFont, QIcon
import traceback
import sys
import os
import subprocess
import glob
import io
import sys
import re
import json
import inspect
import ast
from jaccard_index.jaccard import jaccard_index
from collections import deque
# Check if the output is redirected
if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty():
os.environ["COLUMNS"] = "80" # Set a default console width
def print_caller_name():
print(f'Called by: {inspect.stack()[1][3]}')
def convert_numeric_strings(data):
if isinstance(data, dict):
return {k: convert_numeric_strings(v) for k, v in data.items()}
elif isinstance(data, list):
return [convert_numeric_strings(v) for v in data]
elif isinstance(data, str):
try:
float_val = float(data)
int_val = int(float_val)
return int_val if float_val == int_val else float_val
except ValueError:
return data
else:
return data
def excepthook(type, value, tback):
traceback.print_exception(type, value, tback)
sys.__excepthook__(type, value, tback)
sys.excepthook = excepthook
class NoScrollComboBox(QComboBox):
def wheelEvent(self, event):
event.ignore()
class CustomDialog(QDialog):
def __init__(self, title, text, parent=None):
super().__init__(parent)
self.setWindowTitle(title)
self.setStyleSheet("background-color: #2B2B2B; color: #00FFFF; font-family: Courier New; font-size: 11pt;")
self.text_edit = QTextEdit()
self.text_edit.setPlainText(text)
self.text_edit.setReadOnly(True) # makes the text non-editable
# Add select all button
self.select_all_button = QPushButton("Select All")
self.select_all_button.clicked.connect(self.text_edit.selectAll)
self.layout = QVBoxLayout()
self.layout.addWidget(self.text_edit)
self.layout.addWidget(self.select_all_button) # add the button to the layout
self.setLayout(self.layout)
self.resize(800, 600) # set an initial size
def setDictAsPlainText(self, dictionary):
text = json.dumps(dictionary, indent=4)
self.text_edit.setPlainText(text)
class EmittingStream(QObject):
textWritten = pyqtSignal(str)
def __init__(self, parent=None):
super(EmittingStream, self).__init__(parent)
self.io = io.StringIO()
def write(self, text):
self.io.write(text)
self.textWritten.emit(text)
class TerminalEmulator(QTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
self.setReadOnly(True)
self.cursor = self.textCursor()
self.cursor.movePosition(QTextCursor.Start)
self.cursor.setPosition(0)
self.cursor.setKeepPositionOnInsert(True) # Prevents automatic scrolling
self.last_position = 0
self.is_overwriting = False
def write(self, text):
if text.endswith('\r'):
self.is_overwriting = True
self.cursor.setPosition(self.last_position)
self.setTextCursor(self.cursor)
else:
if self.is_overwriting:
for _ in range(self.cursor.position(), self.last_position):
self.cursor.deleteChar()
self.is_overwriting = False
self.cursor.insertText(text)
self.last_position = self.cursor.position()
self.setTextCursor(self.cursor)
def flush(self):
pass
class DictEditorDialog(QDialog):
def __init__(self, parent, initial_value, schema, options):
super().__init__(parent)
self.editor = DictEditor(schema=schema,
data=initial_value,
options=options)
# Dark theme style for DictEditor
self.editor.setStyleSheet("""
background-color: #2b2b2b;
color: #a9b7c6;
QLineEdit {
background-color: #3c3f41;
color: #a9b7c6;
}
QPushButton {
background-color: #3c3f41;
color: #a9b7c6;
}
""")
# Add editor to dialog layout
layout = QVBoxLayout(self)
layout.addWidget(self.editor)
def get_value(self):
return self.editor.get_value()
class Worker(QObject):
output_line = pyqtSignal(str)
finished = pyqtSignal() # new signal
def __init__(self, process):
super().__init__()
self.process = process
def read_output(self):
while True:
line = self.process.stdout.readline()
if not line and self.process.poll() is not None:
break
self.output_line.emit(line.strip())
self.finished.emit() # emit the finished signal when the process finishes
class JobWidget(QWidget):
# Define a custom signal to activate when data is changed. This updates underlying jobs data.
data_changed = pyqtSignal(object)
def __init__(self, schema, job_number, file_list, parent=None, job_dict=None, verbose=False):
super().__init__(parent)
# Set object name for stylesheet targeting
self.verbose = verbose
self.setObjectName("jobWidget")
# Save parent, schema, file list as attributes of the instance
# -----------------------------------------------------------
# `parent` is a reference to the parent QWidget (or other QObject) that
# this QWidget belongs to. In Qt, objects organized in a parent-child
# hierarchy. This management helps with resource cleanup (when a parent
# is deleted, all child QObjects are also deleted), and with event handling
# (events propagate up from child to parent)
self.parent = parent
# `schema` is a list of dictionaries, each containing information about a
# specific job type that can be processed by this widget. The schema describes
# the parameters each job type needs, their default values, etc. This helps
# dynamically generate the UI based on the job type selected, and also helps
# enforce correctness of user input
self.schema = schema
# `file_list` is a list of files that are relevant to this widget, which might
# be required for processing the jobs. This list is used elsewhere in the
# application where access to the file list is necessary
self.file_list = file_list
# `param_line_edits` is a dictionary used to store references to QLineEdit objects
# created for each parameter of the selected job type. The keys are the names of the
# parameters (fields), and the values are the QLineEdit objects themselves. Storing
# these references allows easy access to user input later when the job is run.
self.param_line_edits = {}
# Connect to the custom signal
self.data_changed.connect(parent.update_job_data)
# `param_labels` is a dictionary used to store QLabel objects created for
# each parameter of the selected job type and their associated keys from the schema.
# The keys are the QLabel objects themselves, and the values are the keys from the schema.
# Storing these references allows easy access to the parameter keys later when the job is run.
self.param_labels = {}
# Initialize self.param_content_labels
self.param_content_labels = {}
# -----------------------------------------------------------
# Setting styles for JobWidget and its elements.
self.setStyleSheet("""
JobWidget {
border: 2px solid blue;
}
QLineEdit, QCheckBox {
border: 1px solid grey;
}
QLabel {
border: none;
}
QCheckBox {
color: white;
}
""")
# Create layout for the widget and set it
self.job_layout = QGridLayout()
self.setLayout(self.job_layout)
self.job_layout.setSpacing(10)
# Create label for Job Number, set its style and position in the layout
self.number_label = QLabel(f'Job {job_number}', self)
self.number_label.setAlignment(Qt.AlignCenter)
self.number_label.setStyleSheet("font-size: 18px;")
self.job_layout.addWidget(self.number_label, 0, 0, 3, 1) # Spanning 3 rows
# Create Expand/Collapse button, connect its click event to self.toggle method
self.toggle_button = QPushButton('Collapse', self)
self.toggle_button.clicked.connect(self.toggle)
self.toggle_button.setStyleSheet("""
QPushButton {
min-width: 60px;
min-height: 20px;
background: #D3D3D3;
color: black;
}
""")
self.job_layout.addWidget(self.toggle_button, 0, 1, 1, 1)
# Create Delete button, connect its click event to self.delete method
self.delete_button = QPushButton('✖', self)
self.delete_button.setStyleSheet("""
QPushButton {
color: #c7c1c2;
background-color: #660914;
border: 1px #635a5c;
border-radius: 5px;
font-size: 20px;
}
""")
self.delete_button.clicked.connect(self.delete)
self.job_layout.addWidget(self.delete_button, 0, 2)
# Create label and combo box for Job Type, fill combo box with types from schema
self.type_label = QLabel('Job Type: ', self)
self.type_combo_box = NoScrollComboBox(self)
self.type_combo_box.addItems([job['type'] for job in schema])
self.type_combo_box.setStyleSheet("color: white;")
self.type_combo_box.currentTextChanged.connect(self.change_job_type)
self.job_layout.addWidget(self.type_label, 1, 1)
self.job_layout.addWidget(self.type_combo_box, 1, 2)
# Create label and line edit for Job Name, set its default text
self.name_label = QLabel('Job Name: ', self)
self.name_line_edit = QLineEdit(self)
self.name_line_edit.setText(self.schema[0]['default_name'])
self.job_layout.addWidget(self.name_label, 2, 1)
self.job_layout.addWidget(self.name_line_edit, 2, 2)
# Create a widget to hold parameters
self.params_widget = QWidget()
self.params_layout = QGridLayout()
self.params_widget.setLayout(self.params_layout)
self.params_layout.setHorizontalSpacing(5)
self.job_layout.addWidget(self.params_widget, 3, 1, 1, 2)
# Create label and line edit for Output Name (hidden by default)
self.output_name_label = QLabel('Output Name: ', self)
self.output_name_label.hide()
self.output_name_line_edit = QLineEdit(self)
self.output_name_line_edit.setReadOnly(True)
self.output_name_line_edit.hide()
self.job_layout.addWidget(self.output_name_label, 4, 1)
self.job_layout.addWidget(self.output_name_line_edit, 4, 2)
self.file_input_layout = None
# If job_dict is provided, load it into the widget
if job_dict is not None:
self.load_job_from_dict(job_dict)
else:
# Load parameters based on the job type
self.change_job_type()
def load_job_from_dict(self, job_dict):
# Set job type, which should trigger change_job_type and create the correct input fields
# self.type_combo_box.setCurrentText(job_dict.get('type', ''))
# Set the job name
current_job_name = job_dict.get('name', '')
if self.verbose:
sys.stderr.write(f'JOB NAME: {current_job_name}\n')
self.name_line_edit.setText(current_job_name)
# Store the job dict for later use in change_job_type
self.loaded_job_dict = job_dict
# Change the job type field which will automatically activate the change_job_type function
self.type_combo_box.setCurrentText(job_dict.get('type', ''))
current_job_data_to_dict = self.to_dict()
if self.verbose:
sys.stderr.write(f'current_job_data_to_dict 1: {current_job_data_to_dict}\n')
def to_dict2(self):
# Return a dictionary representation of the job
job_dict = {
'type': self.type_combo_box.currentText(),
'name': self.name_line_edit.text()
}
# Iterate through the child widgets of params_widget
for i in range(self.params_layout.count()):
layout_item = self.params_layout.itemAt(i)
widget = layout_item.widget()
if widget is None:
# It's a layout
layout = layout_item.layout()
# Assuming the QLineEdit is at index 1
line_edit = layout.itemAt(1).widget()
if isinstance(line_edit, QLineEdit):
# Assuming the QLabel is at index 0
label_widget = layout.itemAt(0).widget()
label_text = self.param_labels[label_widget] # Get the key from param_labels
line_edit_text = line_edit.text()
# Try to parse the line_edit_text back to a dictionary
try:
line_edit_text = json.loads(line_edit_text)
except json.JSONDecodeError:
# If the parsing fails, leave it as a string
pass
job_dict[label_text] = line_edit_text
# If it's a checkbox, use isChecked method to get the boolean value
if isinstance(widget, QCheckBox):
label_text = self.param_labels[widget]
checkbox_value = widget.isChecked()
job_dict[label_text] = checkbox_value
elif isinstance(widget, QLabel):
# Get the corresponding line edit
line_edit = self.params_layout.itemAt(i + 1).widget()
if isinstance(line_edit, QLineEdit):
# Extract label text and line edit text
label_text = self.param_labels[widget] # Get the key from param_labels
line_edit_text = line_edit.text()
# Try to parse the line_edit_text back to a dictionary
try:
line_edit_text = json.loads(line_edit_text)
except json.JSONDecodeError:
# If the parsing fails, leave it as a string
pass
job_dict[label_text] = line_edit_text
caller_name = inspect.stack()[1][3] # Get the caller function name
if self.verbose:
sys.stderr.write(f'Called by: {caller_name}, JOB DICT: {job_dict}\n')
return job_dict
def to_dict3(self):
# Return a dictionary representation of the job
job_dict = {
'type': self.type_combo_box.currentText(),
'name': self.name_line_edit.text()
}
# Get the schema for the current job type
job_type = self.type_combo_box.currentText()
job_schema = None
for job in self.schema:
if job['type'] == job_type:
job_schema = job
break
# Iterate through the child widgets of params_widget
for i in range(self.params_layout.count()):
layout_item = self.params_layout.itemAt(i)
widget = layout_item.widget()
if widget is None:
# It's a layout
layout = layout_item.layout()
# Assuming the QLineEdit is at index 1
line_edit = layout.itemAt(1).widget()
if isinstance(line_edit, QLineEdit):
# Assuming the QLabel is at index 0
label_widget = layout.itemAt(0).widget()
label_text = self.param_labels[label_widget] # Get the key from param_labels
line_edit_text = line_edit.text()
# Use the schema to interpret the line_edit_text
param_type = job_schema['params'][label_text]['type']
if param_type == 'list':
try:
line_edit_text = ast.literal_eval(line_edit_text) if line_edit_text else []
except (ValueError, SyntaxError):
pass # If it fails, leave it as is (it might be a list of strings)
elif param_type == 'dict':
try:
line_edit_text = ast.literal_eval(line_edit_text) if line_edit_text else {}
except (ValueError, SyntaxError):
pass # If it fails, leave it as is (it might be a string representation of a dict)
job_dict[label_text] = line_edit_text
# If it's a checkbox, use isChecked method to get the boolean value
if isinstance(widget, QCheckBox):
label_text = self.param_labels[widget]
checkbox_value = widget.isChecked()
job_dict[label_text] = checkbox_value
elif isinstance(widget, QLabel):
# Get the corresponding line edit
line_edit = self.params_layout.itemAt(i + 1).widget()
if isinstance(line_edit, QLineEdit):
# Extract label text and line edit text
label_text = self.param_labels[widget] # Get the key from param_labels
line_edit_text = line_edit.text()
# Use the schema to interpret the line_edit_text
param_type = job_schema['params'][label_text]['type']
if param_type == 'list':
try:
line_edit_text = ast.literal_eval(line_edit_text) if line_edit_text else []
except (ValueError, SyntaxError):
pass # If it fails, leave it as is (it might be a list of strings)
elif param_type == 'dict':
try:
line_edit_text = ast.literal_eval(line_edit_text) if line_edit_text else {}
except (ValueError, SyntaxError):
pass # If it fails, leave it as is (it might be a string representation of a dict)
job_dict[label_text] = line_edit_text
return job_dict
def to_dict4(self):
# Return a dictionary representation of the job
job_dict = {
'type': self.type_combo_box.currentText(),
'name': self.name_line_edit.text()
}
# Get the schema for the current job type
job_type = self.type_combo_box.currentText()
job_schema = None
for job in self.schema:
if job['type'] == job_type:
job_schema = job
break
# Iterate through the child widgets of params_widget
for i in range(self.params_layout.count()):
layout_item = self.params_layout.itemAt(i)
widget = layout_item.widget()
if widget is None:
# It's a layout
layout = layout_item.layout()
# Assuming the QLineEdit is at index 1
line_edit = layout.itemAt(1).widget()
if isinstance(line_edit, QLineEdit):
# Assuming the QLabel is at index 0
label_widget = layout.itemAt(0).widget()
label_text = self.param_labels[label_widget] # Get the key from param_labels
line_edit_text = line_edit.text()
# Use the schema to interpret the line_edit_text
param_type = job_schema['params'][label_text]['type']
if param_type == 'list':
try:
line_edit_text = ast.literal_eval(line_edit_text) if line_edit_text else []
except (ValueError, SyntaxError):
pass # If it fails, leave it as is (it might be a list of strings)
elif param_type == 'dict':
try:
line_edit_text = ast.literal_eval(line_edit_text) if line_edit_text else {}
except (ValueError, SyntaxError):
pass # If it fails, leave it as is (it might be a string representation of a dict)
elif param_type in ['int', 'float', 'num', 'number']:
try:
line_edit_text = float(line_edit_text) if line_edit_text else None
if param_type == 'int':
line_edit_text = int(line_edit_text) if line_edit_text is not None else None
except ValueError:
pass # If conversion fails, leave it as is (it might be a string representation)
job_dict[label_text] = line_edit_text
# If it's a checkbox, use isChecked method to get the boolean value
if isinstance(widget, QCheckBox):
label_text = self.param_labels[widget]
checkbox_value = widget.isChecked()
job_dict[label_text] = checkbox_value
return job_dict
def to_dict5(self):
# Return a dictionary representation of the job
job_dict = {
'type': self.type_combo_box.currentText(),
'name': self.name_line_edit.text()
}
# Get the schema for the current job type
job_type = self.type_combo_box.currentText()
job_schema = None
for job in self.schema:
if job['type'] == job_type:
job_schema = job
break
# Iterate through the child widgets of params_widget
for i in range(self.params_layout.count()):
layout_item = self.params_layout.itemAt(i)
widget = layout_item.widget()
if widget is None:
# It's a layout
layout = layout_item.layout()
# Assuming the QLineEdit is at index 1
line_edit = layout.itemAt(1).widget()
if isinstance(line_edit, QLineEdit):
# Assuming the QLabel is at index 0
label_widget = layout.itemAt(0).widget()
label_text = self.param_labels[label_widget] # Get the key from param_labels
line_edit_text = line_edit.text()
# Use the schema to interpret the line_edit_text
param_type = job_schema['params'][label_text]['type']
if param_type == 'list':
try:
line_edit_text = ast.literal_eval(line_edit_text) if line_edit_text else []
except (ValueError, SyntaxError):
pass # If it fails, leave it as is (it might be a list of strings)
elif param_type == 'dict':
try:
line_edit_text = ast.literal_eval(line_edit_text) if line_edit_text else {}
except (ValueError, SyntaxError):
pass # If it fails, leave it as is (it might be a string representation of a dict)
elif param_type in ['int', 'float', 'num', 'number']:
try:
if line_edit_text: # Only convert if there's something to convert
line_edit_text = float(line_edit_text)
if param_type == 'int':
line_edit_text = int(line_edit_text)
else:
line_edit_text = None # Or '' if you want it to be an empty string
except ValueError:
pass # If conversion fails, leave it as is (it might be a string representation)
job_dict[label_text] = line_edit_text
elif isinstance(widget, QLineEdit):
# Get the corresponding QLabel
label_widget = self.params_layout.itemAt(i - 1).widget()
if isinstance(label_widget, QLabel):
# Extract label text and line edit text
label_text = self.param_labels[label_widget] # Get the key from param_labels
line_edit_text = widget.text() # Now widget is the QLineEdit
# If it's a checkbox, use isChecked method to get the boolean value
if isinstance(widget, QCheckBox):
label_text = self.param_labels[widget]
checkbox_value = widget.isChecked()
job_dict[label_text] = checkbox_value
return job_dict
# TODO finalize processing of lists and numbers
def to_dict(self):
# Return a dictionary representation of the job
job_dict = {
'type': self.type_combo_box.currentText(),
'name': self.name_line_edit.text()
}
# Get the schema for the current job type
job_type = self.type_combo_box.currentText()
job_schema = None
for job in self.schema:
if job['type'] == job_type:
job_schema = job
break
# Iterate through the child widgets of params_widget
for i in range(self.params_layout.count()):
layout_item = self.params_layout.itemAt(i)
widget = layout_item.widget()
if widget is None:
# It's a layout
layout = layout_item.layout()
# Assuming the QLineEdit is at index 1
line_edit = layout.itemAt(1).widget()
if isinstance(line_edit, QLineEdit):
# Assuming the QLabel is at index 0
label_widget = layout.itemAt(0).widget()
label_text = self.param_labels[label_widget] # Get the key from param_labels
line_edit_text = line_edit.text()
param_type = job_schema['params'][label_text]['type']
if param_type == 'dict':
try:
if self.verbose:
sys.stderr.write(f'{ast.literal_eval(line_edit_text)}\n')
line_edit_text = ast.literal_eval(line_edit_text) if line_edit_text else {}
except (ValueError, SyntaxError):
if self.verbose:
sys.stderr.write(f'DICT SYNTAX VALUE ERROR\n')
pass # If it fails, leave it as is (it might be a string representation of a dict)
job_dict[label_text] = line_edit_text
# If it's a checkbox, use isChecked method to get the boolean value
if isinstance(widget, QCheckBox):
label_text = self.param_labels[widget]
checkbox_value = widget.isChecked()
job_dict[label_text] = checkbox_value
elif isinstance(widget, QLabel):
# Get the corresponding line edit
line_edit = self.params_layout.itemAt(i + 1).widget()
if isinstance(line_edit, QLineEdit):
# Extract label text and line edit text
label_text = self.param_labels[widget] # Get the key from param_labels
line_edit_text = line_edit.text()
# Use the schema to interpret the line_edit_text
param_type = job_schema['params'][label_text]['type']
# if param_type == 'list':
# sys.stderr.write(f'QLabel LIST\n')
# # try:
# # line_edit_text = ast.literal_eval(line_edit_text) if line_edit_text else []
# # except (ValueError, SyntaxError):
# # pass # If it fails, leave it as is (it might be a list of strings)
# try:
# line_edit_text = json.loads(line_edit_text) if line_edit_text else []
# except (json.JSONDecodeError, ValueError):
# pass # If it fails, leave it as is (it might be a list of strings)
if param_type == 'list':
# Try to interpret it as a python expression first (it handles lists of mixed types and nested lists)
try:
line_edit_text = ast.literal_eval(line_edit_text)
except (ValueError, SyntaxError):
# If that fails, treat it as a comma-separated list
line_edit_text = line_edit_text.split(',')
for i, item in enumerate(line_edit_text):
item = item.strip() # Remove leading/trailing whitespace
# Try to convert to int or float if possible
try:
line_edit_text[i] = int(item)
except ValueError:
try:
line_edit_text[i] = float(item)
except ValueError:
# If it's not an int or a float, assume it's a string and remove quotes if present
line_edit_text[i] = item.strip('"').strip("'")
job_dict[label_text] = line_edit_text
elif param_type == 'dict':
try:
line_edit_text = ast.literal_eval(line_edit_text) if line_edit_text else {}
except (ValueError, SyntaxError):
pass # If it fails, leave it as is (it might be a string representation of a dict)
elif param_type in ['int', 'float', 'num', 'number']:
try:
if line_edit_text: # Only convert if there's something to convert
line_edit_text = float(line_edit_text)
if param_type == 'int':
line_edit_text = int(line_edit_text)
else:
# line_edit_text = None # Or '' if you want it to be an empty string
line_edit_text = ""
except ValueError:
pass # If conversion fails, leave it as is (it might be a string representation)
job_dict[label_text] = line_edit_text
caller_name = inspect.stack()[1][3] # Get the caller function name
if self.verbose:
sys.stderr.write(f'Called by: {caller_name}, JOB DICT: {job_dict}\n')
return job_dict
def create_param_input(self, param_name, param_config):
if param_config['type'] == 'file':
# Create layout for file input
file_input_layout = QHBoxLayout()
# Create QLabel for parameter name
param_label = QLabel(f"{param_name}: ", self)
param_label.setStyleSheet("color: white;")
self.param_labels[param_label] = param_name
# Create QLineEdit for file name
file_name_input = QLineEdit(self)
self.param_line_edits[param_name] = file_name_input
file_name_input.textChanged.connect(self.update_output)
file_name_input.textChanged.connect(self.update_data)
# Create QPushButton for file selection
file_selection_button = QPushButton("Select File", self)
file_selection_button.clicked.connect(self.file_dialog)
# Add widgets to the layout
file_input_layout.addWidget(param_label)
file_input_layout.addWidget(file_name_input)
file_input_layout.addWidget(file_selection_button)
# Return the layout
return file_input_layout
elif param_config['type'] == 'dict':
# Create layout for dict input
dict_input_layout = QHBoxLayout()
# Create QLabel for parameter name
param_label = QLabel(f"{param_name}: ", self)
param_label.setStyleSheet("color: white;")
self.param_labels[param_label] = param_name
# Create QLineEdit for dict content
default_dict_content = ""
try:
default_dict_content = json.dumps(param_config['default'])
except Exception as e:
pass
dict_content_label = QLineEdit(default_dict_content, self)
dict_content_label.setReadOnly(True)
dict_content_label.setStyleSheet("color: white;") # Style as needed
self.param_content_labels[param_name] = dict_content_label
# Create QPushButton for dict editing
dict_edit_button = QPushButton("Edit Object", self)
dict_edit_button.clicked.connect(lambda: self.open_dict_editor(param_name, param_config))
# Add widgets to the layout
dict_input_layout.addWidget(param_label)
dict_input_layout.addWidget(dict_content_label)
dict_input_layout.addWidget(dict_edit_button)
# Return the layout
return dict_input_layout
def open_dict_editor(self, param_name, param_config):
# Check if param_line_edits already has a value for this parameter
if param_name in self.param_line_edits and self.param_line_edits[param_name] != "":
initial_value = self.param_line_edits[param_name]
else:
initial_value = param_config.get('default', None) # Use default value here
schema = param_config.get('schema', {}) # Get schema if it exists else use an empty dict
options = param_config.get('options', {}) # Get options if it exists else use an empty dict
# Create dict editor dialog with the schema and initial value
editor_dialog = DictEditorDialog(self,
initial_value=initial_value,
schema=schema,
options=options)
# TODO make sure finished only works with sucessful saves
editor_dialog.finished.connect(lambda: self.update_param_line_edits_and_labels(param_name, editor_dialog))
editor_dialog.show()
def update_param_input(self, param_name, text):
output_prepend = self.current_job_in_schema.get('output_prepends', '')
output_text = f"{output_prepend}{os.path.basename(text)}"
self.param_line_edits[param_name].setText(output_text)
def update_param_line_edits_and_labels(self, param_name, editor_dialog):
new_value = editor_dialog.get_value()
self.param_line_edits[param_name] = new_value
if self.verbose:
sys.stderr.write(f'update_param_line_edits_and_labels -- {param_name} == {new_value}\n')
# Update dict_content_label with a minified version of the new_value
self.param_content_labels[param_name].setText(json.dumps(new_value, separators=(',', ':')))
self.update_data() # makes sure that the dictionary data is added to the output
def change_job_type(self):
# Check if self.loaded_job_dict exists and save it
loaded_job_dict = None
if hasattr(self, 'loaded_job_dict'):
loaded_job_dict = self.loaded_job_dict
del self.loaded_job_dict
caller_name = inspect.stack()[1][3]
if self.verbose:
sys.stderr.write(f'Called by: {caller_name}, LOADED_JOB_DICT: {loaded_job_dict}\n')
# Clear previous job parameters
self.clear_layout(self.params_layout)
self.param_line_edits = {}
self.output_file = None
self.output_name_line_edit.clear()
self.output_name_line_edit.hide()
self.output_name_label.hide()
self.param_labels = {} # Reset the param_labels dictionary
# Create a dictionary to store the widgets for each parameter
self.param_widgets = {}
# Get information about the selected job type to generate input boxes and labels
for job in self.schema:
if job['type'] == self.type_combo_box.currentText():
self.current_job_in_schema = job
if not self.name_line_edit.text():
self.name_line_edit.setText(job['default_name'])
row_index = 0
for param, config in job['params'].items():
# Create parameter widgets based on their type
if config['type'] == 'bool':
checkbox = QCheckBox(f'{param}: ', self)
checkbox.setStyleSheet("color: white;")
self.params_layout.addWidget(checkbox, row_index, 0, 1, 2)
checkbox.stateChanged.connect(self.update_data)
self.param_labels[checkbox] = param # Add QCheckBox and its param to param_labels
self.param_widgets[param] = checkbox
if loaded_job_dict and param in loaded_job_dict:
checkbox.setChecked(loaded_job_dict[param])
elif config['type'] == 'file':
param_input_layout = self.create_param_input(param, config)
self.params_layout.addLayout(param_input_layout, row_index, 0, 1, 2)
self.param_widgets[param] = param_input_layout # Add QLayout to param_widgets
if loaded_job_dict and param in loaded_job_dict:
self.param_line_edits[param].setText(loaded_job_dict[param])
elif config['type'] == 'dict':
param_input_layout = self.create_param_input(param, config)
self.params_layout.addLayout(param_input_layout, row_index, 0, 1, 2)
self.param_widgets[param] = param_input_layout # Add QLayout to param_widgets
if loaded_job_dict and param in loaded_job_dict:
dict_value = loaded_job_dict[param]
self.param_content_labels[param].setText(json.dumps(dict_value, separators=(',', ':')))
self.param_line_edits[param] = dict_value
elif config['type'] == 'list':
label = QLabel(f'{param}: ', self)
label.setStyleSheet("color: white;")
self.param_labels[label] = param
line_edit = QLineEdit(self)
self.params_layout.addWidget(label, row_index, 0)
self.params_layout.addWidget(line_edit, row_index, 1)
line_edit.textChanged.connect(self.update_data)
self.param_widgets[param] = line_edit
if loaded_job_dict and param in loaded_job_dict:
list_value = loaded_job_dict[param]
# Convert list to string representation with double quotes
list_str = json.dumps(list_value)
line_edit.setText(list_str)
else:
label = QLabel(f'{param}: ', self)
label.setStyleSheet("color: white;")
self.param_labels[label] = param
line_edit = QLineEdit(self)
self.params_layout.addWidget(label, row_index, 0)
self.params_layout.addWidget(line_edit, row_index, 1)
line_edit.textChanged.connect(self.update_data)
self.param_widgets[param] = line_edit
if loaded_job_dict and param in loaded_job_dict:
line_edit.setText(str(loaded_job_dict[param]))
row_index += 1
# Show output name if necessary fields exist in job
if all(key in self.current_job_in_schema for key in ['input_param', 'output_prepends', 'output_ext']):
self.output_name_line_edit.show()
self.output_name_label.show()
def job_type_changed(self, job_type):
# Get job schema
job_schema = next((job for job in self.schema if job['type'] == job_type), None)
if not job_schema:
return
# set the default_name line to the one associated with the jbo type form the schema file
self.name_line_edit.setText(job_schema['default_name'])
# Clear previous job parameters
for parameter_widget in self.job_parameters.values():
self.layout.removeRow(parameter_widget)
self.job_parameters.clear()
# Add new job parameters
for parameter, parameter_info in job_schema['params'].items():
# Based on the parameter type, different input widgets can be added
if parameter_info['type'] == 'file':
parameter_widget = QLineEdit()
elif parameter_info['type'] == 'int':
parameter_widget = QSpinBox()
elif parameter_info['type'] == 'float':
parameter_widget = QDoubleSpinBox()
elif parameter_info['type'] == 'bool':
parameter_widget = QComboBox()
parameter_widget.addItems(parameter_info['options'])
elif parameter_info['type'] == 'dict':
parameter_widget = QTextEdit()
else:
parameter_widget = QLineEdit()
self.job_parameters[parameter] = parameter_widget
self.layout.addRow(QLabel(parameter.capitalize() + ":"), parameter_widget)
self.update_data()
def toggle(self):
for i in range(self.params_layout.count()):
widget = self.params_layout.itemAt(i).widget()
if widget:
widget.setVisible(not widget.isVisible())
self.toggle_button.setText('Expand' if self.toggle_button.text() == 'Collapse' else 'Collapse')
def clear_layout(self, layout):
while layout.count():
child = layout.takeAt(0)
if child.widget():
child.widget().deleteLater()
elif child.layout():
self.clear_layout(child.layout())
def update_output(self):
if self.current_job_in_schema['input_param'] in self.param_line_edits:
input_file = self.param_line_edits[self.current_job_in_schema['input_param']].text()
base_input_file, _ = os.path.splitext(os.path.basename(input_file))
self.output_file = \
f"{self.current_job_in_schema['output_prepends']}{base_input_file}.{self.current_job_in_schema['output_ext']}"
self.output_name_line_edit.setText(self.output_file) # Update the output name display
def file_dialog(self):
fname = QFileDialog.getOpenFileName(self, 'Select Input File', filter='All Files (*)')[0]
if fname:
base_fname = os.path.basename(fname)
self.param_line_edits[self.current_job_in_schema['input_param']].setText(base_fname)
def update_job_numbers(self):
for i, job in enumerate(self.jobs, start=1):
job.number_label.setText(f'Job {i}: ')
def delete(self):
self.parent.jobs.remove(self) # Remove this job from the jobs list
self.parent.update_job_numbers() # Update job numbers
self.deleteLater()
# This function should be called whenever the data of the job changes
def update_data(self):
# ... Update the data ...
# Emit the signal
self.data_changed.emit(self)
class BuilderWidget(QWidget):
def __init__(self, exe_mode=False):
# Call to the parent constructor
super().__init__()
self.verbose = True if exe_mode else False
# Create a QVBoxLayout (Vertical Box Layout) and set it as the layout of the current QWidget
self.main_layout = QVBoxLayout()
self.setLayout(self.main_layout)
# File selector
# `file_line_edit` QLineEdit object holds the path of the selected JSON file
# It's updated when user selects a file from the dropdown or using the file dialog
self.file_label = QLabel("JSON Config File:", self)
self.file_line_edit = QLineEdit(self)
self.file_label.setBuddy(self.file_line_edit) # Associate the label with the QLineEdit
# Button to open the file dialog
self.file_button = QPushButton("Select JSON Config", self)
self.file_button.clicked.connect(self.file_dialog)
# Dropdown list to select a JSON file