From d40f8f669a0191b8db4a677901d9628a1093da57 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Wed, 11 Nov 2026 16:13:54 -0500 Subject: [PATCH 1/7] fix(cli): avoid GUI command collision --- LabGym/tests/test_cli.py | 33 +++++++++++++++++++++++++++ LabGym_CLI_Guide.md | 49 ++++++++++++++++++++-------------------- pyproject.toml | 2 +- 3 files changed, 59 insertions(+), 25 deletions(-) diff --git a/LabGym/tests/test_cli.py b/LabGym/tests/test_cli.py index f3c9df20..30d3eed3 100644 --- a/LabGym/tests/test_cli.py +++ b/LabGym/tests/test_cli.py @@ -2,6 +2,8 @@ import os import subprocess import sys +from pathlib import Path + import pytest import yaml from unittest.mock import patch, MagicMock @@ -1673,3 +1675,34 @@ def test_cli_subprocess_headless_execution(): proc_wx = subprocess.run(no_wx_cmd, capture_output=True, text=True) assert proc_wx.returncode == 0 + +def _load_project_console_scripts(): + """Return [project.scripts] from the repo pyproject.toml (Python 3.10-safe).""" + pyproject = Path(__file__).resolve().parents[2] / "pyproject.toml" + text = pyproject.read_text(encoding="utf-8") + try: + import tomllib + except ModuleNotFoundError: # Python < 3.11 + import tomli as tomllib + data = tomllib.loads(text) + scripts = data.get("project", {}).get("scripts") + assert isinstance(scripts, dict) and scripts, "pyproject.toml missing [project.scripts]" + return scripts + + +def test_console_scripts_declare_distinct_gui_and_cli_entry_points(): + scripts = _load_project_console_scripts() + + assert scripts.get("LabGym") == "LabGym.__main__:main" + assert scripts.get("labgym-cli") == "LabGym.cli:main" + assert "labgym" not in scripts + + # Reject case-only collisions (e.g. LabGym vs labgym) that break macOS/Windows installs. + seen = {} + for name in scripts: + key = name.casefold() + assert key not in seen, f"case-only console script collision: {seen[key]!r} vs {name!r}" + seen[key] = name + + assert set(scripts) == {"LabGym", "labgym-cli"} + diff --git a/LabGym_CLI_Guide.md b/LabGym_CLI_Guide.md index ab3c738d..d3c3c92f 100644 --- a/LabGym_CLI_Guide.md +++ b/LabGym_CLI_Guide.md @@ -2,21 +2,23 @@ This guide details the command syntax, configuration contract, parameter precedence, and options for the headless command-line interface (CLI) in LabGym. +**Entry points:** `LabGym` remains the desktop GUI command. `labgym-cli` is the headless command-line interface for training, testing, and inference. Use `LabGym` to open the graphical application; use `labgym-cli` with a subcommand for scripted and HPC workflows. + --- ## 1. Architecture & Subcommand Structure The LabGym CLI is organized into nested subcommands reflecting canonical actions and targets: -* `labgym train categorizer` -* `labgym train detector` -* `labgym test categorizer` -* `labgym test detector` -* `labgym infer` +* `labgym-cli train categorizer` +* `labgym-cli train detector` +* `labgym-cli test categorizer` +* `labgym-cli test detector` +* `labgym-cli infer` -Running `labgym` without a subcommand launches the desktop graphical interface: +Launch the desktop GUI with the separate `LabGym` command: ```bash -labgym +LabGym ``` ### 3-Tier Precedence Hierarchy @@ -37,12 +39,12 @@ The `--config` / `-c` flag specifies a **per-command workflow (job) configuratio ## 2. Command Reference -### `labgym train categorizer` +### `labgym-cli train categorizer` Headless training for behavior classification sub-networks (Pattern Recognizer, Animation Analyzer, or CombNet). * **Syntax**: ```bash - labgym train categorizer --config [inline-overrides] + labgym-cli train categorizer --config [inline-overrides] ``` * **Required Parameters**: @@ -70,12 +72,12 @@ Headless training for behavior classification sub-networks (Pattern Recognizer, * `--color-costar` / `--no-color-costar`: Render supporting actors in RGB scale (default: False) * `--training-onfly` / `--no-training-onfly`: Train on the fly without pre-caching frames (default: False) -### `labgym train detector` +### `labgym-cli train detector` Headless training for Detectron2 object detection models. * **Syntax**: ```bash - labgym train detector --config [inline-overrides] + labgym-cli train detector --config [inline-overrides] ``` * **Required Parameters**: @@ -87,12 +89,12 @@ Headless training for Detectron2 object detection models. * `--iteration-num` (`iteration_num`): Number of training iterations (default: 200) * `--inference-size` (`inference_size`): Image frame resizing dimension for inference (default: 480) -### `labgym test categorizer` +### `labgym-cli test categorizer` Headless evaluation of a trained behavior classifier against ground-truth data. * **Syntax**: ```bash - labgym test categorizer --config [inline-overrides] + labgym-cli test categorizer --config [inline-overrides] ``` * **Required Parameters**: @@ -102,12 +104,12 @@ Headless evaluation of a trained behavior classifier against ground-truth data. * **Key Options**: * `--result-path` (`result_path`): Directory to write evaluation metrics and confusion matrices -### `labgym test detector` +### `labgym-cli test detector` Headless evaluation of a trained object detector against annotated testing images. * **Syntax**: ```bash - labgym test detector --config [inline-overrides] + labgym-cli test detector --config [inline-overrides] ``` * **Required Parameters**: @@ -116,14 +118,14 @@ Headless evaluation of a trained object detector against annotated testing image * `--model-path` (`model_path`): Path to trained Detector directory * `--result-path` (`result_path`): Directory to write detection test results -### `labgym infer` +### `labgym-cli infer` Headless animal tracking and behavior classification on videos or static images. > **Model Metadata Inheritance**: Architecture hyperparameters (`dim_conv`, `dim_tconv`, `channel`, `time_step`) and preprocessing settings (`background_free`, `black_background`, `behavior_mode`, `social_distance`, `color_costar`) are authoritative inside the trained Categorizer model's `model_parameters.txt` and are inherited automatically during inference. * **Syntax**: ```bash - labgym infer --config [inline-overrides] + labgym-cli infer --config [inline-overrides] ``` * **Required Parameters**: @@ -169,7 +171,7 @@ Headless animal tracking and behavior classification on videos or static images. ### Categorizer Training (`train_categorizer.yaml`) ```yaml -# labgym train categorizer -c train_categorizer.yaml +# labgym-cli train categorizer -c train_categorizer.yaml data_path: "~/data/behavior_examples" model_path: "~/models/categorizer_combnet" network_type: "combnet" @@ -196,7 +198,7 @@ social_distance: 0.0 ### Detector Training (`train_detector.yaml`) ```yaml -# labgym train detector -c train_detector.yaml +# labgym-cli train detector -c train_detector.yaml path_to_annotation: "~/data/annotations/train_coco.json" path_to_trainingimages: "~/data/training_images" model_path: "~/models/detector_mouse" @@ -206,7 +208,7 @@ inference_size: 480 ### Model Evaluation (`test_categorizer.yaml`) ```yaml -# labgym test categorizer -c test_categorizer.yaml +# labgym-cli test categorizer -c test_categorizer.yaml groundtruth_path: "~/data/groundtruth_examples" model_path: "~/models/categorizer_combnet" result_path: "~/results/categorizer_eval" @@ -214,7 +216,7 @@ result_path: "~/results/categorizer_eval" ### Detector Evaluation (`test_detector.yaml`) ```yaml -# labgym test detector -c test_detector.yaml +# labgym-cli test detector -c test_detector.yaml path_to_annotation: "~/data/annotations/test_coco.json" path_to_testingimages: "~/data/test_images" model_path: "~/models/detector_mouse" @@ -223,7 +225,7 @@ result_path: "~/results/detector_eval" ### Behavioral Inference (`infer.yaml`) ```yaml -# labgym infer -c infer.yaml +# labgym-cli infer -c infer.yaml path_to_videos: - "~/videos/session_1.mp4" - "~/videos/session_2.mp4" @@ -263,7 +265,7 @@ Below is an example job script for submitting a headless training run on an HPC module load python/3.10 source ~/envs/labgym/bin/activate -labgym train categorizer \ +labgym-cli train categorizer \ --config train_categorizer.yaml \ --data-path ~/data/behavior_dataset \ --model-path ~/models/combnet_run \ @@ -281,4 +283,3 @@ The LabGym CLI adheres to POSIX process exit conventions: * **Exit Code `2`**: Configuration, syntax, or validation error (e.g. missing/unreadable YAML file, unknown keys, invalid types, out-of-range bounds, incompatible parameter combinations, or missing required arguments). * **Standard Output (`stdout`)**: Informational human-readable workflow progress, success confirmations, and successful command help output (`--help` / `-h`). * **Standard Error (`stderr`)**: Error messages, validation diagnostics, and error usage output (syntax or argument errors). - diff --git a/pyproject.toml b/pyproject.toml index a57af5d1..b70da498 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -77,7 +77,7 @@ Issues='http://github.com/umyelab/LabGym/issues' [project.scripts] LabGym='LabGym.__main__:main' -labgym='LabGym.cli:main' +labgym-cli='LabGym.cli:main' [tool.pdm] distribution=true From 053f7926369406b877528d22798d279e587dde31 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 12 Nov 2026 13:50:22 -0500 Subject: [PATCH 2/7] fix(cli): make bare command headless --- LabGym/cli.py | 15 +++++---------- LabGym/tests/test_cli.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/LabGym/cli.py b/LabGym/cli.py index 965acf7c..d3cc5dca 100644 --- a/LabGym/cli.py +++ b/LabGym/cli.py @@ -427,7 +427,7 @@ def add_common_config_arg(parser): def build_parser(): parser = argparse.ArgumentParser( - prog="labgym", + prog="labgym-cli", description="LabGym CLI: Headless command-line interface for training, testing, and behavioral inference." ) subparsers = parser.add_subparsers(dest="action", help="Available actions") @@ -1347,17 +1347,12 @@ def main(argv=None): if argv is None: argv = sys.argv[1:] + parser = build_parser() + if len(argv) == 0: - try: - print("Launching LabGym GUI...", file=sys.stdout) - from LabGym.__main__ import main as gui_main - return gui_main() - except Exception as e: - print(f"Error launching LabGym GUI: {e}", file=sys.stderr) - return 1 + parser.print_help(file=sys.stdout) + return 0 - parser = build_parser() - try: args = parser.parse_args(argv) except SystemExit as e: diff --git a/LabGym/tests/test_cli.py b/LabGym/tests/test_cli.py index 30d3eed3..31b11f90 100644 --- a/LabGym/tests/test_cli.py +++ b/LabGym/tests/test_cli.py @@ -1706,3 +1706,31 @@ def test_console_scripts_declare_distinct_gui_and_cli_entry_points(): assert set(scripts) == {"LabGym", "labgym-cli"} + +def test_parser_prog_is_labgym_cli(): + assert build_parser().prog == "labgym-cli" + + +def test_bare_command_prints_help_exits_zero(capsys): + exit_code = main([]) + assert exit_code == 0 + captured = capsys.readouterr() + assert "labgym-cli" in captured.out + assert "LabGym CLI" in captured.out + assert captured.err == "" + + +def test_bare_command_does_not_import_or_launch_gui(): + cmd = [ + sys.executable, + "-c", + "from LabGym import cli; import sys; " + "code = cli.main([]); " + "blocked = ('wx' in sys.modules) or ('LabGym.__main__' in sys.modules); " + "sys.exit(0 if (code == 0 and not blocked) else 1)" + ] + proc = subprocess.run(cmd, capture_output=True, text=True) + assert proc.returncode == 0 + assert "labgym-cli" in proc.stdout + assert proc.stderr == "" + From 5621531849ade9bc880ba56aa706a9210807c776 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 12 Nov 2026 14:06:37 -0500 Subject: [PATCH 3/7] fix(cli): restore inference summary rollups --- LabGym/cli.py | 47 +++++++++++++++ LabGym/tests/test_cli.py | 120 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 167 insertions(+) diff --git a/LabGym/cli.py b/LabGym/cli.py index d3cc5dca..bb163318 100644 --- a/LabGym/cli.py +++ b/LabGym/cli.py @@ -1099,6 +1099,45 @@ def resolve_media_paths(paths, behavior_mode): return deduped +def rollup_behavior_summaries(result_path, behaviornames_and_colors, use_detector=False, animal_kinds=None): + """Aggregate per-video behavior summaries at the result root (GUI parity).""" + import pandas as pd + + folders = [i for i in os.listdir(result_path) if os.path.isdir(os.path.join(result_path, i))] + folders.sort() + if not use_detector: + for behavior_name in behaviornames_and_colors: + all_summary = [] + for folder in folders: + individual_summary = os.path.join(result_path, folder, behavior_name, 'all_summary.xlsx') + if os.path.exists(individual_summary): + all_summary.append(pd.read_excel(individual_summary)) + if len(all_summary) >= 1: + all_summary = pd.concat(all_summary, ignore_index=True) + all_summary.to_excel( + os.path.join(result_path, behavior_name + '_summary.xlsx'), + float_format='%.2f', + index_label='ID/parameter' + ) + else: + for animal_name in animal_kinds: + for behavior_name in behaviornames_and_colors: + all_summary = [] + for folder in folders: + individual_summary = os.path.join( + result_path, folder, behavior_name, animal_name + '_all_summary.xlsx' + ) + if os.path.exists(individual_summary): + all_summary.append(pd.read_excel(individual_summary)) + if len(all_summary) >= 1: + all_summary = pd.concat(all_summary, ignore_index=True) + all_summary.to_excel( + os.path.join(result_path, animal_name + '_' + behavior_name + '_summary.xlsx'), + float_format='%.2f', + index_label='ID/parameter' + ) + + def handle_infer(args): config = resolve_config( command_name="labgym infer", @@ -1340,6 +1379,14 @@ def handle_infer(args): all_events_df.to_excel(os.path.join(result_path, 'all_events.xlsx'), float_format='%.2f', index_label='time/ID') plot_events(result_path, event_data, all_time, cat_meta['behaviornames_and_colors'], behavior_to_include, width=0, height=0) + if path_to_categorizer is not None: + rollup_behavior_summaries( + result_path, + cat_meta['behaviornames_and_colors'], + use_detector=use_detector, + animal_kinds=animal_kinds, + ) + print("Inference completed successfully.", file=sys.stdout) diff --git a/LabGym/tests/test_cli.py b/LabGym/tests/test_cli.py index 31b11f90..5d345a07 100644 --- a/LabGym/tests/test_cli.py +++ b/LabGym/tests/test_cli.py @@ -8,6 +8,8 @@ import yaml from unittest.mock import patch, MagicMock +import pandas as pd + from LabGym.cli import ( build_parser, resolve_config, @@ -16,6 +18,7 @@ load_categorizer_metadata, load_detector_metadata, resolve_media_paths, + rollup_behavior_summaries, TRAIN_CATEGORIZER_DEFAULTS, ALLOWED_TRAIN_CATEGORIZER_KEYS, REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -1734,3 +1737,120 @@ def test_bare_command_does_not_import_or_launch_gui(): assert "labgym-cli" in proc.stdout assert proc.stderr == "" + +def test_rollup_non_detector_two_videos_sorted_order(tmp_path): + result = tmp_path / "result" + for stem, count in (("video_b", 20), ("video_a", 10)): + behavior_dir = result / stem / "groom" + behavior_dir.mkdir(parents=True) + pd.DataFrame({"count": [count]}).to_excel( + behavior_dir / "all_summary.xlsx", index=False + ) + + rollup_behavior_summaries( + str(result), + behaviornames_and_colors={"groom": ["#ffffff", "#000000"]}, + use_detector=False, + ) + + out = result / "groom_summary.xlsx" + assert out.is_file() + df = pd.read_excel(out) + assert list(df["count"]) == [10, 20] + + +def test_rollup_detector_two_videos(tmp_path): + result = tmp_path / "result" + for stem, count in (("video_b", 5), ("video_a", 3)): + behavior_dir = result / stem / "groom" + behavior_dir.mkdir(parents=True) + pd.DataFrame({"count": [count]}).to_excel( + behavior_dir / "mouse_all_summary.xlsx", index=False + ) + + rollup_behavior_summaries( + str(result), + behaviornames_and_colors={"groom": ["#ffffff", "#000000"]}, + use_detector=True, + animal_kinds=["mouse"], + ) + + out = result / "mouse_groom_summary.xlsx" + assert out.is_file() + assert not (result / "groom_summary.xlsx").exists() + df = pd.read_excel(out) + assert list(df["count"]) == [3, 5] + + +def test_rollup_missing_per_video_summaries_creates_no_root_summary(tmp_path): + result = tmp_path / "result" + (result / "video_a" / "groom").mkdir(parents=True) + (result / "video_b" / "groom").mkdir(parents=True) + + rollup_behavior_summaries( + str(result), + behaviornames_and_colors={"groom": ["#ffffff", "#000000"]}, + use_detector=False, + ) + + assert not (result / "groom_summary.xlsx").exists() + + +def test_infer_without_categorizer_does_not_rollup(tmp_path): + result = tmp_path / "result" + result.mkdir() + video = tmp_path / "v.mp4" + video.write_bytes(b"video") + + planted = result / "video_a" / "groom" + planted.mkdir(parents=True) + pd.DataFrame({"count": [7]}).to_excel(planted / "all_summary.xlsx", index=False) + + class FakeAnimal: + def __init__(self): + self.event_probability = {} + self.all_time = [] + + def prepare_analysis(self, *a, **k): + pass + + def acquire_information(self, *a, **k): + pass + + def craft_data(self): + pass + + def annotate_video(self, *a, **k): + pass + + def export_results(self, *a, **k): + pass + + with patch("LabGym.analyzebehavior.AnalyzeAnimal", FakeAnimal): + exit_code = main([ + "infer", + "--path-to-videos", str(video), + "--result-path", str(result), + ]) + assert exit_code == 0 + assert not (result / "groom_summary.xlsx").exists() + + +def test_rollup_overwrites_existing_root_summary(tmp_path): + result = tmp_path / "result" + behavior_dir = result / "video_a" / "groom" + behavior_dir.mkdir(parents=True) + pd.DataFrame({"count": [42]}).to_excel(behavior_dir / "all_summary.xlsx", index=False) + + stale = result / "groom_summary.xlsx" + pd.DataFrame({"count": [999]}).to_excel(stale, index=False) + + rollup_behavior_summaries( + str(result), + behaviornames_and_colors={"groom": ["#ffffff", "#000000"]}, + use_detector=False, + ) + + df = pd.read_excel(stale) + assert list(df["count"]) == [42] + From 0985ce273f40813f23982d1f9d3bea01a539bb81 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 12 Nov 2026 14:24:21 -0500 Subject: [PATCH 4/7] fix(cli): align command diagnostics and rollup coverage --- LabGym/cli.py | 16 ++-- LabGym/tests/test_cli.py | 158 +++++++++++++++++++++++++++------------ LabGym_CLI_Guide.md | 2 +- docs/changelog.md | 4 + 4 files changed, 123 insertions(+), 57 deletions(-) diff --git a/LabGym/cli.py b/LabGym/cli.py index bb163318..521a1e21 100644 --- a/LabGym/cli.py +++ b/LabGym/cli.py @@ -307,14 +307,14 @@ def validate_types_and_ranges(command_name, config): f"Parameter 'animal_number' must be a positive integer or dictionary (got {type(val).__name__}: {val!r})." ) - if command_name == "labgym infer": + if command_name == "labgym-cli infer": if isinstance(config.get('animal_number'), dict) and not config.get('use_detector'): raise CLIConfigError( "Structured 'animal_number' mapping is only supported when detector inference is enabled ('--use-detector'). " "For non-detector inference, specify a single positive integer." ) - if command_name == "labgym train categorizer": + if command_name == "labgym-cli train categorizer": net_type = config.get('network_type', 'combnet') if config.get('training_onfly'): if config.get('aug_methods'): @@ -527,7 +527,7 @@ def build_parser(): def handle_train_categorizer(args): config = resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -657,7 +657,7 @@ def handle_train_categorizer(args): def handle_train_detector(args): config = resolve_config( - command_name="labgym train detector", + command_name="labgym-cli train detector", defaults=TRAIN_DETECTOR_DEFAULTS, allowed_keys=ALLOWED_TRAIN_DETECTOR_KEYS, required_keys=REQUIRED_TRAIN_DETECTOR_KEYS, @@ -756,7 +756,7 @@ def handle_train_detector(args): def handle_test_categorizer(args): config = resolve_config( - command_name="labgym test categorizer", + command_name="labgym-cli test categorizer", defaults=TEST_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TEST_CATEGORIZER_KEYS, required_keys=REQUIRED_TEST_CATEGORIZER_KEYS, @@ -811,7 +811,7 @@ def handle_test_categorizer(args): def handle_test_detector(args): config = resolve_config( - command_name="labgym test detector", + command_name="labgym-cli test detector", defaults=TEST_DETECTOR_DEFAULTS, allowed_keys=ALLOWED_TEST_DETECTOR_KEYS, required_keys=REQUIRED_TEST_DETECTOR_KEYS, @@ -1140,7 +1140,7 @@ def rollup_behavior_summaries(result_path, behaviornames_and_colors, use_detecto def handle_infer(args): config = resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, @@ -1406,7 +1406,7 @@ def main(argv=None): return e.code if args.action in ['train', 'test'] and getattr(args, 'target', None) is None: - print(f"Error: 'labgym {args.action}' requires a target (e.g. 'categorizer' or 'detector').", file=sys.stderr) + print(f"Error: 'labgym-cli {args.action}' requires a target (e.g. 'categorizer' or 'detector').", file=sys.stderr) return 2 if not hasattr(args, 'func'): diff --git a/LabGym/tests/test_cli.py b/LabGym/tests/test_cli.py index 5d345a07..326c617c 100644 --- a/LabGym/tests/test_cli.py +++ b/LabGym/tests/test_cli.py @@ -105,12 +105,18 @@ def test_command_routing_infer(): assert args.result_path == "out/" -def test_missing_target_fails(): +def test_missing_target_fails(capsys): exit_code = main(["train"]) assert exit_code == 2 + captured = capsys.readouterr() + assert "labgym-cli train" in captured.err + assert "labgym " not in captured.err.replace("labgym-cli", "") exit_code_test = main(["test"]) assert exit_code_test == 2 + captured_test = capsys.readouterr() + assert "labgym-cli test" in captured_test.err + assert "labgym " not in captured_test.err.replace("labgym-cli", "") def test_precedence_defaults_only(): @@ -119,7 +125,7 @@ def test_precedence_defaults_only(): 'model_path': '/my/model', } resolved = resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -148,7 +154,7 @@ def test_precedence_yaml_overrides_defaults(tmp_path): cli_args = {} resolved = resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -181,7 +187,7 @@ def test_precedence_inline_overrides_yaml(tmp_path): 'background_free': True, } resolved = resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -213,7 +219,7 @@ def test_absent_inline_flags_never_overwrite_yaml(tmp_path): 'result_path': None, } resolved = resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, @@ -264,7 +270,7 @@ def test_paired_boolean_flag_overrides_yaml_false_with_true(tmp_path): yaml.dump({'path_to_videos': 'vid.mp4', 'result_path': 'out/', 'use_detector': False}, f) resolved = resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, @@ -280,7 +286,7 @@ def test_paired_boolean_flag_overrides_yaml_true_with_false(tmp_path): yaml.dump({'path_to_videos': 'vid.mp4', 'result_path': 'out/', 'use_detector': True}, f) resolved = resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, @@ -293,7 +299,7 @@ def test_paired_boolean_flag_overrides_yaml_true_with_false(tmp_path): def test_missing_config_file_raises_error(): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -314,7 +320,7 @@ def test_unknown_yaml_key_raises_error(tmp_path): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -328,7 +334,7 @@ def test_unknown_yaml_key_raises_error(tmp_path): def test_missing_required_keys_raises_error(): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -342,7 +348,7 @@ def test_missing_required_keys_raises_error(): def test_invalid_integer_bounds_raises_error(): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym train detector", + command_name="labgym-cli train detector", defaults=TRAIN_DETECTOR_DEFAULTS, allowed_keys=ALLOWED_TRAIN_DETECTOR_KEYS, required_keys=REQUIRED_TRAIN_DETECTOR_KEYS, @@ -354,13 +360,13 @@ def test_invalid_integer_bounds_raises_error(): 'iteration_num': -100 } ) - assert "Parameter 'iteration_num' for 'labgym train detector' must be a positive integer" in str(exc_info.value) + assert "Parameter 'iteration_num' for 'labgym-cli train detector' must be a positive integer" in str(exc_info.value) def test_invalid_channel_raises_error(): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -377,7 +383,7 @@ def test_invalid_channel_raises_error(): def test_invalid_network_type_raises_error(): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -398,7 +404,7 @@ def test_detector_training_does_not_require_categorizer_data(): 'model_path': 'models/detector', } resolved = resolve_config( - command_name="labgym train detector", + command_name="labgym-cli train detector", defaults=TRAIN_DETECTOR_DEFAULTS, allowed_keys=ALLOWED_TRAIN_DETECTOR_KEYS, required_keys=REQUIRED_TRAIN_DETECTOR_KEYS, @@ -416,7 +422,7 @@ def test_user_path_expansion(): 'model_path': '~/my_model', } resolved = resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -442,7 +448,7 @@ def test_cli_main_invalid_args_returns_code_2(): def test_booleans_rejected_for_integer_and_numeric_fields(): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, @@ -453,75 +459,75 @@ def test_booleans_rejected_for_integer_and_numeric_fields(): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, config_path=None, cli_args_dict={'data_path': 'd', 'model_path': 'm', 'dim_conv': True} ) - assert "Parameter 'dim_conv' for 'labgym train categorizer' must be a positive integer" in str(exc_info.value) + assert "Parameter 'dim_conv' for 'labgym-cli train categorizer' must be a positive integer" in str(exc_info.value) with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, config_path=None, cli_args_dict={'path_to_videos': ['v.mp4'], 'result_path': 'r', 'framewidth': True} ) - assert "Parameter 'framewidth' for 'labgym infer' must be a positive integer" in str(exc_info.value) + assert "Parameter 'framewidth' for 'labgym-cli infer' must be a positive integer" in str(exc_info.value) with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, config_path=None, cli_args_dict={'path_to_videos': ['v.mp4'], 'result_path': 'r', 'min_length': False} ) - assert "Parameter 'min_length' for 'labgym infer' must be a positive integer" in str(exc_info.value) + assert "Parameter 'min_length' for 'labgym-cli infer' must be a positive integer" in str(exc_info.value) def test_negative_values_rejected_for_framewidth_and_min_length(): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, config_path=None, cli_args_dict={'path_to_videos': ['v.mp4'], 'result_path': 'r', 'framewidth': -640} ) - assert "Parameter 'framewidth' for 'labgym infer' must be a positive integer" in str(exc_info.value) + assert "Parameter 'framewidth' for 'labgym-cli infer' must be a positive integer" in str(exc_info.value) with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, config_path=None, cli_args_dict={'path_to_videos': ['v.mp4'], 'result_path': 'r', 'min_length': -5} ) - assert "Parameter 'min_length' for 'labgym infer' must be a positive integer" in str(exc_info.value) + assert "Parameter 'min_length' for 'labgym-cli infer' must be a positive integer" in str(exc_info.value) with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, config_path=None, cli_args_dict={'path_to_videos': ['v.mp4'], 'result_path': 'r', 'ex_end': -1} ) - assert "Parameter 'ex_end' for 'labgym infer' must be a non-negative integer" in str(exc_info.value) + assert "Parameter 'ex_end' for 'labgym-cli infer' must be a non-negative integer" in str(exc_info.value) with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, @@ -542,14 +548,14 @@ def test_strings_rejected_where_lists_are_expected(tmp_path): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, config_path=str(cfg), cli_args_dict={} ) - assert "Parameter 'animal_kinds' for 'labgym infer' must be a list of strings" in str(exc_info.value) + assert "Parameter 'animal_kinds' for 'labgym-cli infer' must be a list of strings" in str(exc_info.value) with open(cfg, 'w') as f: yaml.dump({ @@ -560,14 +566,14 @@ def test_strings_rejected_where_lists_are_expected(tmp_path): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym train categorizer", + command_name="labgym-cli train categorizer", defaults=TRAIN_CATEGORIZER_DEFAULTS, allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, config_path=str(cfg), cli_args_dict={} ) - assert "Parameter 'aug_methods' for 'labgym train categorizer' must be a list of strings" in str(exc_info.value) + assert "Parameter 'aug_methods' for 'labgym-cli train categorizer' must be a list of strings" in str(exc_info.value) with open(cfg, 'w') as f: yaml.dump({ @@ -578,14 +584,14 @@ def test_strings_rejected_where_lists_are_expected(tmp_path): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, config_path=str(cfg), cli_args_dict={} ) - assert "Items in 'animal_kinds' for 'labgym infer' must be strings" in str(exc_info.value) + assert "Items in 'animal_kinds' for 'labgym-cli infer' must be strings" in str(exc_info.value) def test_infer_rejects_model_preprocessing_settings(tmp_path): @@ -599,14 +605,14 @@ def test_infer_rejects_model_preprocessing_settings(tmp_path): }, f) with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, config_path=str(cfg), cli_args_dict={} ) - assert f"Unknown configuration key(s) in '{cfg}' for command 'labgym infer': {forbidden_key}" in str(exc_info.value) + assert f"Unknown configuration key(s) in '{cfg}' for command 'labgym-cli infer': {forbidden_key}" in str(exc_info.value) def test_load_categorizer_metadata_success(tmp_path): @@ -839,7 +845,7 @@ def export_results(self, *a, **k): pass def test_path_to_videos_rejects_empty_strings(): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, @@ -850,7 +856,7 @@ def test_path_to_videos_rejects_empty_strings(): with pytest.raises(CLIConfigError) as exc_info: resolve_config( - command_name="labgym infer", + command_name="labgym-cli infer", defaults=INFER_DEFAULTS, allowed_keys=ALLOWED_INFER_KEYS, required_keys=REQUIRED_INFER_KEYS, @@ -1453,36 +1459,36 @@ def test_train_rejects_irrelevant_cross_command_parameters(tmp_path): def test_animal_number_scalar_and_structured_types_and_validation(): cli_args = {'animal_number': '2'} - res = resolve_config("labgym infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, cli_args) + res = resolve_config("labgym-cli infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, cli_args) assert res['animal_number'] == 2 assert isinstance(res['animal_number'], int) cli_args = {'animal_number': 5} - res = resolve_config("labgym infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, cli_args) + res = resolve_config("labgym-cli infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, cli_args) assert res['animal_number'] == 5 assert isinstance(res['animal_number'], int) cli_args = {'animal_number': 5, 'use_detector': True} - res = resolve_config("labgym infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, cli_args) + res = resolve_config("labgym-cli infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, cli_args) assert res['animal_number'] == 5 assert isinstance(res['animal_number'], int) cli_args = {'animal_number': '{"mouse": 2, "fly": 1}', 'use_detector': True} - res = resolve_config("labgym infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, cli_args) + res = resolve_config("labgym-cli infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, cli_args) assert res['animal_number'] == {"mouse": 2, "fly": 1} assert isinstance(res['animal_number'], dict) cli_args = {'animal_number': {"mouse": 3}, 'use_detector': True} - res = resolve_config("labgym infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, cli_args) + res = resolve_config("labgym-cli infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, cli_args) assert res['animal_number'] == {"mouse": 3} assert isinstance(res['animal_number'], dict) with pytest.raises(CLIConfigError) as exc_info: - resolve_config("labgym infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, {'animal_number': '{"mouse": 2}'}) + resolve_config("labgym-cli infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, {'animal_number': '{"mouse": 2}'}) assert "Structured 'animal_number' mapping is only supported when detector inference is enabled" in str(exc_info.value) with pytest.raises(CLIConfigError) as exc_info: - resolve_config("labgym infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, {'animal_number': {"mouse": 2}, 'use_detector': False}) + resolve_config("labgym-cli infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, {'animal_number': {"mouse": 2}, 'use_detector': False}) assert "Structured 'animal_number' mapping is only supported when detector inference is enabled" in str(exc_info.value) invalid_inputs = [ @@ -1503,7 +1509,7 @@ def test_animal_number_scalar_and_structured_types_and_validation(): ] for bad_val in invalid_inputs: with pytest.raises(CLIConfigError): - resolve_config("labgym infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, {'animal_number': bad_val, 'use_detector': True}) + resolve_config("labgym-cli infer", INFER_DEFAULTS, ALLOWED_INFER_KEYS, set(), None, {'animal_number': bad_val, 'use_detector': True}) def test_animal_number_structured_mapping_without_detector_fails_exit_2(tmp_path): @@ -1836,6 +1842,62 @@ def export_results(self, *a, **k): assert not (result / "groom_summary.xlsx").exists() +def test_handle_infer_with_categorizer_creates_root_behavior_summary(tmp_path): + cat_dir = tmp_path / "cat" + cat_dir.mkdir() + (cat_dir / "model_parameters.txt").write_text( + "classnames,dim_conv,channel,time_step,network,inner_code,std," + "background_free,black_background,behavior_kind,social_distance,color_code\n" + "groom,64,1,15,0,0,0,0,0,0,0,1\n" + ) + video = tmp_path / "video_a.mp4" + video.write_bytes(b"video") + out = tmp_path / "out" + + class FakeAnimal: + def __init__(self): + self.event_probability = {0: [["groom", 0.95]]} + self.all_time = [0.1] + self._video_path = None + self._result_path = None + + def prepare_analysis(self, video_path, result_path, *a, **k): + self._video_path = video_path + self._result_path = result_path + + def acquire_information(self, *a, **k): + pass + + def craft_data(self): + pass + + def categorize_behaviors(self, *a, **k): + pass + + def annotate_video(self, *a, **k): + pass + + def export_results(self, *a, **k): + stem = os.path.splitext(os.path.basename(self._video_path))[0] + behavior_dir = Path(self._result_path) / stem / "groom" + behavior_dir.mkdir(parents=True, exist_ok=True) + pd.DataFrame({"count": [3]}).to_excel(behavior_dir / "all_summary.xlsx", index=False) + + with patch("LabGym.analyzebehavior.AnalyzeAnimal", FakeAnimal), patch("LabGym.tools.plot_events"): + exit_code = main([ + "infer", + "--path-to-videos", str(video), + "--result-path", str(out), + "--path-to-categorizer", str(cat_dir), + ]) + + assert exit_code == 0 + root_summary = out / "groom_summary.xlsx" + assert root_summary.exists() + df = pd.read_excel(root_summary) + assert list(df["count"]) == [3] + + def test_rollup_overwrites_existing_root_summary(tmp_path): result = tmp_path / "result" behavior_dir = result / "video_a" / "groom" diff --git a/LabGym_CLI_Guide.md b/LabGym_CLI_Guide.md index d3c3c92f..53c34729 100644 --- a/LabGym_CLI_Guide.md +++ b/LabGym_CLI_Guide.md @@ -130,7 +130,7 @@ Headless animal tracking and behavior classification on videos or static images. * **Required Parameters**: * `--path-to-videos` (`path_to_videos`): One or more video file paths or directories - * `--result-path` (`result_path`): Directory to write tracking and classification results + * `--result-path` (`result_path`): Directory to write tracking and classification results. Reusing an existing directory can include leftover per-video folders in a new root summary roll-up; if a behavior has no new per-video summaries, an outdated root `*_summary.xlsx` file can remain unchanged. Use a clean result directory for each run. * **Model Selection**: * `--path-to-categorizer` (`path_to_categorizer`): Path to trained Categorizer directory diff --git a/docs/changelog.md b/docs/changelog.md index 98166ee4..a8aba953 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased +### What's Changed +* Breaking: the headless console entry point is now `labgym-cli` (formerly `labgym`). `LabGym` remains the desktop GUI command. + ## v3.1.2 ### What's Changed From 29a2a10f62b74a0cc34b50aa1f449802875d01ba Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 12 Nov 2026 14:37:43 -0500 Subject: [PATCH 5/7] fix(cli): support background contrast selection --- LabGym/cli.py | 22 ++++- LabGym/tests/test_cli.py | 193 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 213 insertions(+), 2 deletions(-) diff --git a/LabGym/cli.py b/LabGym/cli.py index 521a1e21..065fb7ca 100644 --- a/LabGym/cli.py +++ b/LabGym/cli.py @@ -99,6 +99,7 @@ class CLIConfigError(Exception): 'ex_start': 0, 'ex_end': None, 'stable_illumination': True, + 'animal_vs_bg': 0, 'ID_colors': [(255, 255, 255)], 'parameter_to_analyze': [], 'uncertain': 0.0, @@ -189,6 +190,14 @@ def validate_types_and_ranges(command_name, config): f"Parameter 'channel' must be 1 or 3 (got {val!r})." ) + if 'animal_vs_bg' in config and config['animal_vs_bg'] is not None: + val = config['animal_vs_bg'] + if isinstance(val, bool) or not isinstance(val, int) or val not in (0, 1, 2): + raise CLIConfigError( + f"Parameter 'animal_vs_bg' must be 0, 1, or 2 " + f"(0=animal brighter than background, 1=animal darker, 2=hard to tell; got {val!r})." + ) + for level_key in ['level_conv', 'level_tconv']: if level_key in config and config[level_key] is not None: val = config[level_key] @@ -313,6 +322,11 @@ def validate_types_and_ranges(command_name, config): "Structured 'animal_number' mapping is only supported when detector inference is enabled ('--use-detector'). " "For non-detector inference, specify a single positive integer." ) + if config.get('use_detector') and config.get('animal_vs_bg', 0) != 0: + raise CLIConfigError( + "Parameter 'animal_vs_bg' applies only to background-subtraction inference. " + "With detector inference enabled ('--use-detector'), leave 'animal_vs_bg' at the default 0." + ) if command_name == "labgym-cli train categorizer": net_type = config.get('network_type', 'combnet') @@ -512,6 +526,12 @@ def build_parser(): infer_parser.add_argument("--ex-start", type=int, default=None, help="Extraction start frame number") infer_parser.add_argument("--ex-end", type=int, default=None, help="Extraction end frame number") infer_parser.add_argument("--stable-illumination", action=argparse.BooleanOptionalAction, default=None, help="Illumination stability") + infer_parser.add_argument( + "--animal-vs-bg", + type=int, + default=None, + help="Animal vs background contrast for background subtraction: 0=brighter (default), 1=darker, 2=hard to tell", + ) infer_parser.add_argument("--ID-colors", type=str, default=None, help="Colormap sequence mapping IDs to colors") infer_parser.add_argument("--parameter-to-analyze", type=str, nargs="+", default=None, help="Kinematic parameters to extract") infer_parser.add_argument("--uncertain", type=float, default=None, help="Uncertainty threshold") @@ -1297,7 +1317,7 @@ def handle_infer(args): categorize_behavior=categorize_behavior, animation_analyzer=cat_meta['animation_analyzer'], path_background=config['background_path'], autofind_t=config['autofind_t'], t=t_val, duration=config['duration'], ex_start=ex_start_val, ex_end=ex_end_val, - length=cat_meta['length'], animal_vs_bg=0 + length=cat_meta['length'], animal_vs_bg=config['animal_vs_bg'] ) if behavior_mode == 0: AA.acquire_information(background_free=cat_meta['background_free'], black_background=cat_meta['black_background']) diff --git a/LabGym/tests/test_cli.py b/LabGym/tests/test_cli.py index 326c617c..f6281d55 100644 --- a/LabGym/tests/test_cli.py +++ b/LabGym/tests/test_cli.py @@ -596,7 +596,7 @@ def test_strings_rejected_where_lists_are_expected(tmp_path): def test_infer_rejects_model_preprocessing_settings(tmp_path): cfg = tmp_path / "bad_infer.yaml" - for forbidden_key in ['background_free', 'black_background', 'behavior_mode', 'animal_vs_bg', 'social_distance', 'color_costar']: + for forbidden_key in ['background_free', 'black_background', 'behavior_mode', 'social_distance', 'color_costar']: with open(cfg, 'w') as f: yaml.dump({ 'path_to_videos': ['v.mp4'], @@ -615,6 +615,197 @@ def test_infer_rejects_model_preprocessing_settings(tmp_path): assert f"Unknown configuration key(s) in '{cfg}' for command 'labgym-cli infer': {forbidden_key}" in str(exc_info.value) +def test_animal_vs_bg_cli_parsing(): + parser = build_parser() + args = parser.parse_args([ + "infer", + "--path-to-videos", "vid.mp4", + "--result-path", "out/", + "--animal-vs-bg", "1", + ]) + assert args.animal_vs_bg == 1 + + args_default = parser.parse_args([ + "infer", + "--path-to-videos", "vid.mp4", + "--result-path", "out/", + ]) + assert args_default.animal_vs_bg is None + + +def test_animal_vs_bg_yaml_default_and_cli_precedence(tmp_path): + cfg = tmp_path / "infer_avb.yaml" + with open(cfg, 'w') as f: + yaml.dump({ + 'path_to_videos': ['vid.mp4'], + 'result_path': 'out/', + 'animal_vs_bg': 2, + }, f) + + from_yaml = resolve_config( + command_name="labgym-cli infer", + defaults=INFER_DEFAULTS, + allowed_keys=ALLOWED_INFER_KEYS, + required_keys=REQUIRED_INFER_KEYS, + config_path=str(cfg), + cli_args_dict={'animal_vs_bg': None}, + ) + assert from_yaml['animal_vs_bg'] == 2 + + overridden = resolve_config( + command_name="labgym-cli infer", + defaults=INFER_DEFAULTS, + allowed_keys=ALLOWED_INFER_KEYS, + required_keys=REQUIRED_INFER_KEYS, + config_path=str(cfg), + cli_args_dict={'animal_vs_bg': 1}, + ) + assert overridden['animal_vs_bg'] == 1 + + defaults_only = resolve_config( + command_name="labgym-cli infer", + defaults=INFER_DEFAULTS, + allowed_keys=ALLOWED_INFER_KEYS, + required_keys=REQUIRED_INFER_KEYS, + config_path=None, + cli_args_dict={'path_to_videos': ['vid.mp4'], 'result_path': 'out/', 'animal_vs_bg': None}, + ) + assert defaults_only['animal_vs_bg'] == 0 + + +def test_animal_vs_bg_rejects_invalid_values(): + for bad in (3, -1, True, "1"): + with pytest.raises(CLIConfigError) as exc_info: + resolve_config( + command_name="labgym-cli infer", + defaults=INFER_DEFAULTS, + allowed_keys=ALLOWED_INFER_KEYS, + required_keys=REQUIRED_INFER_KEYS, + config_path=None, + cli_args_dict={ + 'path_to_videos': ['vid.mp4'], + 'result_path': 'out/', + 'animal_vs_bg': bad, + }, + ) + assert "animal_vs_bg" in str(exc_info.value) + assert "0, 1, or 2" in str(exc_info.value) + + +def test_animal_vs_bg_accepted_in_yaml(tmp_path): + cfg = tmp_path / "infer_avb_ok.yaml" + with open(cfg, 'w') as f: + yaml.dump({ + 'path_to_videos': ['vid.mp4'], + 'result_path': 'out/', + 'animal_vs_bg': 1, + }, f) + resolved = resolve_config( + command_name="labgym-cli infer", + defaults=INFER_DEFAULTS, + allowed_keys=ALLOWED_INFER_KEYS, + required_keys=REQUIRED_INFER_KEYS, + config_path=str(cfg), + cli_args_dict={}, + ) + assert resolved['animal_vs_bg'] == 1 + + +def test_animal_vs_bg_detector_rejects_nonzero(): + with pytest.raises(CLIConfigError) as exc_info: + resolve_config( + command_name="labgym-cli infer", + defaults=INFER_DEFAULTS, + allowed_keys=ALLOWED_INFER_KEYS, + required_keys=REQUIRED_INFER_KEYS, + config_path=None, + cli_args_dict={ + 'path_to_videos': ['vid.mp4'], + 'result_path': 'out/', + 'use_detector': True, + 'animal_vs_bg': 1, + }, + ) + assert "animal_vs_bg" in str(exc_info.value) + assert "background-subtraction" in str(exc_info.value) + + ok = resolve_config( + command_name="labgym-cli infer", + defaults=INFER_DEFAULTS, + allowed_keys=ALLOWED_INFER_KEYS, + required_keys=REQUIRED_INFER_KEYS, + config_path=None, + cli_args_dict={ + 'path_to_videos': ['vid.mp4'], + 'result_path': 'out/', + 'use_detector': True, + 'animal_vs_bg': 0, + }, + ) + assert ok['animal_vs_bg'] == 0 + + +def test_handle_infer_passes_animal_vs_bg_to_prepare_analysis(tmp_path): + v = tmp_path / "vid.mp4" + v.write_bytes(b"video") + out = tmp_path / "out" + seen = {} + + class FakeAnimal: + def __init__(self): + self.event_probability = {} + self.all_time = [] + + def prepare_analysis(self, *a, **k): + seen['animal_vs_bg'] = k.get('animal_vs_bg') + + def acquire_information(self, *a, **k): + pass + + def craft_data(self): + pass + + def annotate_video(self, *a, **k): + pass + + def export_results(self, *a, **k): + pass + + with patch('LabGym.analyzebehavior.AnalyzeAnimal', FakeAnimal): + exit_code = main([ + "infer", + "--path-to-videos", str(v), + "--result-path", str(out), + "--animal-vs-bg", "2", + ]) + assert exit_code == 0 + assert seen['animal_vs_bg'] == 2 + + +def test_handle_infer_detector_nonzero_animal_vs_bg_exits_2(tmp_path, capsys): + det_dir = tmp_path / "det" + det_dir.mkdir() + (det_dir / "model_parameters.txt").write_text( + json.dumps({"animal_mapping": {"0": "mouse"}, "inferencing_framesize": 480}) + ) + v = tmp_path / "v.mp4" + v.write_bytes(b"video") + out = tmp_path / "out_never" + + exit_code = main([ + "infer", + "--path-to-videos", str(v), + "--result-path", str(out), + "--use-detector", + "--path-to-detector", str(det_dir), + "--animal-vs-bg", "1", + ]) + assert exit_code == 2 + captured = capsys.readouterr() + assert "animal_vs_bg" in captured.err + assert not out.exists() + + def test_load_categorizer_metadata_success(tmp_path): cat_dir = tmp_path / "my_categorizer" cat_dir.mkdir() From be2c125fd1d540b3ed434df1dcffc25fec618153 Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 12 Nov 2026 14:43:12 -0500 Subject: [PATCH 6/7] docs(cli): document headless workflows --- LabGym_CLI_Guide.md | 2 +- README.md | 2 ++ docs/installation/index.md | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/LabGym_CLI_Guide.md b/LabGym_CLI_Guide.md index 53c34729..980a8efc 100644 --- a/LabGym_CLI_Guide.md +++ b/LabGym_CLI_Guide.md @@ -157,7 +157,7 @@ Headless animal tracking and behavior classification on videos or static images. * `--decode-extraction` / `--no-decode-extraction`: Extract start/end frames from filenames * `--stable-illumination` / `--no-stable-illumination`: Illumination stability flag (default: True) * `--ID-colors` (`ID_colors`): List of RGB color tuples for animal IDs - * `--parameter-to-analyze` (`parameter_to_analyze`): Kinematic parameters to quantify + * `--parameter-to-analyze` (`parameter_to_analyze`): Kinematic parameters to quantify. If this list is empty (the default), the current run writes no per-video summary workbook, so a Categorizer produces no root `*_summary.xlsx` roll-up from current-run data. Reused result directories can still contain or reuse earlier summaries. * `--uncertain` (`uncertain`): Probability difference gap for uncertainty threshold (default: 0.0) * `--min-length` (`min_length`): Minimum behavior duration in frames * `--show-legend` / `--no-show-legend`: Render behavior legends on output videos (default: True) diff --git a/README.md b/README.md index 18ab4b7e..a7fb7cfe 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,8 @@ Cite LabGym: ## Overview +`LabGym` launches the desktop GUI. `labgym-cli` is the headless command-line interface for training, testing, and inference. See the [LabGym CLI Guide](LabGym_CLI_Guide.md) for command syntax and configuration. + You can use LabGym via its user interface (no coding knowledge needed), or via command prompt. See [**Extended User Guide**](https://github.com/yujiahu415/LabGym/blob/master/LabGym_extended_user_guide.pdf) for details. You may also refer to this [**Practical "How To" Guide**](https://github.com/yujiahu415/LabGym/blob/master/LabGym_practical_guide.pdf) with layman language and examples. diff --git a/docs/installation/index.md b/docs/installation/index.md index f4d21a58..5ce876f9 100644 --- a/docs/installation/index.md +++ b/docs/installation/index.md @@ -11,6 +11,8 @@ We recommend that you follow the instructions below for your operating system to The simplest way to install LabGym is using `pip`. You may also use `pipx` or `Anaconda` to install LabGym in an isolated environment. For more information, please see the system-specific instructions below. +After installation, `LabGym` launches the desktop GUI. For scripted or HPC workflows, use `labgym-cli` (headless). See the [LabGym CLI Guide](https://github.com/umyelab/LabGym/blob/master/LabGym_CLI_Guide.md) for details. + ```{toctree} windows macos From aa942169095e55741ef5a621c8f812b3e333b2ff Mon Sep 17 00:00:00 2001 From: Bobby Tomlinson Date: Thu, 12 Nov 2026 15:04:52 -0500 Subject: [PATCH 7/7] docs(cli): describe background contrast option --- LabGym_CLI_Guide.md | 1 + 1 file changed, 1 insertion(+) diff --git a/LabGym_CLI_Guide.md b/LabGym_CLI_Guide.md index 980a8efc..5ee79305 100644 --- a/LabGym_CLI_Guide.md +++ b/LabGym_CLI_Guide.md @@ -156,6 +156,7 @@ Headless animal tracking and behavior classification on videos or static images. * `--ex-end` (`ex_end`): Extraction end frame number * `--decode-extraction` / `--no-decode-extraction`: Extract start/end frames from filenames * `--stable-illumination` / `--no-stable-illumination`: Illumination stability flag (default: True) + * `--animal-vs-bg` (`animal_vs_bg`): Animal-to-background contrast for background-subtraction inference: `0` = animal brighter than background, `1` = animal darker than background, `2` = hard to tell. Default: `0`. This option is not used with `--use-detector`; a nonzero value in Detector mode is rejected. * `--ID-colors` (`ID_colors`): List of RGB color tuples for animal IDs * `--parameter-to-analyze` (`parameter_to_analyze`): Kinematic parameters to quantify. If this list is empty (the default), the current run writes no per-video summary workbook, so a Categorizer produces no root `*_summary.xlsx` roll-up from current-run data. Reused result directories can still contain or reuse earlier summaries. * `--uncertain` (`uncertain`): Probability difference gap for uncertainty threshold (default: 0.0)