-
Notifications
You must be signed in to change notification settings - Fork 1
/
gradeAnalysisGUI.py
2006 lines (1713 loc) · 78.4 KB
/
gradeAnalysisGUI.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 tkinter as tk
from tkinter import messagebox
import gradeAnalysisFunc as gaf
import gradeAnalysisWidgets as gaw
from tkinter import filedialog
from tkinter import ttk
from functools import partial
import platform
import os
import sys
import subprocess
import json
import dictionary as dic
def file_path(file):
return os.path.join(os.path.dirname(os.path.realpath(__file__)), file)
class GradingAnalysisTool:
def __init__(self):
self.logger = gaw.Logger(__name__)
self.root = tk.Tk()
self.root.title("Grading Analysis Tool")
self.root.configure()
self.terminal_output = None
width = self.root.winfo_screenwidth()
height = self.root.winfo_screenheight()
self.root.configure(
background="#DCDCDC",
bd=2,
padx=10,
pady=10,
highlightbackground="black",
highlightcolor="white",
highlightthickness=1,
width=width,
height=height
)
self.max_sections_threshold = None
self.popup_box_threshold = None
self.analysis_checkbox = None
self.csv_checkbox = None
self.heatmap_checkbox = None
self.grade_dist_checkbox = None
self.confirm_button = None
self.course_names = None
self.reset_gui_button = None
self.file_path_button = None
# GUI elements: Listbox variables
self.commands_listbox = None
self.departments_listbox = None
self.majors_listbox = None
self.faculty_listbox = None
self.unique_listbox = None
# Data analysis variables
self.results = None
self.dept = None
self.major = None
self.unique_selection = None
self.min_enrollment_threshold = None
self.min_enrollment = None
self.max_enrollment_threshold = None
self.max_enrollment = None
self.min_sections_threshold = None
self.min_sections = None
self.max_sections_threshold = None
self.max_sections = None
self.analysis_options = None
##Option to pass whatever between methods
self.generic_instance = None
self.faculty = None
self.departments = None
self.majors = None
self.faculty_set = None
self.unique_list = None
# File and directory variables
self.input_file_name = None
self.output_directory = None
self.department_file = None
self.instructor_file = None
self.major_file = None
self.course_table_file = None
self.file_dict = {}
self.required_files = None
self.commands_directory = None
# Setup commands and GUI
self.root.geometry("")
self.setup_commands()
self.setup_gui() # Run GUI setup
def setup_gui(self):
self.required_files = [
"instTable.csv",
"deptTable.csv",
"filteredData.csv",
"majorTable.csv",
"courseTable.csv",
]
self.pre_processor_check()
self.create_json_file()
self.commands_listbox_widget()
self.change_sourcefile_button()
self.populate_current_file_state()
self.reset_gui_button = tk.Button(
self.root, text="Reset", command=self.reset_button
).grid(row=6, column=2)
self.run_command_button_toggle(state="normal")
tk.Button(self.root, text="Help", command=self.run_selected_help_command).grid(
row=7, column=2
)
self.write_to_GUI()
self.dynamic_resizing()
self.root.iconphoto(
False,
tk.PhotoImage(
file=file_path("Athletic_Logo_Block_F.png")
),
)
self.root.wm_iconphoto(False, tk.PhotoImage(file=file_path("Athletic_Logo_Block_F.png")))
self.root.protocol("WM_DELETE_WINDOW", self.quit_program)
self.root.mainloop()
####################################################################################################
##Thresholds
def enrollment_threshold_widget(self, state="disabled", where=None, row=None, column=None):
self.logger.info("Setting up enrollment threshold widget")
if where is None:
where = self.root
self.logger.debug("Default 'where' parameter used: self.root")
self.min_enrollment_threshold = gaw.ThresholdWidget()
self.min_enrollment_threshold.generic_thresholds_widget(
where=where,
state=state,
text="Min Enrollment:",
row=row,
column=column,
help="Enter an integer for a threshold",
)
self.max_enrollment_threshold = gaw.ThresholdWidget()
self.max_enrollment_threshold.generic_thresholds_widget(
where=where,
state=state,
text="Max Enrollment:",
row=row + 1,
column=column,
help="Enter an integer for a threshold",
)
self.logger.info("Enrollment threshold widget setup completed")
def sections_threshold_widget(self, state="disabled", where=None, row=None, column=None):
self.logger.info("Setting up sections threshold widget")
if where is None:
where = self.root
self.logger.debug("Default 'where' parameter used: self.root")
self.min_sections_threshold = gaw.ThresholdWidget()
self.min_sections_threshold.generic_thresholds_widget(
where=where,
state=state,
text="Min Sections:",
row=row,
column=column,
help="Enter an integer for a threshold",
)
self.max_sections_threshold = gaw.ThresholdWidget()
self.max_sections_threshold.generic_thresholds_widget(
where=where,
state=state,
text="Max Sections:",
row=row + 1,
column=column,
help="Enter an integer for a threshold",
)
self.logger.info("Sections threshold widget setup completed")
def class_size_threshold_widget(self, state="disabled", where=None, row=None, column=None):
self.logger.info("Setting up class size threshold widget")
if where is None:
where = self.root
self.logger.debug("Default 'where' parameter used: self.root")
self.min_enrollment_threshold = gaw.ThresholdWidget()
self.min_enrollment_threshold.generic_thresholds_widget(
where=where,
state=state,
text="Min Class Size:",
row=row,
column=column,
help="Enter an integer for a threshold",
)
self.max_enrollment_threshold = gaw.ThresholdWidget()
self.max_enrollment_threshold.generic_thresholds_widget(
where=where,
state=state,
text="Max Class Size:",
row=row + 1,
column=column,
help="Enter an integer for a threshold",
)
self.logger.info("Class size threshold widget setup completed")
def course_num_taken_threshold_widget(self, state="disabled", where=None, row=None, column=None):
self.logger.info("Setting up course num taken threshold widget")
if where is None:
where = self.root
self.logger.debug("Default 'where' parameter used: self.root")
self.min_enrollment_threshold = gaw.ThresholdWidget()
self.min_enrollment_threshold.generic_thresholds_widget(
where=where,
state=state,
text="Min Courses Taken:",
row=row,
column=column,
help="Enter an integer for a threshold",
)
self.max_enrollment_threshold = gaw.ThresholdWidget()
self.max_enrollment_threshold.generic_thresholds_widget(
where=where,
state=state,
text="Max Courses Taken:",
row=row + 1,
column=column,
help="Enter an integer for a threshold",
)
self.logger.info("Course num taken threshold widget setup completed")
def thresholds_widget(self, state="disabled", where=None, which=None):
self.logger.info(f"Setting up thresholds widget for: {which}")
for threshold_widget in [
self.min_enrollment_threshold,
self.max_enrollment_threshold,
self.min_sections_threshold,
self.max_sections_threshold,
]:
if threshold_widget is not None:
threshold_widget.destroy()
if where is None:
where = self.root
self.logger.debug("Default 'where' parameter used: self.root")
where.protocol("WM_DELETE_WINDOW", self.reset_gui)
def csv_checkbox_widget(self, state="disabled", where=None, row=1, column=4):
self.logger.info("Starting setup of CSV checkbox widget")
if where is None:
where = self.root
self.logger.debug("Default 'where' parameter used: self.root")
self.csv_checkbox = gaw.CheckboxWidget()
self.csv_checkbox.create_checkbox(
where=where,
text="CSV File",
state=state,
row=row,
column=column,
help_text="Check this box to create a csv",
)
self.logger.info("CSV checkbox widget created successfully")
def heatmap_checkbox_widget(self, state="disabled", where=None, row=1, column=4):
self.logger.info("Starting setup of heatmap checkbox widget")
if where is None:
where = self.root
self.logger.debug("Default 'where' parameter used: self.root")
self.heatmap_checkbox = gaw.CheckboxWidget()
self.heatmap_checkbox.create_checkbox(
where=where,
text="Heatmap",
state=state,
row=row,
column=column,
help_text="Check this box to create a heatmap",
)
self.logger.info("Heatmap checkbox widget created successfully")
def grade_distribution_checkbox(
self, state="disabled", where=None, row=1, column=4
):
self.logger.info("Starting setup of grade distribution checkbox widget")
if where is None:
where = self.root
self.logger.debug("Default 'where' parameter used: self.root")
self.grade_dist_checkbox = gaw.CheckboxWidget()
self.grade_dist_checkbox.create_checkbox(
where=where,
text="Generate Grade Distribution?",
state=state,
row=row,
column=column,
help_text="Check this box to create a grade distribution",
)
self.logger.info("Grade distribution checkbox widget created successfully")
# general analysis checkboxes, pick which one you want by passing a list of booleans, like [True, False, True] to use the first and third checkbox
# places them top down
def create_analysis_dropdown(
self,
where=None,
analysis_options=None,
row=0,
column=0,
initial_message="Select Analysis",
):
self.logger.info("Starting setup of analysis dropdowns")
if where is None:
where = self.root
self.logger.debug("Default 'where' parameter used: self.root")
self.logger.debug(f"Analysis options set: {analysis_options}")
self.analysis_dropdown = gaw.tkDropdown(
where, analysis_options, row, column, initial_message=initial_message
)
self.logger.info("Analysis dropdown created successfully")
# Creates the appropriate checkboxes and thresholds when used on the root gui itself
# right now only used for run all commands but can and should be used for future commands
# will add way to control row and column of each widget
def thresholds_on_root(self, which=None, row=0, column=0):
self.logger.info("Setting up thresholds on root")
self.thresholds_widget(
state="normal", where=self.root, which="sections_enrollment"
)
self.logger.debug("Thresholds widget setup completed")
self.logger.info("Thresholds setup on root completed")
# Some commands need thresholds, but it wouldn't look right to have them on main
# popup seemed like the best way
# you can toggle the analysis checkboxes and csv checkbox on or off, but you at least need the thresholds on it
def threshold_popup(
self,
window_length=700,
window_height=100,
):
self.popup_box_threshold = tk.Toplevel(self.root)
self.popup_box_threshold.title("Threshold")
self.popup_box_threshold.geometry(f"{window_length}x{window_height}")
self.logger.debug("Threshold popup window initialized")
self.popup_box_threshold.protocol("WM_DELETE_WINDOW", self.reset_gui)
return self.popup_box_threshold
def confirm_threshold_choice(self, command=None):
self.logger.info("Adding confirm button to threshold popup")
if command:
self.logger.debug(
f"Confirm button will execute command: {command.__name__}"
)
else:
self.logger.warning("No command provided for confirm button")
tk.Button(
self.popup_box_threshold,
text="Go",
command=lambda: self.run_command_confirm_threshold(command),
width=4,
).grid(row=2, column=2)
self.logger.debug("Confirm button added to popup")
if command:
self.logger.debug(f"Confirm button will execute command: {command.__name__}")
else:
self.logger.warning("No command provided for confirm button")
tk.Button(self.popup_box_threshold, text="Go", command=lambda: self.run_command_confirm_threshold(command), width=4).grid(row=2, column=2)
self.logger.debug("Confirm button added to popup")
def run_command_confirm_threshold(self, command):
self.logger.info("Running command for confirming threshold")
self.get_thresholds()
self.logger.debug("Threshold values retrieved")
if command:
self.logger.debug(f"Executing provided command: {command.__name__}")
command()
else:
self.logger.warning("No command provided to execute")
self.reset_gui()
self.logger.info("GUI reset after command execution")
# foolproof function to minimize error brought by thresholds, they love to break
def get_valid_integer(self, threshold=gaw.ThresholdWidget()):
if threshold is not None:
try:
value = threshold.get_entry_value()
return int(value) if value is not None else None
except ValueError:
self.logger.error(f"Value for {threshold} is not a valid integer.")
return None
else:
self.logger.warning(f"Threshold not found")
return None
def get_thresholds(self):
self.logger.info("Retrieving threshold values")
if self.min_enrollment_threshold is not None:
self.min_enrollment = self.get_valid_integer(self.min_enrollment_threshold)
if self.max_enrollment_threshold is not None:
self.max_enrollment = self.get_valid_integer(self.max_enrollment_threshold)
if self.min_sections_threshold is not None:
self.min_sections = self.get_valid_integer(self.min_sections_threshold)
if self.max_sections_threshold is not None:
self.max_sections = self.get_valid_integer(self.max_sections_threshold)
self.logger.debug(
f"Thresholds set - Min Enrollment: {self.min_enrollment}, Max Enrollment: {self.max_enrollment}, Min Sections: {self.min_sections}, Max Sections: {self.max_sections}"
)
##################################################################################
##History File .history.json
def update_filestate(self, file, which):
self.logger.info(f"Updating file state for: {which}")
history_path = file_path(".history.json")
# update the appropriate attribute based on which file is being updated
attribute_map = {
self.input_file_name: "input_file_name",
self.output_directory: "output_directory",
self.course_table_file: "course_table_file",
self.department_file: "department_file",
self.instructor_file: "instructor_file",
self.major_file: "major_file",
}
if which in attribute_map:
setattr(self, attribute_map[which], file)
self.logger.debug(f"Updated {attribute_map[which]} to {file}")
else:
self.logger.warning(f"Unrecognized attribute for update: {which}")
# update .history.json
if os.path.exists(history_path):
with open(history_path, "w") as f:
history = {
"inputfile": str(self.input_file_name),
"outputfile": str(self.output_directory),
"coursetablefile": str(self.course_table_file),
"departmentfile": str(self.department_file),
"instructorfile": str(self.instructor_file),
"majorfile": str(self.major_file),
}
json.dump(history, f)
self.logger.info(f"Updated .history.json with new file paths")
else:
self.logger.warning(".history.json does not exist, creating a new one")
self.create_json_file()
#################################################################################
##Commands
def setup_commands(self):
self.logger.info("Setting up commands for GradingAnalysisTool")
self.commands_directory = {
# "1 Major & Department Analysis": self.command_MajorDepartment,
"Department Analysis": self.command_DeptAnalysis,
"Instructor Analysis": self.command_InstAnalysis,
"Major Analysis": self.command_MjrAnalysis,
"Course Analysis": self.command_CrsAnalysis,
"Section Analysis": self.command_SectionAnalysis,
"Level Analysis": self.command_LevelAnalysis,
"Student Analysis": self.command_student_analysis,
# "Run All Commands": self.command_All_Commands,
"Quit": self.quit_program,
}
self.logger.debug(f"Commands set up: {list(self.commands_directory.keys())}")
self.logger.info("Command setup completed")
def place_commands(self):
self.logger.info("Placing commands in the listbox")
for command in self.commands_directory.keys():
self.commands_listbox.insert(parent="", index=tk.END, values=(command,))
self.logger.debug(f"Command '{command}' added to listbox")
self.logger.info("All commands placed in listbox successfully")
##########################################################################################
##specific functions
# used for Unique List to do some basic top level analysis on main attributes of the data
def numpy_array_metadata(self, arr):
if arr.size == 0:
print("The array is empty.")
return
print(f"Number of Unique Elements: {arr.size}")
print(f"Data Type of Elements: {arr.dtype}")
if arr.ndim == 1 and arr.size >= 5:
print("First 5 Elements:")
print(arr[:5])
def quit_program(self):
self.logger.info("Quitting Program")
exit()
# no idea how this works or if it even works, need to visit again. works for now tho
def dynamic_resizing(self):
self.logger.info("Setting up dynamic resizing for the GUI")
for i in range(9):
self.root.grid_rowconfigure(i, weight=1)
for i in range(3):
self.root.grid_columnconfigure(i, weight=1)
self.logger.info("Dynamic resizing setup completed")
def reset_button(self):
self.terminal_output = None
self.logger.info("Reset Button Clicked")
self.reset_gui()
def pre_processor_check(self):
self.logger.info("Starting pre-processor check for required files")
for file_name in self.required_files:
full_path = file_path(file_name)
self.logger.debug(f"Checking for file: {full_path}")
if not os.path.isfile(full_path):
self.logger.error(
f"Pre-processor check failed. Missing file: {file_name}"
)
messagebox.showerror(
"Preprocessor Check Failed",
f"Please run the generateTables file to use the GUI. Missing file: {file_name}",
)
self.ask_run_generateTables()
sys.exit()
self.logger.info("Pre-processor check completed successfully")
return
def ask_run_generateTables(self):
self.logger.info("Asking user to run generateTables.py")
if messagebox.askyesno(
"Preprocessor Check Failed",
"Please run the generateTables file to use the GUI. Would you like to run it now?",
):
self.logger.debug("User selected to run generateTables.py")
subprocess.Popen([sys.executable, "generateTables.py"])
sys.exit()
else:
self.logger.debug("User selected not to run generateTables.py")
sys.exit()
def run_command_button_toggle(self, state="normal"):
self.logger.info("Toggling run command button")
tk.Button(
self.root,
text="Run Command",
command=self.run_selected_commands,
state=state,
).grid(row=7, column=0, pady=10)
##use this all the time
# lovely command to bind a helpful tooltip to literally anything tkinter
def bind_tooltip_events(self, widget, text):
tooltip = gaw.ToolTip(widget, text)
widget.bind("<Enter>", lambda event: tooltip.showtip())
widget.bind("<Leave>", lambda event: tooltip.hidetip())
# creates the console output for the terminal
def write_to_GUI(self):
self.logger.info("Writing to GUI terminal output")
if self.terminal_output is None:
self.logger.debug("Initializing terminal output console")
self.terminal_output = gaw.Console(self.root)
self.terminal_output.grid(
row=9, rowspan=3, column=0, columnspan=10, sticky="nsew"
)
self.terminal_output.write("Terminal Display:\n\n\n\n\n\n")
self.logger.info("Terminal output console initialized and displayed")
else:
self.logger.debug("Terminal output console already initialized")
return
##Gets the content of the terminal_output Text widget from the beginning to the end.
# Split the content into lines and create a counter
# Check if the line contains the phrase "File Created:".
# If found, split the line into two parts. The left part will be ignored, and the right part will be the file path.
# Increment the line number counter for the next iteration.
def hyperlink_filepath(self):
self.logger.info("Processing file paths for hyperlinks in terminal output")
self.file_dict = {}
content = self.terminal_output.get("1.0", tk.END)
lines = content.split("\n")
arrlines = []
for line_number, line in enumerate(lines, start=1):
if "File Created:" in line:
_, file_path = line.split("File Created:")
file_path = file_path.strip()
arrlines.append((line_number, line, file_path))
self.logger.debug(f"File path identified for hyperlinking: {file_path}")
for arrline in arrlines:
self.create_hyperlink(hyperlink_tuple=arrline)
self.logger.info("Hyperlink processing completed")
def create_hyperlink(self, hyperlink_tuple):
line_number, line, file_path = hyperlink_tuple
self.logger.debug(f"Creating hyperlink for file: {file_path}")
col_start = line.find(file_path)
if col_start != -1:
start_index = f"{line_number}.{col_start}"
end_index = f"{line_number}.{col_start + len(file_path)}"
file_opener = gaw.FileOpener(file_path)
self.file_dict[file_path] = file_opener
a = (start_index, end_index, file_path)
self.hyperlink_binds(a)
self.logger.debug(f"Hyperlink created for: {file_path}")
def clicked_hyperlink(self, file_path, event=None):
self.logger.info(f"Hyperlink clicked for file: {file_path}")
file_opener = self.file_dict.get(file_path)
if file_opener is not None:
file_opener.open_file()
else:
self.logger.warning(f"File path {file_path} not found in dictionary.")
def hyperlink_binds(self, tuple):
(start, end, file_path) = tuple
unique_tag = f"hyperlink_{start}_{end}" # Create a unique tag
self.logger.debug(f"Binding {unique_tag} to: {file_path}")
self.terminal_output.config(state="normal")
self.terminal_output.tag_add(unique_tag, start, end)
self.terminal_output.tag_config(unique_tag, foreground="blue", underline=1)
self.terminal_output.tag_bind(
unique_tag, "<Button-1>", lambda event: self.clicked_hyperlink(file_path)
)
self.terminal_output.config(state="disabled")
self.logger.debug(f"{unique_tag} bound and configured for: {file_path}")
################################################################################################################################################
# goal here is, after every command, the whole gui is reset as it is on startup. Ensures nothing breaks and
# no weird errors occur by variables states being in weird state when running specific commands
def reset_gui(self):
self.logger.info("Resetting the GUI")
self.dept = self.major = self.faculty = self.min_enrollment = (
self.max_enrollment
) = self.min_sections = self.max_sections = self.generic_instance = None
self.logger.debug("State variables reset")
for widget in [
self.departments_listbox,
self.faculty_listbox,
self.popup_box_threshold,
self.csv_checkbox,
self.analysis_checkbox,
self.majors_listbox,
self.commands_listbox,
self.heatmap_checkbox,
self.grade_dist_checkbox,
self.unique_listbox,
self.max_sections_threshold,
self.min_sections_threshold,
self.analysis_checkbox,
self.min_enrollment_threshold,
self.max_enrollment_threshold,
self.confirm_button,
self.min_enrollment_threshold,
self.max_enrollment_threshold,
]:
if widget is not None:
widget.destroy()
self.logger.debug(f"Widget destroyed: {type(widget).__name__}")
self.min_enrollment_threshold = self.min_sections_threshold = (
self.max_enrollment_threshold
) = self.max_sections_threshold = None
try:
self.setup_gui()
self.logger.info("GUI re-setup completed successfully")
except Exception as e:
self.logger.error(f"An error occurred while setting up the GUI: {e}")
print(f"An error occurred while setting up the GUI: {e}")
##############################################################################################
# input and output directory
# history to remember the files that the user selected as the input csv and output files checks if the file exists and if it does
# exits the file, and if it doesn't exist (first startup), creates them with preset paths
def create_json_file(self):
self.logger.info("Creating or checking .history.json file")
history_path = file_path(".history.json")
if os.path.exists(history_path):
self.logger.debug(".history.json already exists")
return
else:
self.logger.debug(
".history.json does not exist, creating with default values"
)
self.input_file_name = str(file_path("data-processed-ready.csv"))
self.output_directory = str(
file_path("grading_analysis_output")
)
self.course_table_file = str(file_path("courseTable.csv"))
self.department_file = str(file_path("deptTable.csv"))
self.instructor_file = str(file_path("instTable.csv"))
self.major_file = str(file_path("majorTable.csv"))
with open(history_path, "w") as f:
history = {
"inputfile": self.input_file_name,
"outputfile": self.output_directory,
"coursetablefile": self.course_table_file,
"departmentfile": self.department_file,
"instructorfile": self.instructor_file,
"majorfile": self.major_file,
}
json.dump(history, f)
self.logger.info(
".history.json created and initialized with default file paths"
)
# read the json (on reset) or when theres changes in the file
def populate_current_file_state(self):
self.logger.info("Populating current file state from .history.json")
history_path = file_path(".history.json")
if os.path.exists(history_path):
self.logger.debug(f"Found .history.json at {history_path}")
with open(history_path, "r") as f:
content = f.read()
if content:
try:
file_data = json.loads(content)
self.logger.debug("File data loaded from .history.json")
except json.JSONDecodeError as e:
self.logger.error(
f"JSON decoding error: {e}. Recreating .history.json"
)
self.create_json_file()
return
self.input_file_name = file_data.get("inputfile")
self.output_directory = file_data.get("outputfile")
self.department_file = file_data.get("departmentfile")
self.instructor_file = file_data.get("instructorfile")
self.major_file = file_data.get("majorfile")
self.course_table_file = file_data.get("coursetablefile")
self.logger.info("File paths updated from .history.json")
else:
self.logger.warning(
".history.json is empty. Recreating file with default values"
)
self.create_json_file()
else:
self.logger.warning(
".history.json not found. Creating new file with default values"
)
self.create_json_file()
# main gui change button
def change_sourcefile_button(self):
self.logger.info("Creating 'File Paths' button for source file change")
self.file_path_button = tk.Button(
self.root, text="File Paths", command=self.sources_popup
)
self.file_path_button.grid(row=6, column=0)
self.logger.debug("'File Paths' button created and placed in GUI")
# popup containing all the paths that are changeable and needed. If more are needed, put here following the format seen
def sources_popup(self):
self.logger.info("Creating 'Source paths' popup window")
source_popup = tk.Toplevel(self.root)
source_popup.title("Source paths")
self.file_path_browse_widget(
source_popup,
row=0,
column=0,
text="Input File:",
file=str(self.input_file_name),
set_command=self.file_call,
required_file=self.input_file_name,
)
self.file_path_browse_widget(
source_popup,
row=1,
column=0,
text="Output directory:",
file=str(self.output_directory),
set_command=self.file_call,
required_file=self.output_directory,
directory=True,
)
self.file_path_browse_widget(
source_popup,
row=2,
column=0,
text="Department file:",
file=str(self.department_file),
set_command=self.file_call,
required_file=self.department_file,
)
self.file_path_browse_widget(
source_popup,
row=3,
column=0,
text="Instructor file:",
file=str(self.instructor_file),
set_command=self.file_call,
required_file=self.instructor_file,
)
self.file_path_browse_widget(
source_popup,
row=4,
column=0,
text="Major file:",
file=str(self.major_file),
set_command=self.file_call,
required_file=self.major_file,
)
self.file_path_browse_widget(
source_popup,
row=5,
column=0,
text="Course Table file:",
file=str(self.course_table_file),
set_command=self.file_call,
required_file=self.course_table_file,
)
tk.Button(source_popup, text="Close", command=source_popup.destroy).grid(
row=6, column=1
)
self.logger.debug(
"'Source paths' popup window created with all file path browse widgets"
)
# label with the path of file and also the browse button
def file_path_browse_widget(
self,
where,
row,
column,
text,
file,
set_command,
required_file,
directory=False,
):
self.logger.info(f"Creating file path browse widget for: {text}")
label = tk.Label(where, text=text)
label.grid(row=row, column=column, sticky=tk.W)
file_path = tk.Label(where, text=file)
file_path.grid(row=row, column=column + 1)
if directory:
browse = tk.Button(
where,
text="Browse",
command=lambda: set_command(
file_path, file, required_file, directory=True
),
)
self.logger.debug(f"Browse button created for directory selection: {text}")
else:
browse = tk.Button(
where,
text="Browse",
command=lambda: set_command(file_path, file, required_file),
)
self.logger.debug(f"Browse button created for file selection: {text}")
browse.grid(row=row, column=column + 2)
self.logger.debug(f"File path browse widget set up completed for: {text}")
# file call mainly for csv and directory
def file_call(self, button=tk.Label, file=str, required_file=None, directory=False):
self.logger.info(
f"Initiating file call for {('directory' if directory else 'file')} selection"
)
if directory:
file_dir = filedialog.askdirectory()
file = str(file_dir)
self.logger.debug(f"Directory selected: {file}")
else:
file_dir = filedialog.askopenfile()
if file_dir:
file = str(file_dir.name)
self.logger.debug(f"File selected: {file}")
else:
self.logger.warning("File selection cancelled")
return
self.update_filestate(file=file, which=required_file)
button.config(text=str(file))
self.logger.info(f"File state updated for {required_file}")
##########################################################################################################
# populate widgets
# any list that needs population gets population here.
def populate_majors_listbox(self):
self.logger.info("Populating majors listbox")
self.majors = gaf.df["Major"].unique().tolist()
self.majors.sort()
for major in self.majors:
self.majors_listbox.insert(parent="", index=tk.END, values=(major,))
def populate_department_listbox(self):
self.logger.info("Populating departments listbox")
self.departments = gaf.df["Department"].unique().tolist()
self.departments.sort()
for dept in self.departments:
self.departments_listbox.insert(parent="", index=tk.END, values=(dept,))
def populate_faculty_listbox(self):
self.logger.info("Populating faculty listbox")
self.faculty_set = gaf.df["FacultyID"].unique().tolist()
for faculty in self.faculty_set:
self.faculty_listbox.insert(parent="", index=tk.END, values=(faculty,))
def populate_unique_listbox(self):
self.logger.info("Populating unique listbox")
self.unique_list = [
"Departments",
"Majors",
"Instructor IDs",
"Courses",
"UniqueCourseID",
"Student IDs",
"All",