From ea604d317a5b8f59c3f12c186caac9674ed80adc Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Tue, 10 Mar 2026 19:31:23 -0400 Subject: [PATCH 01/33] tests: calculate and return confusion matrix and report --- LabGym/categorizer.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/LabGym/categorizer.py b/LabGym/categorizer.py index 8e093548..4c94d8e7 100644 --- a/LabGym/categorizer.py +++ b/LabGym/categorizer.py @@ -33,7 +33,7 @@ from scipy import ndimage from skimage import exposure,transform from skimage.transform import AffineTransform -from sklearn.metrics import classification_report +from sklearn.metrics import classification_report, confusion_matrix from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer import tensorflow as tf @@ -2086,14 +2086,24 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): predictions=[round(i[0]) for i in predictions] print(classification_report(labels,predictions,target_names=classnames)) report=classification_report(labels,predictions,target_names=classnames,output_dict=True) + # ADDED: Calculate binary confusion matrix + cm=confusion_matrix(labels,predictions) else: print(classification_report(labels,predictions.argmax(axis=1),target_names=classnames)) report=classification_report(labels,predictions.argmax(axis=1),target_names=classnames,output_dict=True) + # ADDED: Calculate multi-class confusion matrix + cm=confusion_matrix(labels,predictions.argmax(axis=1)) if result_path is not None: pd.DataFrame(report).transpose().to_excel(os.path.join(result_path,'testing_reports.xlsx'),float_format='%.2f') + # ADDED: Save the confusion matrix to a CSV as a backup/reference + pd.DataFrame(cm, index=classnames, columns=classnames).to_csv(os.path.join(result_path,'confusion_matrix.csv')) print('Testing completed!') + + # ADDED: Return the data so the GUI can catch it! + return report, cm + def generate_probability_matrix(self, path_to_video, path_to_model, output_folder, batch_size=32): """ @@ -2188,4 +2198,4 @@ def generate_probability_matrix(self, path_to_video, path_to_model, output_folde plt.savefig(os.path.join(output_folder, "probability_heatmap.png"), dpi=200) plt.close() - return P \ No newline at end of file + return P From 4fc05a813cce2dd0084ea8fc8e05db24e6364e97 Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Tue, 10 Mar 2026 19:59:12 -0400 Subject: [PATCH 02/33] gui: render automated diagnostics dialog with MSV confusion matrix and performance table --- LabGym/gui_categorizer.py | 84 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 8e119be4..68960a2a 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -36,6 +36,7 @@ import wx import wx.richtext import wx.lib.buttons as wxbuttons +import wx.grid # Local application/library specific imports. logger.debug('importing %s ...', '.analyzebehavior') @@ -2112,7 +2113,12 @@ def test_categorizer(self,event): wx.MessageBox('No Categorizer selected / path to ground-truth behavior examples.','Error',wx.OK|wx.ICON_ERROR) else: CA=Categorizers() - CA.test_categorizer(self.file_path,self.path_to_categorizer,result_path=self.out_path) + report, cm = CA.test_categorizer(self.file_path,self.path_to_categorizer,result_path=self.out_path) + classnames = [k for k in report.keys() if k not in ['accuracy', 'macro avg', 'weighted avg']] + + dialog = AutomatedDiagnosticsDialog(self, report, cm, classnames) + dialog.ShowModal() + dialog.Destroy() def remove_categorizer(self,event): @@ -2134,3 +2140,79 @@ def remove_categorizer(self,event): shutil.rmtree(os.path.join(self.model_path,categorizer)) dialog1.Destroy() dialog.Destroy() + +class AutomatedDiagnosticsDialog(wx.Dialog): + def __init__(self, parent, report, cm, classnames): + super().__init__(parent, title="Automated Diagnostics - Test Results", size=(800, 600), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) + + self.report = report + self.cm = cm + self.classnames = classnames + + self.init_ui() + + def init_ui(self): + sizer = wx.BoxSizer(wx.VERTICAL) + + cm_label = wx.StaticText(self, label="Confusion Matrix:") + font = cm_label.GetFont() + font.SetWeight(wx.FONTWEIGHT_BOLD) + cm_label.SetFont(font) + sizer.Add(cm_label, 0, wx.ALL, 10) + + num_classes = len(self.classnames) + self.cm_grid = wx.grid.Grid(self) + self.cm_grid.CreateGrid(num_classes, num_classes) + + for i, name in enumerate(self.classnames): + self.cm_grid.SetRowLabelValue(i, name) + self.cm_grid.SetColLabelValue(i, name) + + for i in range(num_classes): + for j in range(num_classes): + val = str(self.cm[i][j]) + self.cm_grid.SetCellValue(i, j, val) + self.cm_grid.SetReadOnly(i, j, True) + self.cm_grid.SetCellAlignment(i, j, wx.ALIGN_CENTER, wx.ALIGN_CENTER) + + self.cm_grid.AutoSize() + sizer.Add(self.cm_grid, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) + + perf_label = wx.StaticText(self, label="Per-Class Performance (Highlighting Precision < 60%):") + perf_label.SetFont(font) + sizer.Add(perf_label, 0, wx.ALL, 10) + + self.list_ctrl = wx.ListCtrl(self, style=wx.LC_REPORT | wx.BORDER_SUNKEN) + self.list_ctrl.InsertColumn(0, "Behavior", width=150) + self.list_ctrl.InsertColumn(1, "Precision", width=100) + self.list_ctrl.InsertColumn(2, "Recall", width=100) + self.list_ctrl.InsertColumn(3, "F1-Score", width=100) + self.list_ctrl.InsertColumn(4, "Support", width=100) + + index = 0 + for name in self.classnames: + if name in self.report: + metrics = self.report[name] + self.list_ctrl.InsertItem(index, name) + + precision = metrics.get('precision', 0) + self.list_ctrl.SetItem(index, 1, f"{precision:.2f}") + self.list_ctrl.SetItem(index, 2, f"{metrics.get('recall', 0):.2f}") + self.list_ctrl.SetItem(index, 3, f"{metrics.get('f1-score', 0):.2f}") + self.list_ctrl.SetItem(index, 4, str(metrics.get('support', 0))) + + if precision < 0.60: + self.list_ctrl.SetItemBackgroundColour(index, wx.Colour(255, 200, 200)) + + index += 1 + + sizer.Add(self.list_ctrl, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) + + btn_sizer = wx.BoxSizer(wx.HORIZONTAL) + close_btn = wx.Button(self, wx.ID_CLOSE, "Close") + close_btn.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.ID_CANCEL)) + btn_sizer.Add(close_btn, 0, wx.ALL, 10) + sizer.Add(btn_sizer, 0, wx.ALIGN_RIGHT) + + self.SetSizer(sizer) + self.Layout() \ No newline at end of file From 15ff95d8e9d4da0afbcd588268785e04aa24d5ec Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Tue, 10 Mar 2026 20:06:36 -0400 Subject: [PATCH 03/33] gui: add safety checks to automated diagnostics table and matrix --- LabGym/gui_categorizer.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 68960a2a..7fcdace2 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2168,9 +2168,17 @@ def init_ui(self): self.cm_grid.SetRowLabelValue(i, name) self.cm_grid.SetColLabelValue(i, name) + cm_rows = len(self.cm) + cm_cols = len(self.cm[0]) if cm_rows > 0 else 0 + for i in range(num_classes): for j in range(num_classes): - val = str(self.cm[i][j]) + + if i < cm_rows and j < cm_cols: + val = str(self.cm[i][j]) + else: + val = "0" + self.cm_grid.SetCellValue(i, j, val) self.cm_grid.SetReadOnly(i, j, True) self.cm_grid.SetCellAlignment(i, j, wx.ALIGN_CENTER, wx.ALIGN_CENTER) @@ -2194,12 +2202,16 @@ def init_ui(self): if name in self.report: metrics = self.report[name] self.list_ctrl.InsertItem(index, name) + + precision = float(metrics.get('precision', 0.0)) + recall = float(metrics.get('recall', 0.0)) + f1 = float(metrics.get('f1-score', 0.0)) + support = float(metrics.get('support', 0.0)) - precision = metrics.get('precision', 0) self.list_ctrl.SetItem(index, 1, f"{precision:.2f}") - self.list_ctrl.SetItem(index, 2, f"{metrics.get('recall', 0):.2f}") - self.list_ctrl.SetItem(index, 3, f"{metrics.get('f1-score', 0):.2f}") - self.list_ctrl.SetItem(index, 4, str(metrics.get('support', 0))) + self.list_ctrl.SetItem(index, 2, f"{recall:.2f}") + self.list_ctrl.SetItem(index, 3, f"{f1:.2f}") + self.list_ctrl.SetItem(index, 4, str(support)) if precision < 0.60: self.list_ctrl.SetItemBackgroundColour(index, wx.Colour(255, 200, 200)) From 63a9d051f18137278834bebbde6c6147f05ae674 Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Tue, 10 Mar 2026 20:17:12 -0400 Subject: [PATCH 04/33] gui: add normalized and raw data toggle to confusion matrix --- LabGym/gui_categorizer.py | 68 ++++++++++++++++++++++++++++++--------- 1 file changed, 52 insertions(+), 16 deletions(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 7fcdace2..eec383a9 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2148,17 +2148,38 @@ def __init__(self, parent, report, cm, classnames): self.report = report self.cm = cm self.classnames = classnames + + self.cm_normalized = self.calculate_normalized_cm(cm) + self.is_normalized = False self.init_ui() + def calculate_normalized_cm(self, cm): + norm_cm = [] + for row in cm: + row_sum = sum(row) + if row_sum > 0: + norm_cm.append([round((val / row_sum) * 100, 1) for val in row]) + else: + norm_cm.append([0.0 for _ in row]) + return norm_cm + def init_ui(self): sizer = wx.BoxSizer(wx.VERTICAL) + cm_header_sizer = wx.BoxSizer(wx.HORIZONTAL) + cm_label = wx.StaticText(self, label="Confusion Matrix:") font = cm_label.GetFont() font.SetWeight(wx.FONTWEIGHT_BOLD) cm_label.SetFont(font) - sizer.Add(cm_label, 0, wx.ALL, 10) + cm_header_sizer.Add(cm_label, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 10) + + self.toggle_btn = wx.ToggleButton(self, label="Show Normalized (%)") + self.toggle_btn.Bind(wx.EVT_TOGGLEBUTTON, self.on_toggle_cm) + cm_header_sizer.Add(self.toggle_btn, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) + + sizer.Add(cm_header_sizer, 0, wx.EXPAND) num_classes = len(self.classnames) self.cm_grid = wx.grid.Grid(self) @@ -2168,20 +2189,7 @@ def init_ui(self): self.cm_grid.SetRowLabelValue(i, name) self.cm_grid.SetColLabelValue(i, name) - cm_rows = len(self.cm) - cm_cols = len(self.cm[0]) if cm_rows > 0 else 0 - - for i in range(num_classes): - for j in range(num_classes): - - if i < cm_rows and j < cm_cols: - val = str(self.cm[i][j]) - else: - val = "0" - - self.cm_grid.SetCellValue(i, j, val) - self.cm_grid.SetReadOnly(i, j, True) - self.cm_grid.SetCellAlignment(i, j, wx.ALIGN_CENTER, wx.ALIGN_CENTER) + self.update_grid_data() self.cm_grid.AutoSize() sizer.Add(self.cm_grid, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) @@ -2227,4 +2235,32 @@ def init_ui(self): sizer.Add(btn_sizer, 0, wx.ALIGN_RIGHT) self.SetSizer(sizer) - self.Layout() \ No newline at end of file + self.Layout() + + def update_grid_data(self): + cm_rows = len(self.cm) + cm_cols = len(self.cm[0]) if cm_rows > 0 else 0 + + data_to_use = self.cm_normalized if self.is_normalized else self.cm + + for i in range(len(self.classnames)): + for j in range(len(self.classnames)): + if i < cm_rows and j < cm_cols: + val = f"{data_to_use[i][j]}%" if self.is_normalized else str(data_to_use[i][j]) + else: + val = "0.0%" if self.is_normalized else "0" + + self.cm_grid.SetCellValue(i, j, val) + self.cm_grid.SetReadOnly(i, j, True) + self.cm_grid.SetCellAlignment(i, j, wx.ALIGN_CENTER, wx.ALIGN_CENTER) + + self.cm_grid.ForceRefresh() + + def on_toggle_cm(self, event): + self.is_normalized = self.toggle_btn.GetValue() + if self.is_normalized: + self.toggle_btn.SetLabel("Show Raw Counts") + else: + self.toggle_btn.SetLabel("Show Normalized (%)") + + self.update_grid_data() \ No newline at end of file From 161214c432a7804dc118577d3c6ecf2830c344f8 Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Tue, 10 Mar 2026 20:41:23 -0400 Subject: [PATCH 05/33] gui: implement clickable confusion matrix cells and cross-platform example loading --- LabGym/categorizer.py | 26 +++++++---- LabGym/gui_categorizer.py | 95 ++++++++++++++++++++++++++++++++------- 2 files changed, 97 insertions(+), 24 deletions(-) diff --git a/LabGym/categorizer.py b/LabGym/categorizer.py index 4c94d8e7..f570f248 100644 --- a/LabGym/categorizer.py +++ b/LabGym/categorizer.py @@ -1951,6 +1951,7 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): animations=deque() pattern_images=deque() labels=deque() + test_files=[] parameters=pd.read_csv(os.path.join(model_path,'model_parameters.txt')) @@ -2029,6 +2030,8 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): for i in filenames: + test_files.append(os.path.join(groundtruth_path, behavior, i)) + if network!=0: path_to_animation=os.path.join(groundtruth_path,behavior,i) @@ -2084,25 +2087,32 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): if len(classnames)==2: predictions=[round(i[0]) for i in predictions] + flat_predictions = predictions # Save flat predictions print(classification_report(labels,predictions,target_names=classnames)) report=classification_report(labels,predictions,target_names=classnames,output_dict=True) - # ADDED: Calculate binary confusion matrix cm=confusion_matrix(labels,predictions) else: - print(classification_report(labels,predictions.argmax(axis=1),target_names=classnames)) - report=classification_report(labels,predictions.argmax(axis=1),target_names=classnames,output_dict=True) - # ADDED: Calculate multi-class confusion matrix - cm=confusion_matrix(labels,predictions.argmax(axis=1)) + flat_predictions = predictions.argmax(axis=1) # Save flat predictions + print(classification_report(labels,flat_predictions,target_names=classnames)) + report=classification_report(labels,flat_predictions,target_names=classnames,output_dict=True) + cm=confusion_matrix(labels,flat_predictions) if result_path is not None: pd.DataFrame(report).transpose().to_excel(os.path.join(result_path,'testing_reports.xlsx'),float_format='%.2f') - # ADDED: Save the confusion matrix to a CSV as a backup/reference pd.DataFrame(cm, index=classnames, columns=classnames).to_csv(os.path.join(result_path,'confusion_matrix.csv')) + # ADDED: Build a dictionary mapping (True Class, Predicted Class) -> [List of File Paths] + example_map = {} + for t_label_idx, p_label_idx, f_path in zip(labels, flat_predictions, test_files): + key = (classnames[t_label_idx], classnames[p_label_idx]) + if key not in example_map: + example_map[key] = [] + example_map[key].append(f_path) + print('Testing completed!') - # ADDED: Return the data so the GUI can catch it! - return report, cm + # ADDED: Return example_map as the 3rd variable! + return report, cm, example_map def generate_probability_matrix(self, path_to_video, path_to_model, output_folder, batch_size=32): diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index eec383a9..78ac46d4 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -21,6 +21,9 @@ import json import logging import os +import sys +import subprocess + # from pathlib import Path import shutil @@ -1090,10 +1093,6 @@ def sort_fromcsv(self,event): class PanelLv2_TrainCategorizers(wx.Panel): - ''' - The 'Train Categorizers' functional unit - ''' - def __init__(self, parent): super().__init__(parent) @@ -1984,14 +1983,13 @@ def __init__(self, parent): super().__init__(parent) self.notebook = parent - # Get all of the values needed from config.get_config(). self.config = config.get_config('models') - self.file_path=None # the folder that stores the ground-truth examples (each subfolder is a behavior category) - self.model_path = self.config['models'] # the 'LabGym/models' folder, which stores all the trained Categorizers + self.file_path=None + self.model_path = self.config['models'] logger.debug('%s: %r', 'self.model_path', self.model_path) - self.path_to_categorizer=None # path to the Categorizer - self.out_path=None # for storing the testing reports + self.path_to_categorizer=None + self.out_path=None self.display_window() @@ -2073,10 +2071,10 @@ def select_categorizer(self,event): dialog1=wx.DirDialog(self,'Select a directory','',style=wx.DD_DEFAULT_STYLE) if dialog1.ShowModal()==wx.ID_OK: self.path_to_categorizer=dialog1.GetPath() + self.text_selectcategorizer.SetLabel('The path to the Categorizer to test is: '+self.path_to_categorizer+'.') else: self.path_to_categorizer=None dialog1.Destroy() - self.text_selectcategorizer.SetLabel('The path to the Categorizer to test is: '+self.path_to_categorizer+'.') else: self.path_to_categorizer=os.path.join(self.model_path,categorizer) self.text_selectcategorizer.SetLabel('Categorizer to test: '+categorizer+'.') @@ -2113,10 +2111,11 @@ def test_categorizer(self,event): wx.MessageBox('No Categorizer selected / path to ground-truth behavior examples.','Error',wx.OK|wx.ICON_ERROR) else: CA=Categorizers() - report, cm = CA.test_categorizer(self.file_path,self.path_to_categorizer,result_path=self.out_path) + + report, cm, example_map = CA.test_categorizer(self.file_path,self.path_to_categorizer,result_path=self.out_path) classnames = [k for k in report.keys() if k not in ['accuracy', 'macro avg', 'weighted avg']] - dialog = AutomatedDiagnosticsDialog(self, report, cm, classnames) + dialog = AutomatedDiagnosticsDialog(self, report, cm, classnames, example_map) dialog.ShowModal() dialog.Destroy() @@ -2142,13 +2141,14 @@ def remove_categorizer(self,event): dialog.Destroy() class AutomatedDiagnosticsDialog(wx.Dialog): - def __init__(self, parent, report, cm, classnames): + def __init__(self, parent, report, cm, classnames, example_map): super().__init__(parent, title="Automated Diagnostics - Test Results", size=(800, 600), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) self.report = report self.cm = cm self.classnames = classnames - + self.example_map = example_map + self.cm_normalized = self.calculate_normalized_cm(cm) self.is_normalized = False @@ -2185,6 +2185,8 @@ def init_ui(self): self.cm_grid = wx.grid.Grid(self) self.cm_grid.CreateGrid(num_classes, num_classes) + self.cm_grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.on_cell_click) + for i, name in enumerate(self.classnames): self.cm_grid.SetRowLabelValue(i, name) self.cm_grid.SetColLabelValue(i, name) @@ -2240,7 +2242,6 @@ def init_ui(self): def update_grid_data(self): cm_rows = len(self.cm) cm_cols = len(self.cm[0]) if cm_rows > 0 else 0 - data_to_use = self.cm_normalized if self.is_normalized else self.cm for i in range(len(self.classnames)): @@ -2263,4 +2264,66 @@ def on_toggle_cm(self, event): else: self.toggle_btn.SetLabel("Show Normalized (%)") - self.update_grid_data() \ No newline at end of file + self.update_grid_data() + + def on_cell_click(self, event): + row = event.GetRow() + col = event.GetCol() + + if row < len(self.classnames) and col < len(self.classnames): + true_class = self.classnames[row] + pred_class = self.classnames[col] + + key = (true_class, pred_class) + examples = self.example_map.get(key, []) + + if not examples: + wx.MessageBox(f"No examples found for True='{true_class}' and Predicted='{pred_class}'.", "Info", wx.OK | wx.ICON_INFORMATION) + else: + viewer = ExampleViewerDialog(self, true_class, pred_class, examples) + viewer.ShowModal() + viewer.Destroy() + + event.Skip() + +class ExampleViewerDialog(wx.Dialog): + def __init__(self, parent, true_class, pred_class, examples): + title = f"Reviewing Examples: True '{true_class}' -> Predicted '{pred_class}'" + super().__init__(parent, title=title, size=(600, 400), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) + + self.examples = examples + self.init_ui() + + def init_ui(self): + sizer = wx.BoxSizer(wx.VERTICAL) + + info_label = wx.StaticText(self, label=f"Found {len(self.examples)} example(s). Double-click a file to open it:") + sizer.Add(info_label, 0, wx.ALL, 10) + + self.list_box = wx.ListBox(self, choices=self.examples, style=wx.LB_SINGLE | wx.LB_HSCROLL) + self.list_box.Bind(wx.EVT_LISTBOX_DCLICK, self.on_double_click) + sizer.Add(self.list_box, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 10) + + btn_sizer = wx.BoxSizer(wx.HORIZONTAL) + close_btn = wx.Button(self, wx.ID_CLOSE, "Close") + close_btn.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.ID_CANCEL)) + btn_sizer.Add(close_btn, 0, wx.ALL, 10) + sizer.Add(btn_sizer, 0, wx.ALIGN_RIGHT) + + self.SetSizer(sizer) + self.Layout() + + def on_double_click(self, event): + selection = self.list_box.GetSelection() + if selection != wx.NOT_FOUND: + filepath = self.examples[selection] + + try: + if sys.platform == "win32": + os.startfile(filepath) + elif sys.platform == "darwin": + subprocess.call(["open", filepath]) + else: + subprocess.call(["xdg-open", filepath]) + except Exception as e: + wx.MessageBox(f"Failed to open file:\n{e}", "Error", wx.OK | wx.ICON_ERROR) \ No newline at end of file From bf3f61703625bab89d8bfb8ad615279bd6c8b6ab Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Tue, 24 Mar 2026 23:38:42 -0400 Subject: [PATCH 06/33] gui: heatmap and threshold dropdown --- LabGym/gui_categorizer.py | 140 ++++++++++++++++++++++++++------------ 1 file changed, 98 insertions(+), 42 deletions(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 78ac46d4..e0013745 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2166,40 +2166,50 @@ def calculate_normalized_cm(self, cm): def init_ui(self): sizer = wx.BoxSizer(wx.VERTICAL) + font = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) - cm_header_sizer = wx.BoxSizer(wx.HORIZONTAL) - + # Top header with label and toggle button + header_sizer = wx.BoxSizer(wx.HORIZONTAL) cm_label = wx.StaticText(self, label="Confusion Matrix:") - font = cm_label.GetFont() - font.SetWeight(wx.FONTWEIGHT_BOLD) cm_label.SetFont(font) - cm_header_sizer.Add(cm_label, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 10) - + header_sizer.Add(cm_label, 1, wx.ALIGN_CENTER_VERTICAL) + self.toggle_btn = wx.ToggleButton(self, label="Show Normalized (%)") self.toggle_btn.Bind(wx.EVT_TOGGLEBUTTON, self.on_toggle_cm) - cm_header_sizer.Add(self.toggle_btn, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) - - sizer.Add(cm_header_sizer, 0, wx.EXPAND) + header_sizer.Add(self.toggle_btn, 0, wx.ALIGN_CENTER_VERTICAL) + + sizer.Add(header_sizer, 0, wx.EXPAND | wx.ALL, 10) - num_classes = len(self.classnames) + # Grid setup self.cm_grid = wx.grid.Grid(self) - self.cm_grid.CreateGrid(num_classes, num_classes) - - self.cm_grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.on_cell_click) - + self.cm_grid.CreateGrid(len(self.classnames), len(self.classnames)) + for i, name in enumerate(self.classnames): self.cm_grid.SetRowLabelValue(i, name) self.cm_grid.SetColLabelValue(i, name) + self.cm_grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.on_cell_click) + self.update_grid_data() self.cm_grid.AutoSize() sizer.Add(self.cm_grid, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) - perf_label = wx.StaticText(self, label="Per-Class Performance (Highlighting Precision < 60%):") - perf_label.SetFont(font) - sizer.Add(perf_label, 0, wx.ALL, 10) + # --- DROPDOWN HEADER FOR TABLE --- + table_header_sizer = wx.BoxSizer(wx.HORIZONTAL) + self.table_label = wx.StaticText(self, label="Highlight behaviors below 0.60: ") + self.table_label.SetFont(font) + + self.metric_choice = wx.Choice(self, choices=["F1-score", "Precision", "Recall"]) + self.metric_choice.SetSelection(0) # Default to F1-score + self.metric_choice.Bind(wx.EVT_CHOICE, self.on_metric_change) + + table_header_sizer.Add(self.table_label, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5) + table_header_sizer.Add(self.metric_choice, 0, wx.ALIGN_CENTER_VERTICAL) + + sizer.Add(table_header_sizer, 0, wx.ALL | wx.EXPAND, 10) + # --- TABLE SETUP --- self.list_ctrl = wx.ListCtrl(self, style=wx.LC_REPORT | wx.BORDER_SUNKEN) self.list_ctrl.InsertColumn(0, "Behavior", width=150) self.list_ctrl.InsertColumn(1, "Precision", width=100) @@ -2207,26 +2217,8 @@ def init_ui(self): self.list_ctrl.InsertColumn(3, "F1-Score", width=100) self.list_ctrl.InsertColumn(4, "Support", width=100) - index = 0 - for name in self.classnames: - if name in self.report: - metrics = self.report[name] - self.list_ctrl.InsertItem(index, name) - - precision = float(metrics.get('precision', 0.0)) - recall = float(metrics.get('recall', 0.0)) - f1 = float(metrics.get('f1-score', 0.0)) - support = float(metrics.get('support', 0.0)) - - self.list_ctrl.SetItem(index, 1, f"{precision:.2f}") - self.list_ctrl.SetItem(index, 2, f"{recall:.2f}") - self.list_ctrl.SetItem(index, 3, f"{f1:.2f}") - self.list_ctrl.SetItem(index, 4, str(support)) - - if precision < 0.60: - self.list_ctrl.SetItemBackgroundColour(index, wx.Colour(255, 200, 200)) - - index += 1 + # Populate the table the first time it opens + self.update_table_data() sizer.Add(self.list_ctrl, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) @@ -2245,15 +2237,36 @@ def update_grid_data(self): data_to_use = self.cm_normalized if self.is_normalized else self.cm for i in range(len(self.classnames)): + row_sum = sum(self.cm[i]) if i < cm_rows else 0 + for j in range(len(self.classnames)): if i < cm_rows and j < cm_cols: val = f"{data_to_use[i][j]}%" if self.is_normalized else str(data_to_use[i][j]) + + # --- HEAT MAP LOGIC --- + if i != j and self.cm[i][j] > 0: + # Off-diagonal errors: scale dark to bright red based on error rate + err_pct = self.cm[i][j] / row_sum if row_sum > 0 else 0 + intensity = min(1.0, err_pct / 0.5) + r_val = int(40 + (215 * intensity)) + bg_color = wx.Colour(r_val, 0, 0) + elif i == j and row_sum > 0: + # Diagonal correct predictions: scale dark to bright green + accuracy = self.cm[i][j] / row_sum if row_sum > 0 else 0 + g_val = int(40 + (215 * accuracy)) + bg_color = wx.Colour(0, g_val, 0) + else: + # Empty or zero cells + bg_color = wx.Colour(30, 30, 30) else: val = "0.0%" if self.is_normalized else "0" + bg_color = wx.Colour(30, 30, 30) self.cm_grid.SetCellValue(i, j, val) self.cm_grid.SetReadOnly(i, j, True) self.cm_grid.SetCellAlignment(i, j, wx.ALIGN_CENTER, wx.ALIGN_CENTER) + self.cm_grid.SetCellBackgroundColour(i, j, bg_color) + self.cm_grid.SetCellTextColour(i, j, wx.Colour(255, 255, 255)) self.cm_grid.ForceRefresh() @@ -2266,10 +2279,53 @@ def on_toggle_cm(self, event): self.update_grid_data() + def on_metric_change(self, event): + self.update_table_data() + + def update_table_data(self): + self.list_ctrl.DeleteAllItems() + + selection = self.metric_choice.GetStringSelection() + metric_key = 'f1-score' + if selection == "Precision": + metric_key = 'precision' + elif selection == "Recall": + metric_key = 'recall' + + index = 0 + for name in self.classnames: + if name in self.report and isinstance(self.report[name], dict): + metrics = self.report[name] + self.list_ctrl.InsertItem(index, name) + + precision = float(metrics.get('precision', 0.0)) + recall = float(metrics.get('recall', 0.0)) + f1 = float(metrics.get('f1-score', 0.0)) + support = float(metrics.get('support', 0.0)) + + self.list_ctrl.SetItem(index, 1, f"{precision:.2f}") + self.list_ctrl.SetItem(index, 2, f"{recall:.2f}") + self.list_ctrl.SetItem(index, 3, f"{f1:.2f}") + self.list_ctrl.SetItem(index, 4, str(int(support))) + + # Dynamic highlighting based on dropdown + val_to_check = float(metrics.get(metric_key, 0.0)) + if val_to_check < 0.60: + self.list_ctrl.SetItemBackgroundColour(index, wx.Colour(150, 0, 0)) + else: + self.list_ctrl.SetItemBackgroundColour(index, wx.Colour(30, 30, 30)) + + self.list_ctrl.SetItemTextColour(index, wx.Colour(255, 255, 255)) + index += 1 + def on_cell_click(self, event): row = event.GetRow() col = event.GetCol() - + + if row == -1 or col == -1: + event.Skip() + return + if row < len(self.classnames) and col < len(self.classnames): true_class = self.classnames[row] pred_class = self.classnames[col] @@ -2277,13 +2333,13 @@ def on_cell_click(self, event): key = (true_class, pred_class) examples = self.example_map.get(key, []) - if not examples: - wx.MessageBox(f"No examples found for True='{true_class}' and Predicted='{pred_class}'.", "Info", wx.OK | wx.ICON_INFORMATION) - else: + if examples: viewer = ExampleViewerDialog(self, true_class, pred_class, examples) viewer.ShowModal() viewer.Destroy() - + else: + wx.MessageBox(f"No examples found for True: '{true_class}', Predicted: '{pred_class}'", "No Data", wx.OK | wx.ICON_INFORMATION) + event.Skip() class ExampleViewerDialog(wx.Dialog): From 7c76313cf9c22e7e3883174d989aed8de15185fb Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Mon, 27 Apr 2026 21:31:03 -0400 Subject: [PATCH 07/33] add NLP html base --- LabGym/gui_categorizer.py | 120 +++++++++++++++++++++++++++++++------- 1 file changed, 99 insertions(+), 21 deletions(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index e0013745..2ab2bd40 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -40,6 +40,7 @@ import wx.richtext import wx.lib.buttons as wxbuttons import wx.grid +import wx.html # Local application/library specific imports. logger.debug('importing %s ...', '.analyzebehavior') @@ -2168,7 +2169,6 @@ def init_ui(self): sizer = wx.BoxSizer(wx.VERTICAL) font = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) - # Top header with label and toggle button header_sizer = wx.BoxSizer(wx.HORIZONTAL) cm_label = wx.StaticText(self, label="Confusion Matrix:") cm_label.SetFont(font) @@ -2180,7 +2180,6 @@ def init_ui(self): sizer.Add(header_sizer, 0, wx.EXPAND | wx.ALL, 10) - # Grid setup self.cm_grid = wx.grid.Grid(self) self.cm_grid.CreateGrid(len(self.classnames), len(self.classnames)) @@ -2195,32 +2194,46 @@ def init_ui(self): self.cm_grid.AutoSize() sizer.Add(self.cm_grid, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) - # --- DROPDOWN HEADER FOR TABLE --- + bottom_dashboard_sizer = wx.BoxSizer(wx.HORIZONTAL) + + nlp_sizer = wx.BoxSizer(wx.VERTICAL) + nlp_label = wx.StaticText(self, label="What is the Confusion Matrix telling us?") + nlp_label.SetFont(font) + nlp_sizer.Add(nlp_label, 0, wx.BOTTOM, 5) + + self.nlp_html = wx.html.HtmlWindow(self, style=wx.html.HW_SCROLLBAR_AUTO | wx.BORDER_NONE) + html_content = self.generate_diagnostic_insights_html(top_n=3, support_threshold=50) + self.nlp_html.SetPage(html_content) + self.nlp_html.Bind(wx.html.EVT_HTML_LINK_CLICKED, self.on_insight_link_clicked) + + nlp_sizer.Add(self.nlp_html, 1, wx.EXPAND) + bottom_dashboard_sizer.Add(nlp_sizer, 1, wx.EXPAND | wx.RIGHT, 10) + + table_sizer = wx.BoxSizer(wx.VERTICAL) + table_header_sizer = wx.BoxSizer(wx.HORIZONTAL) self.table_label = wx.StaticText(self, label="Highlight behaviors below 0.60: ") self.table_label.SetFont(font) - self.metric_choice = wx.Choice(self, choices=["F1-score", "Precision", "Recall"]) - self.metric_choice.SetSelection(0) # Default to F1-score + self.metric_choice.SetSelection(0) self.metric_choice.Bind(wx.EVT_CHOICE, self.on_metric_change) table_header_sizer.Add(self.table_label, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5) table_header_sizer.Add(self.metric_choice, 0, wx.ALIGN_CENTER_VERTICAL) - - sizer.Add(table_header_sizer, 0, wx.ALL | wx.EXPAND, 10) + table_sizer.Add(table_header_sizer, 0, wx.BOTTOM, 5) - # --- TABLE SETUP --- self.list_ctrl = wx.ListCtrl(self, style=wx.LC_REPORT | wx.BORDER_SUNKEN) - self.list_ctrl.InsertColumn(0, "Behavior", width=150) - self.list_ctrl.InsertColumn(1, "Precision", width=100) - self.list_ctrl.InsertColumn(2, "Recall", width=100) - self.list_ctrl.InsertColumn(3, "F1-Score", width=100) - self.list_ctrl.InsertColumn(4, "Support", width=100) - - # Populate the table the first time it opens + self.list_ctrl.InsertColumn(0, "Behavior", width=120) + self.list_ctrl.InsertColumn(1, "Precision", width=80) + self.list_ctrl.InsertColumn(2, "Recall", width=80) + self.list_ctrl.InsertColumn(3, "F1", width=80) + self.list_ctrl.InsertColumn(4, "Support", width=80) self.update_table_data() - sizer.Add(self.list_ctrl, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) + table_sizer.Add(self.list_ctrl, 1, wx.EXPAND) + bottom_dashboard_sizer.Add(table_sizer, 1, wx.EXPAND | wx.LEFT, 10) + + sizer.Add(bottom_dashboard_sizer, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) btn_sizer = wx.BoxSizer(wx.HORIZONTAL) close_btn = wx.Button(self, wx.ID_CLOSE, "Close") @@ -2243,20 +2256,16 @@ def update_grid_data(self): if i < cm_rows and j < cm_cols: val = f"{data_to_use[i][j]}%" if self.is_normalized else str(data_to_use[i][j]) - # --- HEAT MAP LOGIC --- if i != j and self.cm[i][j] > 0: - # Off-diagonal errors: scale dark to bright red based on error rate err_pct = self.cm[i][j] / row_sum if row_sum > 0 else 0 intensity = min(1.0, err_pct / 0.5) r_val = int(40 + (215 * intensity)) bg_color = wx.Colour(r_val, 0, 0) elif i == j and row_sum > 0: - # Diagonal correct predictions: scale dark to bright green accuracy = self.cm[i][j] / row_sum if row_sum > 0 else 0 g_val = int(40 + (215 * accuracy)) bg_color = wx.Colour(0, g_val, 0) else: - # Empty or zero cells bg_color = wx.Colour(30, 30, 30) else: val = "0.0%" if self.is_normalized else "0" @@ -2279,6 +2288,22 @@ def on_toggle_cm(self, event): self.update_grid_data() + def on_insight_link_clicked(self, event): + """Highlights the specific grid cell when a user clicks the diagnostic text.""" + href = event.GetLinkInfo().GetHref() + + if href.startswith('cell:'): + coords = href.replace('cell:', '').split(',') + row, col = int(coords[0]), int(coords[1]) + + self.update_grid_data() + + self.cm_grid.SetCellBackgroundColour(row, col, wx.Colour(255, 203, 5)) + self.cm_grid.SetCellTextColour(row, col, wx.Colour(0, 0, 0)) + self.cm_grid.ForceRefresh() + + self.cm_grid.MakeCellVisible(row, col) + def on_metric_change(self, event): self.update_table_data() @@ -2308,7 +2333,6 @@ def update_table_data(self): self.list_ctrl.SetItem(index, 3, f"{f1:.2f}") self.list_ctrl.SetItem(index, 4, str(int(support))) - # Dynamic highlighting based on dropdown val_to_check = float(metrics.get(metric_key, 0.0)) if val_to_check < 0.60: self.list_ctrl.SetItemBackgroundColour(index, wx.Colour(150, 0, 0)) @@ -2318,6 +2342,60 @@ def update_table_data(self): self.list_ctrl.SetItemTextColour(index, wx.Colour(255, 255, 255)) index += 1 + def generate_diagnostic_insights_html(self, top_n=3, support_threshold=50): + cm_rows = len(self.cm) + errors = [] + perfect_classes = [] + + for i in range(cm_rows): + true_class = self.classnames[i] + support_true = self.report.get(true_class, {}).get('support', 0) + + if support_true == 0: + continue + + row_errors = sum(self.cm[i]) - self.cm[i][i] + if row_errors == 0: + perfect_classes.append(true_class) + + for j in range(cm_rows): + if i != j and self.cm[i][j] > 0: + errors.append((self.cm[i][j], i, j)) + + errors.sort(reverse=True, key=lambda x: x[0]) + + html = "" + + if not errors: + html += "

Everything looks great!

No major confusions detected.

" + else: + html += "

Here is where the Categorizer is struggling:

" + + for count, i, j in errors[:top_n]: + true_class = self.classnames[i] + pred_class = self.classnames[j] + support_true = self.report.get(true_class, {}).get('support', 0) + support_pred = self.report.get(pred_class, {}).get('support', 0) + + link = f"{true_class} → {pred_class}" + + html += "
" + + if support_true >= support_threshold and support_pred >= support_threshold: + html += f"

{link} ({count} errors)

Diagnosis: Both behaviors have robust training data. Because the AI is still confusing them, they might be visually redundant. Consider merging these labels.

" + else: + lowest_class = true_class if support_true < support_pred else pred_class + html += f"

{link} ({count} errors)

Diagnosis: The model hasn't seen enough of {lowest_class} to learn it well. Adding more video examples should help clear this up.

" + + html += "
" + + if perfect_classes: + html += "

What's working perfectly:

" + html += "

Zero confusions predicting: " + ", ".join(perfect_classes) + "

" + + html += "" + return html + def on_cell_click(self, event): row = event.GetRow() col = event.GetCol() From 8083fc888ddd071fd4bf04c01ee346ec8236d0dc Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Thu, 30 Apr 2026 13:32:36 -0400 Subject: [PATCH 08/33] NLP tabs and clickable entries --- LabGym/gui_categorizer.py | 247 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 234 insertions(+), 13 deletions(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 2ab2bd40..fbb1541e 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2191,22 +2191,41 @@ def init_ui(self): self.update_grid_data() + self.cm_grid.SetRowLabelSize(wx.grid.GRID_AUTOSIZE) + self.cm_grid.SetColLabelSize(wx.grid.GRID_AUTOSIZE) + self.cm_grid.AutoSize() sizer.Add(self.cm_grid, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) bottom_dashboard_sizer = wx.BoxSizer(wx.HORIZONTAL) nlp_sizer = wx.BoxSizer(wx.VERTICAL) - nlp_label = wx.StaticText(self, label="What is the Confusion Matrix telling us?") - nlp_label.SetFont(font) - nlp_sizer.Add(nlp_label, 0, wx.BOTTOM, 5) + + self.synopsis_label = wx.StaticText(self, label="Analyzing model performance...") + self.synopsis_label.SetFont(font) + nlp_sizer.Add(self.synopsis_label, 0, wx.BOTTOM | wx.ALL, 5) + + btn_row_sizer = wx.BoxSizer(wx.HORIZONTAL) + self.btn_major = wx.Button(self, label="🔴 Major Confusions") + self.btn_minor = wx.Button(self, label="🟡 Minor Confusions") + self.btn_successes = wx.Button(self, label="🟢 Successes") + self.btn_help = wx.Button(self, label="🔵 What is this?") + + self.btn_major.Bind(wx.EVT_BUTTON, self.show_major_confusions_view) + self.btn_minor.Bind(wx.EVT_BUTTON, self.show_minor_confusions_view) + self.btn_successes.Bind(wx.EVT_BUTTON, self.show_successes_view) + self.btn_help.Bind(wx.EVT_BUTTON, self.show_help_view) + + btn_row_sizer.Add(self.btn_major, 0, wx.RIGHT, 5) + btn_row_sizer.Add(self.btn_minor, 0, wx.RIGHT, 5) + btn_row_sizer.Add(self.btn_successes, 0, wx.RIGHT, 5) + btn_row_sizer.Add(self.btn_help, 0, 0, 0) + nlp_sizer.Add(btn_row_sizer, 0, wx.BOTTOM | wx.LEFT, 5) self.nlp_html = wx.html.HtmlWindow(self, style=wx.html.HW_SCROLLBAR_AUTO | wx.BORDER_NONE) - html_content = self.generate_diagnostic_insights_html(top_n=3, support_threshold=50) - self.nlp_html.SetPage(html_content) self.nlp_html.Bind(wx.html.EVT_HTML_LINK_CLICKED, self.on_insight_link_clicked) - nlp_sizer.Add(self.nlp_html, 1, wx.EXPAND) + nlp_sizer.Add(self.nlp_html, 1, wx.EXPAND | wx.ALL, 5) bottom_dashboard_sizer.Add(nlp_sizer, 1, wx.EXPAND | wx.RIGHT, 10) table_sizer = wx.BoxSizer(wx.VERTICAL) @@ -2241,6 +2260,9 @@ def init_ui(self): btn_sizer.Add(close_btn, 0, wx.ALL, 10) sizer.Add(btn_sizer, 0, wx.ALIGN_RIGHT) + self.analyze_confusion_data() + self.show_major_confusions_view(None) + self.SetSizer(sizer) self.Layout() @@ -2289,21 +2311,218 @@ def on_toggle_cm(self, event): self.update_grid_data() def on_insight_link_clicked(self, event): - """Highlights the specific grid cell when a user clicks the diagnostic text.""" + """Highlights the specific grid cell or row when a user clicks the diagnostic text.""" href = event.GetLinkInfo().GetHref() + self.update_grid_data() + if href.startswith('cell:'): coords = href.replace('cell:', '').split(',') row, col = int(coords[0]), int(coords[1]) - - self.update_grid_data() - self.cm_grid.SetCellBackgroundColour(row, col, wx.Colour(255, 203, 5)) self.cm_grid.SetCellTextColour(row, col, wx.Colour(0, 0, 0)) - self.cm_grid.ForceRefresh() - self.cm_grid.MakeCellVisible(row, col) + elif href.startswith('row:'): + row = int(href.replace('row:', '')) + self.cm_grid.MakeCellVisible(row, row) + + self.cm_grid.SetCellBackgroundColour(row, row, wx.Colour(0, 255, 255)) + self.cm_grid.SetCellTextColour(row, row, wx.Colour(0, 0, 0)) + + cm_rows = len(self.cm) + confusions = [] + for j in range(cm_rows): + if row != j and self.cm[row][j] > 0: + confusions.append((self.cm[row][j], j)) + + confusions.sort(reverse=True, key=lambda x: x[0]) + for err_val, col in confusions[:3]: + self.cm_grid.SetCellBackgroundColour(row, col, wx.Colour(255, 203, 5)) + self.cm_grid.SetCellTextColour(row, col, wx.Colour(0, 0, 0)) + + self.cm_grid.ForceRefresh() + self.cm_grid.ClearSelection() + + def analyze_confusion_data(self): + """Runs once to pre-calculate errors and successes using proportional math.""" + cm_rows = len(self.cm) + self.nlp_major = [] + self.nlp_minor = [] + self.nlp_success = [] + self.nlp_meaningless = [] + + total_support = sum(self.report.get(self.classnames[i], {}).get('support', 0) for i in range(cm_rows)) + + for i in range(cm_rows): + true_class = self.classnames[i] + metrics = self.report.get(true_class, {}) + support = float(metrics.get('support', 0)) + f1_score = float(metrics.get('f1-score', 0.0)) + + if support == 0: + continue + + min_support_threshold = max(20, total_support * 0.01) + if support < min_support_threshold: + self.nlp_meaningless.append(true_class) + continue + + if f1_score >= 0.85: + self.nlp_success.append({ + 'index': i, + 'class': true_class, + 'f1': f1_score, + 'support': support + }) + continue + + found_major_confusion = False + for j in range(cm_rows): + if i != j and self.cm[i][j] > 0: + error_count = self.cm[i][j] + error_proportion = error_count / support + + if error_proportion >= 0.10: + self.nlp_major.append((error_count, i, j, error_proportion)) + found_major_confusion = True + + if not found_major_confusion: + row_errors = sum(self.cm[i]) - self.cm[i][i] + pct_errors = (row_errors / support) * 100 if support > 0 else 0 + + specific_confusions = [] + for j in range(cm_rows): + if i != j and self.cm[i][j] > 0: + specific_confusions.append((self.cm[i][j], self.classnames[j])) + + specific_confusions.sort(reverse=True, key=lambda x: x[0]) + top_specifics = specific_confusions[:3] + + self.nlp_minor.append({ + 'index': i, + 'class': true_class, + 'support': support, + 'total_errors': row_errors, + 'pct_errors': pct_errors, + 'top_confusions': top_specifics + }) + + self.nlp_major.sort(reverse=True, key=lambda x: x[0]) + + major_count = len(self.nlp_major) + if major_count == 0: + self.synopsis_label.SetLabel("No major systematic confusions detected. Model looks great!") + else: + self.synopsis_label.SetLabel(f"{major_count} major systematic confusions detected. See Confusions for analysis.") + + + def show_major_confusions_view(self, event=None): + html = "" + + if not self.nlp_major: + html += "

Everything looks great!

No major systematic confusions detected.

" + else: + html += "

Major Systematic Confusions:

" + for count, i, j, prop in self.nlp_major[:5]: + true_class = self.classnames[i] + pred_class = self.classnames[j] + support_true = self.report.get(true_class, {}).get('support', 0) + support_pred = self.report.get(pred_class, {}).get('support', 0) + prop_pct = round(prop * 100, 1) + + link = f"{true_class} → {pred_class}" + html += "
" + + error_txt = f"{count} errors, {prop_pct}% of {true_class} data" + + if support_true >= 50 and support_pred >= 50: + html += f"

{link} ({error_txt})

Diagnosis: Both behaviors have robust training data. Because the Categorizer systematically confuses them, they might be visually redundant. Consider merging these labels.

" + else: + lowest_class = true_class if support_true < support_pred else pred_class + html += f"

{link} ({error_txt})

Diagnosis: The Categorizer hasn't seen enough of {lowest_class} to learn it well. Adding more video examples should help clear this up.

" + html += "
" + + html += "" + self.nlp_html.SetPage(html) + + def show_minor_confusions_view(self, event=None): + html = "" + + if not self.nlp_minor: + html += "

Everything looks great!

No dispersed minor confusions detected.

" + else: + html += "

Dispersed / Minor Confusions:

" + html += "

The Categorizer struggles with these behaviors, but the mistakes are scattered across many categories rather than just one. This usually indicates weak feature extraction signals, highly variable subject movement, or simply, too few video examples.

" + + for mc in self.nlp_minor: + c_idx = mc['index'] + c_name = mc['class'] + supp = int(mc['support']) + errs = mc['total_errors'] + pct = round(mc['pct_errors'], 1) + + warning = " ⚠️ (Low Support)" if supp < 100 else "" + link = f"{c_name}" + + html += f"
" + html += f"

{link}{warning}
" + html += f"Support: {supp} examples | Total Errors: {errs} ({pct}% of data)

" + + if mc['top_confusions']: + html += "

Top confusions:

    " + for err_count, pred_class in mc['top_confusions']: + html += f"
  • To {pred_class}: {err_count} errors
  • " + html += "
" + html += "
" + + html += "" + self.nlp_html.SetPage(html) + + def show_successes_view(self, event=None): + html = "" + if self.nlp_success: + html += "

Performing Reliably (F1 ≥ 85%):

" + html += "

The Categorizer is successfully and consistently predicting the following behaviors:

" + html += "
    " + for sc in self.nlp_success: + c_idx = sc['index'] + c_name = sc['class'] + f1_pct = round(sc['f1'] * 100, 1) + supp = int(sc['support']) + + link = f"{c_name}" + html += f"
  • {link} ({f1_pct}% F1) [{supp} examples]
  • " + html += "
" + else: + html += "

Keep Tuning!

" + html += "

No behaviors have reached the 85% F1-score threshold. Check the Confusions tab to see where to improve the dataset.

" + + if self.nlp_meaningless: + html += "

Statistically Meaningless (Excluded):

" + html += "

The following classes have too few examples to accurately evaluate. They have been excluded from major error analysis:

" + html += "
    " + for mc in self.nlp_meaningless: + html += f"
  • {mc}
  • " + html += "
" + + html += "" + self.nlp_html.SetPage(html) + + def show_help_view(self, event=None): + """Generates the HTML for the layman's explanation.""" + html = """ + +

How to read this chart:

+

A Confusion Matrix is just a simple table that shows where the Categorizer gets confused.

+

Rows (Left): What the subject was actually doing (Ground Truth).

+

Columns (Top): What the Categorizer guessed the subject was doing (Prediction).

+

If you look at the diagonal line going from top-left to bottom-right, those are the correct guesses. Any numbers sitting outside that diagonal line represent mistakes!

+

You can click on any cell in the matrix to view the video examples of where the Categorizer either correctly or incorrectly guessed the behavior!

+ + """ + self.nlp_html.SetPage(html) + def on_metric_change(self, event): self.update_table_data() @@ -2382,7 +2601,7 @@ def generate_diagnostic_insights_html(self, top_n=3, support_threshold=50): html += "
" if support_true >= support_threshold and support_pred >= support_threshold: - html += f"

{link} ({count} errors)

Diagnosis: Both behaviors have robust training data. Because the AI is still confusing them, they might be visually redundant. Consider merging these labels.

" + html += f"

{link} ({count} errors)

Diagnosis: Both behaviors have robust training data. Because the Categorizer is still confusing them, they might be visually redundant. Consider merging these labels.

" else: lowest_class = true_class if support_true < support_pred else pred_class html += f"

{link} ({count} errors)

Diagnosis: The model hasn't seen enough of {lowest_class} to learn it well. Adding more video examples should help clear this up.

" @@ -2400,6 +2619,8 @@ def on_cell_click(self, event): row = event.GetRow() col = event.GetCol() + self.cm_grid.ClearSelection() + if row == -1 or col == -1: event.Skip() return From 1c9ac1739d490dca5fb9229ff192df0efacca135 Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Mon, 11 May 2026 09:39:08 -0400 Subject: [PATCH 09/33] training module GUI --- LabGym/gui_main.py | 76 ++++++++++++++++++++++++---------------------- 1 file changed, 39 insertions(+), 37 deletions(-) diff --git a/LabGym/gui_main.py b/LabGym/gui_main.py index df033cc8..708b90ef 100644 --- a/LabGym/gui_main.py +++ b/LabGym/gui_main.py @@ -185,115 +185,117 @@ def __init__(self, parent): self.notebook = parent self.display_window() - def display_window(self): panel = self - boxsizer=wx.BoxSizer(wx.VERTICAL) - boxsizer.Add(0,60,0) + main_sizer = wx.BoxSizer(wx.VERTICAL) + main_sizer.Add(0, 50, 0) + + columns_sizer = wx.BoxSizer(wx.HORIZONTAL) + + header_font = wx.Font(14, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) + + detector_sizer = wx.BoxSizer(wx.VERTICAL) + + text_detector = wx.StaticText(panel, label='Detector Pipeline') + text_detector.SetFont(header_font) + detector_sizer.Add(text_detector, 0, wx.ALIGN_CENTER | wx.BOTTOM, 25) button_generateimages=wx.Button(panel,label='Generate Image Examples',size=(300,40)) button_generateimages.Bind(wx.EVT_BUTTON,self.generate_images) wx.Button.SetToolTip(button_generateimages,'Extract frames from videos for annotating animals / objects in them so that they can be used to train a Detector to detect animals / objects of your interest. See Extended Guide for how to select images to annotate.') - boxsizer.Add(button_generateimages,0,wx.ALIGN_CENTER,10) - boxsizer.Add(0,5,0) + detector_sizer.Add(button_generateimages,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) - link_annotate=create_hyperlink(panel,'\nAnnotate images with EZannot\n','https://github.com/yujiahu415/EZannot') - boxsizer.Add(link_annotate,0,wx.ALIGN_CENTER,10) - boxsizer.Add(0,5,0) + link_annotate=create_hyperlink(panel,'Annotate images with EZannot','https://github.com/yujiahu415/EZannot') + detector_sizer.Add(link_annotate,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) button_traindetectors=wx.Button(panel,label='Train Detectors',size=(300,40)) button_traindetectors.Bind(wx.EVT_BUTTON,self.train_detectors) wx.Button.SetToolTip(button_traindetectors,'There are two detection methods in LabGym, the Detector-based method is more versatile (useful in any recording conditions and complex interactive behaviors) but slower than the other background subtraction-based method (requires static background and stable illumination in videos).') - boxsizer.Add(button_traindetectors,0,wx.ALIGN_CENTER,10) - boxsizer.Add(0,5,0) + detector_sizer.Add(button_traindetectors,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) button_testdetectors=wx.Button(panel,label='Test Detectors',size=(300,40)) button_testdetectors.Bind(wx.EVT_BUTTON,self.test_detectors) wx.Button.SetToolTip(button_testdetectors,'Test trained Detectors on the annotated ground-truth image dataset (similar to the image dataset used for training a Detector).') - boxsizer.Add(button_testdetectors,0,wx.ALIGN_CENTER,10) - boxsizer.Add(0,50,0) + detector_sizer.Add(button_testdetectors,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) + + + divider_line = wx.StaticLine(panel, style=wx.LI_VERTICAL) + + + categorizer_sizer = wx.BoxSizer(wx.VERTICAL) + + text_categorizer = wx.StaticText(panel, label='Categorizer Pipeline') + text_categorizer.SetFont(header_font) + categorizer_sizer.Add(text_categorizer, 0, wx.ALIGN_CENTER | wx.BOTTOM, 25) button_generatebehaviorexamples=wx.Button(panel,label='Generate Behavior Examples',size=(300,40)) button_generatebehaviorexamples.Bind(wx.EVT_BUTTON,self.generate_behaviorexamples) wx.Button.SetToolTip(button_generatebehaviorexamples,'Generate behavior examples for sorting them so that they can be used to teach a Categorizer to recognize behaviors defined by you.') - boxsizer.Add(button_generatebehaviorexamples,0,wx.ALIGN_CENTER,10) - boxsizer.Add(0,5,0) + categorizer_sizer.Add(button_generatebehaviorexamples,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) button_sortbehaviorexamples=wx.Button(panel,label='Sort Behavior Examples',size=(300,40)) button_sortbehaviorexamples.Bind(wx.EVT_BUTTON,self.sort_behaviorexamples) wx.Button.SetToolTip(button_sortbehaviorexamples,'Set shortcut keys for behavior categories to help sorting the behavior examples in an easier way. See Extended Guide for how to select and sort the behavior examples.') - boxsizer.Add(button_sortbehaviorexamples,0,wx.ALIGN_CENTER,10) - boxsizer.Add(0,5,0) + categorizer_sizer.Add(button_sortbehaviorexamples,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) button_traincategorizers=wx.Button(panel,label='Train Categorizers',size=(300,40)) button_traincategorizers.Bind(wx.EVT_BUTTON,self.train_categorizers) wx.Button.SetToolTip(button_traincategorizers,'Customize a Categorizer and use the sorted behavior examples to train it so that it can recognize the behaviors of your interest during analysis.') - boxsizer.Add(button_traincategorizers,0,wx.ALIGN_CENTER,10) - boxsizer.Add(0,5,0) + categorizer_sizer.Add(button_traincategorizers,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) button_testcategorizers=wx.Button(panel,label='Test Categorizers',size=(300,40)) button_testcategorizers.Bind(wx.EVT_BUTTON,self.test_categorizers) wx.Button.SetToolTip(button_testcategorizers,'Test trained Categorizers on the sorted ground-truth behavior examples (similar to the behavior examples used for training a Categorizer).') - boxsizer.Add(button_testcategorizers,0,wx.ALIGN_CENTER,10) - boxsizer.Add(0,50,0) + categorizer_sizer.Add(button_testcategorizers,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) - panel.SetSizer(boxsizer) + columns_sizer.Add(detector_sizer, 1, wx.EXPAND | wx.RIGHT, 40) + columns_sizer.Add(divider_line, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 20) + columns_sizer.Add(categorizer_sizer, 1, wx.EXPAND | wx.LEFT, 40) + + main_sizer.Add(columns_sizer, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 50) + + panel.SetSizer(main_sizer) self.Centre() self.Show(True) - def generate_images(self,event): """Open the Generate Image Examples panel.""" - title = 'Generate Image Examples' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_GenerateImages(self.notebook), title) - def train_detectors(self,event): """Open the Train Detectors panel.""" - title = 'Train Detectors' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_TrainDetectors(self.notebook), title) - def test_detectors(self,event): """Open the Test Detectors panel.""" - title = 'Test Detectors' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_TestDetectors(self.notebook), title) - def generate_behaviorexamples(self,event): """Open the Generate Behavior Examples panel.""" - title = 'Generate Behavior Examples' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_GenerateExamples(self.notebook), title) - def sort_behaviorexamples(self,event): """Open the Sort Behavior Examples panel.""" - title = 'Sort Behavior Examples' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_SortBehaviors(self.notebook), title) - def train_categorizers(self,event): """Open the Train Categorizers panel.""" - title = 'Train Categorizers' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_TrainCategorizers(self.notebook), title) - def test_categorizers(self,event): """Open the Test Categorizers panel.""" - title = 'Test Categorizers' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_TestCategorizers(self.notebook), title) - class PanelLv1_AnalysisModule(wx.Panel): """The Analysis Module.""" @@ -378,7 +380,7 @@ def calculate_distances(self,event): title = 'Calculate Distances' add_or_select_notebook_page(self.notebook, lambda: PanelLv2_CalculateDistances(self.notebook), title) - + def state_transition_map(self,event): """Open the State Transition Map panel.""" From 4473cafd5155b06d1a4dcd9cdeade5314ecb41f4 Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Mon, 11 May 2026 12:42:59 -0400 Subject: [PATCH 10/33] fix uncontrolled ranking logic creep --- LabGym/gui_categorizer.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index fbb1541e..da7b1c31 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2413,8 +2413,10 @@ def analyze_confusion_data(self): major_count = len(self.nlp_major) if major_count == 0: self.synopsis_label.SetLabel("No major systematic confusions detected. Model looks great!") + elif major_count > 5: + self.synopsis_label.SetLabel(f"{major_count} major systematic confusions detected. Showing top 5 most severe.") else: - self.synopsis_label.SetLabel(f"{major_count} major systematic confusions detected. See Confusions for analysis.") + self.synopsis_label.SetLabel(f"{major_count} major systematic confusions detected.") def show_major_confusions_view(self, event=None): From 30b9c9781008a366f521a305faba810e9c021ac1 Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Tue, 12 May 2026 11:15:41 -0400 Subject: [PATCH 11/33] Implement Differential Diagnosis UI and immutable dataset cloning engine --- LabGym/gui_categorizer.py | 93 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index da7b1c31..9c3b5d9c 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2341,6 +2341,18 @@ def on_insight_link_clicked(self, event): self.cm_grid.SetCellBackgroundColour(row, col, wx.Colour(255, 203, 5)) self.cm_grid.SetCellTextColour(row, col, wx.Colour(0, 0, 0)) + elif href.startswith('action:'): + parts = href.split(':') + action_type = parts[1] + classes = parts[2].split(',') + source_class = classes[0] + target_class = classes[1] + + if action_type == 'add_data': + wx.MessageBox("To solve poor generalization, close the Test Categorizer and use the 'Generate/Sort Behavior Examples' modules to add more diverse data to the Training Set.", "Manual Action Required", wx.OK | wx.ICON_INFORMATION) + else: + self.execute_differential_action(action_type, source_class, target_class) + self.cm_grid.ForceRefresh() self.cm_grid.ClearSelection() @@ -2439,7 +2451,13 @@ def show_major_confusions_view(self, event=None): error_txt = f"{count} errors, {prop_pct}% of {true_class} data" if support_true >= 50 and support_pred >= 50: - html += f"

{link} ({error_txt})

Diagnosis: Both behaviors have robust training data. Because the Categorizer systematically confuses them, they might be visually redundant. Consider merging these labels.

" + html += f"

{link} ({error_txt})

" + html += "

Differential Diagnosis:

" + html += "" else: lowest_class = true_class if support_true < support_pred else pred_class html += f"

{link} ({error_txt})

Diagnosis: The Categorizer hasn't seen enough of {lowest_class} to learn it well. Adding more video examples should help clear this up.

" @@ -2643,6 +2661,79 @@ def on_cell_click(self, event): event.Skip() + def execute_differential_action(self, action_type, source_class, target_class): + """Safely clones the dataset and applies the requested OS-level action.""" + dlg = wx.TextEntryDialog(self, f"To preserve reproducibility, LabGym will clone the dataset before modifying it.\n\nEnter a name for the new dataset folder:", "Dataset Versioning", "dataset_v2") + if dlg.ShowModal() != wx.ID_OK: + dlg.Destroy() + return + new_dataset_name = dlg.GetValue() + dlg.Destroy() + + if not new_dataset_name: + return + + source_files = [] + for (t, p), files in self.example_map.items(): + if t == source_class: + source_files.extend(files) + + if not source_files: + wx.MessageBox(f"Could not locate the files for '{source_class}'.", "Error", wx.OK | wx.ICON_ERROR) + return + + source_class_dir = os.path.dirname(source_files[0]) + original_dataset_dir = os.path.dirname(source_class_dir) + parent_dir = os.path.dirname(original_dataset_dir) + + cloned_dataset_dir = os.path.join(parent_dir, new_dataset_name) + + try: + total_size = sum(os.path.getsize(os.path.join(dirpath, f)) for dirpath, _, filenames in os.walk(original_dataset_dir) for f in filenames) + total_size_mb = total_size / (1024 * 1024) + + total, used, free = shutil.disk_usage(parent_dir) + if total_size > free: + wx.MessageBox(f"Not enough disk space to clone dataset.\nRequired: {total_size_mb:.2f} MB\nAvailable: {free / (1024*1024):.2f} MB", "Disk Space Error", wx.OK | wx.ICON_ERROR) + return + + wx.BeginBusyCursor() + shutil.copytree(original_dataset_dir, cloned_dataset_dir) + + if action_type == 'merge': + cloned_source_dir = os.path.join(cloned_dataset_dir, source_class) + cloned_target_dir = os.path.join(cloned_dataset_dir, target_class) + + if not os.path.exists(cloned_target_dir): + os.makedirs(cloned_target_dir) + + for filename in os.listdir(cloned_source_dir): + shutil.move(os.path.join(cloned_source_dir, filename), os.path.join(cloned_target_dir, filename)) + shutil.rmtree(cloned_source_dir) + + action_msg = f"Merged '{source_class}' into '{target_class}'." + + elif action_type == 'extract': + cloned_source_dir = os.path.join(cloned_dataset_dir, source_class) + if sys.platform == "win32": + os.startfile(cloned_source_dir) + elif sys.platform == "darwin": + subprocess.call(["open", cloned_source_dir]) + else: + subprocess.call(["xdg-open", cloned_source_dir]) + + action_msg = f"Opened '{source_class}' folder for manual extraction of the emergent behavior." + + wx.EndBusyCursor() + wx.MessageBox(f"Successfully cloned dataset to '{new_dataset_name}'.\n{action_msg}\n\nPlease point your Training Module to this new dataset for future iterations.", "Success", wx.OK | wx.ICON_INFORMATION) + + except PermissionError: + wx.EndBusyCursor() + wx.MessageBox("LabGym does not have permission to write to this directory. Check your folder permissions or network drive status.", "Permission Error", wx.OK | wx.ICON_ERROR) + except Exception as e: + wx.EndBusyCursor() + wx.MessageBox(f"An OS error occurred:\n{e}", "System Error", wx.OK | wx.ICON_ERROR) + class ExampleViewerDialog(wx.Dialog): def __init__(self, parent, true_class, pred_class, examples): title = f"Reviewing Examples: True '{true_class}' -> Predicted '{pred_class}'" From 2c40f3b622c07e8ba25f602c7c5325181438195c Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Tue, 12 May 2026 13:40:45 -0400 Subject: [PATCH 12/33] merge visualization --- LabGym/gui_categorizer.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 9c3b5d9c..aed19b98 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2713,6 +2713,13 @@ def execute_differential_action(self, action_type, source_class, target_class): action_msg = f"Merged '{source_class}' into '{target_class}'." + if sys.platform == "win32": + os.startfile(cloned_target_dir) + elif sys.platform == "darwin": + subprocess.call(["open", cloned_target_dir]) + else: + subprocess.call(["xdg-open", cloned_target_dir]) + elif action_type == 'extract': cloned_source_dir = os.path.join(cloned_dataset_dir, source_class) if sys.platform == "win32": From 7d4c24e1b4145eb10486ad0107e8c544d64816f8 Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Tue, 23 Jun 2026 09:28:09 -0400 Subject: [PATCH 13/33] feat: complete triage action plan pdf and h3 variance references --- LabGym/gui_categorizer.py | 567 +++++++++++++++++++++++++++++++++++++- 1 file changed, 561 insertions(+), 6 deletions(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index aed19b98..b6b4ee29 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2143,7 +2143,7 @@ def remove_categorizer(self,event): class AutomatedDiagnosticsDialog(wx.Dialog): def __init__(self, parent, report, cm, classnames, example_map): - super().__init__(parent, title="Automated Diagnostics - Test Results", size=(800, 600), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) + super().__init__(parent, title="Automated Diagnostics - Test Results", size=(1000, 800), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) self.report = report self.cm = cm @@ -2154,6 +2154,8 @@ def __init__(self, parent, report, cm, classnames, example_map): self.is_normalized = False self.init_ui() + + self.Maximize(True) def calculate_normalized_cm(self, cm): norm_cm = [] @@ -2194,6 +2196,9 @@ def init_ui(self): self.cm_grid.SetRowLabelSize(wx.grid.GRID_AUTOSIZE) self.cm_grid.SetColLabelSize(wx.grid.GRID_AUTOSIZE) + self.cm_grid.DisableDragRowSize() + self.cm_grid.DisableDragColSize() + self.cm_grid.AutoSize() sizer.Add(self.cm_grid, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) @@ -2220,8 +2225,26 @@ def init_ui(self): btn_row_sizer.Add(self.btn_minor, 0, wx.RIGHT, 5) btn_row_sizer.Add(self.btn_successes, 0, wx.RIGHT, 5) btn_row_sizer.Add(self.btn_help, 0, 0, 0) + + self.btn_triage = wx.Button(self, label="📝 Build Triage Plan") + self.btn_triage.Bind(wx.EVT_BUTTON, self.on_build_triage) + self.btn_triage.SetForegroundColour(wx.Colour(255, 203, 5)) + btn_row_sizer.Add(self.btn_triage, 0, wx.LEFT, 15) + nlp_sizer.Add(btn_row_sizer, 0, wx.BOTTOM | wx.LEFT, 5) + sort_sizer = wx.BoxSizer(wx.HORIZONTAL) + self.sort_label = wx.StaticText(self, label="Rank Insights By: ") + sort_sizer.Add(self.sort_label, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5) + + self.sort_dropdown = wx.Choice(self, choices=["Instances", "Proportion"]) + self.sort_dropdown.SetSelection(0) + self.sort_dropdown.Bind(wx.EVT_CHOICE, self.on_sort_changed) + sort_sizer.Add(self.sort_dropdown, 0, wx.ALIGN_CENTER_VERTICAL) + + nlp_sizer.Add(sort_sizer, 0, wx.BOTTOM | wx.LEFT, 5) + + self.nlp_html = wx.html.HtmlWindow(self, style=wx.html.HW_SCROLLBAR_AUTO | wx.BORDER_NONE) self.nlp_html.Bind(wx.html.EVT_HTML_LINK_CLICKED, self.on_insight_link_clicked) @@ -2261,11 +2284,45 @@ def init_ui(self): sizer.Add(btn_sizer, 0, wx.ALIGN_RIGHT) self.analyze_confusion_data() - self.show_major_confusions_view(None) + self.show_help_view(None) self.SetSizer(sizer) self.Layout() + def on_build_triage(self, event): + """Gathers all confusions and launches the Triage Builder.""" + all_confusions = [] + + # Grab Major Confusions + for count, i, j, prop in self.nlp_major: + item = f"{self.classnames[i]} -> {self.classnames[j]} ({count} errors)" + if item not in all_confusions: + all_confusions.append(item) + + # Grab Minor Confusions + for mc in self.nlp_minor: + for err_count, pred_class in mc['top_confusions']: + item = f"{mc['class']} -> {pred_class} ({err_count} errors)" + if item not in all_confusions: + all_confusions.append(item) + + if not all_confusions: + wx.MessageBox("No confusions detected to triage!", "All Clear", wx.OK | wx.ICON_INFORMATION) + return + + dialog = TriageBuilderDialog(self, all_confusions, self.example_map, self.report, self.cm, self.classnames) + dialog.ShowModal() + dialog.Destroy() + + def on_sort_changed(self, event): + """Re-sorts the NLP data and refreshes the views when the dropdown changes.""" + self.analyze_confusion_data() + + if getattr(self, 'current_view', 'major') == 'minor': + self.show_minor_confusions_view(None) + else: + self.show_major_confusions_view(None) + def update_grid_data(self): cm_rows = len(self.cm) cm_cols = len(self.cm[0]) if cm_rows > 0 else 0 @@ -2420,7 +2477,16 @@ def analyze_confusion_data(self): 'top_confusions': top_specifics }) - self.nlp_major.sort(reverse=True, key=lambda x: x[0]) + + sort_mode = self.sort_dropdown.GetStringSelection() + + if sort_mode == "Proportion": + self.nlp_major.sort(reverse=True, key=lambda x: x[3]) + self.nlp_minor.sort(reverse=True, key=lambda x: x['pct_errors']) + else: + self.nlp_major.sort(reverse=True, key=lambda x: x[0]) + self.nlp_minor.sort(reverse=True, key=lambda x: x['total_errors']) + major_count = len(self.nlp_major) if major_count == 0: @@ -2432,6 +2498,11 @@ def analyze_confusion_data(self): def show_major_confusions_view(self, event=None): + self.current_view = 'major' + self.sort_label.Show(True) + self.sort_dropdown.Show(True) + self.Layout() + html = "" if not self.nlp_major: @@ -2467,7 +2538,13 @@ def show_major_confusions_view(self, event=None): self.nlp_html.SetPage(html) def show_minor_confusions_view(self, event=None): + self.current_view = 'minor' + self.sort_label.Show(True) + self.sort_dropdown.Show(True) + self.Layout() + html = "" + if not self.nlp_minor: html += "

Everything looks great!

No dispersed minor confusions detected.

" @@ -2500,7 +2577,13 @@ def show_minor_confusions_view(self, event=None): self.nlp_html.SetPage(html) def show_successes_view(self, event=None): + self.current_view = 'successes' + self.sort_label.Show(False) + self.sort_dropdown.Show(False) + self.Layout() + html = "" + if self.nlp_success: html += "

Performing Reliably (F1 ≥ 85%):

" html += "

The Categorizer is successfully and consistently predicting the following behaviors:

" @@ -2531,6 +2614,11 @@ def show_successes_view(self, event=None): def show_help_view(self, event=None): """Generates the HTML for the layman's explanation.""" + self.current_view = 'help' + self.sort_label.Show(False) + self.sort_dropdown.Show(False) + self.Layout() + html = """

How to read this chart:

@@ -2642,7 +2730,6 @@ def on_cell_click(self, event): self.cm_grid.ClearSelection() if row == -1 or col == -1: - event.Skip() return if row < len(self.classnames) and col < len(self.classnames): @@ -2658,8 +2745,8 @@ def on_cell_click(self, event): viewer.Destroy() else: wx.MessageBox(f"No examples found for True: '{true_class}', Predicted: '{pred_class}'", "No Data", wx.OK | wx.ICON_INFORMATION) + - event.Skip() def execute_differential_action(self, action_type, source_class, target_class): """Safely clones the dataset and applies the requested OS-level action.""" @@ -2781,4 +2868,472 @@ def on_double_click(self, event): else: subprocess.call(["xdg-open", filepath]) except Exception as e: - wx.MessageBox(f"Failed to open file:\n{e}", "Error", wx.OK | wx.ICON_ERROR) \ No newline at end of file + wx.MessageBox(f"Failed to open file:\n{e}", "Error", wx.OK | wx.ICON_ERROR) + + +class TriageBuilderDialog(wx.Dialog): + def __init__(self, parent, confusions_list, example_map, report, cm, classnames): + super().__init__(parent, title="Triage Action Plan Builder", size=(900, 600), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) + self.confusions_list = confusions_list + self.example_map = example_map + + # ---> NEW: Store the variables so the PDF generator can use them <--- + self.report = report + self.cm = cm + self.classnames = classnames + + self.init_ui() + + def init_ui(self): + main_sizer = wx.BoxSizer(wx.VERTICAL) + + # --- TITLE HEADER --- + title_lbl = wx.StaticText(self, label="Assign confusions to a root-cause hypothesis to generate your action plan.") + title_font = wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) + title_lbl.SetFont(title_font) + title_lbl.SetForegroundColour(wx.Colour(255, 203, 5)) # Maize for primary branding + main_sizer.Add(title_lbl, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 15) + + # Layout: 3 Columns + columns_sizer = wx.BoxSizer(wx.HORIZONTAL) + + # --- LEFT COLUMN: Unassigned --- + left_sizer = wx.BoxSizer(wx.VERTICAL) + lbl_unassigned = wx.StaticText(self, label="📥 Unassigned Confusions:") + lbl_unassigned.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + left_sizer.Add(lbl_unassigned, 0, wx.BOTTOM, 8) + + self.lb_unassigned = wx.ListBox(self, choices=self.confusions_list, style=wx.LB_EXTENDED) + self.lb_unassigned.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) + left_sizer.Add(self.lb_unassigned, 1, wx.EXPAND) + columns_sizer.Add(left_sizer, 4, wx.EXPAND | wx.ALL, 10) + + # --- MIDDLE COLUMN: Transfer Buttons --- + # Fixed sizes prevent the awkward stretching seen in the screenshot + mid_sizer = wx.BoxSizer(wx.VERTICAL) + mid_sizer.AddStretchSpacer() + + btn_h1 = wx.Button(self, label="Hypothesis 1 (Merge) ➔", size=(190, 40)) + btn_h1.Bind(wx.EVT_BUTTON, lambda evt: self.move_items(self.lb_unassigned, self.lb_h1)) + mid_sizer.Add(btn_h1, 0, wx.BOTTOM | wx.ALIGN_CENTER_HORIZONTAL, 15) + + btn_h2 = wx.Button(self, label="Hypothesis 2 (Extract) ➔", size=(190, 40)) + btn_h2.Bind(wx.EVT_BUTTON, self.on_move_h2) + mid_sizer.Add(btn_h2, 0, wx.BOTTOM | wx.ALIGN_CENTER_HORIZONTAL, 15) + + btn_h3 = wx.Button(self, label="Hypothesis 3 (Add Data) ➔", size=(190, 40)) + btn_h3.Bind(wx.EVT_BUTTON, lambda evt: self.move_items(self.lb_unassigned, self.lb_h3)) + mid_sizer.Add(btn_h3, 0, wx.BOTTOM | wx.ALIGN_CENTER_HORIZONTAL, 15) + + btn_return = wx.Button(self, label="⬅ Return Selected", size=(190, 40)) + btn_return.Bind(wx.EVT_BUTTON, self.on_return_items) + mid_sizer.Add(btn_return, 0, wx.TOP | wx.ALIGN_CENTER_HORIZONTAL, 40) + + mid_sizer.AddStretchSpacer() + columns_sizer.Add(mid_sizer, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 10) + + # --- RIGHT COLUMN: The Buckets --- + right_sizer = wx.BoxSizer(wx.VERTICAL) + + lbl_h1 = wx.StaticText(self, label="🔗 H1: Redundant (Auto-Merged):") + lbl_h1.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + lbl_h1.SetForegroundColour(wx.Colour(100, 200, 100)) # Soft Green + right_sizer.Add(lbl_h1, 0, wx.BOTTOM, 4) + self.lb_h1 = wx.ListBox(self, style=wx.LB_EXTENDED) + right_sizer.Add(self.lb_h1, 1, wx.EXPAND | wx.BOTTOM, 10) + + lbl_h2 = wx.StaticText(self, label="✂️ H2: Emergent (Manual Extraction):") + lbl_h2.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + lbl_h2.SetForegroundColour(wx.Colour(100, 150, 255)) # Soft Blue + right_sizer.Add(lbl_h2, 0, wx.BOTTOM, 4) + self.lb_h2 = wx.ListBox(self, style=wx.LB_EXTENDED) + right_sizer.Add(self.lb_h2, 1, wx.EXPAND | wx.BOTTOM, 10) + + lbl_h3 = wx.StaticText(self, label="📊 H3: Poor Generalization (Needs Data):") + lbl_h3.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + lbl_h3.SetForegroundColour(wx.Colour(255, 150, 100)) # Soft Orange + right_sizer.Add(lbl_h3, 0, wx.BOTTOM, 4) + self.lb_h3 = wx.ListBox(self, style=wx.LB_EXTENDED) + right_sizer.Add(self.lb_h3, 1, wx.EXPAND) + + columns_sizer.Add(right_sizer, 5, wx.EXPAND | wx.ALL, 10) + + main_sizer.Add(columns_sizer, 1, wx.EXPAND) + + # --- FOOTER --- + footer_sizer = wx.BoxSizer(wx.HORIZONTAL) + btn_finish = wx.Button(self, label="Finish and Generate Report", size=(220, 40)) + btn_finish.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + btn_finish.SetForegroundColour(wx.Colour(100, 200, 100)) + btn_finish.Bind(wx.EVT_BUTTON, self.on_finish) + footer_sizer.Add(btn_finish, 0, wx.ALL, 10) + + btn_cancel = wx.Button(self, wx.ID_CANCEL, "Cancel", size=(100, 40)) + footer_sizer.Add(btn_cancel, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 10) + + main_sizer.Add(footer_sizer, 0, wx.ALIGN_RIGHT) + self.SetSizer(main_sizer) + self.Layout() + + def move_items(self, source_lb, target_lb, append_text=""): + selections = source_lb.GetSelections() + if not selections: + return + + for idx in reversed(selections): + item_text = source_lb.GetString(idx) + target_lb.Append(f"{item_text} {append_text}") + source_lb.Delete(idx) + + def on_move_h2(self, event): + if not self.lb_unassigned.GetSelections(): + return + + dlg = wx.TextEntryDialog(self, "What is the name of this new emergent behavior?", "Define Emergent Class") + if dlg.ShowModal() == wx.ID_OK: + new_name = dlg.GetValue().strip() + if new_name: + self.move_items(self.lb_unassigned, self.lb_h2, f"[NEW: {new_name}]") + dlg.Destroy() + + def on_return_items(self, event): + """Returns selected items from any right-side bucket back to unassigned.""" + for lb in [self.lb_h1, self.lb_h2, self.lb_h3]: + selections = lb.GetSelections() + for idx in reversed(selections): + text = lb.GetString(idx) + if "[NEW:" in text: + text = text.split(" [NEW:")[0] + self.lb_unassigned.Append(text) + lb.Delete(idx) + + def on_finish(self, event): + # 1. Ask for the new versioned dataset name + dlg = wx.TextEntryDialog(self, "Enter a name for the new versioned dataset folder:", "Dataset Versioning", "dataset_v2") + if dlg.ShowModal() != wx.ID_OK: + dlg.Destroy() + return + new_dataset_name = dlg.GetValue().strip() + dlg.Destroy() + + if not new_dataset_name: + return + + # 2. Deduce the base directory path from the example map + sample_file = None + for files in self.example_map.values(): + if files: + sample_file = files[0] + break + + if not sample_file: + wx.MessageBox("Could not locate source files to clone.", "Error", wx.OK | wx.ICON_ERROR) + return + + original_dataset_dir = os.path.dirname(os.path.dirname(sample_file)) + parent_dir = os.path.dirname(original_dataset_dir) + cloned_dataset_dir = os.path.join(parent_dir, new_dataset_name) + + # 3. Check Disk Space & Clone + try: + total_size = sum(os.path.getsize(os.path.join(dirpath, f)) for dirpath, _, filenames in os.walk(original_dataset_dir) for f in filenames) + total_size_mb = total_size / (1024 * 1024) + + total, used, free = shutil.disk_usage(parent_dir) + if total_size > free: + wx.MessageBox(f"Not enough disk space to clone dataset.\nRequired: {total_size_mb:.2f} MB\nAvailable: {free / (1024*1024):.2f} MB", "Disk Space Error", wx.OK | wx.ICON_ERROR) + return + + wx.BeginBusyCursor() + shutil.copytree(original_dataset_dir, cloned_dataset_dir) + + # 4. Perform the OS-level H1 Merges inside the cloned directory + for i in range(self.lb_h1.GetCount()): + text = self.lb_h1.GetString(i) + source_class = text.split(" -> ")[0].strip() + target_class = text.split(" -> ")[1].split(" (")[0].strip() + + cloned_source_dir = os.path.join(cloned_dataset_dir, source_class) + cloned_target_dir = os.path.join(cloned_dataset_dir, target_class) + + if os.path.exists(cloned_source_dir): + if not os.path.exists(cloned_target_dir): + os.makedirs(cloned_target_dir) + + for filename in os.listdir(cloned_source_dir): + shutil.move(os.path.join(cloned_source_dir, filename), os.path.join(cloned_target_dir, filename)) + shutil.rmtree(cloned_source_dir) + + # 5. Establish the Consistent Export Directory Structure + export_dir = os.path.join(cloned_dataset_dir, "LabGym_Diagnostics") + os.makedirs(export_dir, exist_ok=True) + pdf_path = os.path.join(export_dir, "Triage_Action_Plan.pdf") + + # ---> NEW: H3 Random Sampling Execution <--- + if self.lb_h3.GetCount() > 0: + import random + h3_ref_dir = os.path.join(export_dir, "H3_Variance_References") + os.makedirs(h3_ref_dir, exist_ok=True) + + for i in range(self.lb_h3.GetCount()): + text = self.lb_h3.GetString(i) + source_class = text.split(" -> ")[0].strip() + target_class = text.split(" -> ")[1].split(" (")[0].strip() + + key = (source_class, target_class) + examples = self.example_map.get(key, []) + + if examples: + # Grab 3 random samples (or fewer if there aren't 3 available) + samples = random.sample(examples, min(3, len(examples))) + for idx, avi_path in enumerate(samples): + if os.path.exists(avi_path): + # Clean strings for safe OS filenames + safe_source = source_class.replace(" ", "_") + safe_target = target_class.replace(" ", "_") + + # Copy the .avi video + new_avi_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.avi" + shutil.copy2(avi_path, os.path.join(h3_ref_dir, new_avi_name)) + + # Copy the corresponding .jpg pattern image + jpg_path = avi_path.replace(".avi", ".jpg") + if os.path.exists(jpg_path): + new_jpg_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.jpg" + shutil.copy2(jpg_path, os.path.join(h3_ref_dir, new_jpg_name)) + + # 6. Generate the PDF Report + self.generate_pdf_report(pdf_path, new_dataset_name) + + wx.EndBusyCursor() + + # ---> REORDERED: Show the message box BEFORE opening Finder <--- + wx.MessageBox(f"Successfully cloned dataset and executed Triage Plan!\n\nYour new dataset and PDF Action Plan are located at:\n{export_dir}", "Triage Complete", wx.OK | wx.ICON_INFORMATION) + + # Close the Triage Builder Dialog + self.EndModal(wx.ID_OK) + + # 7. Instantly open the new Diagnostics folder (now guaranteed to stay on top) + if sys.platform == "win32": + os.startfile(export_dir) + elif sys.platform == "darwin": + subprocess.call(["open", export_dir]) + else: + subprocess.call(["xdg-open", export_dir]) + + except PermissionError: + wx.EndBusyCursor() + wx.MessageBox("LabGym does not have permission to write to this directory. Check your folder permissions.", "Permission Error", wx.OK | wx.ICON_ERROR) + except Exception as e: + wx.EndBusyCursor() + wx.MessageBox(f"An OS error occurred during triage execution:\n{e}", "System Error", wx.OK | wx.ICON_ERROR) + + def generate_pdf_report(self, filepath, dataset_name): + """Generates a styled, professional PDF report with simplified layman descriptions and addressed highlights.""" + try: + from reportlab.lib.pagesizes import letter + from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle + from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle + from reportlab.lib.colors import HexColor, Color + from reportlab.lib import colors + from reportlab.lib.units import inch + import datetime + import os + except ImportError: + wx.MessageBox("ReportLab is required to generate PDFs. Please run 'pip install reportlab'.", "Missing Dependency", wx.OK | wx.ICON_WARNING) + return + + doc = SimpleDocTemplate(filepath, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) + styles = getSampleStyleSheet() + + # --- Typography --- + title_style = ParagraphStyle('Title', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=16, textColor=HexColor("#00274C"), spaceAfter=16) + h2_style = ParagraphStyle('H2', parent=styles['Heading2'], fontName='Helvetica-Bold', fontSize=12, textColor=HexColor("#333333"), spaceBefore=16, spaceAfter=8) + body_style = ParagraphStyle('Body', parent=styles['Normal'], fontName='Helvetica', fontSize=10, leading=14, textColor=HexColor("#1A1A1A")) + action_style = ParagraphStyle('Action', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=10, textColor=HexColor("#D82C20"), spaceAfter=12) + item_style = ParagraphStyle('Item', parent=styles['Normal'], fontName='Helvetica', fontSize=10, leading=14, leftIndent=20, spaceAfter=6) + caption_style = ParagraphStyle('Caption', parent=styles['Normal'], fontName='Helvetica-Oblique', fontSize=8, textColor=HexColor("#666666"), leftIndent=20, spaceBefore=4, spaceAfter=16) + + Story = [] + + # --- Header & Global Metrics --- + accuracy = self.report.get('accuracy', 0.0) + macro_f1 = self.report.get('macro avg', {}).get('f1-score', 0.0) + + Story.append(Paragraph(f"LabGym Scientific Triage Action Plan", title_style)) + Story.append(Paragraph(f"Dataset Target: {dataset_name}", body_style)) + Story.append(Paragraph(f"Date Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}", body_style)) + Story.append(Paragraph(f"Overall Accuracy: {accuracy*100:.1f}% | Macro F1-Score: {macro_f1*100:.1f}%", body_style)) + Story.append(Spacer(1, 15)) + + # --- Embedded Confusion Matrix Table --- + Story.append(Paragraph("Confusion Matrix Overview", h2_style)) + Story.append(Paragraph("Cells highlighted with a thick gold border indicate confusions that were addressed in this triage session.", caption_style)) + + headers = ["True \\ Pred"] + [str(idx + 1) for idx in range(len(self.classnames))] + cm_data = [headers] + + for i in range(len(self.classnames)): + row_data = [f"{i + 1}. {self.classnames[i]}"] + for j in range(len(self.classnames)): + row_data.append(str(self.cm[i][j])) + cm_data.append(row_data) + + t_style = TableStyle([ + ('BACKGROUND', (0,0), (-1,0), HexColor("#00274C")), + ('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke), + ('ALIGN', (0,0), (-1,-1), 'CENTER'), + ('ALIGN', (0,1), (0,-1), 'LEFT'), + ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'), + ('FONTSIZE', (0,0), (-1,-1), 7), + ('BOTTOMPADDING', (0,0), (-1,0), 6), + ('BACKGROUND', (0,1), (0,-1), HexColor("#f0f0f0")), + ('FONTNAME', (0,1), (0,-1), 'Helvetica-Bold'), + ('GRID', (0,0), (-1,-1), 0.5, colors.grey), + ]) + + for i in range(len(self.classnames)): + row_sum = sum(self.cm[i]) + for j in range(len(self.classnames)): + val = self.cm[i][j] + if val > 0: + if i == j: + intensity = min(1.0, val / row_sum) if row_sum > 0 else 0 + bg_color = Color(0, 0.8, 0, alpha=0.1 + (0.4 * intensity)) + else: + pct = val / row_sum if row_sum > 0 else 0 + intensity = min(1.0, pct / 0.5) + bg_color = Color(0.9, 0, 0, alpha=0.1 + (0.5 * intensity)) + t_style.add('BACKGROUND', (j+1, i+1), (j+1, i+1), bg_color) + + # ---> HIGHLIGHT ADDRESSED CONFUSIONS <--- + addressed_pairs = [] + for lb in [self.lb_h1, self.lb_h2, self.lb_h3]: + for idx in range(lb.GetCount()): + item_text = lb.GetString(idx) + clean_text = item_text.split(" [NEW:")[0] + source_class = clean_text.split(" -> ")[0].strip() + target_class = clean_text.split(" -> ")[1].split(" (")[0].strip() + addressed_pairs.append((source_class, target_class)) + + for src, tgt in addressed_pairs: + if src in self.classnames and tgt in self.classnames: + i = self.classnames.index(src) + j = self.classnames.index(tgt) + # Draw a thick 2-point Maize border around the addressed cell + t_style.add('BOX', (j+1, i+1), (j+1, i+1), 2, HexColor("#FFCB05")) + # ---------------------------------------- + + first_col_width = 1.5 * inch + remaining_width = 5.0 * inch + data_col_width = remaining_width / len(self.classnames) + + col_widths = [first_col_width] + [data_col_width] * len(self.classnames) + + cm_table = Table(cm_data, colWidths=col_widths) + cm_table.setStyle(t_style) + Story.append(cm_table) + Story.append(Spacer(1, 15)) + + # --- Hypothesis 1 (Merge) --- + Story.append(Paragraph("Hypothesis 1: Redundant Behaviors", h2_style)) + Story.append(Paragraph("These behaviors look identical to the software. LabGym has automatically combined them into a single category for this dataset. No further action is required.", body_style)) + Story.append(Spacer(1, 5)) + + if self.lb_h1.GetCount() == 0: + Story.append(Paragraph("None selected.", item_style)) + for i in range(self.lb_h1.GetCount()): + Story.append(Paragraph(f"• {self.lb_h1.GetString(i)}", item_style)) + Story.append(Spacer(1, 10)) + + # --- Hypothesis 2 (Emergent) --- + Story.append(Paragraph("Hypothesis 2: Emergent Behaviors", h2_style)) + Story.append(Paragraph("The software is confusing these behaviors because there is likely a third, completely different behavior happening that it hasn't been taught yet.", body_style)) + Story.append(Paragraph("ACTION REQUIRED: Go to the video folders and manually move the mixed-up videos into the new folder you just named.", action_style)) + + if self.lb_h2.GetCount() == 0: + Story.append(Paragraph("None selected.", item_style)) + else: + for i in range(self.lb_h2.GetCount()): + item_text = self.lb_h2.GetString(i) + Story.append(Paragraph(f"• {item_text}", item_style)) + + source_class = item_text.split(" -> ")[0].strip() + target_class = item_text.split(" -> ")[1].split(" (")[0].strip() + key = (source_class, target_class) + examples = self.example_map.get(key, []) + + if examples: + avi_path = examples[0] + jpg_path = avi_path.replace(".avi", ".jpg") + file_name = os.path.basename(avi_path) + + if os.path.exists(jpg_path): + img = Image(jpg_path) + img.drawWidth = 2 * inch + img.drawHeight = 2 * inch + Story.append(img) + Story.append(Paragraph(f"Reference file: {file_name}", caption_style)) + + # --- Hypothesis 3 (Generalization) --- + Story.append(Paragraph("Hypothesis 3: Poor Generalization", h2_style)) + Story.append(Paragraph("The software is failing here because it hasn't seen enough different examples of this behavior.", body_style)) + Story.append(Paragraph("ACTION REQUIRED: Go back to the 'Generate/Sort Behavior Examples' tool and add more videos of these specific behaviors in different environments or angles.", action_style)) + + if self.lb_h3.GetCount() == 0: + Story.append(Paragraph("None selected.", item_style)) + else: + export_dir = os.path.dirname(filepath) + h3_ref_dir = os.path.join(export_dir, "H3_Variance_References") + + for i in range(self.lb_h3.GetCount()): + item_text = self.lb_h3.GetString(i) + Story.append(Paragraph(f"• {item_text}", item_style)) + + source_class = item_text.split(" -> ")[0].strip() + target_class = item_text.split(" -> ")[1].split(" (")[0].strip() + safe_source = source_class.replace(" ", "_") + safe_target = target_class.replace(" ", "_") + + for idx in range(3): + jpg_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.jpg" + avi_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.avi" + jpg_path = os.path.join(h3_ref_dir, jpg_name) + + if os.path.exists(jpg_path): + img = Image(jpg_path) + img.drawWidth = 2 * inch + img.drawHeight = 2 * inch + Story.append(img) + Story.append(Paragraph(f"Reference file: H3_Variance_References/{avi_name}", caption_style)) + + # --- True Positive Baselines (Diagonal) --- + Story.append(Paragraph("Baseline References (True Positives)", h2_style)) + Story.append(Paragraph("Below are representative examples of correctly classified behaviors. Use these as a visual baseline for what the model currently considers an 'ideal' representation of the class.", body_style)) + + has_baselines = False + for i in range(len(self.classnames)): + cls_name = self.classnames[i] + if self.cm[i][i] > 0: + key = (cls_name, cls_name) + examples = self.example_map.get(key, []) + + if examples: + has_baselines = True + Story.append(Paragraph(f"• {cls_name}", item_style)) + + avi_path = examples[0] + jpg_path = avi_path.replace(".avi", ".jpg") + file_name = os.path.basename(avi_path) + + if os.path.exists(jpg_path): + img = Image(jpg_path) + img.drawWidth = 2 * inch + img.drawHeight = 2 * inch + Story.append(img) + Story.append(Paragraph(f"Reference file: {file_name}", caption_style)) + + if not has_baselines: + Story.append(Paragraph("No correct classifications available to generate baselines.", item_style)) + + doc.build(Story) \ No newline at end of file From e77cf3bf00644cb8e1f5479d33df781e54c6be96 Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Wed, 24 Jun 2026 10:55:58 -0400 Subject: [PATCH 14/33] feat: complete centroid calc --- LabGym/categorizer.py | 24 ++++++----- LabGym/gui_categorizer.py | 88 +++++++++++++++++++-------------------- 2 files changed, 57 insertions(+), 55 deletions(-) diff --git a/LabGym/categorizer.py b/LabGym/categorizer.py index f570f248..b57cec0f 100644 --- a/LabGym/categorizer.py +++ b/LabGym/categorizer.py @@ -2078,21 +2078,25 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): model=load_model(model_path) + from keras.models import Model + multi_model = Model(inputs=model.inputs, outputs=[model.layers[-2].output, model.output]) + if network==0: - predictions=model.predict(pattern_images,batch_size=32) + embeddings, predictions = multi_model.predict(pattern_images,batch_size=32) elif network==1: - predictions=model.predict(animations,batch_size=32) + embeddings, predictions = multi_model.predict(animations,batch_size=32) else: - predictions=model.predict([animations,pattern_images],batch_size=32) + embeddings, predictions = multi_model.predict([animations,pattern_images],batch_size=32) + if len(classnames)==2: predictions=[round(i[0]) for i in predictions] - flat_predictions = predictions # Save flat predictions + flat_predictions = predictions print(classification_report(labels,predictions,target_names=classnames)) report=classification_report(labels,predictions,target_names=classnames,output_dict=True) cm=confusion_matrix(labels,predictions) else: - flat_predictions = predictions.argmax(axis=1) # Save flat predictions + flat_predictions = predictions.argmax(axis=1) print(classification_report(labels,flat_predictions,target_names=classnames)) report=classification_report(labels,flat_predictions,target_names=classnames,output_dict=True) cm=confusion_matrix(labels,flat_predictions) @@ -2101,18 +2105,18 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): pd.DataFrame(report).transpose().to_excel(os.path.join(result_path,'testing_reports.xlsx'),float_format='%.2f') pd.DataFrame(cm, index=classnames, columns=classnames).to_csv(os.path.join(result_path,'confusion_matrix.csv')) - # ADDED: Build a dictionary mapping (True Class, Predicted Class) -> [List of File Paths] example_map = {} - for t_label_idx, p_label_idx, f_path in zip(labels, flat_predictions, test_files): + embedding_map = {} + for t_label_idx, p_label_idx, f_path, emb in zip(labels, flat_predictions, test_files, embeddings): key = (classnames[t_label_idx], classnames[p_label_idx]) if key not in example_map: example_map[key] = [] example_map[key].append(f_path) - + embedding_map[f_path] = emb + print('Testing completed!') - # ADDED: Return example_map as the 3rd variable! - return report, cm, example_map + return report, cm, example_map, embedding_map def generate_probability_matrix(self, path_to_video, path_to_model, output_folder, batch_size=32): diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index b6b4ee29..3c9444a2 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2113,10 +2113,10 @@ def test_categorizer(self,event): else: CA=Categorizers() - report, cm, example_map = CA.test_categorizer(self.file_path,self.path_to_categorizer,result_path=self.out_path) + report, cm, example_map, embedding_map = CA.test_categorizer(self.file_path,self.path_to_categorizer,result_path=self.out_path) classnames = [k for k in report.keys() if k not in ['accuracy', 'macro avg', 'weighted avg']] - dialog = AutomatedDiagnosticsDialog(self, report, cm, classnames, example_map) + dialog = AutomatedDiagnosticsDialog(self, report, cm, classnames, example_map, embedding_map) dialog.ShowModal() dialog.Destroy() @@ -2142,13 +2142,14 @@ def remove_categorizer(self,event): dialog.Destroy() class AutomatedDiagnosticsDialog(wx.Dialog): - def __init__(self, parent, report, cm, classnames, example_map): + def __init__(self, parent, report, cm, classnames, example_map, embedding_map): super().__init__(parent, title="Automated Diagnostics - Test Results", size=(1000, 800), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) self.report = report self.cm = cm self.classnames = classnames self.example_map = example_map + self.embedding_map = embedding_map self.cm_normalized = self.calculate_normalized_cm(cm) self.is_normalized = False @@ -2293,13 +2294,11 @@ def on_build_triage(self, event): """Gathers all confusions and launches the Triage Builder.""" all_confusions = [] - # Grab Major Confusions for count, i, j, prop in self.nlp_major: item = f"{self.classnames[i]} -> {self.classnames[j]} ({count} errors)" if item not in all_confusions: all_confusions.append(item) - # Grab Minor Confusions for mc in self.nlp_minor: for err_count, pred_class in mc['top_confusions']: item = f"{mc['class']} -> {pred_class} ({err_count} errors)" @@ -2310,7 +2309,7 @@ def on_build_triage(self, event): wx.MessageBox("No confusions detected to triage!", "All Clear", wx.OK | wx.ICON_INFORMATION) return - dialog = TriageBuilderDialog(self, all_confusions, self.example_map, self.report, self.cm, self.classnames) + dialog = TriageBuilderDialog(self, all_confusions, self.example_map, self.report, self.cm, self.classnames, self.embedding_map) dialog.ShowModal() dialog.Destroy() @@ -2872,32 +2871,59 @@ def on_double_click(self, event): class TriageBuilderDialog(wx.Dialog): - def __init__(self, parent, confusions_list, example_map, report, cm, classnames): + def __init__(self, parent, confusions_list, example_map, report, cm, classnames, embedding_map): super().__init__(parent, title="Triage Action Plan Builder", size=(900, 600), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) self.confusions_list = confusions_list self.example_map = example_map + self.embedding_map = embedding_map - # ---> NEW: Store the variables so the PDF generator can use them <--- self.report = report self.cm = cm self.classnames = classnames self.init_ui() + + def get_centroid(self, file_list): + """Calculates the mathematical centroid of a cluster of videos and returns the most representative file.""" + if not file_list: + return None + if len(file_list) == 1: + return file_list[0] + + import numpy as np + + embs = [self.embedding_map[f] for f in file_list] + + mean_emb = np.mean(embs, axis=0) + mean_norm = np.linalg.norm(mean_emb) + if mean_norm == 0: + return file_list[0] + + best_sim = -2.0 + centroid_file = file_list[0] + + for f, emb in zip(file_list, embs): + emb_norm = np.linalg.norm(emb) + if emb_norm == 0: continue + + sim = np.dot(emb, mean_emb) / (emb_norm * mean_norm) + if sim > best_sim: + best_sim = sim + centroid_file = f + + return centroid_file def init_ui(self): main_sizer = wx.BoxSizer(wx.VERTICAL) - # --- TITLE HEADER --- title_lbl = wx.StaticText(self, label="Assign confusions to a root-cause hypothesis to generate your action plan.") title_font = wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) title_lbl.SetFont(title_font) - title_lbl.SetForegroundColour(wx.Colour(255, 203, 5)) # Maize for primary branding + title_lbl.SetForegroundColour(wx.Colour(255, 203, 5)) main_sizer.Add(title_lbl, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 15) - # Layout: 3 Columns columns_sizer = wx.BoxSizer(wx.HORIZONTAL) - # --- LEFT COLUMN: Unassigned --- left_sizer = wx.BoxSizer(wx.VERTICAL) lbl_unassigned = wx.StaticText(self, label="📥 Unassigned Confusions:") lbl_unassigned.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) @@ -2908,8 +2934,6 @@ def init_ui(self): left_sizer.Add(self.lb_unassigned, 1, wx.EXPAND) columns_sizer.Add(left_sizer, 4, wx.EXPAND | wx.ALL, 10) - # --- MIDDLE COLUMN: Transfer Buttons --- - # Fixed sizes prevent the awkward stretching seen in the screenshot mid_sizer = wx.BoxSizer(wx.VERTICAL) mid_sizer.AddStretchSpacer() @@ -2932,26 +2956,25 @@ def init_ui(self): mid_sizer.AddStretchSpacer() columns_sizer.Add(mid_sizer, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 10) - # --- RIGHT COLUMN: The Buckets --- right_sizer = wx.BoxSizer(wx.VERTICAL) lbl_h1 = wx.StaticText(self, label="🔗 H1: Redundant (Auto-Merged):") lbl_h1.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) - lbl_h1.SetForegroundColour(wx.Colour(100, 200, 100)) # Soft Green + lbl_h1.SetForegroundColour(wx.Colour(100, 200, 100)) right_sizer.Add(lbl_h1, 0, wx.BOTTOM, 4) self.lb_h1 = wx.ListBox(self, style=wx.LB_EXTENDED) right_sizer.Add(self.lb_h1, 1, wx.EXPAND | wx.BOTTOM, 10) lbl_h2 = wx.StaticText(self, label="✂️ H2: Emergent (Manual Extraction):") lbl_h2.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) - lbl_h2.SetForegroundColour(wx.Colour(100, 150, 255)) # Soft Blue + lbl_h2.SetForegroundColour(wx.Colour(100, 150, 255)) right_sizer.Add(lbl_h2, 0, wx.BOTTOM, 4) self.lb_h2 = wx.ListBox(self, style=wx.LB_EXTENDED) right_sizer.Add(self.lb_h2, 1, wx.EXPAND | wx.BOTTOM, 10) lbl_h3 = wx.StaticText(self, label="📊 H3: Poor Generalization (Needs Data):") lbl_h3.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) - lbl_h3.SetForegroundColour(wx.Colour(255, 150, 100)) # Soft Orange + lbl_h3.SetForegroundColour(wx.Colour(255, 150, 100)) right_sizer.Add(lbl_h3, 0, wx.BOTTOM, 4) self.lb_h3 = wx.ListBox(self, style=wx.LB_EXTENDED) right_sizer.Add(self.lb_h3, 1, wx.EXPAND) @@ -2960,7 +2983,6 @@ def init_ui(self): main_sizer.Add(columns_sizer, 1, wx.EXPAND) - # --- FOOTER --- footer_sizer = wx.BoxSizer(wx.HORIZONTAL) btn_finish = wx.Button(self, label="Finish and Generate Report", size=(220, 40)) btn_finish.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) @@ -3008,7 +3030,6 @@ def on_return_items(self, event): lb.Delete(idx) def on_finish(self, event): - # 1. Ask for the new versioned dataset name dlg = wx.TextEntryDialog(self, "Enter a name for the new versioned dataset folder:", "Dataset Versioning", "dataset_v2") if dlg.ShowModal() != wx.ID_OK: dlg.Destroy() @@ -3019,7 +3040,6 @@ def on_finish(self, event): if not new_dataset_name: return - # 2. Deduce the base directory path from the example map sample_file = None for files in self.example_map.values(): if files: @@ -3034,7 +3054,6 @@ def on_finish(self, event): parent_dir = os.path.dirname(original_dataset_dir) cloned_dataset_dir = os.path.join(parent_dir, new_dataset_name) - # 3. Check Disk Space & Clone try: total_size = sum(os.path.getsize(os.path.join(dirpath, f)) for dirpath, _, filenames in os.walk(original_dataset_dir) for f in filenames) total_size_mb = total_size / (1024 * 1024) @@ -3047,7 +3066,6 @@ def on_finish(self, event): wx.BeginBusyCursor() shutil.copytree(original_dataset_dir, cloned_dataset_dir) - # 4. Perform the OS-level H1 Merges inside the cloned directory for i in range(self.lb_h1.GetCount()): text = self.lb_h1.GetString(i) source_class = text.split(" -> ")[0].strip() @@ -3064,12 +3082,10 @@ def on_finish(self, event): shutil.move(os.path.join(cloned_source_dir, filename), os.path.join(cloned_target_dir, filename)) shutil.rmtree(cloned_source_dir) - # 5. Establish the Consistent Export Directory Structure export_dir = os.path.join(cloned_dataset_dir, "LabGym_Diagnostics") os.makedirs(export_dir, exist_ok=True) pdf_path = os.path.join(export_dir, "Triage_Action_Plan.pdf") - # ---> NEW: H3 Random Sampling Execution <--- if self.lb_h3.GetCount() > 0: import random h3_ref_dir = os.path.join(export_dir, "H3_Variance_References") @@ -3084,36 +3100,28 @@ def on_finish(self, event): examples = self.example_map.get(key, []) if examples: - # Grab 3 random samples (or fewer if there aren't 3 available) samples = random.sample(examples, min(3, len(examples))) for idx, avi_path in enumerate(samples): if os.path.exists(avi_path): - # Clean strings for safe OS filenames safe_source = source_class.replace(" ", "_") safe_target = target_class.replace(" ", "_") - # Copy the .avi video new_avi_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.avi" shutil.copy2(avi_path, os.path.join(h3_ref_dir, new_avi_name)) - # Copy the corresponding .jpg pattern image jpg_path = avi_path.replace(".avi", ".jpg") if os.path.exists(jpg_path): new_jpg_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.jpg" shutil.copy2(jpg_path, os.path.join(h3_ref_dir, new_jpg_name)) - # 6. Generate the PDF Report self.generate_pdf_report(pdf_path, new_dataset_name) wx.EndBusyCursor() - # ---> REORDERED: Show the message box BEFORE opening Finder <--- wx.MessageBox(f"Successfully cloned dataset and executed Triage Plan!\n\nYour new dataset and PDF Action Plan are located at:\n{export_dir}", "Triage Complete", wx.OK | wx.ICON_INFORMATION) - # Close the Triage Builder Dialog self.EndModal(wx.ID_OK) - # 7. Instantly open the new Diagnostics folder (now guaranteed to stay on top) if sys.platform == "win32": os.startfile(export_dir) elif sys.platform == "darwin": @@ -3146,7 +3154,6 @@ def generate_pdf_report(self, filepath, dataset_name): doc = SimpleDocTemplate(filepath, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) styles = getSampleStyleSheet() - # --- Typography --- title_style = ParagraphStyle('Title', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=16, textColor=HexColor("#00274C"), spaceAfter=16) h2_style = ParagraphStyle('H2', parent=styles['Heading2'], fontName='Helvetica-Bold', fontSize=12, textColor=HexColor("#333333"), spaceBefore=16, spaceAfter=8) body_style = ParagraphStyle('Body', parent=styles['Normal'], fontName='Helvetica', fontSize=10, leading=14, textColor=HexColor("#1A1A1A")) @@ -3156,7 +3163,6 @@ def generate_pdf_report(self, filepath, dataset_name): Story = [] - # --- Header & Global Metrics --- accuracy = self.report.get('accuracy', 0.0) macro_f1 = self.report.get('macro avg', {}).get('f1-score', 0.0) @@ -3166,7 +3172,6 @@ def generate_pdf_report(self, filepath, dataset_name): Story.append(Paragraph(f"Overall Accuracy: {accuracy*100:.1f}% | Macro F1-Score: {macro_f1*100:.1f}%", body_style)) Story.append(Spacer(1, 15)) - # --- Embedded Confusion Matrix Table --- Story.append(Paragraph("Confusion Matrix Overview", h2_style)) Story.append(Paragraph("Cells highlighted with a thick gold border indicate confusions that were addressed in this triage session.", caption_style)) @@ -3206,7 +3211,6 @@ def generate_pdf_report(self, filepath, dataset_name): bg_color = Color(0.9, 0, 0, alpha=0.1 + (0.5 * intensity)) t_style.add('BACKGROUND', (j+1, i+1), (j+1, i+1), bg_color) - # ---> HIGHLIGHT ADDRESSED CONFUSIONS <--- addressed_pairs = [] for lb in [self.lb_h1, self.lb_h2, self.lb_h3]: for idx in range(lb.GetCount()): @@ -3220,9 +3224,7 @@ def generate_pdf_report(self, filepath, dataset_name): if src in self.classnames and tgt in self.classnames: i = self.classnames.index(src) j = self.classnames.index(tgt) - # Draw a thick 2-point Maize border around the addressed cell t_style.add('BOX', (j+1, i+1), (j+1, i+1), 2, HexColor("#FFCB05")) - # ---------------------------------------- first_col_width = 1.5 * inch remaining_width = 5.0 * inch @@ -3235,7 +3237,6 @@ def generate_pdf_report(self, filepath, dataset_name): Story.append(cm_table) Story.append(Spacer(1, 15)) - # --- Hypothesis 1 (Merge) --- Story.append(Paragraph("Hypothesis 1: Redundant Behaviors", h2_style)) Story.append(Paragraph("These behaviors look identical to the software. LabGym has automatically combined them into a single category for this dataset. No further action is required.", body_style)) Story.append(Spacer(1, 5)) @@ -3246,7 +3247,6 @@ def generate_pdf_report(self, filepath, dataset_name): Story.append(Paragraph(f"• {self.lb_h1.GetString(i)}", item_style)) Story.append(Spacer(1, 10)) - # --- Hypothesis 2 (Emergent) --- Story.append(Paragraph("Hypothesis 2: Emergent Behaviors", h2_style)) Story.append(Paragraph("The software is confusing these behaviors because there is likely a third, completely different behavior happening that it hasn't been taught yet.", body_style)) Story.append(Paragraph("ACTION REQUIRED: Go to the video folders and manually move the mixed-up videos into the new folder you just named.", action_style)) @@ -3264,7 +3264,7 @@ def generate_pdf_report(self, filepath, dataset_name): examples = self.example_map.get(key, []) if examples: - avi_path = examples[0] + avi_path = self.get_centroid(examples) jpg_path = avi_path.replace(".avi", ".jpg") file_name = os.path.basename(avi_path) @@ -3275,7 +3275,6 @@ def generate_pdf_report(self, filepath, dataset_name): Story.append(img) Story.append(Paragraph(f"Reference file: {file_name}", caption_style)) - # --- Hypothesis 3 (Generalization) --- Story.append(Paragraph("Hypothesis 3: Poor Generalization", h2_style)) Story.append(Paragraph("The software is failing here because it hasn't seen enough different examples of this behavior.", body_style)) Story.append(Paragraph("ACTION REQUIRED: Go back to the 'Generate/Sort Behavior Examples' tool and add more videos of these specific behaviors in different environments or angles.", action_style)) @@ -3307,7 +3306,6 @@ def generate_pdf_report(self, filepath, dataset_name): Story.append(img) Story.append(Paragraph(f"Reference file: H3_Variance_References/{avi_name}", caption_style)) - # --- True Positive Baselines (Diagonal) --- Story.append(Paragraph("Baseline References (True Positives)", h2_style)) Story.append(Paragraph("Below are representative examples of correctly classified behaviors. Use these as a visual baseline for what the model currently considers an 'ideal' representation of the class.", body_style)) @@ -3322,7 +3320,7 @@ def generate_pdf_report(self, filepath, dataset_name): has_baselines = True Story.append(Paragraph(f"• {cls_name}", item_style)) - avi_path = examples[0] + avi_path = self.get_centroid(examples) jpg_path = avi_path.replace(".avi", ".jpg") file_name = os.path.basename(avi_path) From 2603c44ab28cebd5eb3a4d35d4bfea0b47a9e367 Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Sun, 5 Jul 2026 16:26:26 -0400 Subject: [PATCH 15/33] cleaned up major conf --- LabGym/gui_categorizer.py | 110 ++------------------------------------ 1 file changed, 3 insertions(+), 107 deletions(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 3c9444a2..f6fdedb7 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2397,18 +2397,6 @@ def on_insight_link_clicked(self, event): self.cm_grid.SetCellBackgroundColour(row, col, wx.Colour(255, 203, 5)) self.cm_grid.SetCellTextColour(row, col, wx.Colour(0, 0, 0)) - elif href.startswith('action:'): - parts = href.split(':') - action_type = parts[1] - classes = parts[2].split(',') - source_class = classes[0] - target_class = classes[1] - - if action_type == 'add_data': - wx.MessageBox("To solve poor generalization, close the Test Categorizer and use the 'Generate/Sort Behavior Examples' modules to add more diverse data to the Training Set.", "Manual Action Required", wx.OK | wx.ICON_INFORMATION) - else: - self.execute_differential_action(action_type, source_class, target_class) - self.cm_grid.ForceRefresh() self.cm_grid.ClearSelection() @@ -2511,8 +2499,6 @@ def show_major_confusions_view(self, event=None): for count, i, j, prop in self.nlp_major[:5]: true_class = self.classnames[i] pred_class = self.classnames[j] - support_true = self.report.get(true_class, {}).get('support', 0) - support_pred = self.report.get(pred_class, {}).get('support', 0) prop_pct = round(prop * 100, 1) link = f"{true_class} → {pred_class}" @@ -2520,17 +2506,8 @@ def show_major_confusions_view(self, event=None): error_txt = f"{count} errors, {prop_pct}% of {true_class} data" - if support_true >= 50 and support_pred >= 50: - html += f"

{link} ({error_txt})

" - html += "

Differential Diagnosis:

" - html += "" - else: - lowest_class = true_class if support_true < support_pred else pred_class - html += f"

{link} ({error_txt})

Diagnosis: The Categorizer hasn't seen enough of {lowest_class} to learn it well. Adding more video examples should help clear this up.

" + html += f"

{link} ({error_txt})

" + html += "
" html += "" @@ -2746,87 +2723,6 @@ def on_cell_click(self, event): wx.MessageBox(f"No examples found for True: '{true_class}', Predicted: '{pred_class}'", "No Data", wx.OK | wx.ICON_INFORMATION) - - def execute_differential_action(self, action_type, source_class, target_class): - """Safely clones the dataset and applies the requested OS-level action.""" - dlg = wx.TextEntryDialog(self, f"To preserve reproducibility, LabGym will clone the dataset before modifying it.\n\nEnter a name for the new dataset folder:", "Dataset Versioning", "dataset_v2") - if dlg.ShowModal() != wx.ID_OK: - dlg.Destroy() - return - new_dataset_name = dlg.GetValue() - dlg.Destroy() - - if not new_dataset_name: - return - - source_files = [] - for (t, p), files in self.example_map.items(): - if t == source_class: - source_files.extend(files) - - if not source_files: - wx.MessageBox(f"Could not locate the files for '{source_class}'.", "Error", wx.OK | wx.ICON_ERROR) - return - - source_class_dir = os.path.dirname(source_files[0]) - original_dataset_dir = os.path.dirname(source_class_dir) - parent_dir = os.path.dirname(original_dataset_dir) - - cloned_dataset_dir = os.path.join(parent_dir, new_dataset_name) - - try: - total_size = sum(os.path.getsize(os.path.join(dirpath, f)) for dirpath, _, filenames in os.walk(original_dataset_dir) for f in filenames) - total_size_mb = total_size / (1024 * 1024) - - total, used, free = shutil.disk_usage(parent_dir) - if total_size > free: - wx.MessageBox(f"Not enough disk space to clone dataset.\nRequired: {total_size_mb:.2f} MB\nAvailable: {free / (1024*1024):.2f} MB", "Disk Space Error", wx.OK | wx.ICON_ERROR) - return - - wx.BeginBusyCursor() - shutil.copytree(original_dataset_dir, cloned_dataset_dir) - - if action_type == 'merge': - cloned_source_dir = os.path.join(cloned_dataset_dir, source_class) - cloned_target_dir = os.path.join(cloned_dataset_dir, target_class) - - if not os.path.exists(cloned_target_dir): - os.makedirs(cloned_target_dir) - - for filename in os.listdir(cloned_source_dir): - shutil.move(os.path.join(cloned_source_dir, filename), os.path.join(cloned_target_dir, filename)) - shutil.rmtree(cloned_source_dir) - - action_msg = f"Merged '{source_class}' into '{target_class}'." - - if sys.platform == "win32": - os.startfile(cloned_target_dir) - elif sys.platform == "darwin": - subprocess.call(["open", cloned_target_dir]) - else: - subprocess.call(["xdg-open", cloned_target_dir]) - - elif action_type == 'extract': - cloned_source_dir = os.path.join(cloned_dataset_dir, source_class) - if sys.platform == "win32": - os.startfile(cloned_source_dir) - elif sys.platform == "darwin": - subprocess.call(["open", cloned_source_dir]) - else: - subprocess.call(["xdg-open", cloned_source_dir]) - - action_msg = f"Opened '{source_class}' folder for manual extraction of the emergent behavior." - - wx.EndBusyCursor() - wx.MessageBox(f"Successfully cloned dataset to '{new_dataset_name}'.\n{action_msg}\n\nPlease point your Training Module to this new dataset for future iterations.", "Success", wx.OK | wx.ICON_INFORMATION) - - except PermissionError: - wx.EndBusyCursor() - wx.MessageBox("LabGym does not have permission to write to this directory. Check your folder permissions or network drive status.", "Permission Error", wx.OK | wx.ICON_ERROR) - except Exception as e: - wx.EndBusyCursor() - wx.MessageBox(f"An OS error occurred:\n{e}", "System Error", wx.OK | wx.ICON_ERROR) - class ExampleViewerDialog(wx.Dialog): def __init__(self, parent, true_class, pred_class, examples): title = f"Reviewing Examples: True '{true_class}' -> Predicted '{pred_class}'" @@ -3166,7 +3062,7 @@ def generate_pdf_report(self, filepath, dataset_name): accuracy = self.report.get('accuracy', 0.0) macro_f1 = self.report.get('macro avg', {}).get('f1-score', 0.0) - Story.append(Paragraph(f"LabGym Scientific Triage Action Plan", title_style)) + Story.append(Paragraph(f"LabGym Triage Action Plan", title_style)) Story.append(Paragraph(f"Dataset Target: {dataset_name}", body_style)) Story.append(Paragraph(f"Date Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}", body_style)) Story.append(Paragraph(f"Overall Accuracy: {accuracy*100:.1f}% | Macro F1-Score: {macro_f1*100:.1f}%", body_style)) From ffc0e4de991f49f875421b8014f1d4c5aebf18f5 Mon Sep 17 00:00:00 2001 From: AL3XPI Date: Sun, 2 Aug 2026 14:13:41 -0400 Subject: [PATCH 16/33] reportlab and toml --- LabGym/config.py | 7 ++++++- LabGym/gui_categorizer.py | 4 ++-- LabGym/mylogging.py | 7 ++++++- LabGym/pkghash/lookup.py | 5 ++++- pyproject.toml | 1 + 5 files changed, 19 insertions(+), 5 deletions(-) diff --git a/LabGym/config.py b/LabGym/config.py index d412a8d0..0b478119 100644 --- a/LabGym/config.py +++ b/LabGym/config.py @@ -40,7 +40,10 @@ # tomllib is included in the Python Standard Library since version 3.11 import tomllib # type: ignore except ModuleNotFoundError: - import tomli as tomllib # A lil' TOML parser + try: + import tomli as tomllib # A lil' TOML parser + except ModuleNotFoundError: + tomllib = None # Related third party imports. import yaml # PyYAML, YAML parser and emitter for Python @@ -121,6 +124,8 @@ def get_config_from_configfile(configfile: Path) -> dict: parser = configparser.ConfigParser() result = parser.read(configfile) elif configfile.name.endswith('.toml'): + if tomllib is None: + raise ModuleNotFoundError("TOML support requires Python >= 3.11 or the 'tomli' package. Please install it with: pip install tomli") with open(configfile, 'rb') as f: result = tomllib.load(f) elif configfile.name.endswith('.yaml'): diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index f6fdedb7..cf218ee4 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -3043,8 +3043,8 @@ def generate_pdf_report(self, filepath, dataset_name): from reportlab.lib.units import inch import datetime import os - except ImportError: - wx.MessageBox("ReportLab is required to generate PDFs. Please run 'pip install reportlab'.", "Missing Dependency", wx.OK | wx.ICON_WARNING) + except ImportError as e: + wx.MessageBox(f"ReportLab is required to generate PDFs ({e}). Please run 'pip install reportlab'.", "Missing Dependency", wx.OK | wx.ICON_WARNING) return doc = SimpleDocTemplate(filepath, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) diff --git a/LabGym/mylogging.py b/LabGym/mylogging.py index ce17dd2b..792949a7 100644 --- a/LabGym/mylogging.py +++ b/LabGym/mylogging.py @@ -112,7 +112,10 @@ # tomllib is included in the Python Standard Library since version 3.11 import tomllib # type: ignore except ModuleNotFoundError: - import tomli as tomllib # A lil' TOML parser + try: + import tomli as tomllib # A lil' TOML parser + except ModuleNotFoundError: + tomllib = None from typing import Dict, List # Related third party imports. @@ -185,6 +188,8 @@ def _mydebug(myobj: str | Exception) -> logging.LogRecord: def get_configdict_from_configfile(configfile: Path) -> Dict: """Read the configfile and return the config dictionary.""" if configfile.name.endswith('.toml'): + if tomllib is None: + raise ModuleNotFoundError("TOML support requires Python >= 3.11 or the 'tomli' package. Please install it with: pip install tomli") with open(configfile, 'rb') as f: result = tomllib.load(f) elif configfile.name.endswith('.yaml'): diff --git a/LabGym/pkghash/lookup.py b/LabGym/pkghash/lookup.py index fbb80329..16b36853 100644 --- a/LabGym/pkghash/lookup.py +++ b/LabGym/pkghash/lookup.py @@ -34,7 +34,10 @@ # tomllib is included in the Python Standard Library since version 3.11 import tomllib # type: ignore except ModuleNotFoundError: - import tomli as tomllib # A lil' TOML parser + try: + import tomli as tomllib # A lil' TOML parser + except ModuleNotFoundError: + tomllib = None # Local application/library specific imports. from .hash import get_hashval diff --git a/pyproject.toml b/pyproject.toml index 3d386147..348b62c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,6 +35,7 @@ dependencies=[ 'torchaudio', 'PyYAML', 'tomli', + 'reportlab', 'Pillow>=7.1', 'matplotlib', 'pycocotools>=2.0.2', From 2576cb2b055a019d3dcb2da295316dbb3bf29eb9 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Wed, 12 Aug 2026 22:34:59 -0400 Subject: [PATCH 17/33] feat(categorizer): add interactive diagnostics --- LabGym/categorizer.py | 156 +-- LabGym/gui_categorizer.py | 948 ++++++++++++++---- LabGym/gui_main.py | 26 +- LabGym/tests/test_ac_categorizer_mismatch.py | 85 ++ LabGym/tests/test_ac_cm_colors.py | 63 ++ LabGym/tests/test_ac_diagnostics_copy.py | 151 +++ .../test_ac_interactive_results_checkbox.py | 144 +++ LabGym/tests/test_ac_triage_guards.py | 407 ++++++++ LabGym/tests/test_ac_triage_layout_pdf.py | 92 ++ LabGym/tests/test_ac_triage_package_names.py | 169 ++++ 10 files changed, 1970 insertions(+), 271 deletions(-) create mode 100644 LabGym/tests/test_ac_categorizer_mismatch.py create mode 100644 LabGym/tests/test_ac_cm_colors.py create mode 100644 LabGym/tests/test_ac_diagnostics_copy.py create mode 100644 LabGym/tests/test_ac_interactive_results_checkbox.py create mode 100644 LabGym/tests/test_ac_triage_guards.py create mode 100644 LabGym/tests/test_ac_triage_layout_pdf.py create mode 100644 LabGym/tests/test_ac_triage_package_names.py diff --git a/LabGym/categorizer.py b/LabGym/categorizer.py index b57cec0f..41bce807 100644 --- a/LabGym/categorizer.py +++ b/LabGym/categorizer.py @@ -223,6 +223,20 @@ def __getitem__(self,idx): +class CategorizerClassMismatchError(Exception): + """Raised when ground-truth folder names do not match Categorizer classes.""" + + def __init__(self, unrecognized_folders, missing_classes): + self.unrecognized_folders = sorted(unrecognized_folders) + self.missing_classes = sorted(missing_classes) + parts = [ + 'Behavior folder names must exactly match the Categorizer classes.', + f'Unrecognized behavior folders: {self.unrecognized_folders}.', + f'Model classes absent from the fixture: {self.missing_classes}.', + ] + super().__init__(' '.join(parts)) + + class Categorizers(): def __init__(self): @@ -2019,91 +2033,105 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): if len(incorrect_classes)>0: print('Unused behavior names in the Categorizer: '+str(incorrect_classes)) - if len(incorrect_behaviors)==0 and len(incorrect_classes)==0: + if len(incorrect_behaviors)>0 or len(incorrect_classes)>0: + raise CategorizerClassMismatchError(incorrect_behaviors, incorrect_classes) - for behavior in behaviornames: + for behavior in behaviornames: - if network!=0: - filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.avi')] - else: - filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.jpg')] + if network!=0: + filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.avi')] + else: + filenames=[i for i in os.listdir(os.path.join(groundtruth_path,behavior)) if i.endswith('.jpg')] - for i in filenames: + for i in filenames: - test_files.append(os.path.join(groundtruth_path, behavior, i)) + test_files.append(os.path.join(groundtruth_path, behavior, i)) - if network!=0: + if network!=0: - path_to_animation=os.path.join(groundtruth_path,behavior,i) + path_to_animation=os.path.join(groundtruth_path,behavior,i) - capture=cv2.VideoCapture(path_to_animation) - animation=deque() - frames=deque(maxlen=length) + capture=cv2.VideoCapture(path_to_animation) + animation=deque() + frames=deque(maxlen=length) - while True: - retval,frame=capture.read() - if frame is None: - break - frames.append(frame) + while True: + retval,frame=capture.read() + if frame is None: + break + frames.append(frame) - capture.release() + capture.release() - for frame in frames: - frame=np.uint8(exposure.rescale_intensity(frame,out_range=(0,255))) - if channel==1: - frame=cv2.cvtColor(np.uint8(frame),cv2.COLOR_BGR2GRAY) - frame=cv2.resize(frame,(dim_tconv,dim_tconv),interpolation=cv2.INTER_AREA) - frame=img_to_array(frame) - animation.append(frame) + for frame in frames: + frame=np.uint8(exposure.rescale_intensity(frame,out_range=(0,255))) + if channel==1: + frame=cv2.cvtColor(np.uint8(frame),cv2.COLOR_BGR2GRAY) + frame=cv2.resize(frame,(dim_tconv,dim_tconv),interpolation=cv2.INTER_AREA) + frame=img_to_array(frame) + animation.append(frame) - animations.append(np.array(animation)) + animations.append(np.array(animation)) - if network!=1: + if network!=1: - path_to_pattern_image=os.path.splitext(os.path.join(groundtruth_path,behavior,i))[0]+'.jpg' - pattern_image=cv2.imread(path_to_pattern_image) - if behavior_mode==3: - if channel==1: - pattern_image=cv2.cvtColor(pattern_image,cv2.COLOR_BGR2GRAY) - pattern_image=cv2.resize(pattern_image,(dim_conv,dim_conv),interpolation=cv2.INTER_AREA) - pattern_images.append(img_to_array(pattern_image)) + path_to_pattern_image=os.path.splitext(os.path.join(groundtruth_path,behavior,i))[0]+'.jpg' + pattern_image=cv2.imread(path_to_pattern_image) + if behavior_mode==3: + if channel==1: + pattern_image=cv2.cvtColor(pattern_image,cv2.COLOR_BGR2GRAY) + pattern_image=cv2.resize(pattern_image,(dim_conv,dim_conv),interpolation=cv2.INTER_AREA) + pattern_images.append(img_to_array(pattern_image)) - labels.append(classnames.index(behavior)) + labels.append(classnames.index(behavior)) - if network!=0: - animations=np.array(animations,dtype='float32')/255.0 - pattern_images=np.array(pattern_images,dtype='float32')/255.0 + if network!=0: + animations=np.array(animations,dtype='float32')/255.0 + pattern_images=np.array(pattern_images,dtype='float32')/255.0 - labels=np.array(labels) + labels=np.array(labels) - model=load_model(model_path) + model=load_model(model_path) - from keras.models import Model - multi_model = Model(inputs=model.inputs, outputs=[model.layers[-2].output, model.output]) + from keras.models import Model + multi_model = Model(inputs=model.inputs, outputs=[model.layers[-2].output, model.output]) - if network==0: - embeddings, predictions = multi_model.predict(pattern_images,batch_size=32) - elif network==1: - embeddings, predictions = multi_model.predict(animations,batch_size=32) - else: - embeddings, predictions = multi_model.predict([animations,pattern_images],batch_size=32) + if network==0: + embeddings, predictions = multi_model.predict(pattern_images,batch_size=32) + elif network==1: + embeddings, predictions = multi_model.predict(animations,batch_size=32) + else: + embeddings, predictions = multi_model.predict([animations,pattern_images],batch_size=32) - if len(classnames)==2: - predictions=[round(i[0]) for i in predictions] - flat_predictions = predictions - print(classification_report(labels,predictions,target_names=classnames)) - report=classification_report(labels,predictions,target_names=classnames,output_dict=True) - cm=confusion_matrix(labels,predictions) - else: - flat_predictions = predictions.argmax(axis=1) - print(classification_report(labels,flat_predictions,target_names=classnames)) - report=classification_report(labels,flat_predictions,target_names=classnames,output_dict=True) - cm=confusion_matrix(labels,flat_predictions) - - if result_path is not None: - pd.DataFrame(report).transpose().to_excel(os.path.join(result_path,'testing_reports.xlsx'),float_format='%.2f') - pd.DataFrame(cm, index=classnames, columns=classnames).to_csv(os.path.join(result_path,'confusion_matrix.csv')) + if len(classnames)==2: + predictions=[round(i[0]) for i in predictions] + flat_predictions = predictions + print(classification_report(labels,predictions,target_names=classnames)) + report=classification_report(labels,predictions,target_names=classnames,output_dict=True) + cm=confusion_matrix(labels,predictions) + else: + flat_predictions = predictions.argmax(axis=1) + print(classification_report(labels,flat_predictions,target_names=classnames)) + report=classification_report(labels,flat_predictions,target_names=classnames,output_dict=True) + cm=confusion_matrix(labels,flat_predictions) + + if result_path is not None: + pd.DataFrame(report).transpose().to_excel(os.path.join(result_path,'testing_reports.xlsx'),float_format='%.2f') + pd.DataFrame(cm, index=classnames, columns=classnames).to_csv(os.path.join(result_path,'confusion_matrix.csv')) + + example_map = {} + embedding_map = {} + for t_label_idx, p_label_idx, f_path, emb in zip(labels, flat_predictions, test_files, embeddings): + key = (classnames[t_label_idx], classnames[p_label_idx]) + if key not in example_map: + example_map[key] = [] + example_map[key].append(f_path) + embedding_map[f_path] = emb + + print('Testing completed!') + + return report, cm, example_map, embedding_map example_map = {} embedding_map = {} diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index cf218ee4..3493d71f 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -21,6 +21,7 @@ import json import logging import os +import re import sys import subprocess @@ -49,7 +50,7 @@ logger.debug('importing %s ...', '.analyzebehavior_dt') from .analyzebehavior_dt import AnalyzeAnimalDetector logger.debug('importing %s done', '.analyzebehavior_dt') -from .categorizer import Categorizers +from .categorizer import Categorizers, CategorizerClassMismatchError from LabGym import config from .tools import sort_examples_from_csv from .gui_utils import ( @@ -63,6 +64,233 @@ ) +# Confusion-matrix correct-cell colors: dark -> approved max green #2E7D32. +CM_CORRECT_RGB_MIN = (20, 40, 20) +CM_CORRECT_RGB_MAX = (46, 125, 50) # #2E7D32 + + +def cm_correct_cell_rgb(accuracy): + """Return RGB for a correct (diagonal) CM cell given row accuracy in [0, 1].""" + accuracy = max(0.0, min(1.0, float(accuracy))) + r0, g0, b0 = CM_CORRECT_RGB_MIN + r1, g1, b1 = CM_CORRECT_RGB_MAX + return ( + int(round(r0 + (r1 - r0) * accuracy)), + int(round(g0 + (g1 - g0) * accuracy)), + int(round(b0 + (b1 - b0) * accuracy)), + ) + + +def triage_assignment_counts(h1_count, h2_count, h3_count): + """Return True when at least one triage hypothesis has an assignment.""" + return (h1_count + h2_count + h3_count) > 0 + + +def reportlab_importable(): + """Return (ok, error_message_or_None) for PDF dependency availability.""" + try: + import reportlab # noqa: F401 + from reportlab.lib.pagesizes import letter # noqa: F401 + from reportlab.platypus import SimpleDocTemplate # noqa: F401 + return True, None + except ImportError as e: + return False, str(e) + + +AC_DIAGNOSTIC_BUTTON_LABELS = ( + 'Overview', + 'Major Confusions', + 'Minor Confusions', + 'Successes', + 'Build Triage Plan', +) + + +def insufficient_support_threshold(total_support): + """Minimum observed support required for automated major/minor ranking.""" + return max(20, float(total_support) * 0.01) + + +def collect_insufficient_support_entries(classnames, report): + """Return low-support class entries, including classes with zero support.""" + total_support = sum( + float(report.get(name, {}).get('support', 0)) for name in classnames + ) + min_support = int(insufficient_support_threshold(total_support)) + entries = [] + for true_class in classnames: + support = float(report.get(true_class, {}).get('support', 0)) + if support < min_support: + entries.append({ + 'class': true_class, + 'support': int(support), + 'min_support': min_support, + }) + return entries + + +def fit_dialog_client_size( + nominal_w, + nominal_h, + work_w, + work_h, + margin=40, + max_frac=0.92, +): + """Clamp a nominal dialog client size to a usable work area.""" + work_w = max(1, int(work_w)) + work_h = max(1, int(work_h)) + margin = max(0, int(margin)) + max_frac = max(0.1, min(1.0, float(max_frac))) + cap_w = min(work_w - 2 * margin, int(work_w * max_frac)) + cap_h = min(work_h - 2 * margin, int(work_h * max_frac)) + cap_w = max(1, cap_w) + cap_h = max(1, cap_h) + return min(int(nominal_w), cap_w), min(int(nominal_h), cap_h) + + +def next_versioned_pdf_path(directory, base='categorizer_diagnostics'): + """Return the next non-overwriting `{base}_vN.pdf` path in directory.""" + pattern = re.compile(r'^' + re.escape(base) + r'_v(\d+)\.pdf$') + max_n = 0 + try: + names = os.listdir(directory) + except OSError: + names = [] + for name in names: + path = os.path.join(directory, name) + if not os.path.isfile(path): + continue + matched = pattern.match(name) + if matched: + max_n = max(max_n, int(matched.group(1))) + return os.path.join(directory, f'{base}_v{max_n + 1}.pdf') + + +_WIN_INVALID_CHARS = set('<>:"|?*') +_WIN_RESERVED = { + 'CON', 'PRN', 'AUX', 'NUL', + *(f'COM{i}' for i in range(1, 10)), + *(f'LPT{i}' for i in range(1, 10)), +} +_TRAILING_TRIAGE_VERSION = re.compile(r'_triage_v\d+$', re.IGNORECASE) + + +def sanitize_triage_package_base(source_name): + """Return a portable basename stem for `_triage_vN` packages.""" + import unicodedata + + text = unicodedata.normalize('NFC', str(source_name or '')) + chars = [] + for ch in text: + category = unicodedata.category(ch) + if category.startswith('C'): + continue + if ch.isalnum() or ch in '-_': + chars.append(ch) + elif ch.isspace() or ch in '/\\' or ch in _WIN_INVALID_CHARS: + chars.append('_') + else: + chars.append('_') + base = ''.join(chars) + while '__' in base: + base = base.replace('__', '_') + base = base.strip(' ._') + base = _TRAILING_TRIAGE_VERSION.sub('', base) + base = base.strip(' ._') + if len(base) > 80: + base = base[:80].rstrip(' ._') + if not base: + base = 'sorted_test_examples' + if base.upper() in _WIN_RESERVED: + base = f'{base}_data' + return base + + +def next_versioned_triage_package_name(parent_dir, source_name): + """Return next `_triage_vN` sibling directory basename.""" + base = sanitize_triage_package_base(source_name) + pattern = re.compile(r'^' + re.escape(base) + r'_triage_v(\d+)$') + max_n = 0 + try: + names = os.listdir(parent_dir) + except OSError: + names = [] + for name in names: + path = os.path.join(parent_dir, name) + if not os.path.isdir(path): + continue + matched = pattern.match(name) + if matched: + max_n = max(max_n, int(matched.group(1))) + return f'{base}_triage_v{max_n + 1}' + + +def validate_triage_package_name(name): + """Return (ok, error_message_or_None) for a user-edited package basename.""" + if name is None: + return False, 'Package name cannot be empty.' + raw = str(name) + if raw.strip() == '': + return False, 'Package name cannot be empty.' + if raw != raw.strip(): + return False, 'Package name cannot start or end with spaces.' + if raw in ('.', '..'): + return False, 'Package name cannot be "." or "..".' + if os.path.isabs(raw) or raw.startswith('~'): + return False, 'Package name must be a folder name, not an absolute path.' + if '/' in raw or '\\' in raw: + return False, 'Package name cannot contain path separators.' + if any(ord(ch) < 32 for ch in raw): + return False, 'Package name cannot contain control characters.' + if any(ch in _WIN_INVALID_CHARS for ch in raw): + return False, 'Package name contains characters that are invalid on Windows.' + if raw.endswith('.') or raw.endswith(' '): + return False, 'Package name cannot end with a period or space.' + stem = raw.split('.')[0].upper() + if stem in _WIN_RESERVED: + return False, f'"{raw}" is a reserved device name on Windows.' + return True, None + + +def collect_h1_filename_collisions(source_root, h1_pairs): + """ + Return sorted collision records for H1 merges against source_root. + + Each record: {'pair': (true, pred), 'filenames': [sorted basenames]} + Also return missing class folders as sorted (kind, class_name) tuples where + kind is 'source' or 'target'. + """ + collisions = [] + missing = [] + seen_pairs = [] + for true_class, pred_class in h1_pairs: + pair = (true_class, pred_class) + if pair in seen_pairs: + continue + seen_pairs.append(pair) + src_dir = os.path.join(source_root, true_class) + tgt_dir = os.path.join(source_root, pred_class) + if not os.path.isdir(src_dir): + missing.append(('source', true_class)) + continue + if not os.path.isdir(tgt_dir): + missing.append(('target', pred_class)) + continue + try: + src_names = set(os.listdir(src_dir)) + tgt_names = set(os.listdir(tgt_dir)) + except OSError: + missing.append(('source', true_class)) + continue + overlap = sorted(src_names & tgt_names) + if overlap: + collisions.append({'pair': pair, 'filenames': overlap}) + collisions.sort(key=lambda rec: (rec['pair'][0], rec['pair'][1])) + missing = sorted(set(missing)) + return collisions, missing + + class PanelLv2_GenerateExamples(wx.Panel): ''' @@ -2032,6 +2260,16 @@ def display_window(self): boxsizer.Add(module_report,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) boxsizer.Add(0,5,0) + module_interactive=wx.BoxSizer(wx.HORIZONTAL) + self.checkbox_open_interactive=wx.CheckBox( + panel, + label='Show interactive results after testing', + ) + self.checkbox_open_interactive.SetValue(True) + module_interactive.Add(self.checkbox_open_interactive,0,wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL,10) + boxsizer.Add(module_interactive,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + boxsizer.Add(0,5,0) + testanddelete=wx.BoxSizer(wx.HORIZONTAL) button_test=wx.Button(panel,label='Test the Categorizer',size=(300,40)) button_test.Bind(wx.EVT_BUTTON,self.test_categorizer) @@ -2112,13 +2350,31 @@ def test_categorizer(self,event): wx.MessageBox('No Categorizer selected / path to ground-truth behavior examples.','Error',wx.OK|wx.ICON_ERROR) else: CA=Categorizers() - - report, cm, example_map, embedding_map = CA.test_categorizer(self.file_path,self.path_to_categorizer,result_path=self.out_path) + try: + report, cm, example_map, embedding_map = CA.test_categorizer(self.file_path,self.path_to_categorizer,result_path=self.out_path) + except CategorizerClassMismatchError as e: + message = ( + 'Behavior folder names must exactly match the Categorizer classes.\n\n' + f'Unrecognized behavior folders: {e.unrecognized_folders}\n' + f'Model classes absent from the fixture: {e.missing_classes}' + ) + wx.MessageBox(message, 'Class name mismatch', wx.OK|wx.ICON_ERROR) + return + classnames = [k for k in report.keys() if k not in ['accuracy', 'macro avg', 'weighted avg']] - dialog = AutomatedDiagnosticsDialog(self, report, cm, classnames, example_map, embedding_map) - dialog.ShowModal() - dialog.Destroy() + if self.checkbox_open_interactive.GetValue(): + dialog = AutomatedDiagnosticsDialog( + self, + report, + cm, + classnames, + example_map, + embedding_map, + source_dataset_root=self.file_path, + ) + dialog.ShowModal() + dialog.Destroy() def remove_categorizer(self,event): @@ -2142,7 +2398,7 @@ def remove_categorizer(self,event): dialog.Destroy() class AutomatedDiagnosticsDialog(wx.Dialog): - def __init__(self, parent, report, cm, classnames, example_map, embedding_map): + def __init__(self, parent, report, cm, classnames, example_map, embedding_map, source_dataset_root=None): super().__init__(parent, title="Automated Diagnostics - Test Results", size=(1000, 800), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) self.report = report @@ -2150,6 +2406,7 @@ def __init__(self, parent, report, cm, classnames, example_map, embedding_map): self.classnames = classnames self.example_map = example_map self.embedding_map = embedding_map + self.source_dataset_root = source_dataset_root self.cm_normalized = self.calculate_normalized_cm(cm) self.is_normalized = False @@ -2212,22 +2469,29 @@ def init_ui(self): nlp_sizer.Add(self.synopsis_label, 0, wx.BOTTOM | wx.ALL, 5) btn_row_sizer = wx.BoxSizer(wx.HORIZONTAL) - self.btn_major = wx.Button(self, label="🔴 Major Confusions") - self.btn_minor = wx.Button(self, label="🟡 Minor Confusions") - self.btn_successes = wx.Button(self, label="🟢 Successes") - self.btn_help = wx.Button(self, label="🔵 What is this?") + ( + label_overview, + label_major, + label_minor, + label_successes, + label_triage, + ) = AC_DIAGNOSTIC_BUTTON_LABELS + self.btn_help = wx.Button(self, label=label_overview) + self.btn_major = wx.Button(self, label=label_major) + self.btn_minor = wx.Button(self, label=label_minor) + self.btn_successes = wx.Button(self, label=label_successes) + self.btn_help.Bind(wx.EVT_BUTTON, self.show_help_view) self.btn_major.Bind(wx.EVT_BUTTON, self.show_major_confusions_view) self.btn_minor.Bind(wx.EVT_BUTTON, self.show_minor_confusions_view) self.btn_successes.Bind(wx.EVT_BUTTON, self.show_successes_view) - self.btn_help.Bind(wx.EVT_BUTTON, self.show_help_view) + btn_row_sizer.Add(self.btn_help, 0, wx.RIGHT, 5) btn_row_sizer.Add(self.btn_major, 0, wx.RIGHT, 5) btn_row_sizer.Add(self.btn_minor, 0, wx.RIGHT, 5) - btn_row_sizer.Add(self.btn_successes, 0, wx.RIGHT, 5) - btn_row_sizer.Add(self.btn_help, 0, 0, 0) + btn_row_sizer.Add(self.btn_successes, 0, 0, 0) - self.btn_triage = wx.Button(self, label="📝 Build Triage Plan") + self.btn_triage = wx.Button(self, label=label_triage) self.btn_triage.Bind(wx.EVT_BUTTON, self.on_build_triage) self.btn_triage.SetForegroundColour(wx.Colour(255, 203, 5)) btn_row_sizer.Add(self.btn_triage, 0, wx.LEFT, 15) @@ -2309,7 +2573,16 @@ def on_build_triage(self, event): wx.MessageBox("No confusions detected to triage!", "All Clear", wx.OK | wx.ICON_INFORMATION) return - dialog = TriageBuilderDialog(self, all_confusions, self.example_map, self.report, self.cm, self.classnames, self.embedding_map) + dialog = TriageBuilderDialog( + self, + all_confusions, + self.example_map, + self.report, + self.cm, + self.classnames, + self.embedding_map, + source_dataset_root=self.source_dataset_root, + ) dialog.ShowModal() dialog.Destroy() @@ -2341,8 +2614,7 @@ def update_grid_data(self): bg_color = wx.Colour(r_val, 0, 0) elif i == j and row_sum > 0: accuracy = self.cm[i][j] / row_sum if row_sum > 0 else 0 - g_val = int(40 + (215 * accuracy)) - bg_color = wx.Colour(0, g_val, 0) + bg_color = wx.Colour(*cm_correct_cell_rgb(accuracy)) else: bg_color = wx.Colour(30, 30, 30) else: @@ -2408,20 +2680,16 @@ def analyze_confusion_data(self): self.nlp_success = [] self.nlp_meaningless = [] - total_support = sum(self.report.get(self.classnames[i], {}).get('support', 0) for i in range(cm_rows)) - + self.nlp_meaningless = collect_insufficient_support_entries(self.classnames, self.report) + low_support_classes = {entry['class'] for entry in self.nlp_meaningless} + for i in range(cm_rows): true_class = self.classnames[i] metrics = self.report.get(true_class, {}) support = float(metrics.get('support', 0)) f1_score = float(metrics.get('f1-score', 0.0)) - - if support == 0: - continue - min_support_threshold = max(20, total_support * 0.01) - if support < min_support_threshold: - self.nlp_meaningless.append(true_class) + if true_class in low_support_classes: continue if f1_score >= 0.85: @@ -2477,7 +2745,7 @@ def analyze_confusion_data(self): major_count = len(self.nlp_major) if major_count == 0: - self.synopsis_label.SetLabel("No major systematic confusions detected. Model looks great!") + self.synopsis_label.SetLabel("No major confusion patterns were identified at the configured thresholds.") elif major_count > 5: self.synopsis_label.SetLabel(f"{major_count} major systematic confusions detected. Showing top 5 most severe.") else: @@ -2493,7 +2761,7 @@ def show_major_confusions_view(self, event=None): html = "" if not self.nlp_major: - html += "

Everything looks great!

No major systematic confusions detected.

" + html += "

No major confusion patterns

No major confusion patterns were identified at the configured thresholds.

" else: html += "

Major Systematic Confusions:

" for count, i, j, prop in self.nlp_major[:5]: @@ -2523,7 +2791,7 @@ def show_minor_confusions_view(self, event=None): if not self.nlp_minor: - html += "

Everything looks great!

No dispersed minor confusions detected.

" + html += "

No dispersed minor confusion patterns

No dispersed minor confusion patterns were identified at the configured thresholds.

" else: html += "

Dispersed / Minor Confusions:

" html += "

The Categorizer struggles with these behaviors, but the mistakes are scattered across many categories rather than just one. This usually indicates weak feature extraction signals, highly variable subject movement, or simply, too few video examples.

" @@ -2535,7 +2803,7 @@ def show_minor_confusions_view(self, event=None): errs = mc['total_errors'] pct = round(mc['pct_errors'], 1) - warning = " ⚠️ (Low Support)" if supp < 100 else "" + warning = " (fewer than 100 examples)" if supp < 100 else "" link = f"{c_name}" html += f"
" @@ -2562,7 +2830,7 @@ def show_successes_view(self, event=None): if self.nlp_success: html += "

Performing Reliably (F1 ≥ 85%):

" - html += "

The Categorizer is successfully and consistently predicting the following behaviors:

" + html += "

On this test set, the following behaviors meet the F1 ≥ 85% threshold (advisory; not a guarantee of field performance):

" html += "
    " for sc in self.nlp_success: c_idx = sc['index'] @@ -2574,15 +2842,19 @@ def show_successes_view(self, event=None): html += f"
  • {link} ({f1_pct}% F1) [{supp} examples]
  • " html += "
" else: - html += "

Keep Tuning!

" - html += "

No behaviors have reached the 85% F1-score threshold. Check the Confusions tab to see where to improve the dataset.

" + html += "

F1 threshold not met

" + html += "

No behaviors reached the F1 ≥ 85% threshold on this test set.

" + html += "

Review Major and Minor Confusions for advisory patterns.

" if self.nlp_meaningless: - html += "

Statistically Meaningless (Excluded):

" - html += "

The following classes have too few examples to accurately evaluate. They have been excluded from major error analysis:

" + html += "

Too few examples for automated analysis

" + html += "

These classes remain listed. Observed support is below the minimum required for automated major/minor interpretation. They are omitted from automated major/minor ranking only.

" html += "
    " for mc in self.nlp_meaningless: - html += f"
  • {mc}
  • " + html += ( + f"
  • {mc['class']}: {mc['support']} examples; " + f"at least {mc['min_support']} required
  • " + ) html += "
" html += "" @@ -2597,12 +2869,13 @@ def show_help_view(self, event=None): html = """ -

How to read this chart:

-

A Confusion Matrix is just a simple table that shows where the Categorizer gets confused.

+

Overview

+

A Confusion Matrix is a table that shows where the Categorizer gets confused on this test set.

Rows (Left): What the subject was actually doing (Ground Truth).

Columns (Top): What the Categorizer guessed the subject was doing (Prediction).

-

If you look at the diagonal line going from top-left to bottom-right, those are the correct guesses. Any numbers sitting outside that diagonal line represent mistakes!

-

You can click on any cell in the matrix to view the video examples of where the Categorizer either correctly or incorrectly guessed the behavior!

+

If you look at the diagonal line going from top-left to bottom-right, those are the correct guesses. Any numbers sitting outside that diagonal line represent mistakes.

+

You can click on any cell in the matrix to view the video examples of where the Categorizer either correctly or incorrectly guessed the behavior.

+

Diagnostic summaries are advisory and are based on the configured thresholds and this test set only.

""" self.nlp_html.SetPage(html) @@ -2670,7 +2943,7 @@ def generate_diagnostic_insights_html(self, top_n=3, support_threshold=50): html = "" if not errors: - html += "

Everything looks great!

No major confusions detected.

" + html += "

No major confusion patterns

No major confusion patterns were identified at the configured thresholds.

" else: html += "

Here is where the Categorizer is struggling:

" @@ -2685,10 +2958,10 @@ def generate_diagnostic_insights_html(self, top_n=3, support_threshold=50): html += "
" if support_true >= support_threshold and support_pred >= support_threshold: - html += f"

{link} ({count} errors)

Diagnosis: Both behaviors have robust training data. Because the Categorizer is still confusing them, they might be visually redundant. Consider merging these labels.

" + html += f"

{link} ({count} errors)

Possible pattern (advisory): Both behaviors have relatively robust support on this test set. Because the Categorizer is still confusing them, they might be visually similar. Consider reviewing whether labels overlap.

" else: lowest_class = true_class if support_true < support_pred else pred_class - html += f"

{link} ({count} errors)

Diagnosis: The model hasn't seen enough of {lowest_class} to learn it well. Adding more video examples should help clear this up.

" + html += f"

{link} ({count} errors)

Possible pattern (advisory): Support for {lowest_class} is limited on this test set. Adding more examples may help, but this is not a definitive diagnosis.

" html += "
" @@ -2767,17 +3040,73 @@ def on_double_click(self, event): class TriageBuilderDialog(wx.Dialog): - def __init__(self, parent, confusions_list, example_map, report, cm, classnames, embedding_map): - super().__init__(parent, title="Triage Action Plan Builder", size=(900, 600), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) + NOMINAL_CLIENT_SIZE = (960, 720) + OPS_HELP_HEIGHT_NOMINAL = 150 + OPS_HELP_HEIGHT_FLOOR = 100 + + def __init__(self, parent, confusions_list, example_map, report, cm, classnames, embedding_map, source_dataset_root=None): + super().__init__( + parent, + title="Triage Action Plan Builder", + style=wx.DEFAULT_DIALOG_STYLE, + ) self.confusions_list = confusions_list self.example_map = example_map self.embedding_map = embedding_map - + self.report = report self.cm = cm self.classnames = classnames - + self.source_dataset_root = source_dataset_root + self.init_ui() + self._apply_fitted_fixed_size() + + def _work_area_size(self): + """Return usable display client area for fitting this dialog.""" + try: + index = wx.Display.GetFromWindow(self) + if index == wx.NOT_FOUND and self.GetParent() is not None: + index = wx.Display.GetFromWindow(self.GetParent()) + if index == wx.NOT_FOUND: + index = 0 + area = wx.Display(index).GetClientArea() + if area.width > 0 and area.height > 0: + return area.width, area.height + except Exception: + pass + parent = self.GetParent() + if parent is not None: + top = parent.GetTopLevelParent() + if top is not None: + size = top.GetClientSize() + if size.width > 0 and size.height > 0: + return size.width, size.height + return 1024, 768 + + def _apply_fitted_fixed_size(self): + """Fit nominal client size to the active display and lock resizing.""" + nominal_w, nominal_h = self.NOMINAL_CLIENT_SIZE + work_w, work_h = self._work_area_size() + fitted_w, fitted_h = fit_dialog_client_size(nominal_w, nominal_h, work_w, work_h) + # Shrink ops-help pane on short fitted heights while keeping a usable floor. + shrink = max(0, nominal_h - fitted_h) + ops_h = max(self.OPS_HELP_HEIGHT_FLOOR, self.OPS_HELP_HEIGHT_NOMINAL - min(shrink, 50)) + if hasattr(self, 'ops_help_html'): + self.ops_help_html.SetMinSize((-1, ops_h)) + self.ops_help_html.SetSize((-1, ops_h)) + if hasattr(self, 'intro_lbl'): + self.intro_lbl.Wrap(max(200, fitted_w - 40)) + self.SetClientSize(fitted_w, fitted_h) + # Lock outer size after client size accounts for title-bar chrome. + outer = self.GetSize() + self.SetMinSize(outer) + self.SetMaxSize(outer) + if self.GetParent() is not None: + self.CentreOnParent() + else: + self.Centre() + self.Layout() def get_centroid(self, file_list): """Calculates the mathematical centroid of a cluster of videos and returns the most representative file.""" @@ -2785,7 +3114,7 @@ def get_centroid(self, file_list): return None if len(file_list) == 1: return file_list[0] - + import numpy as np embs = [self.embedding_map[f] for f in file_list] @@ -2794,105 +3123,146 @@ def get_centroid(self, file_list): mean_norm = np.linalg.norm(mean_emb) if mean_norm == 0: return file_list[0] - + best_sim = -2.0 centroid_file = file_list[0] - + for f, emb in zip(file_list, embs): emb_norm = np.linalg.norm(emb) if emb_norm == 0: continue - + sim = np.dot(emb, mean_emb) / (emb_norm * mean_norm) if sim > best_sim: best_sim = sim centroid_file = f - + return centroid_file - + def init_ui(self): main_sizer = wx.BoxSizer(wx.VERTICAL) - + title_lbl = wx.StaticText(self, label="Assign confusions to a root-cause hypothesis to generate your action plan.") title_font = wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) title_lbl.SetFont(title_font) title_lbl.SetForegroundColour(wx.Colour(255, 203, 5)) main_sizer.Add(title_lbl, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 15) - + + intro_lbl = wx.StaticText( + self, + label=( + "Triage Plan: You are reviewing confusion patterns from this test set. " + "Assign each selected pattern to a possible follow-up hypothesis (H1, H2, or H3). " + "These hypotheses are advisory—they are not diagnoses or required actions. " + "LabGym prepares the plan from your selections; scientific decisions remain yours." + ), + ) + self.intro_lbl = intro_lbl + intro_lbl.Wrap(900) + main_sizer.Add(intro_lbl, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) + + self.ops_help_html = wx.html.HtmlWindow( + self, + size=(-1, self.OPS_HELP_HEIGHT_NOMINAL), + style=wx.html.HW_SCROLLBAR_AUTO | wx.BORDER_SIMPLE, + ) + self.ops_help_html.SetPage( + """ + +

H1 — Merge hypothesis (advisory): Confusion may indicate overlapping behavior definitions. + On Finish, LabGym creates a Triage Plan package and, on the revised sorted test examples only, + moves all examples from the true-class folder into the predicted-class folder and removes the emptied folder. + The original selected test fixture is unchanged. If scientifically accepted, apply the same class-definition + decision to separate training data; do not copy evaluation examples into training; train and reevaluate a new Categorizer.

+

H2 — New-class / extract hypothesis (advisory): H2 is advisory only. LabGym does not create the new class or move examples. + In revised_sorted_test_examples, manually review and organize examples if you accept this hypothesis. + Do not copy evaluation examples into training. Reproduce accepted taxonomy changes in separate training data, + then train and reevaluate a new Categorizer.

+

H3 — Needs-more-data hypothesis (advisory): Confusion may indicate insufficient variety of training examples. + On Finish, LabGym copies up to three reference example pairs into + LabGym_Diagnostics/H3_Variance_References in the package. + These references illustrate variance in the evaluation set. Collect or prepare additional independent training examples; + do not move these evaluation references into training. Train and reevaluate a new Categorizer afterward. + The source dataset is unchanged.

