Skip to content

feat(cli): add headless LabGym workflows - #358

Merged
yujiahu415 merged 21 commits into
umyelab:masterfrom
AL3XPI:feature/headless-cli
Nov 13, 2026
Merged

yujiahu415 merged 21 commits into
umyelab:masterfrom
AL3XPI:feature/headless-cli

Conversation

@AL3XPI

@AL3XPI AL3XPI commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Summary

Primary implementation: Alexander Chumak

Follow-up CLI integration, compatibility, testing, and documentation: Bobby Tomlinson

This PR adds a dedicated headless command-line interface (labgym-cli) to LabGym for training, evaluating, and running behavioral inference without launching or importing the desktop GUI (wxPython). It supports reproducible batch workflows through a three-tier configuration contract (built-in defaults -> workflow YAML -> inline CLI flags), strict pre-execution schema validation, and GUI-compatible analysis outputs.


Changes

Dedicated Headless Entry Point & Command Hierarchy

Problem
Previously, LabGym’s console entry point launched the desktop wxPython GUI, preventing users from running training, evaluation, or inference jobs directly in headless terminal environments, remote SSH sessions, or cluster batch scripts (sbatch). Additionally, using labgym as the CLI command collided with the LabGym GUI entry point on case-insensitive macOS and Windows filesystems.

Implementation
Added the labgym-cli entry point in pyproject.toml and cli.py while preserving LabGym as the desktop GUI command. Structured the CLI into explicit action/target subcommands (labgym-cli train categorizer, labgym-cli train detector, labgym-cli test categorizer, labgym-cli test detector, and labgym-cli infer). Running bare labgym-cli or --help prints usage information to stdout and exits cleanly (0) without importing or launching wx.

Impact
Researchers can execute LabGym workflows in headless and HPC environments without display servers (DISPLAY / Xvfb) while keeping the existing LabGym desktop workflow unchanged.


Three-Tier Configuration Precedence & Fail-Fast Validation

Problem
Batch and cluster workflows require reusable baseline configuration files combined with per-job inline overrides (such as array-task output directories or hyperparameter sweeps). Without strict schema validation, mistyped YAML keys, missing paths, or incompatible parameter combinations could be silently ignored or fail late after initializing GPU resources.

Implementation
Implemented a three-tier configuration merger (built-in defaults -> optional --config YAML -> explicit inline CLI flags) in cli.py using sentinel parser defaults so unspecified flags never overwrite YAML values. Added kebab-case inline flags mapped to snake_case YAML/Python keys, paired boolean flags (--flag / --no-flag), and platform-appropriate home-directory (~) path expansion. Enforced pre-execution validation that rejects unknown YAML keys, unreadable configuration files, invalid parameter values, missing dataset/model files, invalid COCO JSON annotations, and incompatible mode combinations with clear messages on stderr and exit code 2 before starting compute.

Impact
Users can combine shared YAML workflow files with targeted inline CLI overrides, and invalid configurations fail immediately with predictable exit codes (0 success, 1 runtime error, 2 configuration/usage error) suitable for automated scripts.


Headless Training, Evaluation, & GUI-Compatible Inference

Problem
Headless workflows needed to support both Categorizer and Detector pipelines while protecting trained model architecture settings during inference and producing output artifacts compatible with downstream LabGym analysis tools such as Mine Results.

Implementation
Wired train and test subcommands for Categorizers and Detectors (Training and Detector in core.py and detectors.py), and implemented headless video/image inference via AnalyzeAnimal in analyzebehavior.py and AnalyzeAnimalDetector in analyzebehavior_dt.py. During inference, trained Categorizer metadata (model_parameters.txt) is read as authoritative so incompatible architecture overrides are rejected, structured animal_number kind-to-count mappings are restricted to detector inference, animal_vs_bg contrast selection is supported for non-detector background subtraction, and root *_summary.xlsx roll-ups are generated from per-video summaries when requested analysis parameters produce those summaries. Updated LabGym_CLI_Guide.md, README.md, and docs/installation/index.md.

