diff --git a/LabGym/categorizer.py b/LabGym/categorizer.py index 8e093548..501a6216 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 @@ -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): @@ -1951,6 +1965,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')) @@ -2018,82 +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: + + 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 behavior in behaviornames: + test_files.append(os.path.join(groundtruth_path, behavior, i)) 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: + path_to_animation=os.path.join(groundtruth_path,behavior,i) - if network!=0: + capture=cv2.VideoCapture(path_to_animation) + animation=deque() + frames=deque(maxlen=length) - path_to_animation=os.path.join(groundtruth_path,behavior,i) + while True: + retval,frame=capture.read() + if frame is None: + break + frames.append(frame) - capture=cv2.VideoCapture(path_to_animation) - animation=deque() - frames=deque(maxlen=length) + capture.release() - while True: - retval,frame=capture.read() - if frame is None: - break - frames.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) - capture.release() + animations.append(np.array(animation)) - 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) + if network!=1: - animations.append(np.array(animation)) + 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)) - if network!=1: + labels.append(classnames.index(behavior)) - 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)) + if network!=0: + animations=np.array(animations,dtype='float32')/255.0 + pattern_images=np.array(pattern_images,dtype='float32')/255.0 - labels.append(classnames.index(behavior)) + labels=np.array(labels) - if network!=0: - animations=np.array(animations,dtype='float32')/255.0 - pattern_images=np.array(pattern_images,dtype='float32')/255.0 + model=load_model(model_path) - labels=np.array(labels) + from keras.models import Model + multi_model = Model(inputs=model.inputs, outputs=[model.layers[-2].output, model.output]) - model=load_model(model_path) + 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: - predictions=model.predict(pattern_images,batch_size=32) - elif network==1: - predictions=model.predict(animations,batch_size=32) - else: - predictions=model.predict([animations,pattern_images],batch_size=32) - if len(classnames)==2: - 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) - 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) + 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 - if result_path is not None: - pd.DataFrame(report).transpose().to_excel(os.path.join(result_path,'testing_reports.xlsx'),float_format='%.2f') + print('Testing completed!') - 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): """ @@ -2188,4 +2226,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 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_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 diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 8e119be4..12d91d2f 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -21,6 +21,10 @@ import json import logging import os +import re +import sys +import subprocess + # from pathlib import Path import shutil @@ -36,15 +40,11 @@ import wx 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') -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 +from .categorizer import Categorizers, CategorizerClassMismatchError from LabGym import config from .tools import sort_examples_from_csv from .gui_utils import ( @@ -58,6 +58,268 @@ ) +# 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 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))) + 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) + + +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): ''' @@ -614,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) @@ -641,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('_') @@ -1089,10 +1363,6 @@ def sort_fromcsv(self,event): class PanelLv2_TrainCategorizers(wx.Panel): - ''' - The 'Train Categorizers' functional unit - ''' - def __init__(self, parent): super().__init__(parent) @@ -1983,14 +2253,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() @@ -2032,6 +2301,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) @@ -2072,10 +2351,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+'.') @@ -2112,7 +2391,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() - 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']] + + 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): @@ -2134,3 +2437,1409 @@ 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, 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): + 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) + font = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) + + header_sizer = wx.BoxSizer(wx.HORIZONTAL) + 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) + + self.cm_grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.on_cell_click) + + 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.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) + + nlp_sizer = wx.BoxSizer(wx.VERTICAL) + + 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) + ( + label_overview, + label_major, + label_minor, + label_successes, + label_triage, + ) = 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) + + 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, 0, 0) + + 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) + + 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) + + 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) + + self.list_ctrl = wx.ListCtrl(self, style=wx.LC_REPORT | wx.BORDER_SUNKEN) + 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() + + 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") + 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.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, + self.example_map, + self.report, + self.cm, + self.classnames, + self.embedding_map, + source_dataset_root=self.source_dataset_root, + ) + 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 + 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]) + + 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) + r_val = int(40 + (215 * intensity)) + 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 + bg_color = wx.Colour(*cm_correct_cell_rgb(accuracy)) + else: + 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.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) + 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()): + 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: + 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]) + 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.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 = [] + + 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 true_class in low_support_classes: + 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 + }) + + + 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: + 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: + self.synopsis_label.SetLabel(f"{major_count} major systematic confusions detected.") + + + 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: + 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]: + 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) + + 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 += "

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.

" + + 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 = " (fewer than 100 examples)" 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): + 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 += "

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

" + html += "" + else: + 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 += "

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 += "" + + html += "" + self.nlp_html.SetPage(html) + + 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 = """ + +

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.

+

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

+ + """ + self.nlp_html.SetPage(html) + + 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))) + + 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 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 += "

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] + 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)

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: + 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() + + 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: + 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) + + +class TriageBuilderDialog(wx.Dialog): + 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.""" + 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_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.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="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="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="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.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: 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: 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: 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) + + 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: + 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 _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: + 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 + + 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(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 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() + 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(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)) + + 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, + ) + + self.EndModal(wx.ID_OK) + + 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: + 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: + 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): + """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")) + 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 = [] + + 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"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)): + 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) + + 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) + 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 / 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: 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: 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 + img.drawHeight = 2 * inch + Story.append(img) + Story.append(Paragraph(f"Reference file: {file_name}", caption_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 + img.drawHeight = 2 * inch + Story.append(img) + 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 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) + 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 df033cc8..9ae1b1f9 100644 --- a/LabGym/gui_main.py +++ b/LabGym/gui_main.py @@ -185,7 +185,6 @@ def __init__(self, parent): self.notebook = parent self.display_window() - def display_window(self): panel = self @@ -243,57 +242,42 @@ def display_window(self): 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 +362,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.""" 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/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 diff --git a/LabGym/tests/test_categorizer_class_mismatch.py b/LabGym/tests/test_categorizer_class_mismatch.py new file mode 100644 index 00000000..e6e62c26 --- /dev/null +++ b/LabGym/tests/test_categorizer_class_mismatch.py @@ -0,0 +1,85 @@ +"""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_diagnostics_cm_colors.py b/LabGym/tests/test_diagnostics_cm_colors.py new file mode 100644 index 00000000..517bebb4 --- /dev/null +++ b/LabGym/tests/test_diagnostics_cm_colors.py @@ -0,0 +1,177 @@ +"""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, +) + + +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 + + +@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): + font = grid.GetDefaultCellFont() + text_w, _h, _d, _el = grid.GetFullTextExtent('100.0%', font) + 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() diff --git a/LabGym/tests/test_diagnostics_copy_and_training_layout.py b/LabGym/tests/test_diagnostics_copy_and_training_layout.py new file mode 100644 index 00000000..0612bd6d --- /dev/null +++ b/LabGym/tests/test_diagnostics_copy_and_training_layout.py @@ -0,0 +1,151 @@ +"""Training Module single-column structure and diagnostic copy contracts.""" + +from pathlib import Path + +from LabGym import mywx # noqa: F401 + +from LabGym.gui_categorizer import ( + 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(encoding='utf-8') + 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_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(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(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') + start = text.index('def init_ui(self):', class_start) + end = text.index('\tdef update_grid_data', start) + body = text[start:end] + assert '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(encoding='utf-8') + 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_interactive_results_checkbox.py b/LabGym/tests/test_interactive_results_checkbox.py new file mode 100644 index 00000000..caf33289 --- /dev/null +++ b/LabGym/tests/test_interactive_results_checkbox.py @@ -0,0 +1,144 @@ +"""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_triage_guards.py b/LabGym/tests/test_triage_guards.py new file mode 100644 index 00000000..eb71c14f --- /dev/null +++ b/LabGym/tests/test_triage_guards.py @@ -0,0 +1,797 @@ +"""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() + + +# --- 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(encoding='utf-8') + 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(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 + 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/LabGym/tests/test_triage_layout_pdf.py b/LabGym/tests/test_triage_layout_pdf.py new file mode 100644 index 00000000..b596992f --- /dev/null +++ b/LabGym/tests/test_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(encoding='utf-8') + 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_triage_package_names.py b/LabGym/tests/test_triage_package_names.py new file mode 100644 index 00000000..6ad491e8 --- /dev/null +++ b/LabGym/tests/test_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 diff --git a/docs/installation/windows.md b/docs/installation/windows.md index 0725af3c..147d4879 100644 --- a/docs/installation/windows.md +++ b/docs/installation/windows.md @@ -57,4 +57,3 @@ Launch LabGym: ```pwsh-session __main__.main() ``` - diff --git a/noxfile.py b/noxfile.py index e960e264..cf058bdc 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 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 only; they are not +# skipped. Add any future test module that creates/manages a real wx.App +# fixture to this list. +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", + "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): @@ -48,14 +64,34 @@ 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", ".") session.install("pytest") - - session.run("pytest", "-q") + # 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", + "LabGym/tests", + *ignore_args, + "tests/test_load.py", + "tests/test_main.py", + ) + else: + session.run("pytest", "-q") @nox.session(reuse_venv=True) diff --git a/pyproject.toml b/pyproject.toml index 3d386147..89c5ff14 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,11 +30,15 @@ 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', 'Pillow>=7.1', 'matplotlib', 'pycocotools>=2.0.2',