+ + """ + ) + main_sizer.Add(self.ops_help_html, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) + columns_sizer = wx.BoxSizer(wx.HORIZONTAL) - + left_sizer = wx.BoxSizer(wx.VERTICAL) - lbl_unassigned = wx.StaticText(self, label="📥 Unassigned Confusions:") + lbl_unassigned = wx.StaticText(self, label="Unassigned Confusions:") lbl_unassigned.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) left_sizer.Add(lbl_unassigned, 0, wx.BOTTOM, 8) - + self.lb_unassigned = wx.ListBox(self, choices=self.confusions_list, style=wx.LB_EXTENDED) self.lb_unassigned.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) left_sizer.Add(self.lb_unassigned, 1, wx.EXPAND) columns_sizer.Add(left_sizer, 4, wx.EXPAND | wx.ALL, 10) - + mid_sizer = wx.BoxSizer(wx.VERTICAL) mid_sizer.AddStretchSpacer() - - btn_h1 = wx.Button(self, label="Hypothesis 1 (Merge) ➔", size=(190, 40)) + + btn_h1 = wx.Button(self, label="Assign to H1 (Merge)", size=(190, 40)) btn_h1.Bind(wx.EVT_BUTTON, lambda evt: self.move_items(self.lb_unassigned, self.lb_h1)) mid_sizer.Add(btn_h1, 0, wx.BOTTOM | wx.ALIGN_CENTER_HORIZONTAL, 15) - - btn_h2 = wx.Button(self, label="Hypothesis 2 (Extract) ➔", size=(190, 40)) + + btn_h2 = wx.Button(self, label="Assign to H2 (Extract)", size=(190, 40)) btn_h2.Bind(wx.EVT_BUTTON, self.on_move_h2) mid_sizer.Add(btn_h2, 0, wx.BOTTOM | wx.ALIGN_CENTER_HORIZONTAL, 15) - - btn_h3 = wx.Button(self, label="Hypothesis 3 (Add Data) ➔", size=(190, 40)) + + btn_h3 = wx.Button(self, label="Assign to H3 (Add Data)", size=(190, 40)) btn_h3.Bind(wx.EVT_BUTTON, lambda evt: self.move_items(self.lb_unassigned, self.lb_h3)) mid_sizer.Add(btn_h3, 0, wx.BOTTOM | wx.ALIGN_CENTER_HORIZONTAL, 15) - - btn_return = wx.Button(self, label="⬅ Return Selected", size=(190, 40)) + + btn_return = wx.Button(self, label="Return Selected", size=(190, 40)) btn_return.Bind(wx.EVT_BUTTON, self.on_return_items) mid_sizer.Add(btn_return, 0, wx.TOP | wx.ALIGN_CENTER_HORIZONTAL, 40) - + mid_sizer.AddStretchSpacer() columns_sizer.Add(mid_sizer, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 10) - + right_sizer = wx.BoxSizer(wx.VERTICAL) - - lbl_h1 = wx.StaticText(self, label="🔗 H1: Redundant (Auto-Merged):") + + lbl_h1 = wx.StaticText(self, label="H1: Merge on clone:") lbl_h1.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) lbl_h1.SetForegroundColour(wx.Colour(100, 200, 100)) right_sizer.Add(lbl_h1, 0, wx.BOTTOM, 4) self.lb_h1 = wx.ListBox(self, style=wx.LB_EXTENDED) right_sizer.Add(self.lb_h1, 1, wx.EXPAND | wx.BOTTOM, 10) - - lbl_h2 = wx.StaticText(self, label="✂️ H2: Emergent (Manual Extraction):") + + lbl_h2 = wx.StaticText(self, label="H2: New class (manual):") lbl_h2.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) lbl_h2.SetForegroundColour(wx.Colour(100, 150, 255)) right_sizer.Add(lbl_h2, 0, wx.BOTTOM, 4) self.lb_h2 = wx.ListBox(self, style=wx.LB_EXTENDED) right_sizer.Add(self.lb_h2, 1, wx.EXPAND | wx.BOTTOM, 10) - - lbl_h3 = wx.StaticText(self, label="📊 H3: Poor Generalization (Needs Data):") + + lbl_h3 = wx.StaticText(self, label="H3: Needs more data:") lbl_h3.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) lbl_h3.SetForegroundColour(wx.Colour(255, 150, 100)) right_sizer.Add(lbl_h3, 0, wx.BOTTOM, 4) self.lb_h3 = wx.ListBox(self, style=wx.LB_EXTENDED) right_sizer.Add(self.lb_h3, 1, wx.EXPAND) - - columns_sizer.Add(right_sizer, 5, wx.EXPAND | wx.ALL, 10) - + + columns_sizer.Add(right_sizer, 5, wx.EXPAND | wx.ALL, 10) + main_sizer.Add(columns_sizer, 1, wx.EXPAND) - + footer_sizer = wx.BoxSizer(wx.HORIZONTAL) btn_finish = wx.Button(self, label="Finish and Generate Report", size=(220, 40)) btn_finish.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) btn_finish.SetForegroundColour(wx.Colour(100, 200, 100)) btn_finish.Bind(wx.EVT_BUTTON, self.on_finish) footer_sizer.Add(btn_finish, 0, wx.ALL, 10) - + btn_cancel = wx.Button(self, wx.ID_CANCEL, "Cancel", size=(100, 40)) footer_sizer.Add(btn_cancel, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 10) - + main_sizer.Add(footer_sizer, 0, wx.ALIGN_RIGHT) self.SetSizer(main_sizer) self.Layout() - + def move_items(self, source_lb, target_lb, append_text=""): selections = source_lb.GetSelections() if not selections: @@ -2925,131 +3295,278 @@ def on_return_items(self, event): self.lb_unassigned.Append(text) lb.Delete(idx) - def on_finish(self, event): - dlg = wx.TextEntryDialog(self, "Enter a name for the new versioned dataset folder:", "Dataset Versioning", "dataset_v2") - if dlg.ShowModal() != wx.ID_OK: - dlg.Destroy() - return - new_dataset_name = dlg.GetValue().strip() - dlg.Destroy() - - if not new_dataset_name: - return + def _resolve_source_dataset_root(self): + """Return absolute normalized source root, or (None, error_message).""" + explicit = self.source_dataset_root + if explicit: + root = os.path.abspath(os.path.normpath(explicit)) + if not os.path.isdir(root): + return None, f"Selected source dataset root is not a directory:\n{root}" + return root, None sample_file = None for files in self.example_map.values(): if files: sample_file = files[0] break - if not sample_file: - wx.MessageBox("Could not locate source files to clone.", "Error", wx.OK | wx.ICON_ERROR) + return None, "Could not locate source files for the Triage Plan package." + root = os.path.abspath(os.path.normpath(os.path.dirname(os.path.dirname(sample_file)))) + if not os.path.isdir(root): + return None, f"Inferred source dataset root is not a directory:\n{root}" + return root, None + + def _collect_h1_pairs(self): + pairs = [] + for i in range(self.lb_h1.GetCount()): + text = self.lb_h1.GetString(i) + source_class = text.split(" -> ")[0].strip() + target_class = text.split(" -> ")[1].split(" (")[0].strip() + pairs.append((source_class, target_class)) + return pairs + + def _open_folder_safely(self, folder): + try: + if sys.platform == "win32": + os.startfile(folder) + elif sys.platform == "darwin": + subprocess.call(["open", folder]) + else: + subprocess.call(["xdg-open", folder]) + return True, None + except Exception as e: + return False, str(e) + + def on_finish(self, event): + if not triage_assignment_counts(self.lb_h1.GetCount(), self.lb_h2.GetCount(), self.lb_h3.GetCount()): + wx.MessageBox( + "Assign at least one confusion to H1, H2, or H3 before generating a triage plan.", + "Empty triage plan", + wx.OK | wx.ICON_ERROR, + ) + return + + ok_pdf, pdf_err = reportlab_importable() + if not ok_pdf: + wx.MessageBox( + f"ReportLab is required to generate PDFs ({pdf_err}). Please install reportlab before generating a triage plan.", + "Missing Dependency", + wx.OK | wx.ICON_ERROR, + ) + return + + source_root, source_err = self._resolve_source_dataset_root() + if source_root is None: + wx.MessageBox(source_err, "Source Error", wx.OK | wx.ICON_ERROR) return - - original_dataset_dir = os.path.dirname(os.path.dirname(sample_file)) - parent_dir = os.path.dirname(original_dataset_dir) - cloned_dataset_dir = os.path.join(parent_dir, new_dataset_name) + + parent_dir = os.path.dirname(source_root) + suggested_name = next_versioned_triage_package_name(parent_dir, os.path.basename(source_root)) + + dlg = wx.TextEntryDialog( + self, + "Enter a name for the Triage Plan package folder:", + "Triage Plan Package", + suggested_name, + ) + if dlg.ShowModal() != wx.ID_OK: + dlg.Destroy() + return + package_name = dlg.GetValue() + dlg.Destroy() + + ok_name, name_err = validate_triage_package_name(package_name) + if not ok_name: + wx.MessageBox(name_err, "Invalid Package Name", wx.OK | wx.ICON_ERROR) + return + + package_dir = os.path.join(parent_dir, package_name) + if os.path.exists(package_dir): + wx.MessageBox( + f"A folder named \"{package_name}\" already exists.\n\n{package_dir}", + "Package Exists", + wx.OK | wx.ICON_ERROR, + ) + return + + h1_pairs = self._collect_h1_pairs() + if h1_pairs: + collisions, missing = collect_h1_filename_collisions(source_root, h1_pairs) + if missing: + lines = [] + for kind, cls in missing: + label = "true-class (source)" if kind == "source" else "predicted-class (target)" + lines.append(f"- Missing {label} folder: {cls}") + wx.MessageBox( + "H1 class folders are missing from the selected source dataset. " + "No package was created.\n\n" + "\n".join(lines), + "H1 class folder missing", + wx.OK | wx.ICON_ERROR, + ) + return + if collisions: + lines = [] + for rec in collisions: + true_c, pred_c = rec['pair'] + names = ", ".join(rec['filenames']) + lines.append(f"{true_c} → {pred_c}: {names}") + wx.MessageBox( + "The H1 merge would place entries with the same name in one behavior folder. " + "No package was created. Resolve the listed filename collisions, then generate " + "the Triage Plan again.\n\n" + "\n".join(lines), + "H1 filename collision", + wx.OK | wx.ICON_ERROR, + ) + return + + revised_dir = os.path.join(package_dir, "revised_sorted_test_examples") + diagnostics_dir = os.path.join(package_dir, "LabGym_Diagnostics") + busy = False + package_created = False try: - total_size = sum(os.path.getsize(os.path.join(dirpath, f)) for dirpath, _, filenames in os.walk(original_dataset_dir) for f in filenames) + total_size = sum( + os.path.getsize(os.path.join(dirpath, f)) + for dirpath, _, filenames in os.walk(source_root) + for f in filenames + ) total_size_mb = total_size / (1024 * 1024) total, used, free = shutil.disk_usage(parent_dir) if total_size > free: - wx.MessageBox(f"Not enough disk space to clone dataset.\nRequired: {total_size_mb:.2f} MB\nAvailable: {free / (1024*1024):.2f} MB", "Disk Space Error", wx.OK | wx.ICON_ERROR) + wx.MessageBox( + f"Not enough disk space to create the Triage Plan package.\n" + f"Required: {total_size_mb:.2f} MB\nAvailable: {free / (1024*1024):.2f} MB", + "Disk Space Error", + wx.OK | wx.ICON_ERROR, + ) return - wx.BeginBusyCursor() - shutil.copytree(original_dataset_dir, cloned_dataset_dir) - - for i in range(self.lb_h1.GetCount()): - text = self.lb_h1.GetString(i) - source_class = text.split(" -> ")[0].strip() - target_class = text.split(" -> ")[1].split(" (")[0].strip() - - cloned_source_dir = os.path.join(cloned_dataset_dir, source_class) - cloned_target_dir = os.path.join(cloned_dataset_dir, target_class) - - if os.path.exists(cloned_source_dir): - if not os.path.exists(cloned_target_dir): - os.makedirs(cloned_target_dir) - - for filename in os.listdir(cloned_source_dir): - shutil.move(os.path.join(cloned_source_dir, filename), os.path.join(cloned_target_dir, filename)) - shutil.rmtree(cloned_source_dir) - - export_dir = os.path.join(cloned_dataset_dir, "LabGym_Diagnostics") - os.makedirs(export_dir, exist_ok=True) - pdf_path = os.path.join(export_dir, "Triage_Action_Plan.pdf") + wx.BeginBusyCursor() + busy = True + + os.makedirs(package_dir) + package_created = True + shutil.copytree(source_root, revised_dir) + os.makedirs(diagnostics_dir) + + for source_class, target_class in h1_pairs: + revised_source_dir = os.path.join(revised_dir, source_class) + revised_target_dir = os.path.join(revised_dir, target_class) + if not os.path.isdir(revised_source_dir) or not os.path.isdir(revised_target_dir): + raise OSError( + f"H1 class folder missing after copy: {source_class} -> {target_class}" + ) + for filename in os.listdir(revised_source_dir): + shutil.move( + os.path.join(revised_source_dir, filename), + os.path.join(revised_target_dir, filename), + ) + shutil.rmtree(revised_source_dir) + + pdf_path = next_versioned_pdf_path(diagnostics_dir) if self.lb_h3.GetCount() > 0: import random - h3_ref_dir = os.path.join(export_dir, "H3_Variance_References") + h3_ref_dir = os.path.join(diagnostics_dir, "H3_Variance_References") os.makedirs(h3_ref_dir, exist_ok=True) - + for i in range(self.lb_h3.GetCount()): text = self.lb_h3.GetString(i) source_class = text.split(" -> ")[0].strip() target_class = text.split(" -> ")[1].split(" (")[0].strip() - + key = (source_class, target_class) examples = self.example_map.get(key, []) - + if examples: samples = random.sample(examples, min(3, len(examples))) for idx, avi_path in enumerate(samples): if os.path.exists(avi_path): safe_source = source_class.replace(" ", "_") safe_target = target_class.replace(" ", "_") - + new_avi_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.avi" shutil.copy2(avi_path, os.path.join(h3_ref_dir, new_avi_name)) - + jpg_path = avi_path.replace(".avi", ".jpg") if os.path.exists(jpg_path): new_jpg_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.jpg" shutil.copy2(jpg_path, os.path.join(h3_ref_dir, new_jpg_name)) - self.generate_pdf_report(pdf_path, new_dataset_name) + pdf_ok, pdf_fail_reason = self.generate_pdf_report(pdf_path, package_name) + + if busy: + wx.EndBusyCursor() + busy = False + + if not pdf_ok or not os.path.isfile(pdf_path): + detail = pdf_fail_reason or "PDF was not created." + wx.MessageBox( + "The Triage Plan package exists, but the expected PDF was not created.\n\n" + f"Package:\n{package_dir}\n\n" + f"Revised sorted test examples:\n{revised_dir}\n\n" + f"Failure detail:\n{detail}", + "Partial triage outcome", + wx.OK | wx.ICON_WARNING, + ) + return + + wx.MessageBox( + "Triage Plan package created.\n\n" + f"Package:\n{package_dir}\n\n" + f"Revised sorted test examples (select this folder in LabGym):\n{revised_dir}\n\n" + f"PDF:\n{pdf_path}\n\n" + "The original source fixture was not modified.", + "Triage Complete", + wx.OK | wx.ICON_INFORMATION, + ) - wx.EndBusyCursor() - - wx.MessageBox(f"Successfully cloned dataset and executed Triage Plan!\n\nYour new dataset and PDF Action Plan are located at:\n{export_dir}", "Triage Complete", wx.OK | wx.ICON_INFORMATION) - self.EndModal(wx.ID_OK) - - if sys.platform == "win32": - os.startfile(export_dir) - elif sys.platform == "darwin": - subprocess.call(["open", export_dir]) - else: - subprocess.call(["xdg-open", export_dir]) + + opened, open_err = self._open_folder_safely(package_dir) + if not opened: + wx.MessageBox( + "The Triage Plan package was created, but LabGym could not open the package folder.\n\n" + f"Package:\n{package_dir}\n\n" + f"Detail:\n{open_err}", + "Folder Open Failed", + wx.OK | wx.ICON_WARNING, + ) except PermissionError: - wx.EndBusyCursor() - wx.MessageBox("LabGym does not have permission to write to this directory. Check your folder permissions.", "Permission Error", wx.OK | wx.ICON_ERROR) + if busy: + wx.EndBusyCursor() + msg = "LabGym does not have permission to write to this directory. Check your folder permissions." + if package_created: + msg += f"\n\nA partial Triage Plan package may remain at:\n{package_dir}" + wx.MessageBox(msg, "Permission Error", wx.OK | wx.ICON_ERROR) except Exception as e: - wx.EndBusyCursor() - wx.MessageBox(f"An OS error occurred during triage execution:\n{e}", "System Error", wx.OK | wx.ICON_ERROR) + if busy: + wx.EndBusyCursor() + msg = f"An OS error occurred during triage execution:\n{e}" + if package_created: + msg += f"\n\nA partial Triage Plan package may remain at:\n{package_dir}" + wx.MessageBox(msg, "System Error", wx.OK | wx.ICON_ERROR) def generate_pdf_report(self, filepath, dataset_name): - """Generates a styled, professional PDF report with simplified layman descriptions and addressed highlights.""" - try: - from reportlab.lib.pagesizes import letter - from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle - from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle - from reportlab.lib.colors import HexColor, Color - from reportlab.lib import colors - from reportlab.lib.units import inch - import datetime - import os - except ImportError as e: - wx.MessageBox(f"ReportLab is required to generate PDFs ({e}). Please run 'pip install reportlab'.", "Missing Dependency", wx.OK | wx.ICON_WARNING) - return + """Generate triage PDF. Returns (ok, error_message_or_None).""" + try: + from reportlab.lib.pagesizes import letter + from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle + from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle + from reportlab.lib.colors import HexColor, Color + from reportlab.lib import colors + from reportlab.lib.units import inch + import datetime + import os + except ImportError as e: + return False, f"ReportLab is required to generate PDFs ({e})." + try: doc = SimpleDocTemplate(filepath, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) styles = getSampleStyleSheet() - + title_style = ParagraphStyle('Title', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=16, textColor=HexColor("#00274C"), spaceAfter=16) h2_style = ParagraphStyle('H2', parent=styles['Heading2'], fontName='Helvetica-Bold', fontSize=12, textColor=HexColor("#333333"), spaceBefore=16, spaceAfter=8) body_style = ParagraphStyle('Body', parent=styles['Normal'], fontName='Helvetica', fontSize=10, leading=14, textColor=HexColor("#1A1A1A")) @@ -3058,22 +3575,33 @@ def generate_pdf_report(self, filepath, dataset_name): caption_style = ParagraphStyle('Caption', parent=styles['Normal'], fontName='Helvetica-Oblique', fontSize=8, textColor=HexColor("#666666"), leftIndent=20, spaceBefore=4, spaceAfter=16) Story = [] - + accuracy = self.report.get('accuracy', 0.0) macro_f1 = self.report.get('macro avg', {}).get('f1-score', 0.0) - + Story.append(Paragraph(f"LabGym Triage Action Plan", title_style)) - Story.append(Paragraph(f"Dataset Target: {dataset_name}", body_style)) + Story.append(Paragraph(f"Package: {dataset_name}", body_style)) Story.append(Paragraph(f"Date Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}", body_style)) Story.append(Paragraph(f"Overall Accuracy: {accuracy*100:.1f}% | Macro F1-Score: {macro_f1*100:.1f}%", body_style)) Story.append(Spacer(1, 15)) + Story.append(Paragraph("Package layout and remediation", h2_style)) + Story.append(Paragraph( + "revised_sorted_test_examples contains the revised sorted test examples, cloned from the selected evaluation fixture. " + "LabGym_Diagnostics contains this report and optional H3 references. The original source fixture is unchanged. " + "This package is a Triage Plan result, not a complete repair or training workflow. For later LabGym sorted-example steps, " + "select revised_sorted_test_examples, not the package root. Reproduce accepted remediation in separate training data, " + "do not copy evaluation examples into training, and train and reevaluate a new Categorizer.", + body_style, + )) + Story.append(Spacer(1, 15)) + Story.append(Paragraph("Confusion Matrix Overview", h2_style)) Story.append(Paragraph("Cells highlighted with a thick gold border indicate confusions that were addressed in this triage session.", caption_style)) - + headers = ["True \\ Pred"] + [str(idx + 1) for idx in range(len(self.classnames))] cm_data = [headers] - + for i in range(len(self.classnames)): row_data = [f"{i + 1}. {self.classnames[i]}"] for j in range(len(self.classnames)): @@ -3081,18 +3609,18 @@ def generate_pdf_report(self, filepath, dataset_name): cm_data.append(row_data) t_style = TableStyle([ - ('BACKGROUND', (0,0), (-1,0), HexColor("#00274C")), + ('BACKGROUND', (0,0), (-1,0), HexColor("#00274C")), ('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ('ALIGN', (0,1), (0,-1), 'LEFT'), ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'), ('FONTSIZE', (0,0), (-1,-1), 7), ('BOTTOMPADDING', (0,0), (-1,0), 6), - ('BACKGROUND', (0,1), (0,-1), HexColor("#f0f0f0")), + ('BACKGROUND', (0,1), (0,-1), HexColor("#f0f0f0")), ('FONTNAME', (0,1), (0,-1), 'Helvetica-Bold'), ('GRID', (0,0), (-1,-1), 0.5, colors.grey), ]) - + for i in range(len(self.classnames)): row_sum = sum(self.cm[i]) for j in range(len(self.classnames)): @@ -3124,46 +3652,63 @@ def generate_pdf_report(self, filepath, dataset_name): first_col_width = 1.5 * inch remaining_width = 5.0 * inch - data_col_width = remaining_width / len(self.classnames) - + data_col_width = remaining_width / max(len(self.classnames), 1) + col_widths = [first_col_width] + [data_col_width] * len(self.classnames) - + cm_table = Table(cm_data, colWidths=col_widths) cm_table.setStyle(t_style) Story.append(cm_table) Story.append(Spacer(1, 15)) - Story.append(Paragraph("Hypothesis 1: Redundant Behaviors", h2_style)) - Story.append(Paragraph("These behaviors look identical to the software. LabGym has automatically combined them into a single category for this dataset. No further action is required.", body_style)) + Story.append(Paragraph("Hypothesis 1: Merge on revised sorted test examples (advisory)", h2_style)) + Story.append(Paragraph( + "Confusion may indicate overlapping behavior definitions. H1 is an advisory merge hypothesis. " + "The merge is applied only to the revised sorted test examples: LabGym moves all examples from each listed " + "true-class folder into the predicted-class folder and removes the emptied folder. The original selected test fixture remains unchanged. " + "If scientifically accepted, apply the same class-definition decision to the separate training dataset. " + "Do not copy evaluation examples into training. Train and reevaluate a new Categorizer.", + body_style, + )) Story.append(Spacer(1, 5)) - + if self.lb_h1.GetCount() == 0: Story.append(Paragraph("None selected.", item_style)) for i in range(self.lb_h1.GetCount()): Story.append(Paragraph(f"• {self.lb_h1.GetString(i)}", item_style)) Story.append(Spacer(1, 10)) - Story.append(Paragraph("Hypothesis 2: Emergent Behaviors", h2_style)) - Story.append(Paragraph("The software is confusing these behaviors because there is likely a third, completely different behavior happening that it hasn't been taught yet.", body_style)) - Story.append(Paragraph("ACTION REQUIRED: Go to the video folders and manually move the mixed-up videos into the new folder you just named.", action_style)) - + Story.append(Paragraph("Hypothesis 2: New class / extract (advisory)", h2_style)) + Story.append(Paragraph( + "H2 is advisory only. LabGym does not create the new class or move examples. " + "In revised_sorted_test_examples, manually review and organize examples if you accept this hypothesis. " + "Do not copy evaluation examples into training. Reproduce accepted taxonomy changes in separate training data, " + "then train and reevaluate a new Categorizer.", + body_style, + )) + Story.append(Paragraph( + "USER ACTION: In revised_sorted_test_examples, manually review and organize examples if you accept this hypothesis. " + "Reproduce accepted changes in separate training data; do not copy evaluation examples into training.", + action_style, + )) + if self.lb_h2.GetCount() == 0: Story.append(Paragraph("None selected.", item_style)) else: for i in range(self.lb_h2.GetCount()): item_text = self.lb_h2.GetString(i) Story.append(Paragraph(f"• {item_text}", item_style)) - + source_class = item_text.split(" -> ")[0].strip() target_class = item_text.split(" -> ")[1].split(" (")[0].strip() key = (source_class, target_class) examples = self.example_map.get(key, []) - + if examples: avi_path = self.get_centroid(examples) jpg_path = avi_path.replace(".avi", ".jpg") file_name = os.path.basename(avi_path) - + if os.path.exists(jpg_path): img = Image(jpg_path) img.drawWidth = 2 * inch @@ -3171,30 +3716,40 @@ def generate_pdf_report(self, filepath, dataset_name): Story.append(img) Story.append(Paragraph(f"Reference file: {file_name}", caption_style)) - Story.append(Paragraph("Hypothesis 3: Poor Generalization", h2_style)) - Story.append(Paragraph("The software is failing here because it hasn't seen enough different examples of this behavior.", body_style)) - Story.append(Paragraph("ACTION REQUIRED: Go back to the 'Generate/Sort Behavior Examples' tool and add more videos of these specific behaviors in different environments or angles.", action_style)) - + Story.append(Paragraph("Hypothesis 3: Needs more data (advisory)", h2_style)) + Story.append(Paragraph( + "Confusion may indicate insufficient variety of training examples. LabGym copies up to three reference example pairs into " + "LabGym_Diagnostics/H3_Variance_References and does not merge classes. " + "These references illustrate variance in the evaluation set. Collect or prepare additional independent training examples; " + "do not move these evaluation references into training. Train and reevaluate a new Categorizer afterward. " + "The source dataset is unchanged.", + body_style, + )) + Story.append(Paragraph( + "USER ACTION (optional): Collect or prepare additional independent training examples; do not move these evaluation references into training.", + action_style, + )) + if self.lb_h3.GetCount() == 0: Story.append(Paragraph("None selected.", item_style)) else: export_dir = os.path.dirname(filepath) h3_ref_dir = os.path.join(export_dir, "H3_Variance_References") - + for i in range(self.lb_h3.GetCount()): item_text = self.lb_h3.GetString(i) Story.append(Paragraph(f"• {item_text}", item_style)) - + source_class = item_text.split(" -> ")[0].strip() target_class = item_text.split(" -> ")[1].split(" (")[0].strip() safe_source = source_class.replace(" ", "_") safe_target = target_class.replace(" ", "_") - + for idx in range(3): jpg_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.jpg" avi_name = f"{safe_source}_to_{safe_target}_sample{idx+1}.avi" jpg_path = os.path.join(h3_ref_dir, jpg_name) - + if os.path.exists(jpg_path): img = Image(jpg_path) img.drawWidth = 2 * inch @@ -3203,31 +3758,36 @@ def generate_pdf_report(self, filepath, dataset_name): Story.append(Paragraph(f"Reference file: H3_Variance_References/{avi_name}", caption_style)) Story.append(Paragraph("Baseline References (True Positives)", h2_style)) - Story.append(Paragraph("Below are representative examples of correctly classified behaviors. Use these as a visual baseline for what the model currently considers an 'ideal' representation of the class.", body_style)) - + Story.append(Paragraph("Below are representative examples of correctly classified behaviors on this test set. Use these as a visual baseline for what the model currently treats as an example of the class.", body_style)) + has_baselines = False for i in range(len(self.classnames)): cls_name = self.classnames[i] if self.cm[i][i] > 0: key = (cls_name, cls_name) examples = self.example_map.get(key, []) - + if examples: has_baselines = True Story.append(Paragraph(f"• {cls_name}", item_style)) - + avi_path = self.get_centroid(examples) jpg_path = avi_path.replace(".avi", ".jpg") file_name = os.path.basename(avi_path) - + if os.path.exists(jpg_path): img = Image(jpg_path) img.drawWidth = 2 * inch img.drawHeight = 2 * inch Story.append(img) Story.append(Paragraph(f"Reference file: {file_name}", caption_style)) - + if not has_baselines: Story.append(Paragraph("No correct classifications available to generate baselines.", item_style)) - doc.build(Story) \ No newline at end of file + doc.build(Story) + if not os.path.isfile(filepath): + return False, "PDF build completed but the output file was not found." + return True, None + except Exception as e: + return False, str(e) diff --git a/LabGym/gui_main.py b/LabGym/gui_main.py index 708b90ef..2dc2660f 100644 --- a/LabGym/gui_main.py +++ b/LabGym/gui_main.py @@ -204,7 +204,8 @@ def display_window(self): button_generateimages=wx.Button(panel,label='Generate Image Examples',size=(300,40)) button_generateimages.Bind(wx.EVT_BUTTON,self.generate_images) wx.Button.SetToolTip(button_generateimages,'Extract frames from videos for annotating animals / objects in them so that they can be used to train a Detector to detect animals / objects of your interest. See Extended Guide for how to select images to annotate.') - detector_sizer.Add(button_generateimages,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) + boxsizer.Add(button_generateimages,0,wx.ALIGN_CENTER,10) + boxsizer.Add(0,5,0) link_annotate=create_hyperlink(panel,'Annotate images with EZannot','https://github.com/yujiahu415/EZannot') detector_sizer.Add(link_annotate,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) @@ -212,7 +213,8 @@ def display_window(self): button_traindetectors=wx.Button(panel,label='Train Detectors',size=(300,40)) button_traindetectors.Bind(wx.EVT_BUTTON,self.train_detectors) wx.Button.SetToolTip(button_traindetectors,'There are two detection methods in LabGym, the Detector-based method is more versatile (useful in any recording conditions and complex interactive behaviors) but slower than the other background subtraction-based method (requires static background and stable illumination in videos).') - detector_sizer.Add(button_traindetectors,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) + boxsizer.Add(button_traindetectors,0,wx.ALIGN_CENTER,10) + boxsizer.Add(0,5,0) button_testdetectors=wx.Button(panel,label='Test Detectors',size=(300,40)) button_testdetectors.Bind(wx.EVT_BUTTON,self.test_detectors) @@ -232,30 +234,28 @@ def display_window(self): button_generatebehaviorexamples=wx.Button(panel,label='Generate Behavior Examples',size=(300,40)) button_generatebehaviorexamples.Bind(wx.EVT_BUTTON,self.generate_behaviorexamples) wx.Button.SetToolTip(button_generatebehaviorexamples,'Generate behavior examples for sorting them so that they can be used to teach a Categorizer to recognize behaviors defined by you.') - categorizer_sizer.Add(button_generatebehaviorexamples,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) + boxsizer.Add(button_generatebehaviorexamples,0,wx.ALIGN_CENTER,10) + boxsizer.Add(0,5,0) button_sortbehaviorexamples=wx.Button(panel,label='Sort Behavior Examples',size=(300,40)) button_sortbehaviorexamples.Bind(wx.EVT_BUTTON,self.sort_behaviorexamples) wx.Button.SetToolTip(button_sortbehaviorexamples,'Set shortcut keys for behavior categories to help sorting the behavior examples in an easier way. See Extended Guide for how to select and sort the behavior examples.') - categorizer_sizer.Add(button_sortbehaviorexamples,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) + boxsizer.Add(button_sortbehaviorexamples,0,wx.ALIGN_CENTER,10) + boxsizer.Add(0,5,0) button_traincategorizers=wx.Button(panel,label='Train Categorizers',size=(300,40)) button_traincategorizers.Bind(wx.EVT_BUTTON,self.train_categorizers) wx.Button.SetToolTip(button_traincategorizers,'Customize a Categorizer and use the sorted behavior examples to train it so that it can recognize the behaviors of your interest during analysis.') - categorizer_sizer.Add(button_traincategorizers,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) + boxsizer.Add(button_traincategorizers,0,wx.ALIGN_CENTER,10) + boxsizer.Add(0,5,0) button_testcategorizers=wx.Button(panel,label='Test Categorizers',size=(300,40)) button_testcategorizers.Bind(wx.EVT_BUTTON,self.test_categorizers) wx.Button.SetToolTip(button_testcategorizers,'Test trained Categorizers on the sorted ground-truth behavior examples (similar to the behavior examples used for training a Categorizer).') - categorizer_sizer.Add(button_testcategorizers,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) - - columns_sizer.Add(detector_sizer, 1, wx.EXPAND | wx.RIGHT, 40) - columns_sizer.Add(divider_line, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 20) - columns_sizer.Add(categorizer_sizer, 1, wx.EXPAND | wx.LEFT, 40) - - main_sizer.Add(columns_sizer, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 50) + boxsizer.Add(button_testcategorizers,0,wx.ALIGN_CENTER,10) + boxsizer.Add(0,50,0) - panel.SetSizer(main_sizer) + panel.SetSizer(boxsizer) self.Centre() self.Show(True) diff --git a/LabGym/tests/test_ac_categorizer_mismatch.py b/LabGym/tests/test_ac_categorizer_mismatch.py new file mode 100644 index 00000000..853fa95e --- /dev/null +++ b/LabGym/tests/test_ac_categorizer_mismatch.py @@ -0,0 +1,85 @@ +"""AC categorizer class-mismatch contract.""" + +from unittest.mock import patch + +import pandas as pd +import pytest + +from LabGym import mywx # noqa: F401 +import wx + +from LabGym.categorizer import CategorizerClassMismatchError, Categorizers + + +@pytest.fixture(scope='module') +def wx_app(): + app = wx.App(False) + yield app + wx.CallAfter(app.ExitMainLoop) + app.MainLoop() + del app + wx.App._instance = None + + +def test_mismatch_error_lists_are_sorted_and_message_is_explicit(): + err = CategorizerClassMismatchError(['b_extra', 'a_extra'], ['missing_z', 'missing_a']) + assert err.unrecognized_folders == ['a_extra', 'b_extra'] + assert err.missing_classes == ['missing_a', 'missing_z'] + text = str(err) + assert 'exactly match' in text + assert 'a_extra' in text + assert 'missing_a' in text + + +def test_test_categorizer_raises_before_model_load_on_mismatch(tmp_path): + ground = tmp_path / 'gt' + (ground / 'walk').mkdir(parents=True) + (ground / 'extra').mkdir(parents=True) + model = tmp_path / 'model' + model.mkdir(parents=True) + pd.DataFrame( + { + 'network': [0, None], + 'time_step': [15, None], + 'inner_code': [1, None], + 'background_free': [0, None], + 'dim_conv': [8, None], + 'level_conv': [1, None], + 'channel': [1, None], + 'classnames': ['walk', 'run'], + } + ).to_csv(model / 'model_parameters.txt', index=False) + + ca = Categorizers() + with patch('LabGym.categorizer.load_model') as load_model: + with pytest.raises(CategorizerClassMismatchError) as caught: + ca.test_categorizer(str(ground), str(model), result_path=str(tmp_path / 'out')) + load_model.assert_not_called() + assert 'extra' in caught.value.unrecognized_folders + assert 'run' in caught.value.missing_classes + + +def test_gui_mismatch_handler_does_not_unpack_none(wx_app): + from LabGym.gui_categorizer import PanelLv2_TestCategorizers + + with patch.object(PanelLv2_TestCategorizers, 'display_window', lambda self: None): + with patch('LabGym.gui_categorizer.config.get_config', return_value={'models': '/tmp'}): + frame = wx.Frame(None) + panel = PanelLv2_TestCategorizers(frame) + panel.file_path = '/tmp/gt' + panel.path_to_categorizer = '/tmp/model' + panel.out_path = None + panel.checkbox_open_interactive = wx.CheckBox(frame) + panel.checkbox_open_interactive.SetValue(True) + + err = CategorizerClassMismatchError(['extra'], ['missing']) + with patch('LabGym.gui_categorizer.Categorizers') as CA: + CA.return_value.test_categorizer.side_effect = err + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + panel.test_categorizer(None) + mb.assert_called_once() + args, kwargs = mb.call_args + assert args[1] == 'Class name mismatch' + assert 'Unrecognized behavior folders' in args[0] + assert 'Model classes absent' in args[0] + frame.Destroy() diff --git a/LabGym/tests/test_ac_cm_colors.py b/LabGym/tests/test_ac_cm_colors.py new file mode 100644 index 00000000..2b09c6b5 --- /dev/null +++ b/LabGym/tests/test_ac_cm_colors.py @@ -0,0 +1,63 @@ +"""AC matrix correct-cell color endpoint and ordering.""" + +from LabGym import mywx # noqa: F401 # must precede wx-dependent LabGym imports + +from LabGym.gui_categorizer import ( + CM_CORRECT_RGB_MAX, + CM_CORRECT_RGB_MIN, + cm_correct_cell_rgb, +) + + +def _srgb_channel_to_linear(c): + c = c / 255.0 + if c <= 0.04045: + return c / 12.92 + return ((c + 0.055) / 1.055) ** 2.4 + + +def relative_luminance(rgb): + r, g, b = rgb + return ( + 0.2126 * _srgb_channel_to_linear(r) + + 0.7152 * _srgb_channel_to_linear(g) + + 0.0722 * _srgb_channel_to_linear(b) + ) + + +def contrast_ratio(fg_rgb, bg_rgb): + l1 = relative_luminance(fg_rgb) + l2 = relative_luminance(bg_rgb) + lighter = max(l1, l2) + darker = min(l1, l2) + return (lighter + 0.05) / (darker + 0.05) + + +def test_cm_correct_max_endpoint_is_approved_green(): + assert CM_CORRECT_RGB_MAX == (46, 125, 50) + assert cm_correct_cell_rgb(1.0) == (46, 125, 50) + + +def test_cm_correct_min_endpoint_is_darker(): + lo = cm_correct_cell_rgb(0.0) + hi = cm_correct_cell_rgb(1.0) + assert lo == CM_CORRECT_RGB_MIN + assert sum(lo) < sum(hi) + + +def test_cm_correct_scale_is_monotonic_in_green(): + prev_g = -1 + for step in range(0, 11): + r, g, b = cm_correct_cell_rgb(step / 10) + assert g >= prev_g + prev_g = g + assert 0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255 + + +def test_white_text_contrast_at_max_green(): + """Approved max green must meet WCAG AA contrast for white text (>= 4.5:1).""" + rgb = cm_correct_cell_rgb(1.0) + assert rgb == (46, 125, 50) + ratio = contrast_ratio((255, 255, 255), rgb) + assert ratio >= 4.5 + assert abs(ratio - 5.13) < 0.05 diff --git a/LabGym/tests/test_ac_diagnostics_copy.py b/LabGym/tests/test_ac_diagnostics_copy.py new file mode 100644 index 00000000..58b74ecd --- /dev/null +++ b/LabGym/tests/test_ac_diagnostics_copy.py @@ -0,0 +1,151 @@ +"""AC Training Module single-column structure and diagnostic copy contracts.""" + +from pathlib import Path + +from LabGym import mywx # noqa: F401 + +from LabGym.gui_categorizer import ( + AC_DIAGNOSTIC_BUTTON_LABELS, + collect_insufficient_support_entries, + insufficient_support_threshold, +) + + +APPROVED_ORDER = ( + 'Generate Image Examples', + 'Annotate images with EZannot', + 'Train Detectors', + 'Test Detectors', + 'Generate Behavior Examples', + 'Sort Behavior Examples', + 'Train Categorizers', + 'Test Categorizers', +) + + +def test_training_module_source_has_single_column_bindings(): + src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_main.py' + text = src.read_text() + start = text.index('class PanelLv1_TrainingModule') + end = text.index('class PanelLv1_AnalysisModule') + body = text[start:end] + assert 'ACTION_LABELS' not in body + assert 'Detector Pipeline' not in body + assert 'Categorizer Pipeline' not in body + assert 'divider_line' not in body + assert 'columns_sizer' not in body + for label in APPROVED_ORDER: + if label.startswith('Annotate'): + assert 'Annotate images with EZannot' in body + else: + assert f"label='{label}'" in body + for handler in ( + 'generate_images', + 'train_detectors', + 'test_detectors', + 'generate_behaviorexamples', + 'sort_behaviorexamples', + 'train_categorizers', + 'test_categorizers', + ): + assert f'self.{handler}' in body + + +def test_ac_diagnostic_labels_have_no_emoji_and_overview_first(): + assert AC_DIAGNOSTIC_BUTTON_LABELS[0] == 'Overview' + assert AC_DIAGNOSTIC_BUTTON_LABELS == ( + 'Overview', + 'Major Confusions', + 'Minor Confusions', + 'Successes', + 'Build Triage Plan', + ) + joined = ' '.join(AC_DIAGNOSTIC_BUTTON_LABELS) + for ch in ('🔴', '🟡', '🟢', '🔵', '📝', '⚠️', '⚠'): + assert ch not in joined + + +def test_diagnostic_button_construction_uses_label_constant(): + src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py' + text = src.read_text() + start = text.index('def init_ui(self):') + # Limit to AutomatedDiagnosticsDialog.init_ui (first init_ui after that class). + class_start = text.index('class AutomatedDiagnosticsDialog') + start = text.index('def init_ui(self):', class_start) + end = text.index('\tdef update_grid_data', start) + body = text[start:end] + assert 'AC_DIAGNOSTIC_BUTTON_LABELS' in body + assert 'label="Overview"' not in body + assert 'label="🔴' not in body + + +def test_diagnostic_copy_rejects_overconfident_phrases_and_uses_new_low_support(): + src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py' + text = src.read_text() + banned = ( + 'Model looks great!', + 'Statistically Meaningless', + 'successfully and consistently', + 'Everything looks great!', + 'Keep Tuning!', + 'Diagnosis:', + 'Insufficient sample support for automated interpretation', + '⚠️', + ) + for phrase in banned: + assert phrase not in text, phrase + assert 'Too few examples for automated analysis' in text + assert ": {mc['support']} examples; " in text + assert "at least {mc['min_support']} required" in text + assert '(fewer than 100 examples)' in text + assert 'Possible pattern (advisory)' in text + assert 'H1 — Merge hypothesis (advisory)' in text + assert 'LabGym does not create the new class or move examples' in text + assert 'revised_sorted_test_examples' in text + assert 'H3_Variance_References' in text + assert 'Hypothesis 1: Merge on revised sorted test examples (advisory)' in text + assert 'Package layout and remediation' in text + assert 'select revised_sorted_test_examples, not the package root' in text + assert 'do not copy evaluation examples into training' in text + assert 'Triage Plan: You are reviewing confusion patterns' in text + assert 'Build Triage Plan' in text + assert 'scientific decisions remain yours' in text + assert 'Open interactive results when testing finishes' not in text + assert 'Show interactive results after testing' in text + assert 'Triage_Action_Plan.pdf' not in text + assert 'dataset_v2' not in text + assert 'next_versioned_pdf_path' in text + assert 'next_versioned_triage_package_name' in text + assert 'sanitize_triage_package_base' in text + assert 'validate_triage_package_name' in text + assert 'collect_h1_filename_collisions' in text + assert 'fit_dialog_client_size' in text + assert 'NOMINAL_CLIENT_SIZE = (960, 720)' in text + assert 'wx.RESIZE_BORDER' not in text.split('class TriageBuilderDialog')[1].split('def move_items')[0] + assert 'ops_help_html' in text + assert 'self.intro_lbl' in text + assert '→' in text + assert '≥' in text + assert 'Paragraph(f"• ' in text + assert 'LabGym Triage Action Plan' in text + assert 'source_dataset_root' in text + + +def test_zero_and_positive_low_support_entries(): + report = { + 'absent': {'support': 0, 'f1-score': 0.0}, + 'sparse': {'support': 5, 'f1-score': 0.2}, + 'enough': {'support': 100, 'f1-score': 0.5}, + } + classnames = ['absent', 'sparse', 'enough'] + # total support = 105; threshold = max(20, 1.05) = 20 + assert insufficient_support_threshold(105) == 20 + entries = collect_insufficient_support_entries(classnames, report) + by_class = {e['class']: e for e in entries} + assert 'absent' in by_class + assert by_class['absent']['support'] == 0 + assert by_class['absent']['min_support'] == 20 + assert 'sparse' in by_class + assert by_class['sparse']['support'] == 5 + assert by_class['sparse']['min_support'] == 20 + assert 'enough' not in by_class diff --git a/LabGym/tests/test_ac_interactive_results_checkbox.py b/LabGym/tests/test_ac_interactive_results_checkbox.py new file mode 100644 index 00000000..331d1c39 --- /dev/null +++ b/LabGym/tests/test_ac_interactive_results_checkbox.py @@ -0,0 +1,144 @@ +"""AC interactive-results checkbox on Test Categorizers.""" + +from unittest.mock import patch + +import pytest + +from LabGym import mywx # noqa: F401 +import wx + + +@pytest.fixture(scope='module') +def wx_app(): + app = wx.App(False) + yield app + wx.CallAfter(app.ExitMainLoop) + app.MainLoop() + del app + wx.App._instance = None + + +def _make_test_panel(wx_app, display=True): + from LabGym.gui_categorizer import PanelLv2_TestCategorizers + + frame = wx.Frame(None) + if display: + with patch('LabGym.gui_categorizer.config.get_config', return_value={'models': '/tmp'}): + panel = PanelLv2_TestCategorizers(frame) + else: + with patch.object(PanelLv2_TestCategorizers, 'display_window', lambda self: None): + with patch('LabGym.gui_categorizer.config.get_config', return_value={'models': '/tmp'}): + panel = PanelLv2_TestCategorizers(frame) + panel.checkbox_open_interactive = wx.CheckBox( + frame, + label='Show interactive results after testing', + ) + panel.checkbox_open_interactive.SetValue(True) + return frame, panel + + +def test_checkbox_exists_with_exact_label_and_defaults_checked(wx_app): + frame, panel = _make_test_panel(wx_app, display=True) + assert panel.checkbox_open_interactive.GetLabel() == ( + 'Show interactive results after testing' + ) + assert panel.checkbox_open_interactive.GetValue() is True + frame.Destroy() + + +def test_checked_path_opens_diagnostics_dialog(wx_app): + frame, panel = _make_test_panel(wx_app, display=False) + panel.file_path = '/tmp/gt' + panel.path_to_categorizer = '/tmp/model' + panel.out_path = None + panel.checkbox_open_interactive.SetValue(True) + + fake_report = { + 'walk': {'support': 10, 'f1-score': 0.9}, + 'accuracy': 0.9, + 'macro avg': {}, + 'weighted avg': {}, + } + with patch('LabGym.gui_categorizer.Categorizers') as CA: + CA.return_value.test_categorizer.return_value = ( + fake_report, + [[1]], + {}, + {}, + ) + with patch('LabGym.gui_categorizer.AutomatedDiagnosticsDialog') as Dialog: + instance = Dialog.return_value + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + panel.test_categorizer(None) + Dialog.assert_called_once() + instance.ShowModal.assert_called_once() + instance.Destroy.assert_called_once() + mb.assert_not_called() + frame.Destroy() + + +def test_unchecked_path_skips_dialog_and_passes_export_path(wx_app): + frame, panel = _make_test_panel(wx_app, display=False) + panel.file_path = '/tmp/gt' + panel.path_to_categorizer = '/tmp/model' + panel.out_path = '/tmp/export' + panel.checkbox_open_interactive.SetValue(False) + + fake_report = { + 'walk': {'support': 10, 'f1-score': 0.9}, + 'accuracy': 0.9, + 'macro avg': {}, + 'weighted avg': {}, + } + with patch('LabGym.gui_categorizer.Categorizers') as CA: + CA.return_value.test_categorizer.return_value = ( + fake_report, + [[1]], + {}, + {}, + ) + with patch('LabGym.gui_categorizer.AutomatedDiagnosticsDialog') as Dialog: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + panel.test_categorizer(None) + CA.return_value.test_categorizer.assert_called_once_with( + '/tmp/gt', + '/tmp/model', + result_path='/tmp/export', + ) + Dialog.assert_not_called() + mb.assert_not_called() + assert panel.checkbox_open_interactive.GetValue() is False + frame.Destroy() + + +def test_unchecked_without_export_passes_none_result_path(wx_app): + frame, panel = _make_test_panel(wx_app, display=False) + panel.file_path = '/tmp/gt' + panel.path_to_categorizer = '/tmp/model' + panel.out_path = None + panel.checkbox_open_interactive.SetValue(False) + + fake_report = { + 'walk': {'support': 10, 'f1-score': 0.9}, + 'accuracy': 0.9, + 'macro avg': {}, + 'weighted avg': {}, + } + with patch('LabGym.gui_categorizer.Categorizers') as CA: + CA.return_value.test_categorizer.return_value = ( + fake_report, + [[1]], + {}, + {}, + ) + with patch('LabGym.gui_categorizer.AutomatedDiagnosticsDialog') as Dialog: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + panel.test_categorizer(None) + CA.return_value.test_categorizer.assert_called_once_with( + '/tmp/gt', + '/tmp/model', + result_path=None, + ) + Dialog.assert_not_called() + mb.assert_not_called() + frame.Destroy() diff --git a/LabGym/tests/test_ac_triage_guards.py b/LabGym/tests/test_ac_triage_guards.py new file mode 100644 index 00000000..2c1288f0 --- /dev/null +++ b/LabGym/tests/test_ac_triage_guards.py @@ -0,0 +1,407 @@ +"""AC triage empty-plan, PDF preflight, package wrapper, and outcome helpers.""" + +from unittest.mock import MagicMock, patch + +import pytest + +from LabGym import mywx # noqa: F401 +import wx + +from LabGym.gui_categorizer import ( + reportlab_importable, + triage_assignment_counts, + TriageBuilderDialog, +) + + +@pytest.fixture(scope='module') +def wx_app(): + app = wx.App(False) + yield app + wx.CallAfter(app.ExitMainLoop) + app.MainLoop() + del app + wx.App._instance = None + + +def test_triage_assignment_counts_require_at_least_one(): + assert triage_assignment_counts(0, 0, 0) is False + assert triage_assignment_counts(1, 0, 0) is True + assert triage_assignment_counts(0, 2, 0) is True + assert triage_assignment_counts(0, 0, 3) is True + + +def test_reportlab_importable_true_in_review_env(): + ok, err = reportlab_importable() + assert ok is True + assert err is None + + +def _make_triage_dialog(wx_app, source_dataset_root=None, example_map=None): + parent = wx.Frame(None) + with patch.object(TriageBuilderDialog, 'init_ui', lambda self: None): + dlg = TriageBuilderDialog( + parent, + confusions_list=['a -> b (1 errors)'], + example_map=example_map or {('a', 'b'): ['/tmp/ds/a/x.avi']}, + report={'accuracy': 0.5, 'macro avg': {'f1-score': 0.5}}, + cm=[[1, 0], [0, 1]], + classnames=['a', 'b'], + embedding_map={}, + source_dataset_root=source_dataset_root, + ) + dlg.lb_h1 = MagicMock() + dlg.lb_h2 = MagicMock() + dlg.lb_h3 = MagicMock() + dlg.lb_h1.GetCount.return_value = 0 + dlg.lb_h2.GetCount.return_value = 0 + dlg.lb_h3.GetCount.return_value = 0 + return parent, dlg + + +def _src_with_classes(tmp_path, classes=('a', 'b')): + src = tmp_path / 'test' + for cls in classes: + (src / cls).mkdir(parents=True) + (src / cls / f'{cls}_only.avi').write_bytes(b'avi') + return src + + +def test_empty_plan_returns_before_name_dialog_and_copytree(wx_app): + parent, dlg = _make_triage_dialog(wx_app) + with patch('LabGym.gui_categorizer.wx.TextEntryDialog') as name_dlg: + with patch('LabGym.gui_categorizer.shutil.copytree') as copytree: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + mb.assert_called_once() + assert mb.call_args[0][1] == 'Empty triage plan' + name_dlg.assert_not_called() + copytree.assert_not_called() + parent.Destroy() + + +def test_missing_reportlab_returns_before_clone(wx_app): + parent, dlg = _make_triage_dialog(wx_app) + dlg.lb_h1.GetCount.return_value = 1 + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(False, 'no module')): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog') as name_dlg: + with patch('LabGym.gui_categorizer.shutil.copytree') as copytree: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert mb.call_args[0][1] == 'Missing Dependency' + name_dlg.assert_not_called() + copytree.assert_not_called() + parent.Destroy() + + +def test_h1_file_collision_blocks_before_makedirs(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + (src / 'a' / 'same.avi').write_bytes(b'a') + (src / 'b' / 'same.avi').write_bytes(b'b') + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch('LabGym.gui_categorizer.os.makedirs') as makedirs: + with patch('LabGym.gui_categorizer.shutil.copytree') as copytree: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert mb.call_args[0][1] == 'H1 filename collision' + makedirs.assert_not_called() + copytree.assert_not_called() + assert not (tmp_path / 'pkg_out').exists() + parent.Destroy() + + +def test_h1_missing_class_blocks_before_mutation(wx_app, tmp_path): + src = tmp_path / 'test' + (src / 'a').mkdir(parents=True) + (src / 'a' / 'x.avi').write_bytes(b'a') + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch('LabGym.gui_categorizer.shutil.copytree') as copytree: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert mb.call_args[0][1] == 'H1 class folder missing' + copytree.assert_not_called() + assert not (tmp_path / 'pkg_out').exists() + parent.Destroy() + + +def test_invalid_package_name_creates_no_package(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'bad/name' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch('LabGym.gui_categorizer.shutil.copytree') as copytree: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert mb.call_args[0][1] == 'Invalid Package Name' + copytree.assert_not_called() + parent.Destroy() + + +def test_pdf_failure_after_package_suppresses_full_success(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog( + wx_app, + source_dataset_root=str(src), + example_map={('a', 'b'): [str(src / 'a' / 'a_only.avi')]}, + ) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch.object(dlg, 'generate_pdf_report', return_value=(False, 'boom')): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + with patch.object(dlg, '_open_folder_safely') as open_folder: + dlg.on_finish(None) + titles = [c[0][1] for c in mb.call_args_list] + assert 'Partial triage outcome' in titles + assert 'Triage Complete' not in titles + open_folder.assert_not_called() + pkg = tmp_path / 'pkg_out' + assert pkg.is_dir() + assert (pkg / 'revised_sorted_test_examples').is_dir() + assert (pkg / 'LabGym_Diagnostics').is_dir() + assert (src / 'a' / 'a_only.avi').exists() + parent.Destroy() + + +def test_existing_destination_fails_without_overwrite(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + existing = tmp_path / 'pkg_out' + existing.mkdir() + marker = existing / 'keep.txt' + marker.write_text('safe') + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert marker.read_text() == 'safe' + assert mb.call_args[0][1] == 'Package Exists' + assert 'Triage Complete' not in [c[0][1] for c in mb.call_args_list] + parent.Destroy() + + +def test_full_success_package_layout_and_opens_package_root(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog( + wx_app, + source_dataset_root=str(src), + example_map={('a', 'b'): [str(src / 'a' / 'a_only.avi')]}, + ) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + dlg.lb_h2.GetCount.return_value = 0 + dlg.lb_h3.GetCount.return_value = 0 + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + def fake_pdf(path, name): + from pathlib import Path + Path(path).write_bytes(b'%PDF') + return True, None + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch.object(dlg, 'generate_pdf_report', side_effect=fake_pdf): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + with patch.object(dlg, 'EndModal'): + with patch.object(dlg, '_open_folder_safely', return_value=(True, None)) as open_folder: + dlg.on_finish(None) + + pkg = tmp_path / 'pkg_out' + revised = pkg / 'revised_sorted_test_examples' + diagnostics = pkg / 'LabGym_Diagnostics' + assert revised.is_dir() + assert diagnostics.is_dir() + assert not (revised / 'LabGym_Diagnostics').exists() + assert not (revised / 'a').exists() + assert (revised / 'b' / 'a_only.avi').exists() + assert (revised / 'b' / 'b_only.avi').exists() + assert (src / 'a' / 'a_only.avi').exists() + assert list(pkg.iterdir()) # package root opened, not diagnostics alone + open_folder.assert_called_once_with(str(pkg)) + success_msgs = [c[0][0] for c in mb.call_args_list if c[0][1] == 'Triage Complete'] + assert success_msgs + body = success_msgs[0] + assert str(pkg) in body + assert str(revised) in body + assert 'select this folder in LabGym' in body + assert 'categorizer_diagnostics_v1.pdf' in body + assert 'original source fixture was not modified' in body + parent.Destroy() + + +def test_copy_failure_reports_partial_package(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch('LabGym.gui_categorizer.shutil.copytree', side_effect=OSError('disk full')): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + dlg.on_finish(None) + assert (tmp_path / 'pkg_out').is_dir() + assert mb.call_args[0][1] == 'System Error' + assert 'partial Triage Plan package' in mb.call_args[0][0] + assert 'Triage Complete' not in [c[0][1] for c in mb.call_args_list] + parent.Destroy() + + +def test_open_failure_after_success_does_not_delete_package(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 1 + dlg.lb_h1.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + def fake_pdf(path, name): + from pathlib import Path + Path(path).write_bytes(b'%PDF') + return True, None + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch.object(dlg, 'generate_pdf_report', side_effect=fake_pdf): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + with patch.object(dlg, 'EndModal'): + with patch.object(dlg, '_open_folder_safely', return_value=(False, 'denied')): + dlg.on_finish(None) + titles = [c[0][1] for c in mb.call_args_list] + assert 'Triage Complete' in titles + assert 'Folder Open Failed' in titles + assert (tmp_path / 'pkg_out' / 'revised_sorted_test_examples').is_dir() + parent.Destroy() + + +def test_h2_does_not_create_class_or_move_examples(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + parent, dlg = _make_triage_dialog(wx_app, source_dataset_root=str(src)) + dlg.lb_h1.GetCount.return_value = 0 + dlg.lb_h2.GetCount.return_value = 1 + dlg.lb_h2.GetString.return_value = 'a -> b (1 errors) [NEW: novel]' + dlg.lb_h3.GetCount.return_value = 0 + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + def fake_pdf(path, name): + from pathlib import Path + Path(path).write_bytes(b'%PDF') + return True, None + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch.object(dlg, 'generate_pdf_report', side_effect=fake_pdf): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox'): + with patch.object(dlg, 'EndModal'): + with patch.object(dlg, '_open_folder_safely', return_value=(True, None)): + dlg.on_finish(None) + revised = tmp_path / 'pkg_out' / 'revised_sorted_test_examples' + assert (revised / 'a' / 'a_only.avi').exists() + assert (revised / 'b' / 'b_only.avi').exists() + assert not (revised / 'novel').exists() + parent.Destroy() + + +def test_h3_references_go_to_diagnostics_only(wx_app, tmp_path): + src = _src_with_classes(tmp_path) + avi = src / 'a' / 'a_only.avi' + jpg = src / 'a' / 'a_only.jpg' + jpg.write_bytes(b'jpg') + parent, dlg = _make_triage_dialog( + wx_app, + source_dataset_root=str(src), + example_map={('a', 'b'): [str(avi)]}, + ) + dlg.lb_h1.GetCount.return_value = 0 + dlg.lb_h2.GetCount.return_value = 0 + dlg.lb_h3.GetCount.return_value = 1 + dlg.lb_h3.GetString.return_value = 'a -> b (1 errors)' + + name_dlg = MagicMock() + name_dlg.ShowModal.return_value = wx.ID_OK + name_dlg.GetValue.return_value = 'pkg_out' + + def fake_pdf(path, name): + from pathlib import Path + Path(path).write_bytes(b'%PDF') + return True, None + + with patch('LabGym.gui_categorizer.reportlab_importable', return_value=(True, None)): + with patch('LabGym.gui_categorizer.wx.TextEntryDialog', return_value=name_dlg): + with patch.object(dlg, 'generate_pdf_report', side_effect=fake_pdf): + with patch('LabGym.gui_categorizer.wx.BeginBusyCursor'): + with patch('LabGym.gui_categorizer.wx.EndBusyCursor'): + with patch('LabGym.gui_categorizer.wx.MessageBox'): + with patch.object(dlg, 'EndModal'): + with patch.object(dlg, '_open_folder_safely', return_value=(True, None)): + with patch('random.sample', side_effect=lambda seq, k: list(seq)[:k]): + dlg.on_finish(None) + pkg = tmp_path / 'pkg_out' + h3 = pkg / 'LabGym_Diagnostics' / 'H3_Variance_References' + assert h3.is_dir() + assert list(h3.glob('*.avi')) + assert not (pkg / 'revised_sorted_test_examples' / 'H3_Variance_References').exists() + assert avi.exists() + parent.Destroy() diff --git a/LabGym/tests/test_ac_triage_layout_pdf.py b/LabGym/tests/test_ac_triage_layout_pdf.py new file mode 100644 index 00000000..f06b2dc1 --- /dev/null +++ b/LabGym/tests/test_ac_triage_layout_pdf.py @@ -0,0 +1,92 @@ +"""Pure helpers for Triage Builder sizing, PDF allocation, and package naming.""" + +from pathlib import Path + +from LabGym import mywx # noqa: F401 + +from LabGym.gui_categorizer import ( + fit_dialog_client_size, + next_versioned_pdf_path, +) + + +def test_fit_dialog_preserves_nominal_on_large_work_area(): + assert fit_dialog_client_size(960, 720, 1920, 1080) == (960, 720) + + +def test_fit_dialog_clamps_to_margin_and_max_frac(): + w, h = fit_dialog_client_size(960, 720, 1000, 700, margin=40, max_frac=0.92) + assert w == min(960, 1000 - 80, int(1000 * 0.92)) + assert h == min(720, 700 - 80, int(700 * 0.92)) + assert w <= int(1000 * 0.92) + assert h <= int(700 * 0.92) + assert w <= 1000 - 80 + assert h <= 700 - 80 + + +def test_fit_dialog_returns_positive_integers_on_tiny_work_area(): + w, h = fit_dialog_client_size(960, 720, 50, 40, margin=40, max_frac=0.92) + assert isinstance(w, int) and isinstance(h, int) + assert w >= 1 and h >= 1 + assert w <= 50 and h <= 40 + + +def test_next_versioned_pdf_empty_directory_is_v1(tmp_path): + path = next_versioned_pdf_path(str(tmp_path)) + assert path == str(tmp_path / 'categorizer_diagnostics_v1.pdf') + + +def test_next_versioned_pdf_increments_from_existing_v1(tmp_path): + (tmp_path / 'categorizer_diagnostics_v1.pdf').write_bytes(b'pdf') + path = next_versioned_pdf_path(str(tmp_path)) + assert path.endswith('categorizer_diagnostics_v2.pdf') + assert not Path(path).exists() + + +def test_next_versioned_pdf_uses_max_plus_one_and_skips_gaps(tmp_path): + (tmp_path / 'categorizer_diagnostics_v1.pdf').write_bytes(b'a') + (tmp_path / 'categorizer_diagnostics_v3.pdf').write_bytes(b'b') + path = next_versioned_pdf_path(str(tmp_path)) + assert path.endswith('categorizer_diagnostics_v4.pdf') + + +def test_next_versioned_pdf_ignores_unrelated_and_case_mismatches(tmp_path): + (tmp_path / 'categorizer_diagnostics.pdf').write_bytes(b'x') + (tmp_path / 'categorizer_diagnostics_notes.pdf').write_bytes(b'x') + (tmp_path / 'categorizer_diagnostics_vx.pdf').write_bytes(b'x') + (tmp_path / 'Categorizer_diagnostics_v1.pdf').write_bytes(b'x') + (tmp_path / 'categorizer_diagnostics_v1').mkdir() + path = next_versioned_pdf_path(str(tmp_path)) + assert path.endswith('categorizer_diagnostics_v1.pdf') + + +def test_next_versioned_pdf_does_not_overwrite_existing(tmp_path): + existing = tmp_path / 'categorizer_diagnostics_v1.pdf' + existing.write_bytes(b'keep') + path = Path(next_versioned_pdf_path(str(tmp_path))) + assert path != existing + assert existing.read_bytes() == b'keep' + assert path.parent == tmp_path + + +def test_triage_builder_source_is_fixed_and_anchored(): + src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py' + text = src.read_text() + start = text.index('class TriageBuilderDialog') + body = text[start:text.index('def move_items', start)] + assert 'wx.RESIZE_BORDER' not in body + assert 'NOMINAL_CLIENT_SIZE = (960, 720)' in body + assert 'fit_dialog_client_size' in body + assert 'self.intro_lbl' in body + assert 'ops_help_html' in body + assert 'Finish and Generate Report' in body + assert 'wx.ID_CANCEL' in body + assert 'scientific decisions remain yours.' in body + ops_page_start = body.index('self.ops_help_html.SetPage') + assert 'scientific decisions remain yours' not in body[ops_page_start:] + assert 'next_versioned_pdf_path(diagnostics_dir)' in text + assert 'revised_sorted_test_examples' in text + assert 'source_dataset_root' in text + assert 'dataset_v2' not in text + assert 'Triage_Action_Plan.pdf' not in text + assert 'LabGym Triage Action Plan' in text diff --git a/LabGym/tests/test_ac_triage_package_names.py b/LabGym/tests/test_ac_triage_package_names.py new file mode 100644 index 00000000..6ad491e8 --- /dev/null +++ b/LabGym/tests/test_ac_triage_package_names.py @@ -0,0 +1,169 @@ +"""Pure helpers for Triage Plan package naming and H1 collision preflight.""" + +from pathlib import Path + +from LabGym import mywx # noqa: F401 + +from LabGym.gui_categorizer import ( + collect_h1_filename_collisions, + next_versioned_triage_package_name, + sanitize_triage_package_base, + validate_triage_package_name, +) + + +def test_sanitize_source_test_becomes_test(): + assert sanitize_triage_package_base('test') == 'test' + + +def test_sanitize_strips_existing_trailing_triage_version(): + assert sanitize_triage_package_base('test_triage_v3') == 'test' + assert sanitize_triage_package_base('demo_triage_v12') == 'demo' + + +def test_sanitize_spaces_punctuation_and_collapses_underscores(): + assert sanitize_triage_package_base('my test!!set') == 'my_test_set' + assert sanitize_triage_package_base('a___b') == 'a_b' + assert sanitize_triage_package_base('a/b\\c:d*e') == 'a_b_c_d_e' + + +def test_sanitize_preserves_unicode_letters_and_digits(): + assert sanitize_triage_package_base('données_αβ_42') == 'données_αβ_42' + + +def test_sanitize_empty_falls_back(): + assert sanitize_triage_package_base('!!!') == 'sorted_test_examples' + assert sanitize_triage_package_base(' ') == 'sorted_test_examples' + + +def test_sanitize_truncates_to_eighty_before_suffix(): + long_name = 'x' * 100 + base = sanitize_triage_package_base(long_name) + assert len(base) == 80 + assert base == 'x' * 80 + + +def test_sanitize_windows_reserved_appends_data(): + assert sanitize_triage_package_base('CON') == 'CON_data' + assert sanitize_triage_package_base('com1') == 'com1_data' + assert sanitize_triage_package_base('LPT9') == 'LPT9_data' + + +def test_next_version_empty_parent_is_v1(tmp_path): + src = tmp_path / 'test' + src.mkdir() + assert next_versioned_triage_package_name(str(tmp_path), 'test') == 'test_triage_v1' + + +def test_next_version_increments_from_existing_v1(tmp_path): + (tmp_path / 'test_triage_v1').mkdir() + assert next_versioned_triage_package_name(str(tmp_path), 'test') == 'test_triage_v2' + + +def test_next_version_uses_max_plus_one_skips_gaps(tmp_path): + (tmp_path / 'test_triage_v1').mkdir() + (tmp_path / 'test_triage_v3').mkdir() + assert next_versioned_triage_package_name(str(tmp_path), 'test') == 'test_triage_v4' + + +def test_next_version_ignores_files_and_malformed_prefixes(tmp_path): + (tmp_path / 'test_triage_v1.txt').write_text('file') + (tmp_path / 'test_triage_vX').mkdir() + (tmp_path / 'test_triage').mkdir() + (tmp_path / 'other_triage_v1').mkdir() + (tmp_path / 'Test_triage_v1').mkdir() + assert next_versioned_triage_package_name(str(tmp_path), 'test') == 'test_triage_v1' + + +def test_next_version_does_not_create_or_overwrite(tmp_path): + existing = tmp_path / 'test_triage_v1' + existing.mkdir() + marker = existing / 'keep.txt' + marker.write_text('safe') + name = next_versioned_triage_package_name(str(tmp_path), 'test') + assert name == 'test_triage_v2' + assert marker.read_text() == 'safe' + assert not (tmp_path / name).exists() + + +def test_validate_rejects_invalid_user_names(tmp_path): + cases = [ + '', + ' ', + '.', + '..', + '/abs/path', + 'has/slash', + 'has\\slash', + 'bad:name', + 'trail.', + 'CON', + 'con.txt', + 'NUL', + ] + for name in cases: + ok, err = validate_triage_package_name(name) + assert ok is False, name + assert err + + +def test_validate_accepts_simple_basename(): + ok, err = validate_triage_package_name('test_triage_v1') + assert ok is True + assert err is None + + +def test_h1_collision_none(tmp_path): + src = tmp_path / 'src' + (src / 'a').mkdir(parents=True) + (src / 'b').mkdir() + (src / 'a' / 'x.avi').write_bytes(b'a') + (src / 'b' / 'y.avi').write_bytes(b'b') + collisions, missing = collect_h1_filename_collisions(str(src), [('a', 'b')]) + assert collisions == [] + assert missing == [] + + +def test_h1_file_collision_collected(tmp_path): + src = tmp_path / 'src' + (src / 'a').mkdir(parents=True) + (src / 'b').mkdir() + (src / 'a' / 'same.avi').write_bytes(b'a') + (src / 'b' / 'same.avi').write_bytes(b'b') + collisions, missing = collect_h1_filename_collisions(str(src), [('a', 'b')]) + assert missing == [] + assert len(collisions) == 1 + assert collisions[0]['pair'] == ('a', 'b') + assert collisions[0]['filenames'] == ['same.avi'] + + +def test_h1_directory_collision_collected(tmp_path): + src = tmp_path / 'src' + (src / 'a' / 'subdir').mkdir(parents=True) + (src / 'b' / 'subdir').mkdir(parents=True) + collisions, missing = collect_h1_filename_collisions(str(src), [('a', 'b')]) + assert missing == [] + assert collisions[0]['filenames'] == ['subdir'] + + +def test_h1_multiple_collisions_sorted(tmp_path): + src = tmp_path / 'src' + for cls in ('a', 'b', 'c', 'd'): + (src / cls).mkdir(parents=True) + (src / 'a' / 'z.avi').write_bytes(b'1') + (src / 'b' / 'z.avi').write_bytes(b'2') + (src / 'c' / 'm.avi').write_bytes(b'3') + (src / 'd' / 'm.avi').write_bytes(b'4') + (src / 'c' / 'a.avi').write_bytes(b'5') + (src / 'd' / 'a.avi').write_bytes(b'6') + collisions, missing = collect_h1_filename_collisions(str(src), [('c', 'd'), ('a', 'b')]) + assert missing == [] + assert [c['pair'] for c in collisions] == [('a', 'b'), ('c', 'd')] + assert collisions[1]['filenames'] == ['a.avi', 'm.avi'] + + +def test_h1_missing_class_reported(tmp_path): + src = tmp_path / 'src' + (src / 'a').mkdir(parents=True) + collisions, missing = collect_h1_filename_collisions(str(src), [('a', 'b')]) + assert ('target', 'b') in missing From 0123ee785df0e991c921590e146573c522428eb2 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 13 Aug 2026 11:54:27 -0400 Subject: [PATCH 18/33] fix(categorizer): defer analyzer imports --- LabGym/gui_categorizer.py | 53 +++- LabGym/tests/test_ac_triage_guards.py | 390 ++++++++++++++++++++++++++ pyproject.toml | 2 +- 3 files changed, 438 insertions(+), 7 deletions(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 3493d71f..7f720678 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -44,12 +44,6 @@ import wx.html # Local application/library specific imports. -logger.debug('importing %s ...', '.analyzebehavior') -from .analyzebehavior import AnalyzeAnimal -logger.debug('importing %s done', '.analyzebehavior') -logger.debug('importing %s ...', '.analyzebehavior_dt') -from .analyzebehavior_dt import AnalyzeAnimalDetector -logger.debug('importing %s done', '.analyzebehavior_dt') from .categorizer import Categorizers, CategorizerClassMismatchError from LabGym import config from .tools import sort_examples_from_csv @@ -69,6 +63,41 @@ CM_CORRECT_RGB_MAX = (46, 125, 50) # #2E7D32 +def import_generate_examples_analyzer(kind): + """ + Import AnalyzeAnimal ('animal') or AnalyzeAnimalDetector ('detector'). + + Returns the class, or None after logging and a MessageBox when the import + raises ImportError or OSError (for example a missing native library). + Unknown kind values raise ValueError without attempting an import. + """ + if kind not in ('animal', 'detector'): + raise ValueError( + "import_generate_examples_analyzer kind must be 'animal' or 'detector', " + f'got {kind!r}' + ) + try: + if kind == 'animal': + from .analyzebehavior import AnalyzeAnimal + return AnalyzeAnimal + if kind == 'detector': + from .analyzebehavior_dt import AnalyzeAnimalDetector + return AnalyzeAnimalDetector + except (ImportError, OSError): + logger.exception( + 'Failed to import Generate Examples analyzer components (kind=%r)', + kind, + ) + wx.MessageBox( + 'LabGym could not load the analysis components required for this Generate ' + 'Examples workflow. Verify that the LabGym environment and its required ' + 'dependencies are installed correctly, then try again.', + 'Analysis dependency unavailable', + wx.OK | wx.ICON_ERROR, + ) + return None + + def cm_correct_cell_rgb(accuracy): """Return RGB for a correct (diagonal) CM cell given row accuracy in [0, 1].""" accuracy = max(0.0, min(1.0, float(accuracy))) @@ -847,6 +876,9 @@ def generate_data(self,event): if self.path_to_detector is None: wx.MessageBox('You need to select a Detector.','Error',wx.OK|wx.ICON_ERROR) else: + AnalyzeAnimalDetector=import_generate_examples_analyzer('detector') + if AnalyzeAnimalDetector is None: + return AAD=AnalyzeAnimalDetector() AAD.analyze_images_individuals(self.path_to_detector,self.path_to_videos,self.result_path,self.animal_kinds,generate=True,imagewidth=self.framewidth,detection_threshold=self.detection_threshold,background_free=self.background_free,black_background=self.black_background) @@ -874,6 +906,15 @@ def generate_data(self,event): if do_nothing is False: + if self.use_detector is False: + AnalyzeAnimal=import_generate_examples_analyzer('animal') + if AnalyzeAnimal is None: + return + else: + AnalyzeAnimalDetector=import_generate_examples_analyzer('detector') + if AnalyzeAnimalDetector is None: + return + for i in self.path_to_videos: filename=os.path.splitext(os.path.basename(i))[0].split('_') diff --git a/LabGym/tests/test_ac_triage_guards.py b/LabGym/tests/test_ac_triage_guards.py index 2c1288f0..1b261407 100644 --- a/LabGym/tests/test_ac_triage_guards.py +++ b/LabGym/tests/test_ac_triage_guards.py @@ -405,3 +405,393 @@ def fake_pdf(path, name): assert not (pkg / 'revised_sorted_test_examples' / 'H3_Variance_References').exists() assert avi.exists() parent.Destroy() + + +# --- CI #38: deferred analyzer imports --- + +_ANALYZER_MSG = ( + 'LabGym could not load the analysis components required for this Generate ' + 'Examples workflow. Verify that the LabGym environment and its required ' + 'dependencies are installed correctly, then try again.' +) +_ANALYZER_TITLE = 'Analysis dependency unavailable' + + +def test_gui_categorizer_import_does_not_load_analyzer_detector_stack(): + """Fresh interpreter: importing gui_categorizer must not newly load analyzer stack.""" + import os + import subprocess + import sys + from pathlib import Path + + script = ( + "import sys\n" + "before = set(sys.modules)\n" + "import LabGym.gui_categorizer # noqa: F401\n" + "after = set(sys.modules)\n" + "newly = after - before\n" + "forbidden = {\n" + " 'LabGym.analyzebehavior',\n" + " 'LabGym.analyzebehavior_dt',\n" + " 'LabGym.detector',\n" + " 'LabGym.detectron2.model_zoo',\n" + " 'torch',\n" + "}\n" + "hit = sorted(name for name in forbidden if name in newly)\n" + "if hit:\n" + " raise SystemExit('unexpected newly loaded: ' + ','.join(hit))\n" + "print('ok')\n" + ) + env = dict(os.environ) + env['PYTHONDONTWRITEBYTECODE'] = '1' + repo = str(Path(__file__).resolve().parents[2]) + proc = subprocess.run( + [sys.executable, '-c', script], + capture_output=True, + text=True, + env=env, + cwd=repo, + ) + assert proc.returncode == 0, proc.stdout + '\n' + proc.stderr + assert 'ok' in proc.stdout + + +def _analyzer_module_keys(): + return ( + 'LabGym.analyzebehavior', + 'LabGym.analyzebehavior_dt', + ) + + +def _stash_analyzer_modules(): + import sys + import LabGym + + stashed = {k: sys.modules.get(k) for k in _analyzer_module_keys()} + attrs = { + 'analyzebehavior': getattr(LabGym, 'analyzebehavior', _MISSING), + 'analyzebehavior_dt': getattr(LabGym, 'analyzebehavior_dt', _MISSING), + } + return stashed, attrs + + +_MISSING = object() + + +def _restore_analyzer_modules(stashed, attrs): + import sys + import LabGym + + for k, v in stashed.items(): + if v is None and k not in sys.modules: + continue + if v is None: + sys.modules.pop(k, None) + else: + sys.modules[k] = v + for name, val in attrs.items(): + if val is _MISSING: + if hasattr(LabGym, name): + delattr(LabGym, name) + else: + setattr(LabGym, name, val) + + +def _install_fake_analyzer(module_name, class_name, cls): + import sys + import types + import LabGym + + mod = types.ModuleType(module_name) + setattr(mod, class_name, cls) + sys.modules[module_name] = mod + short = module_name.rsplit('.', 1)[-1] + setattr(LabGym, short, mod) + return mod + + +def _install_bomb_analyzer(module_name): + """Module that fails loudly if imported for from-import of analyzer classes.""" + import sys + import types + import LabGym + + class Bomb(types.ModuleType): + def __getattr__(self, name): + raise AssertionError(f'unexpected attribute {module_name}.{name}') + + mod = Bomb(module_name) + sys.modules[module_name] = mod + short = module_name.rsplit('.', 1)[-1] + setattr(LabGym, short, mod) + return mod + + +def _raise_on_analyzer_import(exc): + """Make relative analyzer imports raise ImportError or OSError.""" + import builtins + + orig = builtins.__import__ + + def fake_import(name, globals=None, locals=None, fromlist=(), level=0): + if level > 0 and name in ('analyzebehavior', 'analyzebehavior_dt'): + raise exc + if name in ('LabGym.analyzebehavior', 'LabGym.analyzebehavior_dt'): + raise exc + return orig(name, globals, locals, fromlist, level) + + return patch('builtins.__import__', side_effect=fake_import) + + +def test_import_generate_examples_analyzer_import_error_shows_messagebox_once(): + from LabGym.gui_categorizer import import_generate_examples_analyzer + + with _raise_on_analyzer_import(ImportError('simulated missing analyzer')): + with patch('LabGym.gui_categorizer.logger') as log: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + result = import_generate_examples_analyzer('animal') + assert result is None + assert mb.call_count == 1 + assert mb.call_args[0][0] == _ANALYZER_MSG + assert mb.call_args[0][1] == _ANALYZER_TITLE + assert log.exception.called + + +def test_import_generate_examples_analyzer_oserror_shows_messagebox(): + from LabGym.gui_categorizer import import_generate_examples_analyzer + + with _raise_on_analyzer_import(OSError('simulated native library failure')): + with patch('LabGym.gui_categorizer.logger') as log: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + result = import_generate_examples_analyzer('detector') + assert result is None + assert mb.call_count == 1 + assert mb.call_args[0][0] == _ANALYZER_MSG + assert mb.call_args[0][1] == _ANALYZER_TITLE + assert log.exception.called + + +def test_import_generate_examples_analyzer_invalid_kind_raises(): + """Unknown kind must fail loudly without importing analyzers or showing UI.""" + import builtins + + from LabGym.gui_categorizer import import_generate_examples_analyzer + + seen = [] + orig_import = builtins.__import__ + + def spy_import(name, globals=None, locals=None, fromlist=(), level=0): + if level > 0 and name in ('analyzebehavior', 'analyzebehavior_dt'): + seen.append(name) + if name in ('LabGym.analyzebehavior', 'LabGym.analyzebehavior_dt'): + seen.append(name) + return orig_import(name, globals, locals, fromlist, level) + + with patch('builtins.__import__', side_effect=spy_import): + with patch('LabGym.gui_categorizer.logger') as log: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + with pytest.raises(ValueError, match='animal.*detector'): + import_generate_examples_analyzer('not-a-valid-kind') + assert seen == [] + assert mb.call_count == 0 + assert not log.exception.called + + +def _make_generate_panel(wx_app): + from LabGym.gui_categorizer import PanelLv2_GenerateExamples + + parent = wx.Frame(None) + with patch.object(PanelLv2_GenerateExamples, 'display_window', lambda self: None): + with patch( + 'LabGym.gui_categorizer.config.get_config', + return_value={'detectors': '/tmp', 'models': '/tmp'}, + ): + panel = PanelLv2_GenerateExamples(parent) + panel.path_to_videos = ['/tmp/v.avi'] + panel.result_path = '/tmp/out' + panel.behavior_mode = 0 + panel.use_detector = False + panel.path_to_detector = '/tmp/det' + panel.animal_kinds = ['a'] + panel.animal_number = 1 + panel.framewidth = None + panel.detection_threshold = 0.5 + panel.background_free = True + panel.black_background = True + panel.include_bodyparts = False + panel.std = 0 + panel.delta = 1.2 + panel.stable_illumination = True + panel.background_path = None + panel.autofind_t = False + panel.t = 0 + panel.duration = 0 + panel.ex_start = 0 + panel.ex_end = None + panel.length = 15 + panel.animal_vs_bg = 1 + panel.skip_redundant = 0 + panel.social_distance = 0 + panel.decode_animalnumber = False + panel.decode_t = False + panel.decode_extraction = False + panel.color_costar = False + return parent, panel + + +def _patch_generate_dialogs(): + def factory(*a, **k): + d = MagicMock() + d.ShowModal.return_value = wx.ID_YES + d.GetValue.return_value = 0 + d.Destroy = MagicMock() + return d + + return ( + patch('LabGym.gui_categorizer.wx.MessageDialog', side_effect=factory), + patch('LabGym.gui_categorizer.wx.NumberEntryDialog', side_effect=factory), + ) + + +def test_generate_data_background_branch_imports_animal_only(wx_app): + """Background path imports AnalyzeAnimal from a test-scoped fake; detector stays unused.""" + from LabGym.gui_categorizer import import_generate_examples_analyzer + + parent, panel = _make_generate_panel(wx_app) + panel.use_detector = False + panel.behavior_mode = 0 + constructed = [] + + class FakeAnimal: + def __init__(self): + constructed.append('animal') + + def prepare_analysis(self, *a, **k): + pass + + def generate_data(self, **k): + pass + + def generate_data_interact_basic(self, **k): + pass + + stashed, attrs = _stash_analyzer_modules() + md, nd = _patch_generate_dialogs() + try: + _install_fake_analyzer('LabGym.analyzebehavior', 'AnalyzeAnimal', FakeAnimal) + _install_bomb_analyzer('LabGym.analyzebehavior_dt') + with md, nd: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + # Prove helper returns the real symbol from the fake module. + cls = import_generate_examples_analyzer('animal') + assert cls is FakeAnimal + panel.generate_data(None) + assert constructed == ['animal'] + assert mb.call_count == 0 + finally: + _restore_analyzer_modules(stashed, attrs) + parent.Destroy() + + +def test_generate_data_video_detector_branch_imports_detector_only(wx_app): + parent, panel = _make_generate_panel(wx_app) + panel.use_detector = True + panel.behavior_mode = 0 + constructed = [] + + class FakeDet: + def __init__(self): + constructed.append('detector') + + def prepare_analysis(self, *a, **k): + pass + + def generate_data(self, **k): + pass + + def generate_data_interact_basic(self, **k): + pass + + def generate_data_interact_advance(self, **k): + pass + + stashed, attrs = _stash_analyzer_modules() + md, nd = _patch_generate_dialogs() + try: + _install_bomb_analyzer('LabGym.analyzebehavior') + _install_fake_analyzer('LabGym.analyzebehavior_dt', 'AnalyzeAnimalDetector', FakeDet) + with md, nd: + panel.generate_data(None) + assert constructed == ['detector'] + finally: + _restore_analyzer_modules(stashed, attrs) + parent.Destroy() + + +def test_generate_data_static_detector_branch_imports_detector(wx_app): + parent, panel = _make_generate_panel(wx_app) + panel.behavior_mode = 3 + panel.path_to_detector = '/tmp/det' + constructed = [] + + class FakeDet: + def __init__(self): + constructed.append('detector') + + def analyze_images_individuals(self, *a, **k): + pass + + stashed, attrs = _stash_analyzer_modules() + md, nd = _patch_generate_dialogs() + try: + _install_bomb_analyzer('LabGym.analyzebehavior') + _install_fake_analyzer('LabGym.analyzebehavior_dt', 'AnalyzeAnimalDetector', FakeDet) + with md, nd: + panel.generate_data(None) + assert constructed == ['detector'] + finally: + _restore_analyzer_modules(stashed, attrs) + parent.Destroy() + + +def test_generate_data_import_failure_returns_without_construct_or_repeat(wx_app): + parent, panel = _make_generate_panel(wx_app) + panel.use_detector = False + panel.path_to_videos = ['/tmp/a.avi', '/tmp/b.avi'] + constructed = [] + + md, nd = _patch_generate_dialogs() + with md, nd: + with _raise_on_analyzer_import(ImportError('simulated missing analyzer')): + with patch('LabGym.gui_categorizer.logger') as log: + with patch('LabGym.gui_categorizer.wx.MessageBox') as mb: + panel.generate_data(None) + assert constructed == [] + assert mb.call_count == 1 + assert mb.call_args[0][0] == _ANALYZER_MSG + assert mb.call_args[0][1] == _ANALYZER_TITLE + assert log.exception.called + parent.Destroy() + + +def test_pyproject_declares_reportlab_min_5(): + from pathlib import Path + + text = (Path(__file__).resolve().parents[2] / 'pyproject.toml').read_text() + assert "'reportlab>=5.0.0'" in text + assert text.count('reportlab') == 1 + + +def test_gui_categorizer_has_no_module_level_analyzer_imports(): + from pathlib import Path + import re + + text = (Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py').read_text() + # Imports before the deferred-import helper are module-level. + head = text.split('def import_generate_examples_analyzer', 1)[0] + assert 'from .analyzebehavior import AnalyzeAnimal' not in head + assert 'from .analyzebehavior_dt import AnalyzeAnimalDetector' not in head + # Helper performs both imports; Generate Examples has three call sites. + assert text.count("import_generate_examples_analyzer('detector')") == 2 + assert text.count("import_generate_examples_analyzer('animal')") == 1 + assert len(re.findall(r'from \.analyzebehavior(?:_dt)? import ', text)) == 2 diff --git a/pyproject.toml b/pyproject.toml index 348b62c3..89d7d735 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,7 +35,7 @@ dependencies=[ 'torchaudio', 'PyYAML', 'tomli', - 'reportlab', + 'reportlab>=5.0.0', 'Pillow>=7.1', 'matplotlib', 'pycocotools>=2.0.2', From e56c9a4ec0c4a9770129c4bebaf2ef753e097e70 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 13 Aug 2026 16:28:22 -0400 Subject: [PATCH 19/33] fix(windows): constrain PyTorch compatibility --- docs/contributing/setup.md | 19 +++++++++++++------ docs/installation/windows.md | 15 +++++++-------- noxfile.py | 10 +++++++++- pyproject.toml | 9 ++++++--- 4 files changed, 35 insertions(+), 18 deletions(-) diff --git a/docs/contributing/setup.md b/docs/contributing/setup.md index e3618946..641dd236 100644 --- a/docs/contributing/setup.md +++ b/docs/contributing/setup.md @@ -89,18 +89,25 @@ 5. If you're on Windows or Linux, install PyTorch. If you're on macOS, PyTorch will already be installed. - ````{tab} GPU - ```console - $ python -m pip install --index-url https://download.pytorch.org/whl/cu118 torch==2.0.1 torchvision==0.15.2 - ``` - ```` + Use the aligned PyTorch **2.8** family (`torch==2.8.0`, `torchvision==0.23.0`, + `torchaudio==2.8.0`). LabGym’s Windows metadata pins these base versions; + matching official CPU or CUDA wheel variants are accepted. ````{tab} CPU Only ```console - $ python -m pip install --index-url https://download.pytorch.org/whl/cpu torch==2.0.1 torchvision==0.15.2 + $ python -m pip install torch==2.8.0 torchvision==0.23.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cpu ``` ```` + ````{tab} GPU + Select an official PyTorch **2.8**-compatible CUDA wheel index from + [PyTorch’s installation guidance](https://pytorch.org/get-started/locally/) + for your supported hardware and CUDA runtime, then install the same + `torch==2.8.0`, `torchvision==0.23.0`, and `torchaudio==2.8.0` base versions + from that index. Do not use older LabGym instructions that pinned PyTorch + 2.0.1 / CUDA 11.8. + ```` + 6. Test your setup by launching LabGym. If the LabGym GUI shows up, your setup is successful! diff --git a/docs/installation/windows.md b/docs/installation/windows.md index 0725af3c..f827d4d7 100644 --- a/docs/installation/windows.md +++ b/docs/installation/windows.md @@ -12,18 +12,18 @@ To install LabGym on Windows, you will need to access the terminal. To do this, py -3.10 --version ``` -2. If you're using an NVIDIA GPU, install CUDA Toolkit 11.8 and cuDNN, and install PyTorch v2.0.1 with cu118 support. +2. Install the verified PyTorch 2.8 family for LabGym on Windows. - First, install [CUDA Toolkit 11.8](https://developer.nvidia.com/cuda-11-8-0-download-archive?target_os=Windows&target_arch=x86_64). Select your version of Windows, select "exe (local)," then click "Download." - - Next, install [cuDNN](https://developer.nvidia.com/rdp/cudnn-archive). You will need to register an NVIDIA Developer account, which you can do for free. You can choose cuDNN v8.9.7 that supports CUDA toolkit v11.8. Choose 'Local Installer for Windows (Zip)', download and extract it. And then copy the three folders 'bin', 'lib', and 'include' into where the CUDA toolkit is installed (typcially, 'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8\'), and replace all the three folders with the same names. After that, you may need to add the 'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8' to the 'PATH' environmental variable. - - Finally, install PyTorch v2.0.1 with cu118 support. + The default, verified path is the official PyTorch CPU wheels: ```pwsh-session - py -3.10 -m pip install torch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 --index-url https://download.pytorch.org/whl/cu118 + py -3.10 -m pip install torch==2.8.0 torchvision==0.23.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cpu ``` + LabGym’s Windows package requirements use these base versions. Matching official CPU or CUDA builds (for example `2.8.0+cpu`) satisfy them. + + If you need GPU acceleration, install a PyTorch **2.8**-compatible CUDA wheel from [PyTorch’s current installation guidance](https://pytorch.org/get-started/locally/) for your supported hardware and CUDA runtime. Do not use older LabGym documentation that pinned PyTorch 2.0.1. + 4. Upgrade `pip`, `wheel`, `setuptools`. ```pwsh-session @@ -57,4 +57,3 @@ Launch LabGym: ```pwsh-session __main__.main() ``` - diff --git a/noxfile.py b/noxfile.py index e960e264..e77d8e00 100644 --- a/noxfile.py +++ b/noxfile.py @@ -48,7 +48,15 @@ def tests(session:nox.Session): "torchvision==0.23.0+cpu", "torchaudio==2.8.0+cpu", ) - + elif platform.system() == "Windows": + # Verified Windows CPU family; editable install below enforces numpy<=1.26.4 + session.install( + "--no-cache-dir", + "--index-url", "https://download.pytorch.org/whl/cpu", + "torch==2.8.0", + "torchvision==0.23.0", + "torchaudio==2.8.0", + ) # package and test dependencies session.install("-e", ".") diff --git a/pyproject.toml b/pyproject.toml index 89d7d735..89c5ff14 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,9 +30,12 @@ dependencies=[ 'packaging', 'requests', 'numpy<=1.26.4', - 'torch', - 'torchvision', - 'torchaudio', + 'torch==2.8.0;platform_system=="Windows"', + 'torchvision==0.23.0;platform_system=="Windows"', + 'torchaudio==2.8.0;platform_system=="Windows"', + 'torch;platform_system!="Windows"', + 'torchvision;platform_system!="Windows"', + 'torchaudio;platform_system!="Windows"', 'PyYAML', 'tomli', 'reportlab>=5.0.0', From 10a87e5159151648612064bdec595ceb9c391f4f Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 13 Aug 2026 16:59:41 -0400 Subject: [PATCH 20/33] fix(tests): read AC source files as UTF-8 --- LabGym/tests/test_ac_diagnostics_copy.py | 6 +++--- LabGym/tests/test_ac_triage_guards.py | 4 ++-- LabGym/tests/test_ac_triage_layout_pdf.py | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/LabGym/tests/test_ac_diagnostics_copy.py b/LabGym/tests/test_ac_diagnostics_copy.py index 58b74ecd..a9ff3fa4 100644 --- a/LabGym/tests/test_ac_diagnostics_copy.py +++ b/LabGym/tests/test_ac_diagnostics_copy.py @@ -25,7 +25,7 @@ def test_training_module_source_has_single_column_bindings(): src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_main.py' - text = src.read_text() + text = src.read_text(encoding='utf-8') start = text.index('class PanelLv1_TrainingModule') end = text.index('class PanelLv1_AnalysisModule') body = text[start:end] @@ -67,7 +67,7 @@ def test_ac_diagnostic_labels_have_no_emoji_and_overview_first(): def test_diagnostic_button_construction_uses_label_constant(): src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py' - text = src.read_text() + text = src.read_text(encoding='utf-8') start = text.index('def init_ui(self):') # Limit to AutomatedDiagnosticsDialog.init_ui (first init_ui after that class). class_start = text.index('class AutomatedDiagnosticsDialog') @@ -81,7 +81,7 @@ def test_diagnostic_button_construction_uses_label_constant(): def test_diagnostic_copy_rejects_overconfident_phrases_and_uses_new_low_support(): src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py' - text = src.read_text() + text = src.read_text(encoding='utf-8') banned = ( 'Model looks great!', 'Statistically Meaningless', diff --git a/LabGym/tests/test_ac_triage_guards.py b/LabGym/tests/test_ac_triage_guards.py index 1b261407..78d39151 100644 --- a/LabGym/tests/test_ac_triage_guards.py +++ b/LabGym/tests/test_ac_triage_guards.py @@ -777,7 +777,7 @@ def test_generate_data_import_failure_returns_without_construct_or_repeat(wx_app def test_pyproject_declares_reportlab_min_5(): from pathlib import Path - text = (Path(__file__).resolve().parents[2] / 'pyproject.toml').read_text() + text = (Path(__file__).resolve().parents[2] / 'pyproject.toml').read_text(encoding='utf-8') assert "'reportlab>=5.0.0'" in text assert text.count('reportlab') == 1 @@ -786,7 +786,7 @@ def test_gui_categorizer_has_no_module_level_analyzer_imports(): from pathlib import Path import re - text = (Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py').read_text() + text = (Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py').read_text(encoding='utf-8') # Imports before the deferred-import helper are module-level. head = text.split('def import_generate_examples_analyzer', 1)[0] assert 'from .analyzebehavior import AnalyzeAnimal' not in head diff --git a/LabGym/tests/test_ac_triage_layout_pdf.py b/LabGym/tests/test_ac_triage_layout_pdf.py index f06b2dc1..b596992f 100644 --- a/LabGym/tests/test_ac_triage_layout_pdf.py +++ b/LabGym/tests/test_ac_triage_layout_pdf.py @@ -71,7 +71,7 @@ def test_next_versioned_pdf_does_not_overwrite_existing(tmp_path): def test_triage_builder_source_is_fixed_and_anchored(): src = Path(__file__).resolve().parents[2] / 'LabGym' / 'gui_categorizer.py' - text = src.read_text() + text = src.read_text(encoding='utf-8') start = text.index('class TriageBuilderDialog') body = text[start:text.index('def move_items', start)] assert 'wx.RESIZE_BORDER' not in body From 3ecf256682b2e2013f5c57b0c42c14eb0909e3c6 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 13 Aug 2026 18:12:42 -0400 Subject: [PATCH 21/33] fix(diagnostic): prevent matrix value clipping --- LabGym/gui_categorizer.py | 20 ++++- LabGym/tests/test_ac_cm_colors.py | 117 +++++++++++++++++++++++++++++- 2 files changed, 132 insertions(+), 5 deletions(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 7f720678..698d690d 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2489,8 +2489,6 @@ def init_ui(self): self.cm_grid.SetColLabelValue(i, name) self.cm_grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.on_cell_click) - - self.update_grid_data() self.cm_grid.SetRowLabelSize(wx.grid.GRID_AUTOSIZE) self.cm_grid.SetColLabelSize(wx.grid.GRID_AUTOSIZE) @@ -2498,7 +2496,7 @@ def init_ui(self): self.cm_grid.DisableDragRowSize() self.cm_grid.DisableDragColSize() - self.cm_grid.AutoSize() + self.update_grid_data() sizer.Add(self.cm_grid, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) bottom_dashboard_sizer = wx.BoxSizer(wx.HORIZONTAL) @@ -2667,9 +2665,23 @@ def update_grid_data(self): self.cm_grid.SetCellAlignment(i, j, wx.ALIGN_CENTER, wx.ALIGN_CENTER) self.cm_grid.SetCellBackgroundColour(i, j, bg_color) self.cm_grid.SetCellTextColour(i, j, wx.Colour(255, 255, 255)) - + + self.refresh_cm_column_widths() self.cm_grid.ForceRefresh() + def refresh_cm_column_widths(self): + """Size columns from current labels/values, with a padded floor for ``100.0%``.""" + grid = self.cm_grid + grid.AutoSizeColumns(False) + dc = wx.ClientDC(grid) + dc.SetFont(grid.GetDefaultCellFont()) + text_w, _text_h = dc.GetTextExtent('100.0%') + # Modest horizontal padding so centered percentages are not clipped. + min_width = text_w + 16 + for col in range(grid.GetNumberCols()): + if grid.GetColSize(col) < min_width: + grid.SetColSize(col, min_width) + def on_toggle_cm(self, event): self.is_normalized = self.toggle_btn.GetValue() if self.is_normalized: diff --git a/LabGym/tests/test_ac_cm_colors.py b/LabGym/tests/test_ac_cm_colors.py index 2b09c6b5..75aef420 100644 --- a/LabGym/tests/test_ac_cm_colors.py +++ b/LabGym/tests/test_ac_cm_colors.py @@ -1,10 +1,17 @@ -"""AC matrix correct-cell color endpoint and ordering.""" +"""AC matrix correct-cell color endpoint and CM width refresh.""" + +import inspect +from unittest.mock import patch + +import pytest from LabGym import mywx # noqa: F401 # must precede wx-dependent LabGym imports +import wx from LabGym.gui_categorizer import ( CM_CORRECT_RGB_MAX, CM_CORRECT_RGB_MIN, + AutomatedDiagnosticsDialog, cm_correct_cell_rgb, ) @@ -61,3 +68,111 @@ def test_white_text_contrast_at_max_green(): ratio = contrast_ratio((255, 255, 255), rgb) assert ratio >= 4.5 assert abs(ratio - 5.13) < 0.05 + + +@pytest.fixture(scope='module') +def wx_app(): + app = wx.App(False) + yield app + wx.CallAfter(app.ExitMainLoop) + app.MainLoop() + del app + wx.App._instance = None + + +def _padded_100_pct_min_width(grid): + dc = wx.ClientDC(grid) + dc.SetFont(grid.GetDefaultCellFont()) + text_w, _text_h = dc.GetTextExtent('100.0%') + return text_w + 16 + + +def _make_diagnostics_dialog(wx_app, classnames, cm): + parent = wx.Frame(None) + report = { + name: { + 'support': sum(cm[i]), + 'precision': 0.5, + 'recall': 0.5, + 'f1-score': 0.5, + } + for i, name in enumerate(classnames) + } + report['accuracy'] = 0.5 + report['macro avg'] = {'f1-score': 0.5, 'precision': 0.5, 'recall': 0.5} + report['weighted avg'] = {'f1-score': 0.5, 'precision': 0.5, 'recall': 0.5} + with patch.object(AutomatedDiagnosticsDialog, 'Maximize'): + dlg = AutomatedDiagnosticsDialog( + parent, + report, + cm, + classnames, + {}, + {}, + None, + ) + return parent, dlg + + +def test_diagnostics_cm_raw_first_toggle_refreshes_column_widths(wx_app): + # 198/250 == 79.2%; short labels exercise the padded floor. + classnames = ['idle', 'a', 'walk'] + cm = [ + [198, 52, 0], + [0, 10, 0], + [0, 0, 10], + ] + parent, dlg = _make_diagnostics_dialog(wx_app, classnames, cm) + try: + assert dlg.is_normalized is False + assert dlg.toggle_btn.GetLabel() == 'Show Normalized (%)' + assert dlg.cm_grid.GetCellValue(0, 0) == '198' + helper_src = inspect.getsource(AutomatedDiagnosticsDialog.refresh_cm_column_widths) + assert 'idle' not in helper_src + + refresh_calls = [] + original_refresh = dlg.refresh_cm_column_widths + + def tracking_refresh(): + refresh_calls.append(True) + return original_refresh() + + dlg.refresh_cm_column_widths = tracking_refresh + + dlg.toggle_btn.SetValue(True) + dlg.on_toggle_cm(None) + + assert dlg.is_normalized is True + assert dlg.toggle_btn.GetLabel() == 'Show Raw Counts' + assert dlg.cm_grid.GetCellValue(0, 0) == '79.2%' + assert dlg.cm_grid.GetCellValue(1, 1) == '100.0%' + assert len(refresh_calls) >= 1 + + min_w = _padded_100_pct_min_width(dlg.cm_grid) + for col in range(dlg.cm_grid.GetNumberCols()): + assert dlg.cm_grid.GetColSize(col) >= min_w + + # Generic short label (not idle) still meets the floor after refresh. + idle_w = dlg.cm_grid.GetColSize(0) + short_w = dlg.cm_grid.GetColSize(1) + assert short_w >= min_w + assert idle_w >= min_w + finally: + dlg.Destroy() + parent.Destroy() + + +def test_diagnostics_cm_column_width_helper_is_label_agnostic(wx_app): + classnames = ['z', 'yy'] + cm = [[5, 0], [0, 5]] + parent, dlg = _make_diagnostics_dialog(wx_app, classnames, cm) + try: + dlg.is_normalized = True + dlg.update_grid_data() + assert dlg.cm_grid.GetCellValue(0, 0) == '100.0%' + min_w = _padded_100_pct_min_width(dlg.cm_grid) + for col in range(dlg.cm_grid.GetNumberCols()): + assert dlg.cm_grid.GetColSize(col) >= min_w + finally: + dlg.Destroy() + parent.Destroy() From 11f9e4b2a42c4e79cdbaf2e44d63723a612321d3 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 13 Aug 2026 18:22:10 -0400 Subject: [PATCH 22/33] refactor(tests): use semantic diagnostics names --- LabGym/gui_categorizer.py | 4 ++-- ...match.py => test_categorizer_class_mismatch.py} | 2 +- ..._cm_colors.py => test_diagnostics_cm_colors.py} | 2 +- ...> test_diagnostics_copy_and_training_layout.py} | 14 +++++++------- ...box.py => test_interactive_results_checkbox.py} | 2 +- ...t_ac_triage_guards.py => test_triage_guards.py} | 2 +- ...age_layout_pdf.py => test_triage_layout_pdf.py} | 0 ...ckage_names.py => test_triage_package_names.py} | 0 8 files changed, 13 insertions(+), 13 deletions(-) rename LabGym/tests/{test_ac_categorizer_mismatch.py => test_categorizer_class_mismatch.py} (98%) rename LabGym/tests/{test_ac_cm_colors.py => test_diagnostics_cm_colors.py} (98%) rename LabGym/tests/{test_ac_diagnostics_copy.py => test_diagnostics_copy_and_training_layout.py} (93%) rename LabGym/tests/{test_ac_interactive_results_checkbox.py => test_interactive_results_checkbox.py} (98%) rename LabGym/tests/{test_ac_triage_guards.py => test_triage_guards.py} (99%) rename LabGym/tests/{test_ac_triage_layout_pdf.py => test_triage_layout_pdf.py} (100%) rename LabGym/tests/{test_ac_triage_package_names.py => test_triage_package_names.py} (100%) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 698d690d..3f154829 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -126,7 +126,7 @@ def reportlab_importable(): return False, str(e) -AC_DIAGNOSTIC_BUTTON_LABELS = ( +DIAGNOSTIC_BUTTON_LABELS = ( 'Overview', 'Major Confusions', 'Minor Confusions', @@ -2514,7 +2514,7 @@ def init_ui(self): label_minor, label_successes, label_triage, - ) = AC_DIAGNOSTIC_BUTTON_LABELS + ) = DIAGNOSTIC_BUTTON_LABELS self.btn_help = wx.Button(self, label=label_overview) self.btn_major = wx.Button(self, label=label_major) self.btn_minor = wx.Button(self, label=label_minor) diff --git a/LabGym/tests/test_ac_categorizer_mismatch.py b/LabGym/tests/test_categorizer_class_mismatch.py similarity index 98% rename from LabGym/tests/test_ac_categorizer_mismatch.py rename to LabGym/tests/test_categorizer_class_mismatch.py index 853fa95e..e6e62c26 100644 --- a/LabGym/tests/test_ac_categorizer_mismatch.py +++ b/LabGym/tests/test_categorizer_class_mismatch.py @@ -1,4 +1,4 @@ -"""AC categorizer class-mismatch contract.""" +"""Categorizer class-mismatch contract.""" from unittest.mock import patch diff --git a/LabGym/tests/test_ac_cm_colors.py b/LabGym/tests/test_diagnostics_cm_colors.py similarity index 98% rename from LabGym/tests/test_ac_cm_colors.py rename to LabGym/tests/test_diagnostics_cm_colors.py index 75aef420..88c43d70 100644 --- a/LabGym/tests/test_ac_cm_colors.py +++ b/LabGym/tests/test_diagnostics_cm_colors.py @@ -1,4 +1,4 @@ -"""AC matrix correct-cell color endpoint and CM width refresh.""" +"""Matrix correct-cell color endpoint and CM width refresh.""" import inspect from unittest.mock import patch diff --git a/LabGym/tests/test_ac_diagnostics_copy.py b/LabGym/tests/test_diagnostics_copy_and_training_layout.py similarity index 93% rename from LabGym/tests/test_ac_diagnostics_copy.py rename to LabGym/tests/test_diagnostics_copy_and_training_layout.py index a9ff3fa4..0612bd6d 100644 --- a/LabGym/tests/test_ac_diagnostics_copy.py +++ b/LabGym/tests/test_diagnostics_copy_and_training_layout.py @@ -1,11 +1,11 @@ -"""AC Training Module single-column structure and diagnostic copy contracts.""" +"""Training Module single-column structure and diagnostic copy contracts.""" from pathlib import Path from LabGym import mywx # noqa: F401 from LabGym.gui_categorizer import ( - AC_DIAGNOSTIC_BUTTON_LABELS, + DIAGNOSTIC_BUTTON_LABELS, collect_insufficient_support_entries, insufficient_support_threshold, ) @@ -51,16 +51,16 @@ def test_training_module_source_has_single_column_bindings(): assert f'self.{handler}' in body -def test_ac_diagnostic_labels_have_no_emoji_and_overview_first(): - assert AC_DIAGNOSTIC_BUTTON_LABELS[0] == 'Overview' - assert AC_DIAGNOSTIC_BUTTON_LABELS == ( +def test_diagnostic_labels_have_no_emoji_and_overview_first(): + assert DIAGNOSTIC_BUTTON_LABELS[0] == 'Overview' + assert DIAGNOSTIC_BUTTON_LABELS == ( 'Overview', 'Major Confusions', 'Minor Confusions', 'Successes', 'Build Triage Plan', ) - joined = ' '.join(AC_DIAGNOSTIC_BUTTON_LABELS) + joined = ' '.join(DIAGNOSTIC_BUTTON_LABELS) for ch in ('🔴', '🟡', '🟢', '🔵', '📝', '⚠️', '⚠'): assert ch not in joined @@ -74,7 +74,7 @@ def test_diagnostic_button_construction_uses_label_constant(): start = text.index('def init_ui(self):', class_start) end = text.index('\tdef update_grid_data', start) body = text[start:end] - assert 'AC_DIAGNOSTIC_BUTTON_LABELS' in body + assert 'DIAGNOSTIC_BUTTON_LABELS' in body assert 'label="Overview"' not in body assert 'label="🔴' not in body diff --git a/LabGym/tests/test_ac_interactive_results_checkbox.py b/LabGym/tests/test_interactive_results_checkbox.py similarity index 98% rename from LabGym/tests/test_ac_interactive_results_checkbox.py rename to LabGym/tests/test_interactive_results_checkbox.py index 331d1c39..caf33289 100644 --- a/LabGym/tests/test_ac_interactive_results_checkbox.py +++ b/LabGym/tests/test_interactive_results_checkbox.py @@ -1,4 +1,4 @@ -"""AC interactive-results checkbox on Test Categorizers.""" +"""Interactive-results checkbox on Test Categorizers.""" from unittest.mock import patch diff --git a/LabGym/tests/test_ac_triage_guards.py b/LabGym/tests/test_triage_guards.py similarity index 99% rename from LabGym/tests/test_ac_triage_guards.py rename to LabGym/tests/test_triage_guards.py index 78d39151..eb71c14f 100644 --- a/LabGym/tests/test_ac_triage_guards.py +++ b/LabGym/tests/test_triage_guards.py @@ -1,4 +1,4 @@ -"""AC triage empty-plan, PDF preflight, package wrapper, and outcome helpers.""" +"""Triage empty-plan, PDF preflight, package wrapper, and outcome helpers.""" from unittest.mock import MagicMock, patch diff --git a/LabGym/tests/test_ac_triage_layout_pdf.py b/LabGym/tests/test_triage_layout_pdf.py similarity index 100% rename from LabGym/tests/test_ac_triage_layout_pdf.py rename to LabGym/tests/test_triage_layout_pdf.py diff --git a/LabGym/tests/test_ac_triage_package_names.py b/LabGym/tests/test_triage_package_names.py similarity index 100% rename from LabGym/tests/test_ac_triage_package_names.py rename to LabGym/tests/test_triage_package_names.py From 7d5e02b744c64b025f41d05f22914f5999b916b2 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 13 Aug 2026 19:51:46 -0400 Subject: [PATCH 23/33] fix(diagnostics): avoid native DC finalization --- LabGym/gui_categorizer.py | 5 ++--- LabGym/tests/test_diagnostics_cm_colors.py | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 3f154829..b61d3d9b 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2673,9 +2673,8 @@ def refresh_cm_column_widths(self): """Size columns from current labels/values, with a padded floor for ``100.0%``.""" grid = self.cm_grid grid.AutoSizeColumns(False) - dc = wx.ClientDC(grid) - dc.SetFont(grid.GetDefaultCellFont()) - text_w, _text_h = dc.GetTextExtent('100.0%') + font = grid.GetDefaultCellFont() + text_w, _h, _d, _el = grid.GetFullTextExtent('100.0%', font) # Modest horizontal padding so centered percentages are not clipped. min_width = text_w + 16 for col in range(grid.GetNumberCols()): diff --git a/LabGym/tests/test_diagnostics_cm_colors.py b/LabGym/tests/test_diagnostics_cm_colors.py index 88c43d70..517bebb4 100644 --- a/LabGym/tests/test_diagnostics_cm_colors.py +++ b/LabGym/tests/test_diagnostics_cm_colors.py @@ -81,9 +81,8 @@ def wx_app(): def _padded_100_pct_min_width(grid): - dc = wx.ClientDC(grid) - dc.SetFont(grid.GetDefaultCellFont()) - text_w, _text_h = dc.GetTextExtent('100.0%') + font = grid.GetDefaultCellFont() + text_w, _h, _d, _el = grid.GetFullTextExtent('100.0%', font) return text_w + 16 From 9c19544e98c0cea6781871674765b5964d669466 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Wed, 23 Sep 2026 17:29:06 -0400 Subject: [PATCH 24/33] style: remove trailing whitespace from diagnostics --- LabGym/categorizer.py | 4 +- LabGym/gui_categorizer.py | 146 +++++++++++++++++++------------------- 2 files changed, 75 insertions(+), 75 deletions(-) diff --git a/LabGym/categorizer.py b/LabGym/categorizer.py index 41bce807..e7b3523e 100644 --- a/LabGym/categorizer.py +++ b/LabGym/categorizer.py @@ -2141,9 +2141,9 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): example_map[key] = [] example_map[key].append(f_path) embedding_map[f_path] = emb - + print('Testing completed!') - + return report, cm, example_map, embedding_map diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index b61d3d9b..12d91d2f 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -2441,19 +2441,19 @@ def remove_categorizer(self,event): class AutomatedDiagnosticsDialog(wx.Dialog): def __init__(self, parent, report, cm, classnames, example_map, embedding_map, source_dataset_root=None): super().__init__(parent, title="Automated Diagnostics - Test Results", size=(1000, 800), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) - + self.report = report self.cm = cm self.classnames = classnames self.example_map = example_map self.embedding_map = embedding_map self.source_dataset_root = source_dataset_root - + self.cm_normalized = self.calculate_normalized_cm(cm) self.is_normalized = False - + self.init_ui() - + self.Maximize(True) def calculate_normalized_cm(self, cm): @@ -2474,16 +2474,16 @@ def init_ui(self): cm_label = wx.StaticText(self, label="Confusion Matrix:") cm_label.SetFont(font) header_sizer.Add(cm_label, 1, wx.ALIGN_CENTER_VERTICAL) - + self.toggle_btn = wx.ToggleButton(self, label="Show Normalized (%)") self.toggle_btn.Bind(wx.EVT_TOGGLEBUTTON, self.on_toggle_cm) header_sizer.Add(self.toggle_btn, 0, wx.ALIGN_CENTER_VERTICAL) - + sizer.Add(header_sizer, 0, wx.EXPAND | wx.ALL, 10) self.cm_grid = wx.grid.Grid(self) self.cm_grid.CreateGrid(len(self.classnames), len(self.classnames)) - + for i, name in enumerate(self.classnames): self.cm_grid.SetRowLabelValue(i, name) self.cm_grid.SetColLabelValue(i, name) @@ -2540,30 +2540,30 @@ def init_ui(self): sort_sizer = wx.BoxSizer(wx.HORIZONTAL) self.sort_label = wx.StaticText(self, label="Rank Insights By: ") sort_sizer.Add(self.sort_label, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5) - + self.sort_dropdown = wx.Choice(self, choices=["Instances", "Proportion"]) self.sort_dropdown.SetSelection(0) self.sort_dropdown.Bind(wx.EVT_CHOICE, self.on_sort_changed) sort_sizer.Add(self.sort_dropdown, 0, wx.ALIGN_CENTER_VERTICAL) - + nlp_sizer.Add(sort_sizer, 0, wx.BOTTOM | wx.LEFT, 5) self.nlp_html = wx.html.HtmlWindow(self, style=wx.html.HW_SCROLLBAR_AUTO | wx.BORDER_NONE) self.nlp_html.Bind(wx.html.EVT_HTML_LINK_CLICKED, self.on_insight_link_clicked) - - nlp_sizer.Add(self.nlp_html, 1, wx.EXPAND | wx.ALL, 5) + + nlp_sizer.Add(self.nlp_html, 1, wx.EXPAND | wx.ALL, 5) bottom_dashboard_sizer.Add(nlp_sizer, 1, wx.EXPAND | wx.RIGHT, 10) table_sizer = wx.BoxSizer(wx.VERTICAL) - + table_header_sizer = wx.BoxSizer(wx.HORIZONTAL) self.table_label = wx.StaticText(self, label="Highlight behaviors below 0.60: ") self.table_label.SetFont(font) self.metric_choice = wx.Choice(self, choices=["F1-score", "Precision", "Recall"]) self.metric_choice.SetSelection(0) self.metric_choice.Bind(wx.EVT_CHOICE, self.on_metric_change) - + table_header_sizer.Add(self.table_label, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5) table_header_sizer.Add(self.metric_choice, 0, wx.ALIGN_CENTER_VERTICAL) table_sizer.Add(table_header_sizer, 0, wx.BOTTOM, 5) @@ -2589,29 +2589,29 @@ def init_ui(self): self.analyze_confusion_data() self.show_help_view(None) - + self.SetSizer(sizer) self.Layout() def on_build_triage(self, event): """Gathers all confusions and launches the Triage Builder.""" all_confusions = [] - + for count, i, j, prop in self.nlp_major: item = f"{self.classnames[i]} -> {self.classnames[j]} ({count} errors)" if item not in all_confusions: all_confusions.append(item) - + for mc in self.nlp_minor: for err_count, pred_class in mc['top_confusions']: item = f"{mc['class']} -> {pred_class} ({err_count} errors)" if item not in all_confusions: all_confusions.append(item) - + if not all_confusions: wx.MessageBox("No confusions detected to triage!", "All Clear", wx.OK | wx.ICON_INFORMATION) return - + dialog = TriageBuilderDialog( self, all_confusions, @@ -2628,7 +2628,7 @@ def on_build_triage(self, event): def on_sort_changed(self, event): """Re-sorts the NLP data and refreshes the views when the dropdown changes.""" self.analyze_confusion_data() - + if getattr(self, 'current_view', 'major') == 'minor': self.show_minor_confusions_view(None) else: @@ -2641,14 +2641,14 @@ def update_grid_data(self): for i in range(len(self.classnames)): row_sum = sum(self.cm[i]) if i < cm_rows else 0 - + for j in range(len(self.classnames)): if i < cm_rows and j < cm_cols: val = f"{data_to_use[i][j]}%" if self.is_normalized else str(data_to_use[i][j]) - + if i != j and self.cm[i][j] > 0: err_pct = self.cm[i][j] / row_sum if row_sum > 0 else 0 - intensity = min(1.0, err_pct / 0.5) + intensity = min(1.0, err_pct / 0.5) r_val = int(40 + (215 * intensity)) bg_color = wx.Colour(r_val, 0, 0) elif i == j and row_sum > 0: @@ -2659,7 +2659,7 @@ def update_grid_data(self): else: val = "0.0%" if self.is_normalized else "0" bg_color = wx.Colour(30, 30, 30) - + self.cm_grid.SetCellValue(i, j, val) self.cm_grid.SetReadOnly(i, j, True) self.cm_grid.SetCellAlignment(i, j, wx.ALIGN_CENTER, wx.ALIGN_CENTER) @@ -2687,15 +2687,15 @@ def on_toggle_cm(self, event): self.toggle_btn.SetLabel("Show Raw Counts") else: self.toggle_btn.SetLabel("Show Normalized (%)") - + self.update_grid_data() def on_insight_link_clicked(self, event): """Highlights the specific grid cell or row when a user clicks the diagnostic text.""" href = event.GetLinkInfo().GetHref() - + self.update_grid_data() - + if href.startswith('cell:'): coords = href.replace('cell:', '').split(',') row, col = int(coords[0]), int(coords[1]) @@ -2706,16 +2706,16 @@ def on_insight_link_clicked(self, event): elif href.startswith('row:'): row = int(href.replace('row:', '')) self.cm_grid.MakeCellVisible(row, row) - + self.cm_grid.SetCellBackgroundColour(row, row, wx.Colour(0, 255, 255)) self.cm_grid.SetCellTextColour(row, row, wx.Colour(0, 0, 0)) - + cm_rows = len(self.cm) confusions = [] for j in range(cm_rows): if row != j and self.cm[row][j] > 0: confusions.append((self.cm[row][j], j)) - + confusions.sort(reverse=True, key=lambda x: x[0]) for err_val, col in confusions[:3]: self.cm_grid.SetCellBackgroundColour(row, col, wx.Colour(255, 203, 5)) @@ -2758,7 +2758,7 @@ def analyze_confusion_data(self): if i != j and self.cm[i][j] > 0: error_count = self.cm[i][j] error_proportion = error_count / support - + if error_proportion >= 0.10: self.nlp_major.append((error_count, i, j, error_proportion)) found_major_confusion = True @@ -2771,7 +2771,7 @@ def analyze_confusion_data(self): for j in range(cm_rows): if i != j and self.cm[i][j] > 0: specific_confusions.append((self.cm[i][j], self.classnames[j])) - + specific_confusions.sort(reverse=True, key=lambda x: x[0]) top_specifics = specific_confusions[:3] @@ -2786,7 +2786,7 @@ def analyze_confusion_data(self): sort_mode = self.sort_dropdown.GetStringSelection() - + if sort_mode == "Proportion": self.nlp_major.sort(reverse=True, key=lambda x: x[3]) self.nlp_minor.sort(reverse=True, key=lambda x: x['pct_errors']) @@ -2809,27 +2809,27 @@ def show_major_confusions_view(self, event=None): self.sort_label.Show(True) self.sort_dropdown.Show(True) self.Layout() - + html = "" - + if not self.nlp_major: html += "

No major confusion patterns

No major confusion patterns were identified at the configured thresholds.

" else: html += "

Major Systematic Confusions:

" - for count, i, j, prop in self.nlp_major[:5]: + for count, i, j, prop in self.nlp_major[:5]: true_class = self.classnames[i] pred_class = self.classnames[j] prop_pct = round(prop * 100, 1) link = f"{true_class} → {pred_class}" html += "
" - + error_txt = f"{count} errors, {prop_pct}% of {true_class} data" - + html += f"

{link} ({error_txt})

" - + html += "
" - + html += "" self.nlp_html.SetPage(html) @@ -2838,10 +2838,10 @@ def show_minor_confusions_view(self, event=None): self.sort_label.Show(True) self.sort_dropdown.Show(True) self.Layout() - + html = "" - + if not self.nlp_minor: html += "

No dispersed minor confusion patterns

No dispersed minor confusion patterns were identified at the configured thresholds.

" else: @@ -2854,7 +2854,7 @@ def show_minor_confusions_view(self, event=None): supp = int(mc['support']) errs = mc['total_errors'] pct = round(mc['pct_errors'], 1) - + warning = " (fewer than 100 examples)" if supp < 100 else "" link = f"{c_name}" @@ -2868,7 +2868,7 @@ def show_minor_confusions_view(self, event=None): html += f"
  • To {pred_class}: {err_count} errors
  • " html += "" html += "
    " - + html += "" self.nlp_html.SetPage(html) @@ -2877,7 +2877,7 @@ def show_successes_view(self, event=None): self.sort_label.Show(False) self.sort_dropdown.Show(False) self.Layout() - + html = "" if self.nlp_success: @@ -2889,7 +2889,7 @@ def show_successes_view(self, event=None): c_name = sc['class'] f1_pct = round(sc['f1'] * 100, 1) supp = int(sc['support']) - + link = f"{c_name}" html += f"
  • {link} ({f1_pct}% F1) [{supp} examples]
  • " html += "" @@ -2918,7 +2918,7 @@ def show_help_view(self, event=None): self.sort_label.Show(False) self.sort_dropdown.Show(False) self.Layout() - + html = """

    Overview

    @@ -2937,7 +2937,7 @@ def on_metric_change(self, event): def update_table_data(self): self.list_ctrl.DeleteAllItems() - + selection = self.metric_choice.GetStringSelection() metric_key = 'f1-score' if selection == "Precision": @@ -2955,7 +2955,7 @@ def update_table_data(self): recall = float(metrics.get('recall', 0.0)) f1 = float(metrics.get('f1-score', 0.0)) support = float(metrics.get('support', 0.0)) - + self.list_ctrl.SetItem(index, 1, f"{precision:.2f}") self.list_ctrl.SetItem(index, 2, f"{recall:.2f}") self.list_ctrl.SetItem(index, 3, f"{f1:.2f}") @@ -2966,7 +2966,7 @@ def update_table_data(self): self.list_ctrl.SetItemBackgroundColour(index, wx.Colour(150, 0, 0)) else: self.list_ctrl.SetItemBackgroundColour(index, wx.Colour(30, 30, 30)) - + self.list_ctrl.SetItemTextColour(index, wx.Colour(255, 255, 255)) index += 1 @@ -2978,9 +2978,9 @@ def generate_diagnostic_insights_html(self, top_n=3, support_threshold=50): for i in range(cm_rows): true_class = self.classnames[i] support_true = self.report.get(true_class, {}).get('support', 0) - + if support_true == 0: - continue + continue row_errors = sum(self.cm[i]) - self.cm[i][i] if row_errors == 0: @@ -2993,12 +2993,12 @@ def generate_diagnostic_insights_html(self, top_n=3, support_threshold=50): errors.sort(reverse=True, key=lambda x: x[0]) html = "" - + if not errors: html += "

    No major confusion patterns

    No major confusion patterns were identified at the configured thresholds.

    " else: html += "

    Here is where the Categorizer is struggling:

    " - + for count, i, j in errors[:top_n]: true_class = self.classnames[i] pred_class = self.classnames[j] @@ -3006,15 +3006,15 @@ def generate_diagnostic_insights_html(self, top_n=3, support_threshold=50): support_pred = self.report.get(pred_class, {}).get('support', 0) link = f"{true_class} → {pred_class}" - + html += "
    " - + if support_true >= support_threshold and support_pred >= support_threshold: html += f"

    {link} ({count} errors)

    Possible pattern (advisory): Both behaviors have relatively robust support on this test set. Because the Categorizer is still confusing them, they might be visually similar. Consider reviewing whether labels overlap.

    " else: lowest_class = true_class if support_true < support_pred else pred_class html += f"

    {link} ({count} errors)

    Possible pattern (advisory): Support for {lowest_class} is limited on this test set. Adding more examples may help, but this is not a definitive diagnosis.

    " - + html += "
    " if perfect_classes: @@ -3027,54 +3027,54 @@ def generate_diagnostic_insights_html(self, top_n=3, support_threshold=50): def on_cell_click(self, event): row = event.GetRow() col = event.GetCol() - + self.cm_grid.ClearSelection() - + if row == -1 or col == -1: return - + if row < len(self.classnames) and col < len(self.classnames): true_class = self.classnames[row] pred_class = self.classnames[col] - + key = (true_class, pred_class) examples = self.example_map.get(key, []) - + if examples: viewer = ExampleViewerDialog(self, true_class, pred_class, examples) viewer.ShowModal() viewer.Destroy() else: wx.MessageBox(f"No examples found for True: '{true_class}', Predicted: '{pred_class}'", "No Data", wx.OK | wx.ICON_INFORMATION) - + class ExampleViewerDialog(wx.Dialog): def __init__(self, parent, true_class, pred_class, examples): title = f"Reviewing Examples: True '{true_class}' -> Predicted '{pred_class}'" super().__init__(parent, title=title, size=(600, 400), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) - + self.examples = examples self.init_ui() - + def init_ui(self): sizer = wx.BoxSizer(wx.VERTICAL) - + info_label = wx.StaticText(self, label=f"Found {len(self.examples)} example(s). Double-click a file to open it:") sizer.Add(info_label, 0, wx.ALL, 10) - + self.list_box = wx.ListBox(self, choices=self.examples, style=wx.LB_SINGLE | wx.LB_HSCROLL) self.list_box.Bind(wx.EVT_LISTBOX_DCLICK, self.on_double_click) sizer.Add(self.list_box, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 10) - + btn_sizer = wx.BoxSizer(wx.HORIZONTAL) close_btn = wx.Button(self, wx.ID_CLOSE, "Close") close_btn.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.ID_CANCEL)) btn_sizer.Add(close_btn, 0, wx.ALL, 10) sizer.Add(btn_sizer, 0, wx.ALIGN_RIGHT) - + self.SetSizer(sizer) self.Layout() - + def on_double_click(self, event): selection = self.list_box.GetSelection() if selection != wx.NOT_FOUND: @@ -3319,23 +3319,23 @@ def move_items(self, source_lb, target_lb, append_text=""): selections = source_lb.GetSelections() if not selections: return - + for idx in reversed(selections): item_text = source_lb.GetString(idx) target_lb.Append(f"{item_text} {append_text}") source_lb.Delete(idx) - + def on_move_h2(self, event): if not self.lb_unassigned.GetSelections(): return - + dlg = wx.TextEntryDialog(self, "What is the name of this new emergent behavior?", "Define Emergent Class") if dlg.ShowModal() == wx.ID_OK: new_name = dlg.GetValue().strip() if new_name: self.move_items(self.lb_unassigned, self.lb_h2, f"[NEW: {new_name}]") dlg.Destroy() - + def on_return_items(self, event): """Returns selected items from any right-side bucket back to unassigned.""" for lb in [self.lb_h1, self.lb_h2, self.lb_h3]: From f70cf53d058299795bcf0c7b53c0fb30d9179719 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Wed, 23 Sep 2026 17:33:09 -0400 Subject: [PATCH 25/33] fix(categorizer): remove duplicate diagnostics return block --- LabGym/categorizer.py | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/LabGym/categorizer.py b/LabGym/categorizer.py index e7b3523e..501a6216 100644 --- a/LabGym/categorizer.py +++ b/LabGym/categorizer.py @@ -2133,20 +2133,6 @@ def test_categorizer(self,groundtruth_path,model_path,result_path=None): return report, cm, example_map, embedding_map - example_map = {} - embedding_map = {} - for t_label_idx, p_label_idx, f_path, emb in zip(labels, flat_predictions, test_files, embeddings): - key = (classnames[t_label_idx], classnames[p_label_idx]) - if key not in example_map: - example_map[key] = [] - example_map[key].append(f_path) - embedding_map[f_path] = emb - - print('Testing completed!') - - return report, cm, example_map, embedding_map - - def generate_probability_matrix(self, path_to_video, path_to_model, output_folder, batch_size=32): """ Frame-level probability matrix (T x K) using the trained Categorizer. From 540701e8b4ee6404d415cc3aca59a10a77d4801f Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Wed, 23 Sep 2026 17:36:13 -0400 Subject: [PATCH 26/33] fix(gui): restore accepted training module layout --- LabGym/gui_main.py | 32 +++++++------------------------- 1 file changed, 7 insertions(+), 25 deletions(-) diff --git a/LabGym/gui_main.py b/LabGym/gui_main.py index 2dc2660f..9ae1b1f9 100644 --- a/LabGym/gui_main.py +++ b/LabGym/gui_main.py @@ -188,18 +188,8 @@ def __init__(self, parent): def display_window(self): panel = self - main_sizer = wx.BoxSizer(wx.VERTICAL) - main_sizer.Add(0, 50, 0) - - columns_sizer = wx.BoxSizer(wx.HORIZONTAL) - - header_font = wx.Font(14, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) - - detector_sizer = wx.BoxSizer(wx.VERTICAL) - - text_detector = wx.StaticText(panel, label='Detector Pipeline') - text_detector.SetFont(header_font) - detector_sizer.Add(text_detector, 0, wx.ALIGN_CENTER | wx.BOTTOM, 25) + boxsizer=wx.BoxSizer(wx.VERTICAL) + boxsizer.Add(0,60,0) button_generateimages=wx.Button(panel,label='Generate Image Examples',size=(300,40)) button_generateimages.Bind(wx.EVT_BUTTON,self.generate_images) @@ -207,8 +197,9 @@ def display_window(self): boxsizer.Add(button_generateimages,0,wx.ALIGN_CENTER,10) boxsizer.Add(0,5,0) - link_annotate=create_hyperlink(panel,'Annotate images with EZannot','https://github.com/yujiahu415/EZannot') - detector_sizer.Add(link_annotate,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) + link_annotate=create_hyperlink(panel,'\nAnnotate images with EZannot\n','https://github.com/yujiahu415/EZannot') + boxsizer.Add(link_annotate,0,wx.ALIGN_CENTER,10) + boxsizer.Add(0,5,0) button_traindetectors=wx.Button(panel,label='Train Detectors',size=(300,40)) button_traindetectors.Bind(wx.EVT_BUTTON,self.train_detectors) @@ -219,17 +210,8 @@ def display_window(self): button_testdetectors=wx.Button(panel,label='Test Detectors',size=(300,40)) button_testdetectors.Bind(wx.EVT_BUTTON,self.test_detectors) wx.Button.SetToolTip(button_testdetectors,'Test trained Detectors on the annotated ground-truth image dataset (similar to the image dataset used for training a Detector).') - detector_sizer.Add(button_testdetectors,0,wx.ALIGN_CENTER|wx.BOTTOM, 15) - - - divider_line = wx.StaticLine(panel, style=wx.LI_VERTICAL) - - - categorizer_sizer = wx.BoxSizer(wx.VERTICAL) - - text_categorizer = wx.StaticText(panel, label='Categorizer Pipeline') - text_categorizer.SetFont(header_font) - categorizer_sizer.Add(text_categorizer, 0, wx.ALIGN_CENTER | wx.BOTTOM, 25) + boxsizer.Add(button_testdetectors,0,wx.ALIGN_CENTER,10) + boxsizer.Add(0,50,0) button_generatebehaviorexamples=wx.Button(panel,label='Generate Behavior Examples',size=(300,40)) button_generatebehaviorexamples.Bind(wx.EVT_BUTTON,self.generate_behaviorexamples) From 40c716b38fd184de8715a823de4c8bcebbfe6692 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Wed, 23 Sep 2026 20:53:34 -0400 Subject: [PATCH 27/33] fix(gui): avoid Windows-only curses import --- LabGym/gui_analyzer.py | 1 - 1 file changed, 1 deletion(-) diff --git a/LabGym/gui_analyzer.py b/LabGym/gui_analyzer.py index 805ef980..f14905b1 100644 --- a/LabGym/gui_analyzer.py +++ b/LabGym/gui_analyzer.py @@ -18,7 +18,6 @@ # Standard library imports. -from curses.panel import panel import json import logging import os From 1099daa83788283effc159fdc1cfdb60bc5e72c6 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 24 Sep 2026 14:22:23 -0400 Subject: [PATCH 28/33] fix(ci): avoid macOS native teardown crash --- noxfile.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/noxfile.py b/noxfile.py index e77d8e00..f41d9221 100644 --- a/noxfile.py +++ b/noxfile.py @@ -17,6 +17,7 @@ ''' import nox +import os import platform @@ -63,7 +64,16 @@ def tests(session:nox.Session): session.install("pytest") - session.run("pytest", "-q") + if platform.system() == "Darwin": + # wxPython/PyObjC can abort during macOS interpreter teardown after + # pytest has completed successfully; preserve pytest's exit status. + session.run( + "python", + "-c", + "import os, pytest; os._exit(pytest.main(['-q']))", + ) + else: + session.run("pytest", "-q") @nox.session(reuse_venv=True) From 9784ab1b6deece9da69e2077621de71bc5a70f4e Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 24 Sep 2026 14:36:26 -0400 Subject: [PATCH 29/33] fix(ci): pin macOS GUI test dependencies --- noxfile.py | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/noxfile.py b/noxfile.py index f41d9221..7ade9c95 100644 --- a/noxfile.py +++ b/noxfile.py @@ -17,7 +17,6 @@ ''' import nox -import os import platform @@ -49,6 +48,13 @@ def tests(session:nox.Session): "torchvision==0.23.0+cpu", "torchaudio==2.8.0+cpu", ) + elif platform.system() == "Darwin": + # Keep the macOS GUI stack on the version family that completes CI cleanly. + session.install( + "--only-binary=:all:", + "wxPython==4.2.4", + "pyobjc-framework-Cocoa==11.1", + ) elif platform.system() == "Windows": # Verified Windows CPU family; editable install below enforces numpy<=1.26.4 session.install( @@ -64,16 +70,7 @@ def tests(session:nox.Session): session.install("pytest") - if platform.system() == "Darwin": - # wxPython/PyObjC can abort during macOS interpreter teardown after - # pytest has completed successfully; preserve pytest's exit status. - session.run( - "python", - "-c", - "import os, pytest; os._exit(pytest.main(['-q']))", - ) - else: - session.run("pytest", "-q") + session.run("pytest", "-q") @nox.session(reuse_venv=True) From 6fbbb4142698ca0901fca0effcf66ad614c2f50c Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 13 Aug 2026 22:31:26 -0400 Subject: [PATCH 30/33] ci(nox): isolate macOS 3.9 wx.App tests --- noxfile.py | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/noxfile.py b/noxfile.py index 7ade9c95..56134cb1 100644 --- a/noxfile.py +++ b/noxfile.py @@ -25,6 +25,22 @@ EXTRAS_WX_URL = "https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-22.04" +# macOS Python 3.9 (wxPython ~4.2.x / Cocoa) can abort during interpreter +# teardown when repeated real-wx.App lifecycle modules are alphabetically +# interleaved with the rest of the native-importing suite. Isolate those +# modules in a separate pytest process for Darwin+3.9 only; they are not +# skipped. Add any future test module that creates/manages a real wx.App +# fixture to this list. +MACOS39_REAL_APP_TEST_FILES = ( + "LabGym/tests/test_categorizer_class_mismatch.py", + "LabGym/tests/test_diagnostics_cm_colors.py", + "LabGym/tests/test_interactive_results_checkbox.py", + "LabGym/tests/test_triage_guards.py", + "LabGym/tests/test_mywx.py", + "LabGym/tests/test_registration.py", + "LabGym/tests/test_userdata_survey.py", +) + @nox.session(python=['3.9','3.10']) def tests(session:nox.Session): @@ -69,8 +85,23 @@ def tests(session:nox.Session): session.install("-e", ".") session.install("pytest") - - session.run("pytest", "-q") + # Darwin + Python 3.9: isolate real-wx.App lifecycle modules in process 1. + session_python = str(session.python) + if platform.system() == "Darwin" and ( + session_python == "3.9" or session_python.startswith("3.9.") + ): + session.run("pytest", "-q", *MACOS39_REAL_APP_TEST_FILES) + ignore_args = [f"--ignore={path}" for path in MACOS39_REAL_APP_TEST_FILES] + session.run( + "pytest", + "-q", + "LabGym/tests", + *ignore_args, + "tests/test_load.py", + "tests/test_main.py", + ) + else: + session.run("pytest", "-q") @nox.session(reuse_venv=True) From 6102323dfd134f5396839b636b61bc520e208a78 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 24 Sep 2026 14:54:04 -0400 Subject: [PATCH 31/33] fix(ci): isolate macOS wx.App test lifecycles --- noxfile.py | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/noxfile.py b/noxfile.py index 56134cb1..cf058bdc 100644 --- a/noxfile.py +++ b/noxfile.py @@ -25,13 +25,13 @@ EXTRAS_WX_URL = "https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-22.04" -# macOS Python 3.9 (wxPython ~4.2.x / Cocoa) can abort during interpreter +# macOS native GUI frameworks can abort during interpreter # teardown when repeated real-wx.App lifecycle modules are alphabetically # interleaved with the rest of the native-importing suite. Isolate those -# modules in a separate pytest process for Darwin+3.9 only; they are not +# modules in a separate pytest process for Darwin only; they are not # skipped. Add any future test module that creates/manages a real wx.App # fixture to this list. -MACOS39_REAL_APP_TEST_FILES = ( +MACOS_REAL_APP_TEST_FILES = ( "LabGym/tests/test_categorizer_class_mismatch.py", "LabGym/tests/test_diagnostics_cm_colors.py", "LabGym/tests/test_interactive_results_checkbox.py", @@ -64,13 +64,6 @@ def tests(session:nox.Session): "torchvision==0.23.0+cpu", "torchaudio==2.8.0+cpu", ) - elif platform.system() == "Darwin": - # Keep the macOS GUI stack on the version family that completes CI cleanly. - session.install( - "--only-binary=:all:", - "wxPython==4.2.4", - "pyobjc-framework-Cocoa==11.1", - ) elif platform.system() == "Windows": # Verified Windows CPU family; editable install below enforces numpy<=1.26.4 session.install( @@ -85,13 +78,10 @@ def tests(session:nox.Session): session.install("-e", ".") session.install("pytest") - # Darwin + Python 3.9: isolate real-wx.App lifecycle modules in process 1. - session_python = str(session.python) - if platform.system() == "Darwin" and ( - session_python == "3.9" or session_python.startswith("3.9.") - ): - session.run("pytest", "-q", *MACOS39_REAL_APP_TEST_FILES) - ignore_args = [f"--ignore={path}" for path in MACOS39_REAL_APP_TEST_FILES] + # Darwin: isolate real-wx.App lifecycle modules in process 1. + if platform.system() == "Darwin": + session.run("pytest", "-q", *MACOS_REAL_APP_TEST_FILES) + ignore_args = [f"--ignore={path}" for path in MACOS_REAL_APP_TEST_FILES] session.run( "pytest", "-q", From cd0142e1d73f9414248e0cdd9d1f42b5689519f7 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 13 Aug 2026 23:12:25 -0400 Subject: [PATCH 32/33] ci(pytest): remove unused coverage filters --- LabGym/tests/pytest.ini | 5 ----- 1 file changed, 5 deletions(-) diff --git a/LabGym/tests/pytest.ini b/LabGym/tests/pytest.ini index 385a3fef..13aa2a3d 100644 --- a/LabGym/tests/pytest.ini +++ b/LabGym/tests/pytest.ini @@ -1,7 +1,2 @@ # pytest.ini [pytest] -# Avoid two coverage warnings from detectron2's import of cv2. -# (see Notes.opencv-python-and-coverage-warnings.txt) -filterwarnings = - ignore:Couldn't parse .*/config-3.py:coverage.exceptions.CoverageWarning - ignore:Couldn't parse .*/config.py:coverage.exceptions.CoverageWarning From ec377298dbcff298fc083b7f1d7625746f02f322 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 24 Sep 2026 15:27:04 -0400 Subject: [PATCH 33/33] docs: restore Windows installation guidance --- docs/contributing/setup.md | 19 ++++++------------- docs/installation/windows.md | 14 +++++++------- 2 files changed, 13 insertions(+), 20 deletions(-) diff --git a/docs/contributing/setup.md b/docs/contributing/setup.md index 641dd236..e3618946 100644 --- a/docs/contributing/setup.md +++ b/docs/contributing/setup.md @@ -89,23 +89,16 @@ 5. If you're on Windows or Linux, install PyTorch. If you're on macOS, PyTorch will already be installed. - Use the aligned PyTorch **2.8** family (`torch==2.8.0`, `torchvision==0.23.0`, - `torchaudio==2.8.0`). LabGym’s Windows metadata pins these base versions; - matching official CPU or CUDA wheel variants are accepted. - - ````{tab} CPU Only + ````{tab} GPU ```console - $ python -m pip install torch==2.8.0 torchvision==0.23.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cpu + $ python -m pip install --index-url https://download.pytorch.org/whl/cu118 torch==2.0.1 torchvision==0.15.2 ``` ```` - ````{tab} GPU - Select an official PyTorch **2.8**-compatible CUDA wheel index from - [PyTorch’s installation guidance](https://pytorch.org/get-started/locally/) - for your supported hardware and CUDA runtime, then install the same - `torch==2.8.0`, `torchvision==0.23.0`, and `torchaudio==2.8.0` base versions - from that index. Do not use older LabGym instructions that pinned PyTorch - 2.0.1 / CUDA 11.8. + ````{tab} CPU Only + ```console + $ python -m pip install --index-url https://download.pytorch.org/whl/cpu torch==2.0.1 torchvision==0.15.2 + ``` ```` 6. Test your setup by launching LabGym. If the LabGym GUI shows up, your setup diff --git a/docs/installation/windows.md b/docs/installation/windows.md index f827d4d7..147d4879 100644 --- a/docs/installation/windows.md +++ b/docs/installation/windows.md @@ -12,17 +12,17 @@ To install LabGym on Windows, you will need to access the terminal. To do this, py -3.10 --version ``` -2. Install the verified PyTorch 2.8 family for LabGym on Windows. +2. If you're using an NVIDIA GPU, install CUDA Toolkit 11.8 and cuDNN, and install PyTorch v2.0.1 with cu118 support. - The default, verified path is the official PyTorch CPU wheels: + First, install [CUDA Toolkit 11.8](https://developer.nvidia.com/cuda-11-8-0-download-archive?target_os=Windows&target_arch=x86_64). Select your version of Windows, select "exe (local)," then click "Download." - ```pwsh-session - py -3.10 -m pip install torch==2.8.0 torchvision==0.23.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cpu - ``` + Next, install [cuDNN](https://developer.nvidia.com/rdp/cudnn-archive). You will need to register an NVIDIA Developer account, which you can do for free. You can choose cuDNN v8.9.7 that supports CUDA toolkit v11.8. Choose 'Local Installer for Windows (Zip)', download and extract it. And then copy the three folders 'bin', 'lib', and 'include' into where the CUDA toolkit is installed (typcially, 'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8\'), and replace all the three folders with the same names. After that, you may need to add the 'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8' to the 'PATH' environmental variable. - LabGym’s Windows package requirements use these base versions. Matching official CPU or CUDA builds (for example `2.8.0+cpu`) satisfy them. + Finally, install PyTorch v2.0.1 with cu118 support. - If you need GPU acceleration, install a PyTorch **2.8**-compatible CUDA wheel from [PyTorch’s current installation guidance](https://pytorch.org/get-started/locally/) for your supported hardware and CUDA runtime. Do not use older LabGym documentation that pinned PyTorch 2.0.1. + ```pwsh-session + py -3.10 -m pip install torch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 --index-url https://download.pytorch.org/whl/cu118 + ``` 4. Upgrade `pip`, `wheel`, `setuptools`.