Impact
Users can train, test, and run inference headlessly from start to finish while preserving full compatibility with trained LabGym models and downstream GUI analysis workflows.


Python 3.9 ReportLab Compatibility

Problem
LabGym supports Python 3.9, but ReportLab 5.1.0 can be installed under Python 3.9 and then fails at import time because it requires Python 3.10 or newer.

Implementation
Pinned ReportLab to >=5.0.0,<5.1 and updated the packaging assertion for that dependency declaration.

Impact
Keeps the supported Python 3.9 environment able to import ReportLab and restores the Python 3.9 CI path without changing LabGym’s supported Python-version policy.


Testing

Focused automated validation and package checks passed:

  • 70 passed in LabGym/tests/test_cli.py (python -m pytest LabGym/tests/test_cli.py -q --tb=short -p no:cacheprovider).
  • Full CI: Python 3.9 and 3.10 test sessions passed on Ubuntu and Windows.
  • Coverage includes:
    • Separate entry points (LabGym vs labgym-cli) and clean bare/--help execution without importing wx.
    • Three-tier configuration precedence (defaults -> YAML -> CLI), paired boolean flags, home-directory (~) expansion, and structured animal_number / ID_colors / specific_behaviors parsing.
    • Fail-fast exit code 2 validation for missing/unreadable --config files, unknown YAML keys, invalid parameter ranges, incompatible training/inference combinations, invalid COCO annotations, and missing model artifacts without leaving partial output directories.
    • Authoritative model_parameters.txt metadata inheritance and protection during inference.
    • animal_vs_bg background contrast selection (0, 1, 2) for non-detector inference.
    • Root *_summary.xlsx inference roll-ups across videos and result-directory reuse behavior.
    • Mocked workflow smoke tests covering Categorizer and Detector training, testing, and inference, plus isolated subprocess execution verifying zero wx imports.
  • Package installation verification:
    • Installed in a fresh Python 3.10 macOS Conda environment and confirmed LabGym and labgym-cli install as distinct wrappers and labgym-cli --help exits 0.

Known limitations

  • labgym-cli covers training, testing, and inference workflows; interactive preprocessing utilities (such as interactive video cropping/trimming and drawing environment landmarks) and post-hoc statistical data-mining dialogs remain part of the LabGym desktop GUI.

AL3XPI and others added 21 commits October 17, 2026 22:02

@btmlnsn btmlnsn left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I completed a quick integration re-review of the headless CLI surface and our follow-up changes.
I checked the console-entry-point behavior, headless GUI isolation, configuration validation, inference-output parity with the GUI workflow, Python 3.9 dependency compatibility, focused CLI coverage, and the fresh-install smoke check.

Comment thread LabGym/cli.py
return deduped


def rollup_behavior_summaries(result_path, behaviornames_and_colors, use_detector=False, animal_kinds=None):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed against the GUI inference workflow. The CLI intentionally follows the GUI’s per-video summary layout, sorted result-folder scan, root workbook naming, and overwrite behavior so Mine Results can consume the same outputs.

Comment thread LabGym_CLI_Guide.md
* `--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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed this against the GUI background-subtraction control. Values 0, 1, and 2 preserve the existing brighter, darker, and hard-to-tell contrast choices; nonzero values remain invalid for detector inference.

Comment thread pyproject.toml
'PyYAML',
'tomli',
'reportlab>=5.0.0',
'reportlab>=5.0.0,<5.1',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This preserves LabGym’s existing Python 3.9 support. ReportLab 5.1.0 resolves on Python 3.9 but fails during import because it now requires Python 3.10; the upper bound keeps CI on the last Python 3.9-importable release line.

Comment thread pyproject.toml

[project.scripts]
LabGym='LabGym.__main__:main'
labgym-cli='LabGym.cli:main'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the entry-point split. LabGym remains the GUI command, while labgym-cli is the headless command. This avoids the case-insensitive filename collision between LabGym and labgym on macOS and Windows. I also verified both installed as distinct wrappers in a fresh macOS environment.

@yujiahu415
yujiahu415 merged commit 1750a94 into umyelab:master Nov 13, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants