-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgradeAnalysisGUI.py
1956 lines (1665 loc) · 82.7 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
from gradeAnalysisFunc import return_filtered_dataframe
# from ctypes import windll
# windll.shcore.SetProcessDpiAwareness(1)
def file_path(file):
"""
Returns the absolute path of a file located in the same directory as the script.
Args:
file (str): The name of the file.
Returns:
str: The absolute path of the file.
"""
return os.path.join(os.path.dirname(os.path.realpath(__file__)), file)
def check_list_is_subset(target_list: list, check_list: list) -> bool:
"""
Checks if all elements of the target_list are present in the check_list.
Args:
target_list (list): The list of elements to check.
check_list (list): The list in which to check for the presence of target_list elements.
Returns:
bool: True if all elements of target_list are in check_list, False otherwise.
"""
if set(target_list) == set(check_list):
return True
return all(item in check_list for item in target_list)
def return_filtered_dataframe(df: gaf.pd.DataFrame, column: str, values: list) -> gaf.pd.DataFrame:
"""
Filters a DataFrame based on a column and a list of values.
Args:
df (pd.DataFrame): The DataFrame to filter.
column (str): The column name to filter on.
values (list): The list of values to filter by.
Returns:
pd.DataFrame: A filtered DataFrame containing only the rows where the column's value is in the provided list.
"""
mask = df[column].isin(values)
return df[mask]
class GradingAnalysisTool:
def __init__(self):
"""
Initializes the GradingAnalysisTool class, setting up the main GUI window,
loading the initial data, and configuring various GUI elements and variables.
"""
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.dataframe = gaf.pd.read_csv('data-processed-ready.csv')
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.min_gpa_threshold = None
self.min_gpa = None
self.max_gpa_threshold = None
self.max_gpa = 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.commands_directory = None
self.rand_data = None
# Setup commands and GUI
self.root.geometry("")
self.setup_commands()
self.setup_gui() # Run GUI setup
def setup_gui(self):
"""
Creates the main GUI window, retrieves the file paths from the .history.json file, adds the buttons
seen in the main command screen, sets up the Terminal redirect for stdout, and starts the mainloop.
"""
self.create_json_file()
self.commands_listbox_widget()
self.change_sourcefile_button()
self.populate_current_file_state()
if self.reset_gui_button is None:
self.reset_gui_button = tk.Button(
self.root, text="Reset", command=self.reset_button
)
self.reset_gui_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):
"""
Sets up the enrollment threshold widget with two threshold widgets for minimum and maximum enrollment values.
"""
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):
"""
Sets up the sections threshold widget with two threshold widgets for minimum and maximum sections values.
"""
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):
"""
Sets up the class size threshold widget with two threshold widgets for minimum and maximum class size
This is the same as the enrollment threshold widget, but with different text labels.
"""
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 gpa_threshold_widget(self, state="disabled", where=None, row=None, column=None):
"""
Sets up the GPA threshold widget with two threshold widgets for minimum and maximum GPA values.
"""
#not really used like that, gotta find a good use for it
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_gpa_threshold = gaw.ThresholdWidget()
self.min_gpa_threshold.generic_thresholds_widget(
where=where,
state=state,
text="Min GPA:",
row=row,
column=column,
help="Enter an integer for a threshold",
)
self.max_gpa_threshold = gaw.ThresholdWidget()
self.max_gpa_threshold.generic_thresholds_widget(
where=where,
state=state,
text="Max GPA:",
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):
"""
Sets up the course num taken threshold widget with two threshold widgets for minimum and maximum course num taken values.
"""
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 csv_checkbox_widget(self, state="disabled", where=None, row=1, column=4):
"""
Sets up the CSV checkbox widget with a single checkbox for creating a CSV file.
Creates a csv of the state of the dataframe based on the filters and chocies made by the user,
weather that be by thresholding or filtering via department, majors, courses, etc.
"""
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):
"""
Used by the few commands that can create a heatmap, this checkbox is used to toggle the heatmap creation.
"""
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
):
"""
This checkbox is used to toggle the grade distribution creation. When checked, creates a
parallel plot of the normalized frequency of each letter grade seen in the data.
"""
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")
def create_analysis_dropdown(
self,
where=None,
analysis_options=None,
row=0,
column=0,
initial_message="Select Analysis",
):
"""
creates the drop down for picking which analysis to run based on the dictionary.py file,
which defines dictionaries of option: bool pairs for each analysis type.
"""
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")
# 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: int=700,
window_height: int=100,
) -> tk.Toplevel:
"""
Creates a popup window for the selected analysis command. This pop up handles filtering via choices, thresholding,
selecting analysis type, baisically everything that it takes to go to the next step and actually running the analysis and aggregation
"""
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.popup_box_threshold.transient(self.root) # Keep the window attached to the root
self.popup_box_threshold.attributes("-topmost", True) # Always on top
self.popup_box_threshold.grab_set() # Ensure it stays in front and modal
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):
"""
binds the command of the analysis you want to run to the Go button, usually placed on the threshold popup
"""
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")
def run_command_confirm_threshold(self, command):
"""
Runs the selected command after confirming your options on the threshold popup,
now we really really for real run the 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()):
"""
Gets the integer value from the threshold widget, if it exists and is a number (int or float).
"""
if threshold is not None:
try:
value = threshold.get_entry_value()
return float(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):
"""
Retrieves the threshold values from the widgets. yea probably not the best way to do check every threshold value but boohoo cry about it
"""
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)
if self.min_gpa_threshold is not None:
self.min_gpa = self.get_valid_integer(self.min_gpa_threshold)
if self.max_gpa_threshold is not None:
self.max_gpa = self.get_valid_integer(self.max_gpa_threshold)
##################################################################################
##History File .history.json
def update_filestate(self, file, which):
"""
Updates the file state for the files in the json, easily expandable
"""
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",
}
if which in attribute_map:
if which == self.input_file_name:
self.dataframe = gaf.pd.read_csv(file)
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),
}
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):
"""
Sets up the commands for the tool, these are the main runable commands
"""
self.logger.info("Setting up commands for GradingAnalysisTool")
self.commands_directory = {
"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,
"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):
"""
Places the commands from self.setup_commands in the listbox for the user to select from
"""
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
def quit_program(self):
"""
quits the program, i mean ive never used it but you gotta have a quit option
"""
self.logger.info("Quitting Program")
exit()
# no idea how this works or if it even works, need to visit again. works for now tho
# literally does not work this is stupid and not useful for a tool with such minimal buttons
# theres never even a reason to honestly resize the tool
# however the numbers in the for loops are not changeable right now because of the way the grid is set up
# terrible mistake on marios end, if we want to change the avaliale grid space we have to change the numbers EVRYWHERE grid is used
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):
"""
binds the reset button to the reset_gui function
"""
self.terminal_output = None
self.logger.info("Reset Button Clicked")
self.reset_gui()
def run_command_button_toggle(self, state="normal"):
"""
Toggles the run command button to be enabled or disabled, like when threshold popup is open. dont run multiple commands
"""
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):
"""
Writes to the GUI terminal output. The Console class was taken from reddit a while ago, its great and I have no idea how it works
"""
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):
"""
Processes the terminal output to identify file paths and create hyperlinks
"""
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):
"""
Resets the GUI to its initial state, clearing all widgets and variables.
"""
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.max_gpa_threshold,
self.min_gpa_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 = self.min_gpa_threshold = self.max_gpa_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):
"""
Creates a .history.json file with default file paths if it does not exist.
"""
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")
)
with open(history_path, "w") as f:
history = {
"inputfile": self.input_file_name,
"outputfile": self.output_directory,
}
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.dataframe = gaf.pd.read_csv(self.input_file_name)
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,
)
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)
if file == self.input_file_name:
print('Input File updated, Dataframe changed, to undo this, change the path of the input file')
button.config(text=str(file))
self.logger.info(f"File state updated for {required_file}")
def update_df(self):
if isinstance(self.dataframe, gaf.pd.Dataframe()):
self.dataframe = gaf.pd.read_csv(self.input_file_name)
self.reset_gui()
else:
return
##########################################################################################################
# populate widgets
# any list that needs population gets population here.