diff --git a/LabGym/__main__.py b/LabGym/__main__.py index 0a806a41..179bf962 100644 --- a/LabGym/__main__.py +++ b/LabGym/__main__.py @@ -103,6 +103,10 @@ def main() -> None: wx.App() mywx.bring_wxapp_to_foreground() + # Establish Windows AppUserModelID / macOS Dock icon before any + # probe dialog or main window is shown (taskbar process identity only). + gui_main.setup_application_icons() + # Perform some pre-op sanity checks and probes of outside resources. probes.probes() diff --git a/LabGym/assets/icons/labgym.icns b/LabGym/assets/icons/labgym.icns index a1f45819..6d16f03a 100644 Binary files a/LabGym/assets/icons/labgym.icns and b/LabGym/assets/icons/labgym.icns differ diff --git a/LabGym/assets/icons/labgym.ico b/LabGym/assets/icons/labgym.ico index b46976ea..7fd62605 100644 Binary files a/LabGym/assets/icons/labgym.ico and b/LabGym/assets/icons/labgym.ico differ diff --git a/LabGym/assets/icons/labgym.png b/LabGym/assets/icons/labgym.png index cfdca7ed..3b4a8a6b 100644 Binary files a/LabGym/assets/icons/labgym.png and b/LabGym/assets/icons/labgym.png differ diff --git a/LabGym/gui_analyzer.py b/LabGym/gui_analyzer.py index 7e492186..1a672d9f 100644 --- a/LabGym/gui_analyzer.py +++ b/LabGym/gui_analyzer.py @@ -41,6 +41,7 @@ from LabGym import config from .minedata import data_mining from .tools import plot_events, parse_all_events_file, calculate_distances +from .gui_utils import add_info_button, INFO_COLOUR_S3, INFO_COLOUR_S4 class ColorPicker(wx.Dialog): @@ -142,6 +143,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_selectcategorizer=wx.BoxSizer(wx.HORIZONTAL) button_selectcategorizer=wx.Button(panel,label='Select a Categorizer for\nbehavior classification',size=(300,40)) @@ -1134,6 +1136,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S4) module_inputfolder=wx.BoxSizer(wx.HORIZONTAL) button_inputfolder=wx.Button(panel,label='Select the folder that contains\nthe LabGym analysis output folders',size=(300,40)) @@ -1309,6 +1312,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S4) module_inputfile=wx.BoxSizer(wx.HORIZONTAL) button_inputfile=wx.Button(panel,label='Select the\nall_events.xlsx file',size=(300,40)) @@ -1425,6 +1429,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S4) module_inputfolder=wx.BoxSizer(wx.HORIZONTAL) button_inputfolder=wx.Button(panel,label='Select the folder that stores\nLabGym analysis results',size=(300,40)) diff --git a/LabGym/gui_app_icon.py b/LabGym/gui_app_icon.py index 284b2283..eedc9dd6 100644 --- a/LabGym/gui_app_icon.py +++ b/LabGym/gui_app_icon.py @@ -17,11 +17,11 @@ ''' '''GUI application icon module for LabGym. -This module provides cross-platform icon handling functionality for the LabGym -GUI, including support for different icon formats (ICO, ICNS, PNG) and -contexts (normal, small). +This module provides cross-platform icon handling for the LabGym GUI using one +simplified LabGym artwork set (ICO on Windows, PNG elsewhere, ICNS on macOS Dock). ''' # Standard library imports. +import logging import sys from pathlib import Path from importlib.resources import files @@ -36,6 +36,9 @@ from AppKit import NSApplication, NSImage except ImportError: NSApplication = None + NSImage = None + +logger = logging.getLogger(__name__) @lru_cache(maxsize=1) @@ -43,77 +46,98 @@ def _get_icon_paths(): """Get all icon paths once and cache them.""" base_path = files("LabGym") / "assets/icons" return { - 'small_ico': base_path / "labgym_small.ico", - 'main_ico': base_path / "labgym.ico", + 'ico': base_path / "labgym.ico", 'icns': base_path / "labgym.icns", - 'png': base_path / "labgym.png" + 'png': base_path / "labgym.png", } -def get_icon_for_context(context='normal', size=16): - """Get appropriate icon path for given context and size.""" +def get_frame_icon_path(): + """Return the platform-appropriate path for wx frame icons. + + Windows uses the multi-resolution labgym.ico. macOS and other platforms + use the matching labgym.png. + """ icon_paths = _get_icon_paths() if sys.platform.startswith("win"): - # Windows: Use ICO files for better compatibility - if context == 'small' or size <= 24: - return str(icon_paths['small_ico']) if icon_paths['small_ico'].is_file() else str(icon_paths['png']) - else: - return str(icon_paths['main_ico']) if icon_paths['main_ico'].is_file() else str(icon_paths['png']) + if icon_paths['ico'].is_file(): + return str(icon_paths['ico']) + if icon_paths['png'].is_file(): + return str(icon_paths['png']) + return "" - # macOS or fallback - return str(icon_paths['png']) if icon_paths['png'].is_file() else "" + # macOS and non-Windows fallback + if icon_paths['png'].is_file(): + return str(icon_paths['png']) + return "" -def set_frame_icon(frame, context='normal', size=16): - """Set frame icon with proper error handling.""" +def set_frame_icon(frame): + """Set the frame icon from the unified simplified artwork.""" try: - icon_path = get_icon_for_context(context, size) + icon_path = get_frame_icon_path() if not icon_path or not Path(icon_path).is_file(): + logger.warning('Frame icon asset not found') return icon = wx.Icon(icon_path, wx.BITMAP_TYPE_ANY) if icon.IsOk(): frame.SetIcon(icon) + else: + logger.warning('Failed to load frame icon from %s', icon_path) except Exception: - pass + logger.exception('Error setting frame icon') + +def set_windows_app_user_model_id(): + """Establish Windows process/taskbar identity via AppUserModelID. -def set_windows_taskbar_icon(): - """Set the Windows taskbar icon. - Set the Windows taskbar icon using small ICO for better small-size - visibility. + Call this early (before the first visible window) when practical. + This does not embed an executable icon; it only sets runtime process + identity used by the shell for taskbar grouping. """ if not sys.platform.startswith("win"): return try: - # This sets AppUserModelID first - this is crucial for proper taskbar icon association app_id = "umyelab.LabGym" ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(app_id) except Exception: - pass + logger.exception('Failed to set Windows AppUserModelID') + + +# Backward-compatible name used by older call sites. +set_windows_taskbar_icon = set_windows_app_user_model_id def set_macos_dock_icon(): - """Set the Dock icon on macOS. - Set the Dock icon at runtime on macOS (requires optional PyObjC). - """ + """Set the Dock icon on macOS for unbundled runs (optional PyObjC).""" if sys.platform != "darwin" or not NSApplication: return try: - baseIconDir = files("LabGym") - icns = baseIconDir / "assets/icons/labgym.icns" - png = baseIconDir / "assets/icons/labgym.png" + icon_paths = _get_icon_paths() + if icon_paths['icns'].is_file(): + icon_path = str(icon_paths['icns']) + elif icon_paths['png'].is_file(): + icon_path = str(icon_paths['png']) + else: + logger.warning('macOS Dock icon asset not found') + return - icon_path = str(icns if icns.is_file() else png) img = NSImage.alloc().initWithContentsOfFile_(icon_path) if img: NSApplication.sharedApplication().setApplicationIconImage_(img) + else: + logger.warning('Failed to load macOS Dock icon from %s', icon_path) except Exception: - pass + logger.exception('Error setting macOS Dock icon') def setup_application_icons(): - """Set up all application icons for the current platform.""" + """Set up process/Dock icons for the current platform. + + Safe to call more than once. Prefer an early call before the first + visible window so Windows AppUserModelID is established first. + """ + set_windows_app_user_model_id() set_macos_dock_icon() - set_windows_taskbar_icon() diff --git a/LabGym/gui_appearance.py b/LabGym/gui_appearance.py new file mode 100644 index 00000000..d6e64729 --- /dev/null +++ b/LabGym/gui_appearance.py @@ -0,0 +1,98 @@ +''' +Copyright (C) +This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +You should have received a copy of the GNU General Public License along with this program. If not, see https://tldrlegal.com/license/gnu-general-public-license-v3-(gpl-3)#fulltext. + +For license issues, please contact: + +Dr. Bing Ye +Life Sciences Institute +University of Michigan +210 Washtenaw Avenue, Room 5403 +Ann Arbor, MI 48109-2216 +USA + +Email: bingye@umich.edu +''' + + +'''Native appearance helpers for LabGym. + +Reports whether the OS / wxPython effective appearance is dark so callers can +pick appearance-dependent values (e.g. colours). Does not implement a custom +theme, Light/Dark/System override, preference persistence, or widget recoloring. +''' + +import wx + + +def _colour_luminance(colour) -> float: + """Return approximate relative luminance of a wx colour (0–255 scale).""" + try: + r, g, b = colour.Red(), colour.Green(), colour.Blue() + except Exception: + try: + r, g, b = colour.Get()[:3] + except Exception: + return 128.0 + # ITU-R BT.601 luma coefficients, full 8-bit channel range. + return 0.299 * r + 0.587 * g + 0.114 * b + + +def _is_dark_from_system_colours() -> bool: + """Infer dark appearance by comparing system window background vs text.""" + bg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW) + fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT) + return _colour_luminance(bg) < _colour_luminance(fg) + + +def is_dark_appearance() -> bool: + """Return True when the effective native wx appearance is dark. + + Detection order: + 1. ``wx.SystemSettings.GetAppearance().IsDark()`` when available. + 2. ``GetAppearance().IsUsingDarkBackground()`` when ``IsDark`` is missing + or raises (older / partial APIs). + 3. System window vs window-text luminance when the appearance API is + unavailable or fails. + 4. Light (``False``) as a final safe default. + """ + get_appearance = getattr(wx.SystemSettings, 'GetAppearance', None) + if callable(get_appearance): + try: + appearance = get_appearance() + except Exception: + appearance = None + + if appearance is not None: + is_dark = getattr(appearance, 'IsDark', None) + if callable(is_dark): + try: + return bool(is_dark()) + except Exception: + pass + + # Fallback / older builds: IsUsingDarkBackground without IsDark. + is_using_dark_bg = getattr(appearance, 'IsUsingDarkBackground', None) + if callable(is_using_dark_bg): + try: + return bool(is_using_dark_bg()) + except Exception: + pass + + try: + return bool(_is_dark_from_system_colours()) + except Exception: + return False + + +def select_for_appearance(light_value, dark_value): + """Return ``dark_value`` under dark native appearance, else ``light_value``. + + Values may be ``wx.Colour`` instances or any other small appearance-dependent + objects; this helper does not inspect or convert them. + """ + if is_dark_appearance(): + return dark_value + return light_value diff --git a/LabGym/gui_categorizer.py b/LabGym/gui_categorizer.py index 8fb85e4e..8e119be4 100644 --- a/LabGym/gui_categorizer.py +++ b/LabGym/gui_categorizer.py @@ -34,6 +34,8 @@ import cv2 import numpy as np import wx +import wx.richtext +import wx.lib.buttons as wxbuttons # Local application/library specific imports. logger.debug('importing %s ...', '.analyzebehavior') @@ -45,7 +47,15 @@ from .categorizer import Categorizers from LabGym import config from .tools import sort_examples_from_csv -from .gui_utils import add_or_select_notebook_page +from .gui_utils import ( + add_or_select_notebook_page, + add_info_button, + create_hyperlink, + INFO_COLOUR_S3, + count_prepared_examples, + count_sorted_examples, + counts_enable_diagnostics, +) class PanelLv2_GenerateExamples(wx.Panel): @@ -100,6 +110,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_specifymode=wx.BoxSizer(wx.HORIZONTAL) button_specifymode=wx.Button(panel,label='Specify the mode of behavior\nexamples to generate',size=(300,40)) @@ -701,6 +712,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) boxsizer.Add(0,40,0) button_sortexamples=wx.Button(panel,label='Sort Examples (LabGym UI)',size=(300,40)) @@ -715,6 +727,16 @@ def display_window(self): boxsizer.Add(button_sortexamplescsv,0,wx.ALIGN_CENTER,10) boxsizer.Add(0,30,0) + # Align with the centered 300px button column (same wx.ALIGN_CENTER as buttons above). + boxsizer.Add( + create_hyperlink( + panel, + 'Sorting Behavior Examples using LabGym', + 'https://youtu.be/WDCJ2HdrYJo?si=O6orNTNZiwR1girH', + ), + 0, wx.ALIGN_CENTER, 10) + boxsizer.Add(0, 10, 0) + panel.SetSizer(boxsizer) self.Centre() @@ -756,6 +778,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_inputfolder=wx.BoxSizer(wx.HORIZONTAL) button_inputfolder=wx.Button(panel,label='Select the folder that stores\nunsorted behavior examples',size=(300,40)) @@ -1001,6 +1024,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_inputexamples=wx.BoxSizer(wx.HORIZONTAL) button_inputexamples=wx.Button(panel,label='Select the folder that stores\nthe unsorted behavior examples',size=(300,40)) @@ -1112,14 +1136,23 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_inputexamples=wx.BoxSizer(wx.HORIZONTAL) button_inputexamples=wx.Button(panel,label='Select the folder that stores\nthe sorted behavior examples',size=(300,40)) button_inputexamples.Bind(wx.EVT_BUTTON,self.select_filepath) wx.Button.SetToolTip(button_inputexamples,'This folder should contain all the sorted behavior examples. Each subfolder in this folder should contain behavior examples of a behavior type. The names of the subfolders will be read by LabGym as the behavior names.') + # Right-hand content: path label + compact count button (always present; Enable/Disable only) + inputexamples_right=wx.BoxSizer(wx.VERTICAL) self.text_inputexamples=wx.StaticText(panel,label='None.',style=wx.ALIGN_LEFT|wx.ST_ELLIPSIZE_END) + self.button_view_sorted_counts=wx.Button(panel,label='View Behavior Counts',size=(200,28)) + self.button_view_sorted_counts.Bind(wx.EVT_BUTTON,self.show_sorted_count_popup) + self.button_view_sorted_counts.Disable() + wx.Button.SetToolTip(self.button_view_sorted_counts,'View example counts for each sorted behavior category.') + inputexamples_right.Add(self.text_inputexamples,0,wx.EXPAND) + inputexamples_right.Add(self.button_view_sorted_counts,0,wx.TOP,4) module_inputexamples.Add(button_inputexamples,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) - module_inputexamples.Add(self.text_inputexamples,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + module_inputexamples.Add(inputexamples_right,1,wx.EXPAND|wx.LEFT|wx.RIGHT,10) boxsizer.Add(0,10,0) boxsizer.Add(module_inputexamples,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) boxsizer.Add(0,5,0) @@ -1175,9 +1208,17 @@ def display_window(self): button_trainingfolder=wx.Button(panel,label='Select the folder that stores\nall the prepared training examples',size=(300,40)) button_trainingfolder.Bind(wx.EVT_BUTTON,self.select_datapath) wx.Button.SetToolTip(button_trainingfolder,'The folder that stores all the prepared behavior examples. If these are previously augmented, this folder should contain a "train" and a "vadilation" subfolder. If body parts are included, the STD value can be found in the filenames of the generated behavior examples with "_stdXX_" where "XX" is the STD value.') + # Right-hand content: path label + compact count button (always present; Enable/Disable only) + trainingfolder_right=wx.BoxSizer(wx.VERTICAL) self.text_trainingfolder=wx.StaticText(panel,label='None',style=wx.ALIGN_LEFT|wx.ST_ELLIPSIZE_END) + self.button_view_counts=wx.Button(panel,label='View Behavior Counts',size=(200,28)) + self.button_view_counts.Bind(wx.EVT_BUTTON,self.show_count_popup) + self.button_view_counts.Disable() + wx.Button.SetToolTip(self.button_view_counts,'View example counts for each prepared training category.') + trainingfolder_right.Add(self.text_trainingfolder,0,wx.EXPAND) + trainingfolder_right.Add(self.button_view_counts,0,wx.TOP,4) module_trainingfolder.Add(button_trainingfolder,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) - module_trainingfolder.Add(self.text_trainingfolder,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + module_trainingfolder.Add(trainingfolder_right,1,wx.EXPAND|wx.LEFT|wx.RIGHT,10) boxsizer.Add(module_trainingfolder,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) boxsizer.Add(0,5,0) @@ -1213,12 +1254,342 @@ def display_window(self): self.Show(True) + def _count_examples(self,folder_path): + return count_prepared_examples(folder_path) + + + def _update_count_display(self,folder_path): + counts=self._count_examples(folder_path) + if not counts_enable_diagnostics(counts): + self._counts={} + self.button_view_counts.Disable() + return + self._counts=counts + self.button_view_counts.Enable() + + + def _iter_count_rows(self,counts): + '''Yield behavior-name rows matching the 3-items-per-row body layout.''' + names=sorted(counts) + i=0 + while i200: + chunk=names[i:i+2] + yield chunk + i+=len(chunk) + + + def _count_display_lines(self,counts,threshold): + '''Return (count_rows, add_rows) for the body layout at the given threshold.''' + count_rows=0 + add_rows=0 + for row in self._iter_count_rows(counts): + count_rows+=1 + if any(counts[name] SD + values=list(counts.values()) + mean=sum(values)/len(values) + std=(sum((v-mean)**2 for v in values)/len(values))**0.5 + rtc.Clear() + for row in self._iter_count_rows(counts): + for i_item,name in enumerate(row): + count=counts[name] + attr=wx.richtext.RichTextAttr() + attr.SetTextColour(wx.Colour(180,0,0) if count0 and abs(count-mean)>std: + attr.SetBackgroundColour(wx.YELLOW) + rtc.BeginStyle(attr) + rtc.WriteText(f'{name}: {count} examples') + rtc.EndStyle() + if i_item=1 else None + + def _filter_threshold_char(evt): + key=evt.GetKeyCode() + if key in ( + wx.WXK_BACK,wx.WXK_DELETE,wx.WXK_TAB,wx.WXK_LEFT,wx.WXK_RIGHT, + wx.WXK_HOME,wx.WXK_END,wx.WXK_RETURN,wx.WXK_NUMPAD_ENTER, + wx.WXK_NUMPAD_DELETE): + evt.Skip() + return + if wx.WXK_NUMPAD0<=key<=wx.WXK_NUMPAD9: + evt.Skip() + return + if 32<=key<256 and chr(key).isdigit(): + evt.Skip() + return + # ignore non-digit characters + + def on_apply(evt): + t=_parse_threshold() + if t is None: + thr_txt.SetValue(str(popup._applied_threshold)) + return + popup._applied_threshold=t + set_threshold(t) + red_explain.SetLabel(f' Example count is below {t} (minimum threshold)') + self._render_body(rtc_counts,counts,t) + new_h,_=self._counts_area_height(counts,t,max_counts_h) + rtc_counts.SetMinSize((popup_w-2*margin,new_h)) + rtc_counts.SetSize((popup_w-2*margin,new_h)) + outer.Layout() + popup.SetClientSize(popup_w,outer.GetMinSize().height+2) + + thr_txt.Bind(wx.EVT_CHAR,_filter_threshold_char) + thr_txt.Bind(wx.EVT_TEXT_ENTER,on_apply) + btn.Bind(wx.EVT_BUTTON,on_apply) + close_btn.Bind(wx.EVT_BUTTON,lambda evt:popup.Dismiss()) + + ph=popup.GetSize().height + popup.SetPosition(wx.Point(fr.x+(fr.width-popup_w)//2,fr.y+(fr.height-ph)//2)) + popup.Popup() + + + def show_count_popup(self,event): + counts=getattr(self,'_counts',{}) + if not counts_enable_diagnostics(counts): + return + if not hasattr(self,'_count_threshold'): + self._count_threshold=250 + self._show_behavior_count_popup( + 'Prepared Training Examples',counts,self._count_threshold, + lambda t:setattr(self,'_count_threshold',t)) + + + def _count_from_subfolders(self,folder_path): + return count_sorted_examples(folder_path) + + + def _update_sorted_count_display(self,folder_path): + counts=self._count_from_subfolders(folder_path) + if not counts_enable_diagnostics(counts): + self._sorted_counts={} + self.button_view_sorted_counts.Disable() + return + self._sorted_counts=counts + self.button_view_sorted_counts.Enable() + + + def show_sorted_count_popup(self,event): + counts=getattr(self,'_sorted_counts',{}) + if not counts_enable_diagnostics(counts): + return + if not hasattr(self,'_sorted_count_threshold'): + self._sorted_count_threshold=250 + self._show_behavior_count_popup( + 'Sorted Behavior Examples',counts,self._sorted_count_threshold, + lambda t:setattr(self,'_sorted_count_threshold',t)) + + def select_filepath(self,event): dialog=wx.DirDialog(self,'Select a directory','',style=wx.DD_DEFAULT_STYLE) if dialog.ShowModal()==wx.ID_OK: self.file_path=dialog.GetPath() self.text_inputexamples.SetLabel('Path to sorted behavior examples: '+self.file_path+'.') + self._update_sorted_count_display(self.file_path) dialog.Destroy() @@ -1467,6 +1838,9 @@ def select_datapath(self,event): else: self.text_trainingfolder.SetLabel('Pattern images w/o bodyparts in: '+self.data_path+'.') + if self.data_path is not None: + self._update_count_display(self.data_path) + def specify_augmentation(self,event): @@ -1625,6 +1999,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S3) module_selectcategorizer=wx.BoxSizer(wx.HORIZONTAL) button_selectcategorizer=wx.Button(panel,label='Select a Categorizer\nto test',size=(300,40)) diff --git a/LabGym/gui_detector.py b/LabGym/gui_detector.py index 93db96c9..053f1fcd 100644 --- a/LabGym/gui_detector.py +++ b/LabGym/gui_detector.py @@ -37,6 +37,7 @@ from LabGym import config from .detector import Detector from .tools import extract_frames +from .gui_utils import add_info_button, create_hyperlink, INFO_COLOUR_S2 class PanelLv2_GenerateImages(wx.Panel): @@ -62,6 +63,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S2) module_inputvideos=wx.BoxSizer(wx.HORIZONTAL) button_inputvideos=wx.Button(panel,label='Select the video(s) to generate\nimage examples',size=(300,40)) @@ -253,6 +255,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S2) module_selectimages=wx.BoxSizer(wx.HORIZONTAL) button_selectimages=wx.Button(panel,label='Select the folder containing\nall the training images',size=(300,40)) @@ -302,6 +305,18 @@ def display_window(self): boxsizer.Add(button_train,0,wx.RIGHT|wx.ALIGN_RIGHT,90) boxsizer.Add(0,10,0) + # Match nested 10px module + button margins so the link lines up with the button column. + module_tutorial=wx.BoxSizer(wx.HORIZONTAL) + module_tutorial.Add( + create_hyperlink( + panel, + 'Training a Detector using LabGym', + 'https://youtu.be/mvwc-kK1dCc?si=OLywKfHwg3qOz_u4', + ), + 0, wx.LEFT|wx.RIGHT, 10) + boxsizer.Add(module_tutorial,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + boxsizer.Add(0, 10, 0) + panel.SetSizer(boxsizer) self.Centre() @@ -419,6 +434,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S2) module_selectdetector=wx.BoxSizer(wx.HORIZONTAL) button_selectdetector=wx.Button(panel,label='Select a Detector\nto test',size=(300,40)) diff --git a/LabGym/gui_main.py b/LabGym/gui_main.py index cad4e057..b8483602 100644 --- a/LabGym/gui_main.py +++ b/LabGym/gui_main.py @@ -19,7 +19,6 @@ # Standard library imports. import logging -import sys from .gui_app_icon import set_frame_icon, setup_application_icons # Log the load of this module (by the module loader, on first import). @@ -31,11 +30,19 @@ # Related third party imports. import wx import wx.aui -import wx.lib.agw.hyperlink as hl +import wx.html +import webbrowser # Local application/library specific imports. from LabGym import __version__ -from .gui_utils import add_or_select_notebook_page +from .gui_appearance import select_for_appearance +from .gui_utils import ( + add_or_select_notebook_page, + compute_workflow_map_transform, + create_hyperlink, + hyperlink_html_style, + is_protected_notebook_page, +) logger.debug('importing %s ...', '.gui_categorizer') from .gui_categorizer import PanelLv2_GenerateExamples,PanelLv2_TrainCategorizers,PanelLv2_SortBehaviors,PanelLv2_TestCategorizers logger.debug('importing %s done', '.gui_categorizer') @@ -70,12 +77,11 @@ def display_window(self): boxsizer.Add(self.text_developers,0,wx.LEFT|wx.RIGHT|wx.EXPAND,5) boxsizer.Add(0,60,0) - links=wx.BoxSizer(wx.HORIZONTAL) - homepage=hl.HyperLinkCtrl(panel,0,'Home Page',URL='https://github.com/umyelab/LabGym') - userguide=hl.HyperLinkCtrl(panel,0,'Extended Guide',URL='https://github.com/yujiahu415/LabGym/blob/master/LabGym_extended_user_guide.pdf') - links.Add(homepage,0,wx.LEFT|wx.EXPAND,10) - links.Add(userguide,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) - boxsizer.Add(links,0,wx.ALIGN_CENTER,50) + homepage=create_hyperlink(panel,'Home Page','https://www.labgym.org') + boxsizer.Add(homepage,0,wx.ALIGN_CENTER,50) + boxsizer.Add(0,14,0) + resources=create_hyperlink(panel,'Resources','https://www.labgym.org/resources') + boxsizer.Add(resources,0,wx.ALIGN_CENTER,50) boxsizer.Add(0,50,0) module_modules=wx.BoxSizer(wx.HORIZONTAL) @@ -192,7 +198,7 @@ def display_window(self): boxsizer.Add(button_generateimages,0,wx.ALIGN_CENTER,10) boxsizer.Add(0,5,0) - link_annotate=wx.lib.agw.hyperlink.HyperLinkCtrl(panel,0,'\nAnnotate images with EZannot\n',URL='https://github.com/yujiahu415/EZannot') + link_annotate=create_hyperlink(panel,'\nAnnotate images with EZannot\n','https://github.com/yujiahu415/EZannot') boxsizer.Add(link_annotate,0,wx.ALIGN_CENTER,10) boxsizer.Add(0,5,0) @@ -362,19 +368,572 @@ def calculate_distances(self,event): add_or_select_notebook_page(self.notebook, lambda: PanelLv2_CalculateDistances(self.notebook), title) +# Popup content for each clickable workflow-map box: (section_title, box_title, description, guide_sections) +_BOX_POPUP = { + 'collect_footage': ( + 'Video Prep', + 'Collect Footage', + 'This is the video collection stage. Before LabGym can track animals or classify behaviors, you need videos that clearly capture the animals and the behaviors of interest. Good video quality, appropriate lighting, and consistent recording conditions will make downstream tracking and classification much more accurate.', + 'Part 2, Part 3.5', + ), + 'preprocessing': ( + 'Video Prep', + 'Preprocessing (Optional)', + 'This step involves modifying videos before analysis if needed. Examples include cropping, trimming, stabilizing recordings, adjusting contrast, or adding spatial markers. LabGym also includes tools that can help prepare videos for later analysis.', + 'Part 4.5, Part 4.6, Section l', + ), + 'tracking': ( + 'Tracking', + 'Tracking / Animal Detection', + 'This is where LabGym finds and follows animals across video frames. Every animal receives an identity and location over time, creating the movement information needed for behavior classification later. LabGym can use either background subtraction or a trained detector depending on video complexity.', + 'Part 3.1, Part 4.1, Section ll', + ), + 'bg_sub': ( + 'Tracking', + 'Background Subtraction', + 'For videos with stable lighting and a fixed background, LabGym automatically estimates the background and removes it. This leaves only the moving animal(s), making tracking faster and more reliable.', + 'Part 3.1, Part 4.1, Section lll A', + ), + 'detector': ( + 'Tracking', + 'Detector', + 'When backgrounds are complicated, lighting changes, or animals frequently overlap, LabGym can use a trained object detector instead of simple background subtraction. The detector learns what the target animal looks like and identifies it directly in each frame.', + 'Part 3.1, Part 4.1, Section ll', + ), + 'generate_images': ( + 'Tracking', + 'Generate Images', + "LabGym extracts representative frames from your videos that will be used to train a detector. These images become the dataset that you'll later annotate with animal locations.", + 'Section ll A', + ), + 'roboflow': ( + 'Tracking', + 'Roboflow OR EZannot', + 'These tools are used to annotate the generated images. You draw boxes around animals and label them so the detector can learn what the target animal looks like.', + 'Section ll B', + ), + 'train_detector': ( + 'Tracking', + 'Train Detector', + 'LabGym uses the annotated images to train an object detection model. The resulting detector can then automatically locate animals in new videos.', + 'Section ll C, Section ll D', + ), + 'generate_examples': ( + 'Classification', + 'Generate and Sort Behavior Examples', + 'LabGym tracks animals and automatically generates behavior examples. Each example contains both an animation and a "pattern image" that summarizes the animal\'s movement through time. Users then sort these examples into behavior categories such as grooming, rearing, or locomotion.', + 'Section lll A, Section lll B', + ), + 'train_categorizer': ( + 'Classification', + 'Train Categorizer', + 'The categorized behavior examples are used to train LabGym\'s "Categorizer," the deep-learning model that identifies behaviors. It learns from both the raw animations and the movement-pattern images.', + 'Section lll C', + ), + 'test_categorizer': ( + 'Classification', + 'Test Categorizer', + 'After training, LabGym evaluates how accurately the categorizer identifies behaviors it has not seen before. This helps determine whether more training examples are needed.', + 'Part 4.3, Section lll D', + ), + 'analyze_behaviors': ( + 'Classification', + 'Analyze Behaviors', + 'The trained categorizer is applied to experimental videos. LabGym classifies behaviors frame-by-frame and records when each behavior occurs. It also generates quantitative measurements such as duration, frequency, and movement metrics.', + 'Part 4.4, Section lV', + ), + 'mine_results': ( + 'Post Classification Analysis', + 'Mine Results', + 'LabGym exports spreadsheets and structured behavioral data that can be explored statistically. Users can compare groups, quantify treatment effects, or examine temporal patterns in behavior.', + 'Section lV B', + ), + 'generate_plot': ( + 'Post Classification Analysis', + 'Generate Behavior Plot', + 'LabGym can visualize behavior occurrence over time using raster plots and other summaries. These plots help users quickly identify patterns, transitions, and temporal organization of behaviors.', + 'Section lV C', + ), + 'calc_distances': ( + 'Post Classification Analysis', + 'Calculate Distances', + 'Using tracking information, LabGym computes movement-based measurements such as distance traveled, speed, and location-related metrics. These can be analyzed alongside behavior classifications.', + 'Part 4.4, Section lV', + ), +} + +# Practical-guide page numbers keyed by reference text (lowercase for case-insensitive lookup) +_GUIDE_PAGES = { + 'part 2': 4, + 'part 3.1': 5, + 'part 3.5': 6, + 'part 4.1': 7, + 'part 4.3': 8, + 'part 4.4': 8, + 'part 4.5': 9, + 'part 4.6': 9, + 'section l': 14, + 'section ll': 16, + 'section ll a': 16, + 'section ll b': 18, + 'section ll c': 21, + 'section ll d': 23, + # Section III A → practical guide page 28 (user-confirmed for Background Subtraction). + 'section lll a': 28, + 'section lll b': 31, + 'section lll c': 33, + 'section lll d': 37, + 'section lv': 38, + 'section lv b': 44, + 'section lv c': 44, +} + + +def resolve_guide_page_number(ref: str): + """Return practical-guide page number for a map popup guide token, or None.""" + if not ref: + return None + return _GUIDE_PAGES.get(ref.strip().lower()) + + +class BoxInfoPopup(wx.Frame): + """Info popup shown when clicking a workflow-map box. Closes on focus loss.""" + + def __init__(self, parent, section, title, description, guide, fill, ink): + super().__init__(None, style=wx.FRAME_NO_TASKBAR | wx.STAY_ON_TOP | wx.NO_BORDER) + self.SetBackgroundColour(ink) # ink peeks through as the border + + # Blend fill 50% toward white for a softer popup background + pf = wx.Colour( + fill.Red() + (255 - fill.Red()) // 2, + fill.Green() + (255 - fill.Green()) // 2, + fill.Blue() + (255 - fill.Blue()) // 2, + ) + + panel = wx.Panel(self) + panel.SetBackgroundColour(pf) + + html_win = wx.html.HtmlWindow(panel, size=(440, 100), style=wx.html.HW_NO_SELECTION) + html_win.SetBackgroundColour(pf) + html_win.SetBorders(0) + html_win.SetPage(self._make_html(section, title, description, guide, pf)) + html_win.Bind(wx.html.EVT_HTML_LINK_CLICKED, self._on_link) + + content_h = html_win.GetInternalRepresentation().GetHeight() + html_win.SetMinSize((440, content_h + 4)) + + inner = wx.BoxSizer(wx.VERTICAL) + inner.Add(html_win, 0, wx.ALL, 20) + panel.SetSizer(inner) + panel.Fit() + + outer = wx.BoxSizer(wx.VERTICAL) + outer.Add(panel, 1, wx.ALL | wx.EXPAND, 3) # 3px gap exposes ink-coloured frame background as border + self.SetSizer(outer) + self.Fit() + + frame = wx.GetTopLevelParent(parent) + fx, fy = frame.GetPosition() + fw, fh = frame.GetSize() + pw, ph = self.GetSize() + self.SetPosition((fx + (fw - pw) // 2, fy + (fh - ph) // 2)) + + self._ready = False + self.Bind(wx.EVT_ACTIVATE, self._on_activate) + wx.CallLater(150, self._set_ready) + + def _set_ready(self): + self._ready = True + + def _on_activate(self, evt): + if self._ready and not evt.GetActive(): + wx.CallAfter(self.Close) + evt.Skip() + + def _on_link(self, evt): + webbrowser.open(evt.GetLinkInfo().GetHref()) + + def _make_html(self, section, title, description, guide, fill): + import html as _h + bg = '#{:02X}{:02X}{:02X}'.format(fill.Red(), fill.Green(), fill.Blue()) + # Section-tinted cards stay light; pin dark body text for contrast under + # OS dark mode (HtmlWindow may otherwise inherit a light default). + text = select_for_appearance('#000000', '#111111') + # Shared cyan link family: normal == visited; hover slightly brighter. + link_c, vlink_c, hover_c = hyperlink_html_style() + base = 'https://www.labgym.org/guides/practical-guide#page-' + refs = [] + for ref in (r.strip() for r in guide.split(',')): + page = resolve_guide_page_number(ref) + refs.append( + '{}'.format(base, page, _h.escape(ref)) if page + else _h.escape(ref) + ) + guide_html = ', '.join(refs) + # body link/vlink + CSS cover both classic HtmlWindow and engines that + # honor style rules; visited never becomes purple. + return ( + '' + '' + '
' + '{section}
{title}
' + '

' + '{desc}' + '

' + 'Learn more in the following LabGym Practical Guide sections: {guide}' + '
' + '' + ).format( + bg=bg, + text=text, + link=link_c, + vlink=vlink_c, + hover=hover_c, + section=_h.escape(section), + title=_h.escape(title), + desc=_h.escape(description, quote=False), + guide=guide_html, + ) + + +def _system_colour(index, fallback): + """Return a wx.SystemSettings colour, or fallback if unavailable.""" + try: + colour = wx.SystemSettings.GetColour(index) + if colour and colour.IsOk(): + return colour + except Exception: + pass + return fallback + + +def _workflow_map_surface_colours(): + """Native canvas / text colours for the Workflow Map (not connector greys). + + Canvas and free-canvas text follow the system window colour pair. Connector + styles are resolved separately so greys can be tuned for hierarchy. + """ + window_bg = _system_colour(wx.SYS_COLOUR_WINDOW, wx.WHITE) + window_fg = _system_colour(wx.SYS_COLOUR_WINDOWTEXT, wx.BLACK) + # Light: retain a light canvas (prefer system window, else white). + # Dark: native/system window background (near-native dark surface). + canvas_bg = select_for_appearance(window_bg, window_bg) + # Titles and free-canvas labels follow system window text for contrast. + text_fg = select_for_appearance(window_fg, window_fg) + return canvas_bg, text_fg + + +def _workflow_map_connector_styles(): + """Appearance-aware connector colours for the Workflow Map. + + Between-phase greys are the most prominent neutrals; within-phase greys are + clearly visible but slightly less strong. Explicit greys (not grey-text / + button system roles) so connectors do not disappear against the canvas. + """ + # Between-phase: strongest neutrals — medium–dark on light; light on dark. + between_color = select_for_appearance( + wx.Colour(80, 80, 80), + wx.Colour(205, 205, 205), + ) + # Within-phase: secondary neutrals — medium on light; slightly dimmer light grey on dark. + within_color = select_for_appearance( + wx.Colour(120, 120, 120), + wx.Colour(168, 168, 168), + ) + return between_color, within_color + + +class WorkflowMapPanel(wx.Panel): + """Displays the LabGym workflow map scaled to the panel client size. + + The main frame remains fixed at ``MainFrame.FIXED_FRAME_SIZE``. Logical layout + coordinates are fixed; scale and centering are recomputed each paint from + the actual client size so hit rectangles stay aligned with drawn boxes. + """ + + # Logical (virtual) coordinate space — source of truth for layout. + VW = 2200 + VH = 660 + # Fallback client size when GetClientSize is temporarily invalid (startup). + _FALLBACK_CLIENT_W = 1100 + _FALLBACK_CLIENT_H = 560 + + # Connector geometry (logical units → client pixels via ps()). + # Between-phase: filled polygonal chevrons (most prominent neutrals). + BETWEEN_SHAFT_HALF = 9 # half-height of the thick shaft + BETWEEN_HEAD_HALF = 17 # arrowhead half-width + BETWEEN_NECK = 26 # distance from tip to neck + BETWEEN_OUTLINE_W = 2 # outline pen (logical; scaled with floor) + # Within-phase: stroke arrows (vertical / diagonal), secondary weight. + WITHIN_LINE_W = 4 # shaft thickness (logical; becomes ≥2 px) + WITHIN_HEAD_HALF = 6 # arrowhead half-width + WITHIN_HEAD_LEN = 11 # arrowhead length along shaft + + def __init__(self, parent): + super().__init__(parent) + self._clickable_boxes = [] # list of (bx, by, bw, bh, fill, ink, popup_data) in client pixels + self._apply_surface_colours() + self.Bind(wx.EVT_PAINT, self.on_paint) + self.Bind(wx.EVT_LEFT_DOWN, self._on_box_click) + # Refresh this map only when the OS appearance/system colours change. + if hasattr(wx, 'EVT_SYS_COLOUR_CHANGED'): + self.Bind(wx.EVT_SYS_COLOUR_CHANGED, self._on_sys_colour_changed) + # Some platforms update appearance on reactivation rather than colour-change. + frame = wx.GetTopLevelParent(self) + if frame is not None: + frame.Bind(wx.EVT_ACTIVATE, self._on_parent_activate) + + def _map_transform(self): + """Return (client_w, client_h, scale, ox, oy) from the current client size. + + Tiny or invalid dimensions fall back to a nominal canvas so drawing and + hit tests remain well-defined during early layout passes. + """ + try: + cw, ch = self.GetClientSize() + except Exception: + cw, ch = 0, 0 + return compute_workflow_map_transform( + cw, ch, vw=self.VW, vh=self.VH, + fallback_w=self._FALLBACK_CLIENT_W, fallback_h=self._FALLBACK_CLIENT_H, + ) + + def _apply_surface_colours(self): + """Set the panel background from the current native appearance.""" + canvas_bg, _ = _workflow_map_surface_colours() + self.SetBackgroundColour(canvas_bg) + + def _on_sys_colour_changed(self, event): + self._apply_surface_colours() + self.Refresh() + event.Skip() + + def _on_parent_activate(self, event): + if event.GetActive(): + self._apply_surface_colours() + self.Refresh() + event.Skip() + + def on_paint(self, event): + canvas_bg, text_fg = _workflow_map_surface_colours() + between_color, within_color = _workflow_map_connector_styles() + self.SetBackgroundColour(canvas_bg) + dc = wx.PaintDC(self) + dc.SetBackground(wx.Brush(canvas_bg)) + dc.Clear() + self._draw(dc, text_fg, between_color, within_color) + + def _draw(self, dc, text_fg, between_color, within_color): + import math # needed for diagonal arrow angle calculations + self._clickable_boxes = [] # reset so hit-test rects match this paint + W, _H, scale, ox, oy = self._map_transform() + + def px(v): return int(ox + v * scale) # logical x → client pixel + def py(v): return int(oy + v * scale) # logical y → client pixel + def ps(v): return max(1, int(v * scale))# logical size/thickness → pixels (minimum 1) + + # Centralized connector metrics (client pixels). Floors keep hierarchy at scale 0.5. + between_outline_w = max(1, ps(self.BETWEEN_OUTLINE_W)) + between_sh = max(5, ps(self.BETWEEN_SHAFT_HALF)) + between_hw = max(10, ps(self.BETWEEN_HEAD_HALF)) + between_neck = max(14, ps(self.BETWEEN_NECK)) + within_line_w = max(2, ps(self.WITHIN_LINE_W)) + within_ah = max(3, ps(self.WITHIN_HEAD_HALF)) + within_al = max(5, ps(self.WITHIN_HEAD_LEN)) + + # Section fill and ink (border only) colors — unchanged identity colours + s1_fill = wx.Colour(255, 210, 210) # super light red — section 1 + s1_ink = wx.Colour(160, 55, 55) # darker red — section 1 borders + s2_fill = wx.Colour(210, 228, 255) # super light blue — section 2 + s2_ink = wx.Colour(55, 95, 165) # darker blue — section 2 borders + s3_fill = wx.Colour(255, 228, 195) # super light orange — section 3 + s3_ink = wx.Colour(175, 100, 20) # darker orange — section 3 borders + s4_fill = wx.Colour(235, 215, 255) # light lavender — section 4 + s4_ink = wx.Colour(120, 60, 180) # deeper purple — section 4 borders + + font = wx.Font(max(12, ps(16)), wx.FONTFAMILY_DEFAULT, + wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) # body text font at fixed map scale + bold_font = wx.Font(max(18, ps(26)), wx.FONTFAMILY_DEFAULT, + wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) # large bold font for the main title + head_font = wx.Font(max(15, ps(22)), wx.FONTFAMILY_DEFAULT, + wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) # smaller bold font for section headings + + dc.SetFont(font) + lh = dc.GetCharHeight() # single-line height in pixels + MX = ps(14) # horizontal margin each side in pixels + MY = ps(8) # vertical margin each side in pixels + def hbh(n): return (lh * n + 2 * MY) / 2 / scale # virtual half-box-height for n lines of text + + def draw_box(cx, cy, lines, fill, ink, key=None): + dc.SetFont(font) + # Light pastel fills: keep black labels (already correct contrast). + dc.SetTextForeground(wx.BLACK) + line_widths = [dc.GetTextExtent(l)[0] for l in lines] + box_w = max(line_widths) + 2 * MX + box_h = lh * len(lines) + 2 * MY + bx = px(cx) - box_w // 2 + by = py(cy) - box_h // 2 + dc.SetPen(wx.Pen(ink, ps(1))) + dc.SetBrush(wx.Brush(fill)) + dc.DrawRoundedRectangle(bx, by, box_w, box_h, ps(5)) + ty = by + MY + for i, (line, lw) in enumerate(zip(lines, line_widths)): + dc.DrawText(line, px(cx) - lw // 2, ty + i * lh) + if key is not None: + self._clickable_boxes.append((bx, by, box_w, box_h, fill, ink, _BOX_POPUP[key])) + + def v_arr(x, y1, y2): + """Vertical within-phase connector (downward) using secondary neutral style.""" + dc.SetPen(wx.Pen(within_color, within_line_w)) + dc.SetBrush(wx.Brush(within_color)) + dc.DrawLine(px(x), py(y1), px(x), py(y2)) + dc.DrawPolygon([(px(x), py(y2)), + (px(x)-within_ah, py(y2)-within_al), + (px(x)+within_ah, py(y2)-within_al)]) + + def diag_arr(x1, y1, x2, y2, lines=(), label_dx=0, label_dy=0): + """Diagonal within-phase connector using secondary neutral style.""" + dc.SetPen(wx.Pen(within_color, within_line_w)) + dc.SetBrush(wx.Brush(within_color)) + dc.DrawLine(px(x1), py(y1), px(x2), py(y2)) + dx_v, dy_v = x2 - x1, y2 - y1 + length = math.hypot(dx_v, dy_v) + ux, uy = dx_v / length, dy_v / length + tip_x, tip_y = px(x2), py(y2) + lft_x = int(tip_x - within_al * ux + within_ah * (-uy)) + lft_y = int(tip_y - within_al * uy + within_ah * ux) + rgt_x = int(tip_x - within_al * ux - within_ah * (-uy)) + rgt_y = int(tip_y - within_al * uy - within_ah * ux) + dc.DrawPolygon([(tip_x, tip_y), (lft_x, lft_y), (rgt_x, rgt_y)]) + if lines: + perp_x, perp_y = uy, -ux # 90 degrees left of arrow direction in screen coords + if perp_y > 0: # if that points downward, flip so label is always above the arrow + perp_x, perp_y = -perp_x, -perp_y + offset = ps(80) # pixels to push text away from the shaft + cx_label = px((x1 + x2) / 2) + int(perp_x * offset) + label_dx + cy_label = py((y1 + y2) / 2) + int(perp_y * offset) + label_dy + dc.SetFont(font) + dc.SetTextForeground(text_fg) + lh = dc.GetCharHeight() + top = cy_label - (lh * len(lines)) // 2 + for i, line in enumerate(lines): + lw, _ = dc.GetTextExtent(line) + dc.DrawText(line, cx_label - lw // 2, top + i * lh) + + def big_arr(x1, x2, cy): + """Large between-phase connector (right-pointing) using primary neutral style.""" + neck = px(x2) - between_neck + dc.SetPen(wx.Pen(between_color, between_outline_w)) + dc.SetBrush(wx.Brush(between_color)) + dc.DrawPolygon([ + (px(x1), py(cy) - between_sh), + (neck, py(cy) - between_sh), + (neck, py(cy) - between_hw), + (px(x2), py(cy)), + (neck, py(cy) + between_hw), + (neck, py(cy) + between_sh), + (px(x1), py(cy) + between_sh), + ]) + + + # MAIN TITLE + dc.SetFont(bold_font) + dc.SetTextForeground(text_fg) + tw, _ = dc.GetTextExtent('LabGym Workflow Map') + dc.DrawText('LabGym Workflow Map', (W - tw) // 2, py(65) // 3) + + # SECTION HEADINGS + dc.SetFont(head_font) + dc.SetTextForeground(text_fg) + for label, cx in [('1. Video Prep', 155), ('2. Tracking', 755), ('3. Classification', 1355)]: + tw, _ = dc.GetTextExtent(label) + dc.DrawText(label, px(cx) - tw // 2, py(65)) + lh_head = dc.GetCharHeight() + for i, line in enumerate(['4. Post Classification', 'Analysis']): + tw, _ = dc.GetTextExtent(line) + dc.DrawText(line, px(1955) - tw // 2, py(65) + i * lh_head) + + + # ── Section 1: Video Prep ────────────────────────────────────────────── + v_arr(155, 154 + hbh(2), 259 - hbh(2)) # Collect Footage -> Preprocessing + big_arr(380, 555, 65) # section 1 -> section 2 transition (centred in gap, at subtitle height) + + # ── Section 2: Tracking ─────────────────────────────────────────────── + diag_arr(715, 148 + hbh(2), 540, 280 - hbh(2), ['Static', 'Background'], label_dx=-ps(30), label_dy=ps(38)) # Tracking -> Background Subtraction (steeper angle) + diag_arr(795, 148 + hbh(2), 950, 280 - hbh(1), ['Dynamic', 'Background'], label_dx= ps(30), label_dy=ps(25)) # Tracking -> Detector (steeper angle) + v_arr(950, 280 + hbh(1), 380 - hbh(2)) # Detector -> Generate Images + v_arr(933, 380 + hbh(2), 480 - hbh(2)) # Generate Images -> Roboflow OR EZannot (left fork) + v_arr(967, 380 + hbh(2), 480 - hbh(2)) # Generate Images -> Roboflow OR EZannot (right fork) + v_arr(950, 480 + hbh(2), 580 - hbh(2)) # Roboflow OR EZannot -> Train Detector + big_arr(967, 1142, 65) # section 2 -> section 3 transition (centred in gap, at subtitle height) + + # ── Section 3: Classification ───────────────────────────────────────── + v_arr(1355, 164 + hbh(3), 278 - hbh(2)) # Generate and sort -> Train Categorizer + v_arr(1355, 278 + hbh(2), 378 - hbh(2)) # Train Categorizer -> Test Categorizer + v_arr(1355, 378 + hbh(2), 478 - hbh(2)) # Test Categorizer -> Analyze Behaviors + big_arr(1567, 1742, 65) # section 3 -> section 4 transition (centred in gap, at subtitle height) + + + # BOXES + + # section 1 + draw_box( 155, 154, ['Collect', 'Footage'], s1_fill, s1_ink, 'collect_footage') + draw_box( 155, 259, ['Preprocessing', '(Optional)'], s1_fill, s1_ink, 'preprocessing') + + # section 2 + draw_box( 755, 148, ['Tracking /', 'Animal Detection'], s2_fill, s2_ink, 'tracking') + draw_box( 540, 280, ['Background', 'Subtraction'], s2_fill, s2_ink, 'bg_sub') + draw_box( 950, 280, ['Detector'], s2_fill, s2_ink, 'detector') + draw_box( 950, 380, ['Generate', 'Images'], s2_fill, s2_ink, 'generate_images') + draw_box( 950, 480, ['Roboflow OR', 'EZannot'], s2_fill, s2_ink, 'roboflow') + draw_box( 950, 580, ['Train', 'Detector'], s2_fill, s2_ink, 'train_detector') + + # section 3 + draw_box(1355, 164, ['Generate and', 'Sort Behavior', 'Examples'], s3_fill, s3_ink, 'generate_examples') + draw_box(1355, 278, ['Train', 'Categorizer'], s3_fill, s3_ink, 'train_categorizer') + draw_box(1355, 378, ['Test', 'Categorizer'], s3_fill, s3_ink, 'test_categorizer') + draw_box(1355, 478, ['Analyze', 'Behaviors'], s3_fill, s3_ink, 'analyze_behaviors') + + # section 4 + draw_box(1955, 195, ['Mine', 'Results'], s4_fill, s4_ink, 'mine_results') + draw_box(1955, 295, ['Generate', 'Behavior Plot'], s4_fill, s4_ink, 'generate_plot') + draw_box(1955, 395, ['Calculate', 'Distances'], s4_fill, s4_ink, 'calc_distances') + + def _on_box_click(self, evt): + # Click coords are already in client space; box rects are recorded in the same space during paint. + x, y = evt.GetPosition() + for bx, by, bw, bh, fill, ink, data in self._clickable_boxes: + if bx <= x < bx + bw and by <= y < by + bh: + section, title, desc, guide = data + popup = BoxInfoPopup(self, section, title, desc, guide, fill, ink) + popup.Show() + return + evt.Skip() + class MainFrame(wx.Frame): """Main frame and its notebook.""" + # Fixed outer window size — large enough for the full Workflow Map (canvas 1100×560) without scroll. + # Height includes map client + notebook tabs + menubar/chrome (~90px). Not resizable. + FIXED_FRAME_SIZE = (1100, 650) + def __init__(self): - super().__init__(None, title=f'LabGym v{__version__}') + # Disable resize border and maximize so the frame stays at FIXED_FRAME_SIZE. + style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) + super().__init__(None, title=f'LabGym v{__version__}', style=style) - self.SetSize((1000, 600)) + self.SetSize(self.FIXED_FRAME_SIZE) + self.SetMinSize(self.FIXED_FRAME_SIZE) + self.SetMaxSize(self.FIXED_FRAME_SIZE) - # Set the app icon within GUI - set_frame_icon(self, context='normal') # Set normal icon first - if sys.platform.startswith("win"): - set_frame_icon(self, context='small', size=16) # Override with small icon for title bar + # Set the app icon within GUI (unified simplified artwork on all platforms) + set_frame_icon(self) self.init_menubar() @@ -390,12 +949,13 @@ def __init__(self): wx.aui.AuiPaneInfo().CenterPane(), ) - # Add panel as a page to the notebook. - panel = InitialPanel(self.notebook) - title = 'Home' - self.notebook.AddPage(panel, title, select=True) + # Store page objects for navigation/close protection (identity, not index/title). + self.home_page = InitialPanel(self.notebook) + self.notebook.AddPage(self.home_page, 'Home', select=True) + self.workflow_map_page = WorkflowMapPanel(self.notebook) + self.notebook.AddPage(self.workflow_map_page, 'Workflow Map', select=False) - # Bind the close event to prevent Home tab from being closed + # Bind the close event to protect stored Home / Workflow Map pages self.notebook.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.on_page_close) # Use a sizer to ensure the notebook fills the frame. @@ -409,9 +969,14 @@ def __init__(self): self.Show() # display the frame def on_page_close(self, event): - """Handle page close events to prevent Home tab from being closed.""" - # Prevent the Home tab (index 0) from being closed - if event.GetSelection() == 0: + """Veto closing of the stored Home and Workflow Map page objects.""" + selection = event.GetSelection() + try: + page = self.notebook.GetPage(selection) + except Exception: + page = None + if is_protected_notebook_page( + page, (self.home_page, self.workflow_map_page)): event.Veto() else: # Allow other tabs to be closed normally diff --git a/LabGym/gui_preprocessor.py b/LabGym/gui_preprocessor.py index 1a8b7bb5..8c7038a8 100644 --- a/LabGym/gui_preprocessor.py +++ b/LabGym/gui_preprocessor.py @@ -35,6 +35,7 @@ # Local application/library specific imports. from .tools import preprocess_video +from .gui_utils import add_info_button, create_hyperlink, INFO_COLOUR_S1 class PanelLv2_ProcessVideos(wx.Panel): @@ -71,6 +72,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S1) module_inputvideos=wx.BoxSizer(wx.HORIZONTAL) button_inputvideos=wx.Button(panel,label='Select the video(s)\nfor preprocessing',size=(300,40)) @@ -140,6 +142,18 @@ def display_window(self): boxsizer.Add(button_preprocessvideos,0,wx.RIGHT|wx.ALIGN_RIGHT,90) boxsizer.Add(0,10,0) + # Match nested 10px module + button margins so the link lines up with the button column. + module_tutorial=wx.BoxSizer(wx.HORIZONTAL) + module_tutorial.Add( + create_hyperlink( + panel, + 'Preprocessing Basics Tutorial Video', + 'https://youtu.be/51F-whqGIzU?si=IYMT3_etdnu46Zh3', + ), + 0, wx.LEFT|wx.RIGHT, 10) + boxsizer.Add(module_tutorial,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + boxsizer.Add(0, 10, 0) + panel.SetSizer(boxsizer) self.Centre() @@ -442,6 +456,7 @@ def display_window(self): panel = self boxsizer=wx.BoxSizer(wx.VERTICAL) + add_info_button(self, boxsizer, INFO_COLOUR_S1) module_inputvideos=wx.BoxSizer(wx.HORIZONTAL) button_inputvideos=wx.Button(panel,label='Select the video(s)\nfor marker drawing',size=(300,40)) @@ -471,6 +486,18 @@ def display_window(self): boxsizer.Add(button_preprocessvideos,0,wx.RIGHT|wx.ALIGN_RIGHT,90) boxsizer.Add(0,10,0) + # Match nested 10px module + button margins so the link lines up with the button column. + module_tutorial=wx.BoxSizer(wx.HORIZONTAL) + module_tutorial.Add( + create_hyperlink( + panel, + 'Video preprocessing: Draw Markers Tutorial Video', + 'https://youtu.be/8Y9RQUGuPtk?si=3jPVZCddf62o2EUB', + ), + 0, wx.LEFT|wx.RIGHT, 10) + boxsizer.Add(module_tutorial,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10) + boxsizer.Add(0, 10, 0) + panel.SetSizer(boxsizer) self.Centre() diff --git a/LabGym/gui_utils.py b/LabGym/gui_utils.py index d75961cd..e724c183 100644 --- a/LabGym/gui_utils.py +++ b/LabGym/gui_utils.py @@ -21,6 +21,287 @@ This module provides additional utility functions for the LabGym GUI. Currently, it contains a function to add a new page or select existing page if it already exists. ''' +import os + +import wx +import wx.lib.agw.hyperlink as hl +import wx.lib.buttons as wxbuttons + +from .gui_appearance import select_for_appearance + +# Section colour constants — match the workflow-map fill colours +INFO_COLOUR_S1 = wx.Colour(255, 210, 210) # light red — 1. Video Prep +INFO_COLOUR_S2 = wx.Colour(210, 228, 255) # light blue — 2. Tracking +INFO_COLOUR_S3 = wx.Colour(255, 228, 195) # light orange — 3. Classification +INFO_COLOUR_S4 = wx.Colour(235, 215, 255) # light lavender — 4. Post-Classification Analysis +INFO_COLOUR_GREY = wx.Colour(220, 220, 220) # light grey — fallback + +# Shared cyan/teal hyperlink family for all LabGym GUI links (AGW + HTML). +# Normal and visited are identical so AGW and browsers never show purple. +_LINK_LIGHT_NORMAL = wx.Colour(0, 140, 158) # darker cyan/teal on light surfaces +_LINK_DARK_NORMAL = wx.Colour(70, 230, 240) # brighter cyan on dark surfaces +_LINK_LIGHT_ROLLOVER = wx.Colour(0, 175, 195) # lighter cyan (same family) +_LINK_DARK_ROLLOVER = wx.Colour(140, 245, 255) # brighter cyan (same family) + + +def behavior_label_from_filename(filename): + """Return the prepared-example category label matching categorizer training. + + LabGym training takes the final underscore-delimited segment of the stem. + Filenames without an underscore yield None and are ignored by counting. + """ + base = os.path.splitext(os.path.basename(filename))[0] + if '_' not in base: + return None + return base.split('_')[-1] + + +def _list_media_for_counts(entries): + """Prefer AVI listings in a directory; otherwise use JPG listings.""" + avis = [f for f in entries if f.endswith('.avi')] + if avis: + return avis + return [f for f in entries if f.endswith('.jpg')] + + +def _count_prepared_files_in_dir(dir_path): + """Count prepared examples in a single flat directory (no recursion).""" + try: + entries = os.listdir(dir_path) + except OSError: + return {} + counts = {} + for f in _list_media_for_counts(entries): + label = behavior_label_from_filename(f) + if label is None: + continue + counts[label] = counts.get(label, 0) + 1 + return counts + + +def count_prepared_examples(folder_path): + """Count prepared training examples by behavior label. + + Supports: + - flat prepared folders (files directly under folder_path); or + - onfly layout with train/ plus validation/ (or counting-only vadilation/). + + Split mode is used only when train/ and either validation/ or vadilation/ + exist; counts are summed across recognized split directories (not recursive + below those directories). Incomplete split layouts fall back to flat-root scan. + """ + if not folder_path: + return {} + try: + os.listdir(folder_path) + except OSError: + return {} + + train_path = os.path.join(folder_path, 'train') + validation_path = os.path.join(folder_path, 'validation') + vadilation_path = os.path.join(folder_path, 'vadilation') + has_train = os.path.isdir(train_path) + has_validation = os.path.isdir(validation_path) + has_vadilation = os.path.isdir(vadilation_path) + + if has_train and (has_validation or has_vadilation): + counts = {} + for path in (train_path, validation_path, vadilation_path): + if not os.path.isdir(path): + continue + for label, n in _count_prepared_files_in_dir(path).items(): + counts[label] = counts.get(label, 0) + n + return counts + + return _count_prepared_files_in_dir(folder_path) + + +def count_sorted_examples(folder_path): + """Count sorted behavior examples per immediate behavior subfolder name. + + AVI-over-JPG precedence applies independently within each subfolder. + Empty behavior subfolders are included with count 0. + """ + if not folder_path: + return {} + try: + names = os.listdir(folder_path) + except OSError: + return {} + counts = {} + for name in names: + path = os.path.join(folder_path, name) + if not os.path.isdir(path): + continue + try: + entries = os.listdir(path) + except OSError: + counts[name] = 0 + continue + counts[name] = len(_list_media_for_counts(entries)) + return counts + + +def counts_enable_diagnostics(counts): + """True when at least one category has one or more counted examples.""" + return any(n > 0 for n in counts.values()) if counts else False + + +def compute_workflow_map_transform( + client_w, client_h, vw=2200, vh=660, + fallback_w=1100, fallback_h=560): + """Compute (client_w, client_h, scale, ox, oy) for the Workflow Map layout. + + Tiny or invalid client dimensions fall back to nominal sizes so drawing and + hit tests remain well-defined during early layout passes. + """ + try: + cw, ch = int(client_w), int(client_h) + except Exception: + cw, ch = 0, 0 + if cw < 1 or ch < 1: + cw, ch = fallback_w, fallback_h + scale = min(cw / vw, ch / vh) + if scale <= 0: + scale = min(fallback_w / vw, fallback_h / vh) + ox = (cw - vw * scale) / 2 + oy = (ch - vh * scale) / 2 + return cw, ch, scale, ox, oy + + +def _colour_to_hex(colour) -> str: + """Format a wx.Colour as #RRGGBB for HTML/CSS.""" + return '#{:02X}{:02X}{:02X}'.format(colour.Red(), colour.Green(), colour.Blue()) + + +def hyperlink_colours(): + """Return (normal, visited, rollover) wx.Colour for the current appearance. + + Visited is always identical to normal. + """ + normal = select_for_appearance(_LINK_LIGHT_NORMAL, _LINK_DARK_NORMAL) + rollover = select_for_appearance(_LINK_LIGHT_ROLLOVER, _LINK_DARK_ROLLOVER) + return normal, normal, rollover + + +def hyperlink_html_style(): + """Return (link_hex, visited_hex, hover_hex) for HTML anchors. + + Uses the same cyan family as AGW HyperLinkCtrl. Visited matches normal. + """ + normal, visited, rollover = hyperlink_colours() + return ( + _colour_to_hex(normal), + _colour_to_hex(visited), + _colour_to_hex(rollover), + ) + + +def style_hyperlink(link): + """Apply the shared cyan appearance-aware style to an AGW HyperLinkCtrl. + + Sets normal/visited/rollover colours, enables rollover, refreshes the link, + and binds a light restyle when the OS system colours change (if supported). + Preserves URL and browser-opening behaviour. + """ + if link is None: + return link + + def _apply(_event=None): + try: + if not link: # destroyed + return + normal, visited, rollover = hyperlink_colours() + link.SetColours(link=normal, visited=visited, rollover=rollover) + link.EnableRollover(True) + try: + # Keep internal visited flag from forcing a purple brand; colours already match. + link.SetVisited(False) + except Exception: + pass + link.UpdateLink(True) + except RuntimeError: + # Window may already be destroyed. + pass + + _apply() + + if not getattr(link, '_labgym_hyperlink_styled', False): + link._labgym_hyperlink_styled = True + if hasattr(wx, 'EVT_SYS_COLOUR_CHANGED'): + link.Bind(wx.EVT_SYS_COLOUR_CHANGED, lambda evt: (_apply(), evt.Skip())) + # Some platforms update appearance on reactivation. + frame = wx.GetTopLevelParent(link) + if frame is not None: + def _on_activate(evt): + if evt.GetActive(): + _apply() + evt.Skip() + frame.Bind(wx.EVT_ACTIVATE, _on_activate) + + return link + + +def create_hyperlink(parent, label, url): + """Create an AGW HyperLinkCtrl with LabGym's shared cyan link style.""" + link = hl.HyperLinkCtrl(parent, -1, label, URL=url) + return style_hyperlink(link) + + +# Backwards-compatible alias for earlier tutorial-only helper name. +create_tutorial_hyperlink = create_hyperlink + + +def select_notebook_page(notebook, page) -> bool: + """Select a notebook page by stored page-object identity (not index or title). + + Returns True if the page was found and selected. + """ + if notebook is None or page is None: + return False + for i in range(notebook.GetPageCount()): + if notebook.GetPage(i) is page: + notebook.SetSelection(i) + return True + return False + + +def is_protected_notebook_page(page, protected_pages) -> bool: + """Return True when page is one of the protected main-frame page objects.""" + if page is None: + return False + for protected in protected_pages: + if protected is not None and page is protected: + return True + return False + + +def add_info_button(panel, boxsizer, colour): + """Insert a coloured 'i' button at the top-right of a panel's vertical sizer. + + Clicking the button selects the main frame's stored Workflow Map page object + (``frame.workflow_map_page``) regardless of its notebook index or displayed title. + Use one of INFO_COLOUR_S1/S2/S3/GREY as the colour argument. + """ + bar = wx.BoxSizer(wx.HORIZONTAL) + bar.AddStretchSpacer() + btn = wxbuttons.GenButton(panel, label='i', size=(28, 28)) + btn.SetBackgroundColour(colour) + btn.SetForegroundColour(wx.Colour(60, 60, 60)) + btn.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) + btn.SetToolTip('View Workflow Map') + bar.Add(btn, 0, wx.RIGHT | wx.TOP, 6) + boxsizer.Add(bar, 0, wx.EXPAND) + + def _go_to_workflow(evt): + frame = wx.GetTopLevelParent(panel) + notebook = getattr(frame, 'notebook', None) + workflow_page = getattr(frame, 'workflow_map_page', None) + select_notebook_page(notebook, workflow_page) + + btn.Bind(wx.EVT_BUTTON, _go_to_workflow) + + def add_or_select_notebook_page(notebook, panel_factory, title): """Helper function to add a new page or select existing page if it already exists. diff --git a/LabGym/tests/test_behavior_counts.py b/LabGym/tests/test_behavior_counts.py new file mode 100644 index 00000000..c0f73764 --- /dev/null +++ b/LabGym/tests/test_behavior_counts.py @@ -0,0 +1,117 @@ +"""AF regression: prepared/sorted behavior-count helpers (no live GUI).""" + +import os +from pathlib import Path + +from LabGym import mywx # patch wx.App before any import of wx / gui_utils +from LabGym.gui_utils import ( + behavior_label_from_filename, + count_prepared_examples, + count_sorted_examples, + counts_enable_diagnostics, +) + + +def _touch(path: Path): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b'') + + +def test_behavior_label_final_underscore_segment(): + assert behavior_label_from_filename('0_grooming.avi') == 'grooming' + assert behavior_label_from_filename('0_approach_partner.jpg') == 'partner' + assert behavior_label_from_filename('nounderscore.jpg') is None + assert behavior_label_from_filename('plain.jpg') is None + + +def test_flat_avi_examples(tmp_path): + _touch(tmp_path / '0_grooming.avi') + _touch(tmp_path / '1_rearing.avi') + _touch(tmp_path / '2_grooming.avi') + assert count_prepared_examples(str(tmp_path)) == { + 'grooming': 2, + 'rearing': 1, + } + + +def test_filenames_without_underscore_ignored(tmp_path): + _touch(tmp_path / 'orphan.avi') + _touch(tmp_path / '1_valid.avi') + assert count_prepared_examples(str(tmp_path)) == {'valid': 1} + + +def test_avi_over_jpg_no_double_count(tmp_path): + _touch(tmp_path / '0_grooming.avi') + _touch(tmp_path / '0_grooming.jpg') + _touch(tmp_path / '1_grooming.jpg') + # Any AVI present in the directory: count only AVI, not JPG. + assert count_prepared_examples(str(tmp_path)) == {'grooming': 1} + + +def test_jpg_only_when_no_avi(tmp_path): + _touch(tmp_path / '0_grooming.jpg') + _touch(tmp_path / '1_rearing.jpg') + assert count_prepared_examples(str(tmp_path)) == { + 'grooming': 1, + 'rearing': 1, + } + + +def test_train_validation_aggregation(tmp_path): + _touch(tmp_path / 'train' / '0_a.avi') + _touch(tmp_path / 'train' / '1_b.avi') + _touch(tmp_path / 'validation' / '2_a.avi') + _touch(tmp_path / 'validation' / '3_c.avi') + assert count_prepared_examples(str(tmp_path)) == {'a': 2, 'b': 1, 'c': 1} + + +def test_train_vadilation_compatibility(tmp_path): + _touch(tmp_path / 'train' / '0_x.avi') + _touch(tmp_path / 'vadilation' / '1_x.avi') + _touch(tmp_path / 'vadilation' / '2_y.avi') + assert count_prepared_examples(str(tmp_path)) == {'x': 2, 'y': 1} + + +def test_incomplete_split_falls_back_to_flat_root(tmp_path): + # train/ only — not split mode; flat-root scan ignores nested files. + _touch(tmp_path / 'train' / '0_hidden.avi') + _touch(tmp_path / '0_root.avi') + assert count_prepared_examples(str(tmp_path)) == {'root': 1} + + +def test_empty_and_unreadable(tmp_path): + assert count_prepared_examples(str(tmp_path)) == {} + assert count_prepared_examples(str(tmp_path / 'missing')) == {} + assert count_prepared_examples('') == {} + assert counts_enable_diagnostics({}) is False + + +def test_one_populated_category_enables_diagnostics(tmp_path): + _touch(tmp_path / '0_only.avi') + counts = count_prepared_examples(str(tmp_path)) + assert counts == {'only': 1} + assert counts_enable_diagnostics(counts) is True + + +def test_sorted_multiple_folders_and_empty_zero(tmp_path): + _touch(tmp_path / 'grooming' / 'a.avi') + _touch(tmp_path / 'grooming' / 'b.avi') + _touch(tmp_path / 'rearing' / 'c.jpg') + (tmp_path / 'empty_behavior').mkdir() + counts = count_sorted_examples(str(tmp_path)) + assert counts == {'grooming': 2, 'rearing': 1, 'empty_behavior': 0} + assert counts_enable_diagnostics(counts) is True + + +def test_sorted_per_folder_avi_jpg_precedence(tmp_path): + _touch(tmp_path / 'mixed' / '0.avi') + _touch(tmp_path / 'mixed' / '0.jpg') + _touch(tmp_path / 'mixed' / '1.jpg') + _touch(tmp_path / 'jpg_only' / 'x.jpg') + counts = count_sorted_examples(str(tmp_path)) + assert counts['mixed'] == 1 # avis only + assert counts['jpg_only'] == 1 + + +def test_sorted_unreadable_root(tmp_path): + assert count_sorted_examples(str(tmp_path / 'nope')) == {} diff --git a/LabGym/tests/test_gui_appearance.py b/LabGym/tests/test_gui_appearance.py new file mode 100644 index 00000000..7e5395ba --- /dev/null +++ b/LabGym/tests/test_gui_appearance.py @@ -0,0 +1,120 @@ +"""Unit tests for LabGym.gui_appearance (no GUI window required).""" + +from types import SimpleNamespace +from unittest.mock import MagicMock + +from LabGym import mywx # patch wx.App before any import of wx +import wx + +from LabGym import gui_appearance + + +class _FakeColour: + """Minimal stand-in for wx.Colour with Red/Green/Blue accessors.""" + + def __init__(self, r, g, b): + self._r, self._g, self._b = r, g, b + + def Red(self): + return self._r + + def Green(self): + return self._g + + def Blue(self): + return self._b + + +def test_is_dark_appearance_true_when_IsDark(monkeypatch): + appearance = MagicMock() + appearance.IsDark.return_value = True + monkeypatch.setattr(wx.SystemSettings, 'GetAppearance', lambda: appearance) + + assert gui_appearance.is_dark_appearance() is True + appearance.IsDark.assert_called_once() + appearance.IsUsingDarkBackground.assert_not_called() + + +def test_is_dark_appearance_false_when_IsDark(monkeypatch): + appearance = MagicMock() + appearance.IsDark.return_value = False + monkeypatch.setattr(wx.SystemSettings, 'GetAppearance', lambda: appearance) + + assert gui_appearance.is_dark_appearance() is False + appearance.IsDark.assert_called_once() + + +def test_is_dark_appearance_falls_back_to_IsUsingDarkBackground(monkeypatch): + """Prefer IsDark; when absent, use IsUsingDarkBackground.""" + appearance = SimpleNamespace() + # No IsDark attribute. + appearance.IsUsingDarkBackground = MagicMock(return_value=True) + monkeypatch.setattr(wx.SystemSettings, 'GetAppearance', lambda: appearance) + + assert gui_appearance.is_dark_appearance() is True + appearance.IsUsingDarkBackground.assert_called_once() + + +def test_is_dark_appearance_falls_back_to_luminance_when_no_appearance_api( + monkeypatch): + """Without GetAppearance, compare system window colours.""" + if hasattr(wx.SystemSettings, 'GetAppearance'): + monkeypatch.delattr(wx.SystemSettings, 'GetAppearance') + + def fake_get_colour(index): + if index == wx.SYS_COLOUR_WINDOW: + return _FakeColour(30, 30, 30) # dark bg + if index == wx.SYS_COLOUR_WINDOWTEXT: + return _FakeColour(220, 220, 220) # light text + return _FakeColour(128, 128, 128) + + monkeypatch.setattr(wx.SystemSettings, 'GetColour', fake_get_colour) + + assert gui_appearance.is_dark_appearance() is True + + +def test_is_dark_appearance_luminance_light(monkeypatch): + if hasattr(wx.SystemSettings, 'GetAppearance'): + monkeypatch.delattr(wx.SystemSettings, 'GetAppearance') + + def fake_get_colour(index): + if index == wx.SYS_COLOUR_WINDOW: + return _FakeColour(255, 255, 255) + if index == wx.SYS_COLOUR_WINDOWTEXT: + return _FakeColour(0, 0, 0) + return _FakeColour(128, 128, 128) + + monkeypatch.setattr(wx.SystemSettings, 'GetColour', fake_get_colour) + + assert gui_appearance.is_dark_appearance() is False + + +def test_is_dark_appearance_IsDark_exception_then_IsUsingDarkBackground( + monkeypatch): + appearance = MagicMock() + appearance.IsDark.side_effect = RuntimeError('unavailable') + appearance.IsUsingDarkBackground.return_value = False + monkeypatch.setattr(wx.SystemSettings, 'GetAppearance', lambda: appearance) + + assert gui_appearance.is_dark_appearance() is False + appearance.IsUsingDarkBackground.assert_called_once() + + +def test_select_for_appearance_dark(monkeypatch): + monkeypatch.setattr(gui_appearance, 'is_dark_appearance', lambda: True) + assert gui_appearance.select_for_appearance('light', 'dark') == 'dark' + + +def test_select_for_appearance_light(monkeypatch): + monkeypatch.setattr(gui_appearance, 'is_dark_appearance', lambda: False) + assert gui_appearance.select_for_appearance('light', 'dark') == 'light' + + +def test_select_for_appearance_with_colours(monkeypatch): + light = _FakeColour(255, 255, 255) + dark = _FakeColour(20, 20, 20) + monkeypatch.setattr(gui_appearance, 'is_dark_appearance', lambda: True) + assert gui_appearance.select_for_appearance(light, dark) is dark + + monkeypatch.setattr(gui_appearance, 'is_dark_appearance', lambda: False) + assert gui_appearance.select_for_appearance(light, dark) is light diff --git a/LabGym/tests/test_guide_mapping.py b/LabGym/tests/test_guide_mapping.py new file mode 100644 index 00000000..28cb7d5d --- /dev/null +++ b/LabGym/tests/test_guide_mapping.py @@ -0,0 +1,74 @@ +"""AF regression: Workflow Map popup guide tokens resolve to page numbers. + +Isolated from gui_main import (and its heavy panel/selftest dependencies) by +reading the module source and evaluating only the guide table assignments. +""" + +import ast +from pathlib import Path + + +def _gui_main_source_path() -> Path: + # LabGym/tests/this_file.py -> LabGym/gui_main.py + return Path(__file__).resolve().parent.parent / 'gui_main.py' + + +def _literal_assign(tree: ast.AST, name: str): + """Return the literal value of a top-level assignment ``name = ``.""" + for node in tree.body: + if not isinstance(node, ast.Assign): + continue + for target in node.targets: + if isinstance(target, ast.Name) and target.id == name: + return ast.literal_eval(node.value) + raise AssertionError('Assignment {!r} not found in gui_main.py'.format(name)) + + +def _load_guide_tables(): + source = _gui_main_source_path().read_text(encoding='utf-8') + tree = ast.parse(source, filename=str(_gui_main_source_path())) + box_popup = _literal_assign(tree, '_BOX_POPUP') + guide_pages = _literal_assign(tree, '_GUIDE_PAGES') + return box_popup, guide_pages + + +def _resolve_guide_page_number(guide_pages, ref: str): + if not ref: + return None + return guide_pages.get(ref.strip().lower()) + + +def _iter_box_popup_guide_refs(box_popup): + for key, data in box_popup.items(): + guide = data[3] + for ref in guide.split(','): + ref = ref.strip() + if ref: + yield key, ref + + +def _practical_guide_url(page_number: int) -> str: + return 'https://www.labgym.org/guides/practical-guide#page-{}'.format(page_number) + + +def test_every_intentional_popup_guide_token_resolves(): + box_popup, guide_pages = _load_guide_tables() + unresolved = [] + for box_key, ref in _iter_box_popup_guide_refs(box_popup): + page = _resolve_guide_page_number(guide_pages, ref) + if page is None: + unresolved.append((box_key, ref)) + assert unresolved == [], 'Unresolved guide tokens: {}'.format(unresolved) + + +def test_background_subtraction_section_lll_a_is_page_28(): + box_popup, guide_pages = _load_guide_tables() + guide = box_popup['bg_sub'][3] + tokens = [r.strip() for r in guide.split(',')] + assert 'Part 3.1' in tokens + assert 'Part 4.1' in tokens + assert 'Section lll A' in tokens + assert _resolve_guide_page_number(guide_pages, 'Section lll A') == 28 + assert _practical_guide_url(28) == ( + 'https://www.labgym.org/guides/practical-guide#page-28' + ) diff --git a/LabGym/tests/test_notebook_page_identity.py b/LabGym/tests/test_notebook_page_identity.py new file mode 100644 index 00000000..409b06fe --- /dev/null +++ b/LabGym/tests/test_notebook_page_identity.py @@ -0,0 +1,117 @@ +"""AF regression: notebook page selection and close protection by object identity.""" + +from LabGym import mywx # patch wx.App before any import of wx / gui_utils +from LabGym.gui_utils import is_protected_notebook_page, select_notebook_page + + +class _StubNotebook: + """Minimal notebook stand-in with reordering support (no live wx session).""" + + def __init__(self): + self._pages = [] + self._titles = [] + self.selection = None + + def AddPage(self, page, title, select=False): + self._pages.append(page) + self._titles.append(title) + if select or self.selection is None: + self.selection = len(self._pages) - 1 + + def GetPageCount(self): + return len(self._pages) + + def GetPage(self, index): + return self._pages[index] + + def GetPageText(self, index): + return self._titles[index] + + def SetPageText(self, index, title): + self._titles[index] = title + + def SetSelection(self, index): + self.selection = index + + def InsertPage(self, index, page, title, select=False): + self._pages.insert(index, page) + self._titles.insert(index, title) + if select: + self.selection = index + elif self.selection is not None and self.selection >= index: + self.selection += 1 + + def MovePage(self, old_index, new_index): + page = self._pages.pop(old_index) + title = self._titles.pop(old_index) + self._pages.insert(new_index, page) + self._titles.insert(new_index, title) + + +def test_select_workflow_map_after_unrelated_tabs_inserted_or_reordered(): + home = object() + workflow = object() + other = object() + nb = _StubNotebook() + nb.AddPage(home, 'Home', select=True) + nb.AddPage(workflow, 'Workflow Map') + nb.InsertPage(0, other, 'Other Tab') + assert nb.GetPage(0) is other + assert select_notebook_page(nb, workflow) is True + assert nb.GetPage(nb.selection) is workflow + + nb.MovePage(nb.selection, 0) + assert nb.GetPage(0) is workflow + extra = object() + nb.AddPage(extra, 'Extra') + assert select_notebook_page(nb, workflow) is True + assert nb.GetPage(nb.selection) is workflow + + +def test_home_and_workflow_protected_after_reordering(): + home = object() + workflow = object() + other = object() + nb = _StubNotebook() + nb.AddPage(home, 'Home') + nb.AddPage(workflow, 'Workflow Map') + nb.AddPage(other, 'Analysis') + nb.MovePage(0, 2) # home no longer at index 0 + protected = (home, workflow) + + for i in range(nb.GetPageCount()): + page = nb.GetPage(i) + should_protect = page is home or page is workflow + assert is_protected_notebook_page(page, protected) is should_protect + + +def test_other_pages_not_protected(): + home = object() + workflow = object() + other = object() + assert is_protected_notebook_page(other, (home, workflow)) is False + assert is_protected_notebook_page(None, (home, workflow)) is False + + +def test_title_change_does_not_break_object_identity(): + home = object() + workflow = object() + nb = _StubNotebook() + nb.AddPage(home, 'Home') + nb.AddPage(workflow, 'Workflow Map') + nb.SetPageText(0, 'Renamed Home') + nb.SetPageText(1, 'Renamed Map') + assert select_notebook_page(nb, home) is True + assert nb.GetPage(nb.selection) is home + assert select_notebook_page(nb, workflow) is True + assert nb.GetPage(nb.selection) is workflow + assert is_protected_notebook_page(home, (home, workflow)) + assert is_protected_notebook_page(workflow, (home, workflow)) + + +def test_select_missing_page_returns_false(): + nb = _StubNotebook() + nb.AddPage(object(), 'Home') + assert select_notebook_page(nb, object()) is False + assert select_notebook_page(None, object()) is False + assert select_notebook_page(nb, None) is False diff --git a/LabGym/tests/test_workflow_map_transform.py b/LabGym/tests/test_workflow_map_transform.py new file mode 100644 index 00000000..e0305e7b --- /dev/null +++ b/LabGym/tests/test_workflow_map_transform.py @@ -0,0 +1,18 @@ +"""AF regression: Workflow Map client-size transform (no live GUI windows).""" + +from LabGym import mywx # patch wx.App before any import of wx / gui_utils +from LabGym.gui_utils import compute_workflow_map_transform + + +def test_map_transform_uses_client_size(): + cw, ch, scale, ox, oy = compute_workflow_map_transform(1100, 560) + assert cw == 1100 and ch == 560 + assert abs(scale - min(1100 / 2200, 560 / 660)) < 1e-9 + assert abs(ox - (1100 - 2200 * scale) / 2) < 1e-9 + assert abs(oy - (560 - 660 * scale) / 2) < 1e-9 + + +def test_map_transform_tiny_client_falls_back(): + cw, ch, scale, ox, oy = compute_workflow_map_transform(0, 0) + assert cw == 1100 and ch == 560 + assert scale > 0