diff --git a/LabGym/cli.py b/LabGym/cli.py new file mode 100644 index 00000000..065fb7ca --- /dev/null +++ b/LabGym/cli.py @@ -0,0 +1,1451 @@ +''' +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. +''' + +import argparse +import json +import logging +import os +import sys +import yaml + +logger = logging.getLogger(__name__) + +class CLIConfigError(Exception): + """Raised when CLI or YAML configuration validation fails.""" + pass + + +TRAIN_CATEGORIZER_DEFAULTS = { + 'network_type': 'combnet', + 'out_path': None, + 'out_folder': None, + 'dim_conv': 64, + 'dim_tconv': 32, + 'channel': 1, + 'time_step': 15, + 'level_conv': 2, + 'level_tconv': 1, + 'aug_methods': [], + 'augvalid': True, + 'include_bodyparts': True, + 'std': 0.0, + 'background_free': True, + 'black_background': True, + 'behavior_mode': 0, + 'social_distance': 0.0, + 'color_costar': False, + 'training_onfly': False, +} +REQUIRED_TRAIN_CATEGORIZER_KEYS = {'data_path', 'model_path'} +ALLOWED_TRAIN_CATEGORIZER_KEYS = set(TRAIN_CATEGORIZER_DEFAULTS.keys()) | REQUIRED_TRAIN_CATEGORIZER_KEYS + +AUG_METHOD_MAP = { + 'random rotation': 'random rotation', + 'horizontal flipping': 'horizontal flipping', + 'vertical flipping': 'vertical flipping', + 'random brightening': 'random brightening', + 'random dimming': 'random dimming', + 'random shearing': 'random shearing', + 'random rescaling': 'random rescaling', + 'random deletion': 'random deletion', + 'rotation': 'random rotation', + 'flipping': 'horizontal flipping', + 'brightening': 'random brightening', + 'dimming': 'random dimming', + 'shearing': 'random shearing', + 'rescaling': 'random rescaling', + 'deletion': 'random deletion', +} + +TRAIN_DETECTOR_DEFAULTS = { + 'iteration_num': 200, + 'inference_size': 480, +} +REQUIRED_TRAIN_DETECTOR_KEYS = {'path_to_annotation', 'path_to_trainingimages', 'model_path'} +ALLOWED_TRAIN_DETECTOR_KEYS = set(TRAIN_DETECTOR_DEFAULTS.keys()) | REQUIRED_TRAIN_DETECTOR_KEYS + +TEST_CATEGORIZER_DEFAULTS = { + 'result_path': None, +} +REQUIRED_TEST_CATEGORIZER_KEYS = {'groundtruth_path', 'model_path'} +ALLOWED_TEST_CATEGORIZER_KEYS = set(TEST_CATEGORIZER_DEFAULTS.keys()) | REQUIRED_TEST_CATEGORIZER_KEYS + +TEST_DETECTOR_DEFAULTS = {} +REQUIRED_TEST_DETECTOR_KEYS = {'path_to_annotation', 'path_to_testingimages', 'model_path', 'result_path'} +ALLOWED_TEST_DETECTOR_KEYS = set(TEST_DETECTOR_DEFAULTS.keys()) | REQUIRED_TEST_DETECTOR_KEYS + +INFER_DEFAULTS = { + 'path_to_categorizer': None, + 'path_to_detector': None, + 'use_detector': False, + 'background_path': None, + 'framewidth': None, + 'delta': 10000.0, + 'animal_kinds': ['animal'], + 'animal_to_include': [], + 'behavior_to_include': ['all'], + 'detector_batch': 1, + 'detection_threshold': 0.0, + 'decode_animalnumber': False, + 'animal_number': None, + 'autofind_t': False, + 'decode_t': False, + 't': 0.0, + 'duration': 0.0, + 'decode_extraction': False, + 'ex_start': 0, + 'ex_end': None, + 'stable_illumination': True, + 'animal_vs_bg': 0, + 'ID_colors': [(255, 255, 255)], + 'parameter_to_analyze': [], + 'uncertain': 0.0, + 'min_length': None, + 'show_legend': True, + 'normalize_distance': True, + 'correct_ID': False, + 'specific_behaviors': {}, +} +REQUIRED_INFER_KEYS = {'path_to_videos', 'result_path'} +ALLOWED_INFER_KEYS = ( + set(INFER_DEFAULTS.keys()) + | REQUIRED_INFER_KEYS + | {'correct_id', 'id_colors'} +) + +PATH_KEYS = { + 'data_path', 'model_path', 'out_path', 'out_folder', + 'path_to_annotation', 'path_to_trainingimages', 'path_to_testingimages', + 'groundtruth_path', 'result_path', 'path_to_categorizer', 'path_to_detector', + 'background_path' +} + + +def parse_json_or_val(v): + if v is None: + return None + if isinstance(v, str) and (v.startswith('{') or v.startswith('[')): + try: + return json.loads(v) + except Exception: + pass + return v + + +def validate_types_and_ranges(command_name, config): + for path_key in PATH_KEYS: + if path_key in config and config[path_key] is not None: + val = config[path_key] + if isinstance(val, bool) or not isinstance(val, str) or not val.strip(): + raise CLIConfigError( + f"Parameter '{path_key}' must be a non-empty string path (got {type(val).__name__}: {val!r})." + ) + + if 'path_to_videos' in config and config['path_to_videos'] is not None: + val = config['path_to_videos'] + if isinstance(val, bool) or not isinstance(val, list) or len(val) == 0: + raise CLIConfigError( + f"Parameter 'path_to_videos' must be a non-empty list of video paths (got {val!r})." + ) + for item in val: + if isinstance(item, bool) or not isinstance(item, str) or not item.strip(): + raise CLIConfigError( + f"Items in 'path_to_videos' must be non-empty string paths (got {item!r})." + ) + + pos_int_keys = [ + 'dim_conv', 'dim_tconv', 'iteration_num', 'inference_size', 'detector_batch', + 'framewidth', 'min_length' + ] + for key in pos_int_keys: + if key in config and config[key] is not None: + val = config[key] + if isinstance(val, bool) or not isinstance(val, int) or val <= 0: + raise CLIConfigError( + f"Parameter '{key}' for '{command_name}' must be a positive integer (got {val!r})." + ) + + non_neg_int_keys = ['time_step', 'ex_start', 'ex_end'] + for key in non_neg_int_keys: + if key in config and config[key] is not None: + val = config[key] + if isinstance(val, bool) or not isinstance(val, int) or val < 0: + raise CLIConfigError( + f"Parameter '{key}' for '{command_name}' must be a non-negative integer (got {val!r})." + ) + + if config.get('ex_start') is not None and config.get('ex_end') is not None: + if config['ex_end'] < config['ex_start']: + raise CLIConfigError( + f"Parameter 'ex_end' ({config['ex_end']}) must be greater than or equal to 'ex_start' ({config['ex_start']})." + ) + + if 'channel' in config and config['channel'] is not None: + val = config['channel'] + if isinstance(val, bool) or not isinstance(val, int) or val not in (1, 3): + raise CLIConfigError( + 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] + if isinstance(val, bool) or not isinstance(val, int) or not (1 <= val <= 5): + raise CLIConfigError( + f"Parameter '{level_key}' must be an integer between 1 and 5 (got {val!r})." + ) + + if 'network_type' in config and config['network_type'] is not None: + val = config['network_type'] + valid_nets = {'combnet', 'pattern_recognizer', 'animation_analyzer', 'combined_network'} + if isinstance(val, bool) or not isinstance(val, str) or val not in valid_nets: + raise CLIConfigError( + f"Invalid network_type '{val}'. Choose from: {sorted(valid_nets)}." + ) + + if 'behavior_mode' in config and config['behavior_mode'] is not None: + val = config['behavior_mode'] + if isinstance(val, bool) or not isinstance(val, int) or not (0 <= val <= 3): + raise CLIConfigError( + f"Parameter 'behavior_mode' must be an integer between 0 and 3 (got {val!r})." + ) + + list_str_keys = [ + 'aug_methods', 'animal_kinds', 'animal_to_include', + 'behavior_to_include', 'parameter_to_analyze' + ] + for key in list_str_keys: + if key in config and config[key] is not None: + val = config[key] + if isinstance(val, bool) or not isinstance(val, list): + raise CLIConfigError( + f"Parameter '{key}' for '{command_name}' must be a list of strings (got {type(val).__name__}: {val!r})." + ) + for item in val: + if isinstance(item, bool) or not isinstance(item, str): + raise CLIConfigError( + f"Items in '{key}' for '{command_name}' must be strings (got {item!r})." + ) + + if 'aug_methods' in config and config['aug_methods'] is not None: + for item in config['aug_methods']: + if item not in AUG_METHOD_MAP: + raise CLIConfigError( + f"Invalid augmentation method '{item}'. Choose from: {sorted(set(AUG_METHOD_MAP.values()))}." + ) + + float_keys = ['std', 'social_distance', 't', 'duration', 'delta'] + for key in float_keys: + if key in config and config[key] is not None: + val = config[key] + if isinstance(val, bool) or not isinstance(val, (int, float)) or val < 0: + raise CLIConfigError( + f"Parameter '{key}' must be a non-negative float (got {val!r})." + ) + + for thresh_key in ['detection_threshold', 'uncertain']: + if thresh_key in config and config[thresh_key] is not None: + val = config[thresh_key] + if isinstance(val, bool) or not isinstance(val, (int, float)) or not (0.0 <= float(val) <= 1.0): + raise CLIConfigError( + f"Parameter '{thresh_key}' must be between 0.0 and 1.0 (got {val!r})." + ) + + bool_keys = [ + 'training_onfly', 'augvalid', 'include_bodyparts', 'background_free', 'black_background', + 'color_costar', 'use_detector', 'decode_animalnumber', 'autofind_t', 'decode_t', + 'decode_extraction', 'stable_illumination', 'show_legend', 'normalize_distance', + 'correct_ID', 'correct_id' + ] + for key in bool_keys: + if key in config and config[key] is not None: + val = config[key] + if not isinstance(val, bool): + raise CLIConfigError( + f"Parameter '{key}' must be a boolean True/False (got {type(val).__name__}: {val!r})." + ) + + if 'ID_colors' in config and config['ID_colors'] is not None: + val = config['ID_colors'] + if isinstance(val, bool) or not isinstance(val, (list, tuple)): + raise CLIConfigError( + f"Parameter 'ID_colors' must be a list of color entries (got {type(val).__name__}: {val!r})." + ) + + if 'specific_behaviors' in config and config['specific_behaviors'] is not None: + val = config['specific_behaviors'] + if isinstance(val, bool) or not isinstance(val, dict): + raise CLIConfigError( + f"Parameter 'specific_behaviors' must be a dictionary (got {type(val).__name__}: {val!r})." + ) + + if 'animal_number' in config and config['animal_number'] is not None: + val = config['animal_number'] + if isinstance(val, bool): + raise CLIConfigError( + f"Parameter 'animal_number' must be a positive integer or dictionary (got {val!r})." + ) + if isinstance(val, int): + if val <= 0: + raise CLIConfigError( + f"Parameter 'animal_number' must be a positive integer (got {val!r})." + ) + elif isinstance(val, dict): + for k, v in val.items(): + if not isinstance(k, str) or not k.strip(): + raise CLIConfigError( + f"Animal kinds in 'animal_number' dictionary must be non-empty strings (got {k!r})." + ) + if isinstance(v, bool) or not isinstance(v, int) or v <= 0: + raise CLIConfigError( + f"Animal counts in 'animal_number' dictionary must be positive integers (got {v!r} for '{k}')." + ) + else: + raise CLIConfigError( + f"Parameter 'animal_number' must be a positive integer or dictionary (got {type(val).__name__}: {val!r})." + ) + + 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 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') + if config.get('training_onfly'): + if config.get('aug_methods'): + raise CLIConfigError( + "On-the-fly training ('training_onfly') does not support augmentation settings ('aug_methods')." + ) + if config.get('augvalid') is False: + raise CLIConfigError( + "On-the-fly training ('training_onfly') does not support '--no-augvalid' / 'augvalid: false'." + ) + if config.get('out_folder') is not None: + raise CLIConfigError( + "On-the-fly training ('training_onfly') does not support caching frames to 'out_folder'." + ) + if net_type == 'pattern_recognizer' and config.get('color_costar'): + raise CLIConfigError( + "Option '--color-costar' / 'color_costar' is not supported for 'pattern_recognizer'." + ) + if config.get('behavior_mode', 0) >= 3 and net_type != 'pattern_recognizer': + raise CLIConfigError( + f"behavior_mode={config['behavior_mode']} (static images) is only supported when network_type is 'pattern_recognizer' (got '{net_type}')." + ) + + +def resolve_config(command_name, defaults, allowed_keys, required_keys, config_path, cli_args_dict): + """Resolve config from defaults, YAML file, and CLI overrides.""" + resolved = defaults.copy() + + if config_path is not None: + expanded_config = os.path.expanduser(config_path) + if not os.path.isfile(expanded_config): + raise CLIConfigError(f"Specified configuration file not found: '{config_path}'") + try: + with open(expanded_config, 'r', encoding='utf-8') as f: + yaml_data = yaml.safe_load(f) + except Exception as e: + raise CLIConfigError(f"Error reading YAML file '{config_path}': {e}") + + if yaml_data is not None: + if not isinstance(yaml_data, dict): + raise CLIConfigError( + f"Configuration file '{config_path}' must contain a key-value mapping (YAML dictionary)." + ) + unknown_keys = set(yaml_data.keys()) - allowed_keys + if unknown_keys: + raise CLIConfigError( + f"Unknown configuration key(s) in '{config_path}' for command '{command_name}': " + f"{', '.join(sorted(unknown_keys))}" + ) + for k, v in yaml_data.items(): + resolved[k] = v + + for k, v in cli_args_dict.items(): + if k not in ['config', 'action', 'target', 'func'] and v is not None: + resolved[k] = v + + if 'correct_id' in resolved: + resolved['correct_ID'] = resolved.pop('correct_id') + if 'id_colors' in resolved: + resolved['ID_colors'] = resolved.pop('id_colors') + + for pk in PATH_KEYS: + if pk in resolved and isinstance(resolved[pk], str) and not isinstance(resolved[pk], bool): + resolved[pk] = os.path.expanduser(resolved[pk]) + + if 'path_to_videos' in resolved and resolved['path_to_videos'] is not None: + val = resolved['path_to_videos'] + if isinstance(val, str) and not isinstance(val, bool): + resolved['path_to_videos'] = [os.path.expanduser(val)] + elif isinstance(val, list): + resolved['path_to_videos'] = [ + os.path.expanduser(item) if isinstance(item, str) and not isinstance(item, bool) else item + for item in val + ] + + if 'specific_behaviors' in resolved and isinstance(resolved['specific_behaviors'], str): + resolved['specific_behaviors'] = parse_json_or_val(resolved['specific_behaviors']) + if 'ID_colors' in resolved and isinstance(resolved['ID_colors'], str): + resolved['ID_colors'] = parse_json_or_val(resolved['ID_colors']) + if 'animal_number' in resolved and isinstance(resolved['animal_number'], str): + val_str = resolved['animal_number'].strip() + if val_str.startswith('{') or val_str.startswith('['): + resolved['animal_number'] = parse_json_or_val(val_str) + else: + try: + resolved['animal_number'] = int(val_str) + except ValueError: + pass + + validate_types_and_ranges(command_name, resolved) + + missing = [rk for rk in required_keys if resolved.get(rk) is None] + if missing: + raise CLIConfigError( + f"Missing required parameter(s) for '{command_name}': {', '.join(sorted(missing))}. " + f"Please supply via --config YAML or explicit inline options." + ) + + return resolved + + +def add_common_config_arg(parser): + parser.add_argument( + '-c', '--config', + type=str, + default=None, + help="Path to YAML workflow configuration file specifying settings." + ) + + +def build_parser(): + parser = argparse.ArgumentParser( + 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") + + train_parser = subparsers.add_parser("train", help="Train categorizers or detectors") + train_sub = train_parser.add_subparsers(dest="target", help="Target network to train", required=False) + + p_train_cat = train_sub.add_parser("categorizer", help="Train behavior classifier (Pattern Recognizer, CombNet, etc.)") + add_common_config_arg(p_train_cat) + p_train_cat.add_argument("--data-path", type=str, default=None, help="Path to training examples dataset") + p_train_cat.add_argument("--model-path", type=str, default=None, help="Path to output model directory") + p_train_cat.add_argument("--network-type", type=str, choices=['combnet', 'pattern_recognizer', 'animation_analyzer', 'combined_network'], default=None, help="Type of network architecture") + p_train_cat.add_argument("--out-path", type=str, default=None, help="Output path for logs/reports") + p_train_cat.add_argument("--out-folder", type=str, default=None, help="Target folder for caching prepared frames") + p_train_cat.add_argument("--dim-conv", type=int, default=None, help="Input dimension for Pattern Recognizer") + p_train_cat.add_argument("--dim-tconv", type=int, default=None, help="Input dimension for Animation Analyzer") + p_train_cat.add_argument("--channel", type=int, choices=[1, 3], default=None, help="Channel depth (1 or 3)") + p_train_cat.add_argument("--time-step", type=int, default=None, help="Time steps/frames per behavior sequence") + p_train_cat.add_argument("--level-conv", type=int, default=None, help="Complexity level of Pattern Recognizer (1-5)") + p_train_cat.add_argument("--level-tconv", type=int, default=None, help="Complexity level of Animation Analyzer (1-5)") + p_train_cat.add_argument("--aug-methods", type=str, nargs="+", default=None, help="List of augmentation methods") + p_train_cat.add_argument("--augvalid", action=argparse.BooleanOptionalAction, default=None, help="Validate augmentation data") + p_train_cat.add_argument("--include-bodyparts", action=argparse.BooleanOptionalAction, default=None, help="Include body parts in calculations") + p_train_cat.add_argument("--std", type=float, default=None, help="Standard deviation parameter for body parts") + p_train_cat.add_argument("--background-free", action=argparse.BooleanOptionalAction, default=None, help="Exclude background") + p_train_cat.add_argument("--black-background", action=argparse.BooleanOptionalAction, default=None, help="Use black background") + p_train_cat.add_argument("--behavior-mode", type=int, default=None, help="Behavior mode selection") + p_train_cat.add_argument("--social-distance", type=float, default=None, help="Social distance threshold") + p_train_cat.add_argument("--color-costar", action=argparse.BooleanOptionalAction, default=None, help="Keep supporting actors in color") + p_train_cat.add_argument("--training-onfly", action=argparse.BooleanOptionalAction, default=None, help="Train using on-the-fly behavior generator") + p_train_cat.set_defaults(func=handle_train_categorizer) + + p_train_det = train_sub.add_parser("detector", help="Train object detector (Detectron2)") + add_common_config_arg(p_train_det) + p_train_det.add_argument("--path-to-annotation", type=str, default=None, help="Path to COCO JSON annotation file") + p_train_det.add_argument("--path-to-trainingimages", type=str, default=None, help="Path to training images folder") + p_train_det.add_argument("--model-path", type=str, default=None, help="Path to output model directory") + p_train_det.add_argument("--iteration-num", type=int, default=None, help="Number of training iterations") + p_train_det.add_argument("--inference-size", type=int, default=None, help="Inference image frame size") + p_train_det.set_defaults(func=handle_train_detector) + + test_parser = subparsers.add_parser("test", help="Evaluate models headlessly") + test_sub = test_parser.add_subparsers(dest="target", help="Target model to test", required=False) + + p_test_cat = test_sub.add_parser("categorizer", help="Evaluate behavior classifier") + add_common_config_arg(p_test_cat) + p_test_cat.add_argument("--groundtruth-path", type=str, default=None, help="Path to ground-truth testing dataset") + p_test_cat.add_argument("--model-path", type=str, default=None, help="Path to trained categorizer directory") + p_test_cat.add_argument("--result-path", type=str, default=None, help="Path to output test results") + p_test_cat.set_defaults(func=handle_test_categorizer) + + p_test_det = test_sub.add_parser("detector", help="Evaluate object detector") + add_common_config_arg(p_test_det) + p_test_det.add_argument("--path-to-annotation", type=str, default=None, help="Path to COCO JSON annotation file") + p_test_det.add_argument("--path-to-testingimages", type=str, default=None, help="Path to testing images directory") + p_test_det.add_argument("--model-path", type=str, default=None, help="Path to trained detector directory") + p_test_det.add_argument("--result-path", type=str, default=None, help="Path to output test results") + p_test_det.set_defaults(func=handle_test_detector) + + infer_parser = subparsers.add_parser("infer", help="Execute animal tracking and behavior classification on videos or images") + add_common_config_arg(infer_parser) + infer_parser.add_argument("--path-to-videos", type=str, nargs="+", default=None, help="Path(s) to video files or directory") + infer_parser.add_argument("--result-path", type=str, default=None, help="Path to write inference results") + infer_parser.add_argument("--path-to-categorizer", type=str, default=None, help="Path to trained categorizer directory") + infer_parser.add_argument("--path-to-detector", type=str, default=None, help="Path to trained detector directory") + infer_parser.add_argument("--use-detector", action=argparse.BooleanOptionalAction, default=None, help="Use detector for animal tracking") + infer_parser.add_argument("--background-path", type=str, default=None, help="Path to background image") + infer_parser.add_argument("--framewidth", type=int, default=None, help="Target resizing width for frames") + infer_parser.add_argument("--delta", type=float, default=None, help="Optogenetics stimulation delta trigger threshold") + infer_parser.add_argument("--animal-kinds", type=str, nargs="+", default=None, help="Animal categories in detector") + infer_parser.add_argument("--animal-to-include", type=str, nargs="+", default=None, help="Animals to keep in outputs") + infer_parser.add_argument("--behavior-to-include", type=str, nargs="+", default=None, help="Behaviors to categorize") + infer_parser.add_argument("--detector-batch", type=int, default=None, help="Detection processing batch size") + infer_parser.add_argument("--detection-threshold", type=float, default=None, help="Detection confidence threshold") + infer_parser.add_argument("--decode-animalnumber", action=argparse.BooleanOptionalAction, default=None, help="Extract animal count from video filenames") + infer_parser.add_argument("--animal-number", type=str, default=None, help="Animal count or mapping") + infer_parser.add_argument("--autofind-t", action=argparse.BooleanOptionalAction, default=None, help="Auto-calculate optogenetics trigger") + infer_parser.add_argument("--decode-t", action=argparse.BooleanOptionalAction, default=None, help="Extract start times from filenames") + infer_parser.add_argument("--t", type=float, default=None, help="Start time offset in seconds") + infer_parser.add_argument("--duration", type=float, default=None, help="Total analysis window in seconds") + infer_parser.add_argument("--decode-extraction", action=argparse.BooleanOptionalAction, default=None, help="Extract start/end frame times") + 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") + infer_parser.add_argument("--min-length", type=int, default=None, help="Minimum behavior length in frames") + infer_parser.add_argument("--show-legend", action=argparse.BooleanOptionalAction, default=None, help="Render behavior legend overlays") + infer_parser.add_argument("--normalize-distance", action=argparse.BooleanOptionalAction, default=None, help="Normalize metrics relative to contour sizes") + infer_parser.add_argument("--correct-id", action=argparse.BooleanOptionalAction, default=None, help="Run ID correction heuristics") + infer_parser.add_argument("--specific-behaviors", type=str, default=None, help="Specific behavior definitions JSON") + infer_parser.set_defaults(func=handle_infer) + + return parser + + +def handle_train_categorizer(args): + config = resolve_config( + command_name="labgym-cli train categorizer", + defaults=TRAIN_CATEGORIZER_DEFAULTS, + allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, + required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, + config_path=args.config, + cli_args_dict=vars(args) + ) + + data_path = config['data_path'] + model_path = config['model_path'] + out_path = config.get('out_path') + out_folder = config.get('out_folder') + + if not os.path.exists(data_path): + raise CLIConfigError(f"Training data directory not found: '{data_path}'") + if not os.path.isdir(data_path): + raise CLIConfigError(f"Training data path must be a directory: '{data_path}'") + + if config.get('training_onfly'): + train_sub = os.path.join(data_path, 'train') + val_sub = os.path.join(data_path, 'validation') + if not os.path.isdir(train_sub) or not os.path.isdir(val_sub): + raise CLIConfigError( + f"On-the-fly training requires both 'train' and 'validation' subdirectories in '{data_path}'." + ) + else: + valid_exts = {'.jpg', '.jpeg', '.png', '.tiff', '.bmp'} + found_images = [ + f for f in os.listdir(data_path) + if os.path.splitext(f)[1].lower() in valid_exts and os.path.isfile(os.path.join(data_path, f)) + ] + if not found_images: + raise CLIConfigError( + f"No supported image files found in '{data_path}'. Supported extensions: {', '.join(sorted(valid_exts))}." + ) + + if os.path.isfile(model_path): + raise CLIConfigError(f"Model path must be a directory, not an existing file: '{model_path}'") + + if out_path and os.path.isfile(out_path): + raise CLIConfigError(f"Output path must be a directory, not an existing file: '{out_path}'") + + if out_folder and os.path.isfile(out_folder): + raise CLIConfigError(f"Output folder must be a directory, not an existing file: '{out_folder}'") + + if config.get('aug_methods'): + config['aug_methods'] = [AUG_METHOD_MAP[m] for m in config['aug_methods']] + + os.makedirs(model_path, exist_ok=True) + if out_path: + os.makedirs(out_path, exist_ok=True) + if out_folder: + os.makedirs(out_folder, exist_ok=True) + + print(f"Starting headless Categorizer training ({config['network_type']})...", file=sys.stdout) + + from LabGym.categorizer import Categorizers + CA = Categorizers() + + net_type = config['network_type'] + onfly = config['training_onfly'] + + if net_type == 'pattern_recognizer': + if onfly: + CA.train_pattern_recognizer_onfly( + data_path, model_path, out_path=out_path, + dim=config['dim_conv'], channel=config['channel'], time_step=config['time_step'], + level=config['level_conv'], include_bodyparts=config['include_bodyparts'], + std=config['std'], background_free=config['background_free'], + black_background=config['black_background'], behavior_mode=config['behavior_mode'], + social_distance=config['social_distance'] + ) + else: + CA.train_pattern_recognizer( + data_path, model_path, out_path=out_path, + dim=config['dim_conv'], channel=config['channel'], time_step=config['time_step'], + level=config['level_conv'], aug_methods=config['aug_methods'], augvalid=config['augvalid'], + include_bodyparts=config['include_bodyparts'], std=config['std'], + background_free=config['background_free'], black_background=config['black_background'], + behavior_mode=config['behavior_mode'], social_distance=config['social_distance'], + out_folder=out_folder + ) + elif net_type == 'animation_analyzer': + if onfly: + CA.train_animation_analyzer_onfly( + data_path, model_path, out_path=out_path, + dim=config['dim_tconv'], channel=config['channel'], time_step=config['time_step'], + level=config['level_tconv'], include_bodyparts=config['include_bodyparts'], + std=config['std'], background_free=config['background_free'], + black_background=config['black_background'], behavior_mode=config['behavior_mode'], + social_distance=config['social_distance'], color_costar=config['color_costar'] + ) + else: + CA.train_animation_analyzer( + data_path, model_path, out_path=out_path, + dim=config['dim_tconv'], channel=config['channel'], time_step=config['time_step'], + level=config['level_tconv'], aug_methods=config['aug_methods'], augvalid=config['augvalid'], + include_bodyparts=config['include_bodyparts'], std=config['std'], + background_free=config['background_free'], black_background=config['black_background'], + behavior_mode=config['behavior_mode'], social_distance=config['social_distance'], + color_costar=config['color_costar'], out_folder=out_folder + ) + else: + if onfly: + CA.train_combnet_onfly( + data_path, model_path, out_path=out_path, + dim_tconv=config['dim_tconv'], dim_conv=config['dim_conv'], channel=config['channel'], + time_step=config['time_step'], level_tconv=config['level_tconv'], level_conv=config['level_conv'], + include_bodyparts=config['include_bodyparts'], std=config['std'], + background_free=config['background_free'], black_background=config['black_background'], + behavior_mode=config['behavior_mode'], social_distance=config['social_distance'], + color_costar=config['color_costar'] + ) + else: + CA.train_combnet( + data_path, model_path, out_path=out_path, + dim_tconv=config['dim_tconv'], dim_conv=config['dim_conv'], channel=config['channel'], + time_step=config['time_step'], level_tconv=config['level_tconv'], level_conv=config['level_conv'], + aug_methods=config['aug_methods'], augvalid=config['augvalid'], + include_bodyparts=config['include_bodyparts'], std=config['std'], + background_free=config['background_free'], black_background=config['black_background'], + behavior_mode=config['behavior_mode'], social_distance=config['social_distance'], + color_costar=config['color_costar'], out_folder=out_folder + ) + + print("Categorizer training completed successfully.", file=sys.stdout) + + +def handle_train_detector(args): + config = resolve_config( + command_name="labgym-cli train detector", + defaults=TRAIN_DETECTOR_DEFAULTS, + allowed_keys=ALLOWED_TRAIN_DETECTOR_KEYS, + required_keys=REQUIRED_TRAIN_DETECTOR_KEYS, + config_path=args.config, + cli_args_dict=vars(args) + ) + + path_to_annotation = config['path_to_annotation'] + path_to_trainingimages = config['path_to_trainingimages'] + model_path = config['model_path'] + + if not os.path.exists(path_to_annotation): + raise CLIConfigError(f"Annotation file not found: '{path_to_annotation}'") + if not os.path.isfile(path_to_annotation): + raise CLIConfigError(f"Annotation path must be a file: '{path_to_annotation}'") + + try: + with open(path_to_annotation, 'r', encoding='utf-8') as f: + anno_data = json.load(f) + except Exception as e: + raise CLIConfigError(f"Error reading annotation file '{path_to_annotation}': {e}") + + if not isinstance(anno_data, dict): + raise CLIConfigError(f"Annotation file '{path_to_annotation}' must contain a JSON object.") + + if 'images' not in anno_data or not isinstance(anno_data['images'], list): + raise CLIConfigError( + f"Annotation file '{path_to_annotation}' must contain an 'images' list." + ) + + if 'annotations' not in anno_data or not isinstance(anno_data['annotations'], list): + raise CLIConfigError( + f"Annotation file '{path_to_annotation}' must contain an 'annotations' list." + ) + + if 'categories' not in anno_data or not isinstance(anno_data['categories'], list) or len(anno_data['categories']) == 0: + raise CLIConfigError( + f"Annotation file '{path_to_annotation}' must contain a non-empty 'categories' list." + ) + + has_positive_id = False + for idx, cat in enumerate(anno_data['categories']): + if not isinstance(cat, dict): + raise CLIConfigError( + f"Item {idx} in 'categories' of '{path_to_annotation}' must be a dictionary." + ) + if 'id' not in cat or isinstance(cat['id'], bool) or not isinstance(cat['id'], int): + raise CLIConfigError( + f"Category item {idx} in '{path_to_annotation}' must have an integer 'id' (got {cat.get('id')!r})." + ) + if 'name' not in cat or isinstance(cat['name'], bool) or not isinstance(cat['name'], str) or not cat['name'].strip(): + raise CLIConfigError( + f"Category item {idx} in '{path_to_annotation}' must have a non-empty string 'name'." + ) + if cat['id'] > 0: + has_positive_id = True + + if not has_positive_id: + raise CLIConfigError( + f"Annotation file '{path_to_annotation}' must contain at least one category with 'id' > 0." + ) + + if not os.path.exists(path_to_trainingimages): + raise CLIConfigError(f"Training images directory not found: '{path_to_trainingimages}'") + if not os.path.isdir(path_to_trainingimages): + raise CLIConfigError(f"Training images path must be a directory: '{path_to_trainingimages}'") + + if os.path.isfile(model_path): + raise CLIConfigError(f"Model path must be a directory, not an existing file: '{model_path}'") + + if os.path.exists(model_path): + raise CLIConfigError( + f"Model directory already exists: '{model_path}'. Detector training requires a path to a new directory." + ) + + parent_dir = os.path.dirname(model_path) + if parent_dir and os.path.isfile(parent_dir): + raise CLIConfigError(f"Parent path of model directory is a file: '{parent_dir}'") + + print( + f"Starting headless Detector training (Iterations: {config['iteration_num']}, Inference Size: {config['inference_size']})...", + file=sys.stdout + ) + + from LabGym.detector import Detector + DT = Detector() + DT.train( + path_to_annotation, + path_to_trainingimages, + model_path, + config['iteration_num'], + config['inference_size'] + ) + print("Detector training completed successfully.", file=sys.stdout) + + +def handle_test_categorizer(args): + config = resolve_config( + command_name="labgym-cli test categorizer", + defaults=TEST_CATEGORIZER_DEFAULTS, + allowed_keys=ALLOWED_TEST_CATEGORIZER_KEYS, + required_keys=REQUIRED_TEST_CATEGORIZER_KEYS, + config_path=args.config, + cli_args_dict=vars(args) + ) + + groundtruth_path = config['groundtruth_path'] + model_path = config['model_path'] + result_path = config['result_path'] + + if not os.path.exists(groundtruth_path): + raise CLIConfigError(f"Ground-truth dataset directory not found: '{groundtruth_path}'") + if not os.path.isdir(groundtruth_path): + raise CLIConfigError(f"Ground-truth dataset path must be a directory: '{groundtruth_path}'") + if not os.path.exists(model_path): + raise CLIConfigError(f"Categorizer model directory not found: '{model_path}'") + if not os.path.isdir(model_path): + raise CLIConfigError(f"Categorizer model path must be a directory: '{model_path}'") + param_path = os.path.join(model_path, 'model_parameters.txt') + if not os.path.isfile(param_path): + raise CLIConfigError( + f"Categorizer model parameters file not found in '{model_path}'. Expected 'model_parameters.txt'." + ) + + import pandas as pd + try: + parameters = pd.read_csv(param_path) + except Exception as e: + raise CLIConfigError(f"Error reading Categorizer model parameters in '{param_path}': {e}") + + required_cat_test_fields = ['classnames', 'time_step', 'network', 'inner_code', 'background_free'] + for field in required_cat_test_fields: + if field not in parameters or len(parameters[field]) == 0 or pd.isna(parameters[field][0]): + raise CLIConfigError( + f"Malformed Categorizer model parameters in '{param_path}': missing required field '{field}'." + ) + + classnames = [str(x) for x in list(parameters['classnames']) if pd.notna(x)] + if not classnames: + raise CLIConfigError(f"Malformed Categorizer model parameters in '{param_path}': 'classnames' is empty.") + + if result_path: + os.makedirs(result_path, exist_ok=True) + + print(f"Starting headless Categorizer testing on '{groundtruth_path}'...", file=sys.stdout) + from LabGym.categorizer import Categorizers + CA = Categorizers() + CA.test_categorizer(groundtruth_path, model_path, result_path=result_path) + print("Categorizer testing completed successfully.", file=sys.stdout) + + +def handle_test_detector(args): + config = resolve_config( + command_name="labgym-cli test detector", + defaults=TEST_DETECTOR_DEFAULTS, + allowed_keys=ALLOWED_TEST_DETECTOR_KEYS, + required_keys=REQUIRED_TEST_DETECTOR_KEYS, + config_path=args.config, + cli_args_dict=vars(args) + ) + + path_to_annotation = config['path_to_annotation'] + path_to_testingimages = config['path_to_testingimages'] + model_path = config['model_path'] + result_path = config['result_path'] + + if not os.path.exists(path_to_annotation): + raise CLIConfigError(f"Annotation file not found: '{path_to_annotation}'") + if not os.path.isfile(path_to_annotation): + raise CLIConfigError(f"Annotation path must be a file: '{path_to_annotation}'") + if not os.path.exists(path_to_testingimages): + raise CLIConfigError(f"Testing images directory not found: '{path_to_testingimages}'") + if not os.path.isdir(path_to_testingimages): + raise CLIConfigError(f"Testing images path must be a directory: '{path_to_testingimages}'") + if not os.path.exists(model_path): + raise CLIConfigError(f"Detector model directory not found: '{model_path}'") + if not os.path.isdir(model_path): + raise CLIConfigError(f"Detector model path must be a directory: '{model_path}'") + + for text_file in ['model_parameters.txt', 'config.yaml']: + fpath = os.path.join(model_path, text_file) + if not os.path.isfile(fpath): + raise CLIConfigError( + f"Detector model directory '{model_path}' is missing required file: '{text_file}'." + ) + try: + with open(fpath, 'r', encoding='utf-8') as f: + f.read() + except Exception as e: + raise CLIConfigError(f"Error reading Detector model file '{fpath}': {e}") + + weights_file = os.path.join(model_path, 'model_final.pth') + if not os.path.isfile(weights_file): + raise CLIConfigError( + f"Detector model directory '{model_path}' is missing required file: 'model_final.pth'." + ) + try: + with open(weights_file, 'rb') as f: + f.read(1024) + except Exception as e: + raise CLIConfigError(f"Error reading Detector model file '{weights_file}': {e}") + + os.makedirs(result_path, exist_ok=True) + + print(f"Starting headless Detector testing on '{path_to_testingimages}'...", file=sys.stdout) + from LabGym.detector import Detector + DT = Detector() + DT.test( + path_to_annotation, + path_to_testingimages, + model_path, + result_path + ) + print("Detector testing completed successfully.", file=sys.stdout) + + +def load_categorizer_metadata(path_to_categorizer): + if not os.path.isdir(path_to_categorizer): + raise CLIConfigError(f"Categorizer model directory not found: '{path_to_categorizer}'") + + param_path = os.path.join(path_to_categorizer, 'model_parameters.txt') + if not os.path.isfile(param_path): + raise CLIConfigError( + f"Categorizer model parameters file not found in '{path_to_categorizer}'. Expected 'model_parameters.txt'." + ) + + import pandas as pd + import matplotlib as mpl + + try: + parameters = pd.read_csv(param_path) + except Exception as e: + raise CLIConfigError(f"Error reading Categorizer parameters in '{param_path}': {e}") + + required_cols = [ + 'classnames', 'channel', 'time_step', 'network', + 'inner_code', 'std', 'background_free', 'black_background', + 'behavior_kind', 'social_distance' + ] + for col in required_cols: + if col not in parameters or len(parameters[col]) == 0 or pd.isna(parameters[col][0]): + raise CLIConfigError( + f"Malformed Categorizer model parameters in '{param_path}': missing required field '{col}'." + ) + + classnames = [str(x) for x in list(parameters['classnames']) if pd.notna(x)] + if not classnames: + raise CLIConfigError(f"Malformed Categorizer model parameters in '{param_path}': 'classnames' is empty.") + + try: + categorizer_type = int(parameters['network'][0]) + except (ValueError, TypeError): + raise CLIConfigError(f"Malformed Categorizer model parameters in '{param_path}': 'network' must be an integer.") + + if categorizer_type not in (0, 1, 2): + raise CLIConfigError( + f"Malformed Categorizer model parameters in '{param_path}': invalid 'network' value {categorizer_type} (expected 0, 1, or 2)." + ) + + if categorizer_type in (0, 2): + if 'dim_conv' not in parameters or pd.isna(parameters['dim_conv'][0]): + raise CLIConfigError( + f"Malformed Categorizer model parameters in '{param_path}': missing required architecture field 'dim_conv'." + ) + try: + dim_conv = int(parameters['dim_conv'][0]) + except (ValueError, TypeError): + raise CLIConfigError(f"Malformed Categorizer model parameters in '{param_path}': 'dim_conv' must be an integer.") + else: + dim_conv = int(parameters['dim_conv'][0]) if ('dim_conv' in parameters and pd.notna(parameters['dim_conv'][0])) else 0 + + if categorizer_type in (1, 2): + if 'dim_tconv' not in parameters or pd.isna(parameters['dim_tconv'][0]): + raise CLIConfigError( + f"Malformed Categorizer model parameters in '{param_path}': missing required architecture field 'dim_tconv'." + ) + try: + dim_tconv = int(parameters['dim_tconv'][0]) + except (ValueError, TypeError): + raise CLIConfigError(f"Malformed Categorizer model parameters in '{param_path}': 'dim_tconv' must be an integer.") + if 'color_code' not in parameters or pd.isna(parameters['color_code'][0]): + raise CLIConfigError( + f"Malformed Categorizer model parameters in '{param_path}': missing required field 'color_code'." + ) + try: + color_costar = (int(parameters['color_code'][0]) == 0) + except (ValueError, TypeError): + raise CLIConfigError(f"Malformed Categorizer model parameters in '{param_path}': 'color_code' must be an integer.") + else: + dim_tconv = int(parameters['dim_tconv'][0]) if ('dim_tconv' in parameters and pd.notna(parameters['dim_tconv'][0])) else 0 + if 'color_code' in parameters and pd.notna(parameters['color_code'][0]): + try: + color_costar = (int(parameters['color_code'][0]) == 0) + except (ValueError, TypeError): + raise CLIConfigError(f"Malformed Categorizer model parameters in '{param_path}': 'color_code' must be an integer.") + else: + color_costar = False + + try: + channel = int(parameters['channel'][0]) + length = int(parameters['time_step'][0]) + inner_code = int(parameters['inner_code'][0]) + std = int(parameters['std'][0]) + background_free_val = int(parameters['background_free'][0]) + black_background_val = int(parameters['black_background'][0]) + behavior_mode = int(parameters['behavior_kind'][0]) + social_distance = float(parameters['social_distance'][0]) + except (ValueError, TypeError) as e: + raise CLIConfigError(f"Malformed Categorizer model parameters in '{param_path}': invalid numeric value ({e}).") + + if channel not in (1, 3): + raise CLIConfigError(f"Malformed Categorizer model parameters in '{param_path}': invalid channel {channel} (expected 1 or 3).") + + if length < 3 and behavior_mode < 3: + length = 3 + + animation_analyzer = (categorizer_type == 2) + include_bodyparts = (inner_code == 0) + background_free = (background_free_val == 0) + black_background = not (black_background_val == 1) + if behavior_mode == 2 and social_distance == 0: + social_distance = float('inf') + + complete_colors = list(mpl.colors.cnames.values()) + colors = [['#ffffff', c] for c in complete_colors] + behaviornames_and_colors = {} + for behavior_name in classnames: + idx = classnames.index(behavior_name) + if idx < len(colors): + behaviornames_and_colors[behavior_name] = colors[idx] + else: + behaviornames_and_colors[behavior_name] = ['#ffffff', '#ffffff'] + + return { + 'classnames': classnames, + 'dim_conv': dim_conv, + 'dim_tconv': dim_tconv, + 'channel': channel, + 'length': length, + 'animation_analyzer': animation_analyzer, + 'include_bodyparts': include_bodyparts, + 'std': std, + 'background_free': background_free, + 'black_background': black_background, + 'behavior_mode': behavior_mode, + 'social_distance': social_distance, + 'color_costar': color_costar, + 'behaviornames_and_colors': behaviornames_and_colors, + } + + +def load_detector_metadata(path_to_detector): + if not os.path.isdir(path_to_detector): + raise CLIConfigError(f"Detector model directory not found: '{path_to_detector}'") + + param_path = os.path.join(path_to_detector, 'model_parameters.txt') + if not os.path.isfile(param_path): + raise CLIConfigError( + f"Detector model parameters file not found in '{path_to_detector}'. Expected 'model_parameters.txt'." + ) + + try: + with open(param_path, 'r', encoding='utf-8') as f: + detector_dict = json.load(f) + except Exception as e: + raise CLIConfigError(f"Error reading Detector model parameters in '{param_path}': {e}") + + if not isinstance(detector_dict, dict): + raise CLIConfigError(f"Malformed Detector model parameters in '{param_path}': must be a JSON object.") + + if 'animal_mapping' not in detector_dict: + raise CLIConfigError( + f"Malformed Detector model parameters in '{param_path}': missing required field 'animal_mapping'." + ) + animal_mapping = detector_dict['animal_mapping'] + if not isinstance(animal_mapping, dict) or not animal_mapping: + raise CLIConfigError( + f"Malformed Detector model parameters in '{param_path}': 'animal_mapping' must be a non-empty dictionary." + ) + + if 'inferencing_framesize' not in detector_dict: + raise CLIConfigError( + f"Malformed Detector model parameters in '{param_path}': missing required field 'inferencing_framesize'." + ) + val = detector_dict['inferencing_framesize'] + if isinstance(val, bool): + raise CLIConfigError( + f"Malformed Detector model parameters in '{param_path}': 'inferencing_framesize' cannot be a boolean." + ) + try: + inferencing_framesize = int(val) + except (ValueError, TypeError): + raise CLIConfigError( + f"Malformed Detector model parameters in '{param_path}': 'inferencing_framesize' must be an integer." + ) + if inferencing_framesize <= 0: + raise CLIConfigError( + f"Malformed Detector model parameters in '{param_path}': 'inferencing_framesize' must be a positive integer." + ) + + return { + 'animal_mapping': animal_mapping, + 'inferencing_framesize': inferencing_framesize, + } + + +def resolve_media_paths(paths, behavior_mode): + if behavior_mode == 3: + valid_exts = {'.jpg', '.jpeg', '.png', '.tiff', '.bmp'} + else: + valid_exts = {'.avi', '.mpg', '.mpeg', '.wmv', '.mp4', '.mkv', '.m4v', '.mov'} + + media_type = "image" if behavior_mode == 3 else "video" + resolved = [] + for p in paths: + if os.path.isdir(p): + found = [ + os.path.join(p, f) for f in os.listdir(p) + if os.path.splitext(f)[1].lower() in valid_exts + ] + found.sort() + if not found: + raise CLIConfigError(f"No valid {media_type} files found in directory: '{p}'") + resolved.extend(found) + elif os.path.isfile(p): + ext = os.path.splitext(p)[1].lower() + if ext not in valid_exts: + supported = ", ".join(sorted(valid_exts)) + raise CLIConfigError( + f"Unsupported {media_type} file format: '{p}'. Supported extensions: {supported}" + ) + resolved.append(p) + else: + raise CLIConfigError(f"Specified media path does not exist: '{p}'") + + deduped = list(dict.fromkeys(resolved)) + if not deduped: + raise CLIConfigError(f"No valid {media_type} files found for inference.") + 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-cli infer", + defaults=INFER_DEFAULTS, + allowed_keys=ALLOWED_INFER_KEYS, + required_keys=REQUIRED_INFER_KEYS, + config_path=args.config, + cli_args_dict=vars(args) + ) + + path_to_categorizer = config['path_to_categorizer'] + path_to_detector = config['path_to_detector'] + use_detector = config['use_detector'] + result_path = config['result_path'] + + if use_detector and not path_to_detector: + raise CLIConfigError("Option '--use-detector' requires '--path-to-detector' to be specified.") + + if path_to_categorizer: + cat_meta = load_categorizer_metadata(path_to_categorizer) + else: + cat_meta = { + 'classnames': [], + 'dim_conv': 64, + 'dim_tconv': 32, + 'channel': 1, + 'length': 15, + 'animation_analyzer': False, + 'include_bodyparts': True, + 'std': 0, + 'background_free': True, + 'black_background': True, + 'behavior_mode': 0, + 'social_distance': 0.0, + 'color_costar': False, + 'behaviornames_and_colors': {}, + } + + behavior_mode = cat_meta['behavior_mode'] + + if path_to_detector: + det_meta = load_detector_metadata(path_to_detector) + if config['animal_kinds'] == ['animal'] and det_meta['animal_mapping']: + animal_kinds = [str(v) for v in det_meta['animal_mapping'].values()] + else: + animal_kinds = list(config['animal_kinds']) + else: + animal_kinds = list(config['animal_kinds']) + + animal_to_include = list(config['animal_to_include']) if config['animal_to_include'] else list(animal_kinds) + + behavior_to_include = list(config['behavior_to_include']) + if not path_to_categorizer: + behavior_to_include = [] + elif not behavior_to_include or behavior_to_include == ['all']: + behavior_to_include = list(cat_meta['behaviornames_and_colors'].keys()) + else: + for b in behavior_to_include: + if b not in cat_meta['classnames']: + raise CLIConfigError( + f"Behavior '{b}' not found in Categorizer model. Available: {cat_meta['classnames']}" + ) + + input_paths = resolve_media_paths(config['path_to_videos'], behavior_mode) + + if behavior_mode == 3 and (not path_to_categorizer or not path_to_detector): + raise CLIConfigError("Static image inference (behavior_mode=3) requires both Categorizer and Detector.") + + os.makedirs(result_path, exist_ok=True) + print(f"Starting headless behavioral inference on {len(input_paths)} file(s)...", file=sys.stdout) + + if behavior_mode == 3: + from LabGym.analyzebehavior_dt import AnalyzeAnimalDetector + AAD = AnalyzeAnimalDetector() + detector_batch = max(1, config['detector_batch']) + AAD.analyze_images_individuals( + path_to_detector, input_paths, result_path, animal_kinds, + path_to_categorizer=path_to_categorizer, generate=False, + animal_to_include=animal_to_include, behavior_to_include=behavior_to_include, + names_and_colors=cat_meta['behaviornames_and_colors'], imagewidth=config['framewidth'], + dim_conv=cat_meta['dim_conv'], channel=cat_meta['channel'], + detection_threshold=config['detection_threshold'], uncertain=config['uncertain'], + background_free=cat_meta['background_free'], black_background=cat_meta['black_background'], + social_distance=0 + ) + else: + import pandas as pd + from LabGym.tools import plot_events + + all_events = {} + event_data = {} + all_time = [] + + if use_detector: + for animal_name in animal_kinds: + all_events[animal_name] = {} + detector_batch = max(1, config['detector_batch']) + + categorize_behavior = (path_to_categorizer is not None) + + for video_path in input_paths: + filename = os.path.splitext(os.path.basename(video_path))[0].split('_') + animal_num = config['animal_number'] + t_val = config['t'] + ex_start_val = config['ex_start'] + ex_end_val = config['ex_end'] + + if config['decode_animalnumber']: + if use_detector: + animal_num = {} + number = [x[1:] for x in filename if len(x) > 1 and x[0] == 'n'] + for a, animal_name in enumerate(animal_kinds): + if a < len(number) and number[a].isdigit(): + animal_num[animal_name] = int(number[a]) + else: + animal_num[animal_name] = 1 + else: + for x in filename: + if len(x) > 1 and x[0] == 'n' and x[1:].isdigit(): + animal_num = int(x[1:]) + elif animal_num is None: + if use_detector: + animal_num = {animal_name: 1 for animal_name in animal_kinds} + else: + animal_num = 1 + elif isinstance(animal_num, int): + if use_detector: + animal_num = {animal_name: animal_num for animal_name in animal_kinds} + elif isinstance(animal_num, dict): + animal_num = {animal_name: int(animal_num.get(animal_name, 1)) for animal_name in animal_kinds} + + if config['decode_t']: + for x in filename: + if len(x) > 1 and x[0] == 'b': + try: + t_val = float(x[1:]) + except ValueError: + pass + + if config['decode_extraction']: + for x in filename: + if len(x) > 2: + if x[:2] == 'xs' and x[2:].isdigit(): + ex_start_val = int(x[2:]) + if x[:2] == 'xe' and x[2:].isdigit(): + ex_end_val = int(x[2:]) + + if not use_detector: + from LabGym.analyzebehavior import AnalyzeAnimal + AA = AnalyzeAnimal() + AA.prepare_analysis( + video_path, result_path, animal_num, delta=config['delta'], + names_and_colors=cat_meta['behaviornames_and_colors'], framewidth=config['framewidth'], + stable_illumination=config['stable_illumination'], dim_tconv=cat_meta['dim_tconv'], + dim_conv=cat_meta['dim_conv'], channel=cat_meta['channel'], + include_bodyparts=cat_meta['include_bodyparts'], std=cat_meta['std'], + 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=config['animal_vs_bg'] + ) + if behavior_mode == 0: + AA.acquire_information(background_free=cat_meta['background_free'], black_background=cat_meta['black_background']) + AA.craft_data() + interact_all = False + else: + AA.acquire_information_interact_basic(background_free=cat_meta['background_free'], black_background=cat_meta['black_background']) + interact_all = True + + if path_to_categorizer is not None: + AA.categorize_behaviors(path_to_categorizer, uncertain=config['uncertain'], min_length=config['min_length']) + + AA.annotate_video(config['ID_colors'], behavior_to_include, show_legend=config['show_legend'], interact_all=interact_all) + AA.export_results(normalize_distance=config['normalize_distance'], parameter_to_analyze=config['parameter_to_analyze']) + + if path_to_categorizer is not None: + for n in AA.event_probability: + all_events[len(all_events)] = AA.event_probability[n] + if len(all_time) < len(AA.all_time): + all_time = AA.all_time + else: + from LabGym.analyzebehavior_dt import AnalyzeAnimalDetector + AAD = AnalyzeAnimalDetector() + AAD.prepare_analysis( + path_to_detector, video_path, result_path, animal_num, animal_kinds, behavior_mode, + names_and_colors=cat_meta['behaviornames_and_colors'], framewidth=config['framewidth'], + dim_tconv=cat_meta['dim_tconv'], dim_conv=cat_meta['dim_conv'], channel=cat_meta['channel'], + include_bodyparts=cat_meta['include_bodyparts'], std=cat_meta['std'], + categorize_behavior=categorize_behavior, animation_analyzer=cat_meta['animation_analyzer'], + t=t_val, duration=config['duration'], length=cat_meta['length'], social_distance=cat_meta['social_distance'] + ) + if behavior_mode == 1: + AAD.acquire_information_interact_basic( + batch_size=detector_batch, background_free=cat_meta['background_free'], black_background=cat_meta['black_background'] + ) + else: + AAD.acquire_information( + batch_size=detector_batch, background_free=cat_meta['background_free'], black_background=cat_meta['black_background'], + color_costar=cat_meta['color_costar'] + ) + if behavior_mode != 1: + AAD.craft_data() + + if path_to_categorizer is not None: + AAD.categorize_behaviors(path_to_categorizer, uncertain=config['uncertain'], min_length=config['min_length']) + + if config['correct_ID']: + AAD.correct_identity(config['specific_behaviors']) + + AAD.annotate_video(animal_to_include, config['ID_colors'], behavior_to_include, show_legend=config['show_legend']) + AAD.export_results(normalize_distance=config['normalize_distance'], parameter_to_analyze=config['parameter_to_analyze']) + + if path_to_categorizer is not None: + for animal_name in animal_kinds: + if animal_name in AAD.event_probability: + for n in AAD.event_probability[animal_name]: + all_events[animal_name][len(all_events[animal_name])] = AAD.event_probability[animal_name][n] + if len(all_time) < len(AAD.all_time): + all_time = AAD.all_time + + if path_to_categorizer is not None and all_time: + max_length = len(all_time) + if not use_detector: + for n in all_events: + event_data[len(event_data)] = all_events[n] + [['NA', -1]] * (max_length - len(all_events[n])) + if event_data: + all_events_df = pd.DataFrame(event_data, index=all_time) + 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) + else: + for animal_name in animal_to_include: + if animal_name in all_events: + for n in all_events[animal_name]: + event_data[len(event_data)] = all_events[animal_name][n] + [['NA', -1]] * (max_length - len(all_events[animal_name][n])) + event_data[len(event_data)] = [['NA', -1]] * max_length + if event_data: + del event_data[len(event_data) - 1] + all_events_df = pd.DataFrame(event_data, index=all_time) + 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) + + +def main(argv=None): + if argv is None: + argv = sys.argv[1:] + + parser = build_parser() + + if len(argv) == 0: + parser.print_help(file=sys.stdout) + return 0 + + try: + args = parser.parse_args(argv) + except SystemExit as e: + return e.code + + if args.action in ['train', 'test'] and getattr(args, 'target', None) is None: + 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'): + parser.print_help(file=sys.stderr) + return 2 + + try: + args.func(args) + return 0 + except CLIConfigError as e: + print(f"Error: {e}", file=sys.stderr) + return 2 + except NotImplementedError as e: + print(f"Error: {e}", file=sys.stderr) + return 1 + except Exception as e: + print(f"Execution Error: {e}", file=sys.stderr) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/LabGym/tests/test_cli.py b/LabGym/tests/test_cli.py new file mode 100644 index 00000000..f6281d55 --- /dev/null +++ b/LabGym/tests/test_cli.py @@ -0,0 +1,2109 @@ +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest +import yaml +from unittest.mock import patch, MagicMock + +import pandas as pd + +from LabGym.cli import ( + build_parser, + resolve_config, + CLIConfigError, + main, + load_categorizer_metadata, + load_detector_metadata, + resolve_media_paths, + rollup_behavior_summaries, + TRAIN_CATEGORIZER_DEFAULTS, + ALLOWED_TRAIN_CATEGORIZER_KEYS, + REQUIRED_TRAIN_CATEGORIZER_KEYS, + TRAIN_DETECTOR_DEFAULTS, + ALLOWED_TRAIN_DETECTOR_KEYS, + REQUIRED_TRAIN_DETECTOR_KEYS, + TEST_CATEGORIZER_DEFAULTS, + ALLOWED_TEST_CATEGORIZER_KEYS, + REQUIRED_TEST_CATEGORIZER_KEYS, + TEST_DETECTOR_DEFAULTS, + ALLOWED_TEST_DETECTOR_KEYS, + REQUIRED_TEST_DETECTOR_KEYS, + INFER_DEFAULTS, + ALLOWED_INFER_KEYS, + REQUIRED_INFER_KEYS, +) + + +def test_command_routing_train_categorizer(): + parser = build_parser() + args = parser.parse_args([ + "train", "categorizer", + "--data-path", "/path/to/data", + "--model-path", "/path/to/model" + ]) + assert args.action == "train" + assert args.target == "categorizer" + assert args.data_path == "/path/to/data" + assert args.model_path == "/path/to/model" + + +def test_command_routing_train_detector(): + parser = build_parser() + args = parser.parse_args([ + "train", "detector", + "--path-to-annotation", "annot.json", + "--path-to-trainingimages", "imgs/", + "--model-path", "det_model/" + ]) + assert args.action == "train" + assert args.target == "detector" + assert args.path_to_annotation == "annot.json" + assert args.path_to_trainingimages == "imgs/" + assert args.model_path == "det_model/" + + +def test_command_routing_test_categorizer(): + parser = build_parser() + args = parser.parse_args([ + "test", "categorizer", + "--groundtruth-path", "gt/", + "--model-path", "cat_model/" + ]) + assert args.action == "test" + assert args.target == "categorizer" + assert args.groundtruth_path == "gt/" + assert args.model_path == "cat_model/" + + +def test_command_routing_test_detector(): + parser = build_parser() + args = parser.parse_args([ + "test", "detector", + "--path-to-annotation", "test_annot.json", + "--path-to-testingimages", "test_imgs/", + "--model-path", "det_model/" + ]) + assert args.action == "test" + assert args.target == "detector" + assert args.path_to_annotation == "test_annot.json" + assert args.path_to_testingimages == "test_imgs/" + assert args.model_path == "det_model/" + + +def test_command_routing_infer(): + parser = build_parser() + args = parser.parse_args([ + "infer", + "--path-to-videos", "vid1.mp4", "vid2.mp4", + "--result-path", "out/" + ]) + assert args.action == "infer" + assert args.path_to_videos == ["vid1.mp4", "vid2.mp4"] + assert args.result_path == "out/" + + +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(): + cli_args = { + 'data_path': '/my/data', + 'model_path': '/my/model', + } + resolved = resolve_config( + 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=cli_args + ) + assert resolved['dim_conv'] == 64 + assert resolved['channel'] == 1 + assert resolved['level_conv'] == 2 + assert resolved['background_free'] is True + assert resolved['data_path'] == '/my/data' + assert resolved['model_path'] == '/my/model' + + +def test_precedence_yaml_overrides_defaults(tmp_path): + config_file = tmp_path / "train_cat.yaml" + yaml_content = { + 'data_path': '/yaml/data', + 'model_path': '/yaml/model', + 'dim_conv': 128, + 'channel': 3, + 'background_free': False, + } + with open(config_file, 'w') as f: + yaml.dump(yaml_content, f) + + cli_args = {} + resolved = resolve_config( + 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(config_file), + cli_args_dict=cli_args + ) + + assert resolved['dim_conv'] == 128 + assert resolved['channel'] == 3 + assert resolved['background_free'] is False + assert resolved['data_path'] == '/yaml/data' + assert resolved['dim_tconv'] == 32 + assert resolved['time_step'] == 15 + + +def test_precedence_inline_overrides_yaml(tmp_path): + config_file = tmp_path / "train_cat.yaml" + yaml_content = { + 'data_path': '/yaml/data', + 'model_path': '/yaml/model', + 'dim_conv': 128, + 'channel': 3, + 'background_free': False, + } + with open(config_file, 'w') as f: + yaml.dump(yaml_content, f) + + cli_args = { + 'dim_conv': 256, + 'background_free': True, + } + resolved = resolve_config( + 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(config_file), + cli_args_dict=cli_args + ) + + assert resolved['dim_conv'] == 256 + assert resolved['background_free'] is True + assert resolved['channel'] == 3 + assert resolved['data_path'] == '/yaml/data' + + +def test_absent_inline_flags_never_overwrite_yaml(tmp_path): + config_file = tmp_path / "infer_job.yaml" + yaml_content = { + 'path_to_videos': ['/yaml/vids'], + 'result_path': '/yaml/results', + 'use_detector': True, + 'delta': 500.0, + } + with open(config_file, 'w') as f: + yaml.dump(yaml_content, f) + + cli_args = { + 'use_detector': None, + 'delta': None, + 'path_to_videos': None, + 'result_path': None, + } + resolved = resolve_config( + command_name="labgym-cli infer", + defaults=INFER_DEFAULTS, + allowed_keys=ALLOWED_INFER_KEYS, + required_keys=REQUIRED_INFER_KEYS, + config_path=str(config_file), + cli_args_dict=cli_args + ) + + assert resolved['use_detector'] is True + assert resolved['delta'] == 500.0 + assert resolved['result_path'] == '/yaml/results' + + +def test_paired_boolean_flags_positive(): + parser = build_parser() + args = parser.parse_args([ + "infer", + "--path-to-videos", "vid.mp4", + "--result-path", "out/", + "--use-detector" + ]) + assert args.use_detector is True + + +def test_paired_boolean_flags_negative(): + parser = build_parser() + args = parser.parse_args([ + "infer", + "--path-to-videos", "vid.mp4", + "--result-path", "out/", + "--no-use-detector" + ]) + assert args.use_detector is False + + +def test_paired_boolean_flags_unspecified_defaults_to_none(): + parser = build_parser() + args = parser.parse_args([ + "infer", + "--path-to-videos", "vid.mp4", + "--result-path", "out/" + ]) + assert args.use_detector is None + + +def test_paired_boolean_flag_overrides_yaml_false_with_true(tmp_path): + cfg = tmp_path / "config.yaml" + with open(cfg, 'w') as f: + yaml.dump({'path_to_videos': 'vid.mp4', 'result_path': 'out/', 'use_detector': False}, 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={'use_detector': True} + ) + assert resolved['use_detector'] is True + + +def test_paired_boolean_flag_overrides_yaml_true_with_false(tmp_path): + cfg = tmp_path / "config.yaml" + with open(cfg, 'w') as f: + yaml.dump({'path_to_videos': 'vid.mp4', 'result_path': 'out/', 'use_detector': True}, 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={'use_detector': False} + ) + assert resolved['use_detector'] is False + + +def test_missing_config_file_raises_error(): + with pytest.raises(CLIConfigError) as exc_info: + resolve_config( + command_name="labgym-cli train categorizer", + defaults=TRAIN_CATEGORIZER_DEFAULTS, + allowed_keys=ALLOWED_TRAIN_CATEGORIZER_KEYS, + required_keys=REQUIRED_TRAIN_CATEGORIZER_KEYS, + config_path="/nonexistent/path/to/missing_config.yaml", + cli_args_dict={} + ) + assert "Specified configuration file not found" in str(exc_info.value) + + +def test_unknown_yaml_key_raises_error(tmp_path): + bad_cfg = tmp_path / "bad.yaml" + with open(bad_cfg, 'w') as f: + yaml.dump({ + 'data_path': '/data', + 'model_path': '/model', + 'unknown_bad_key': 123 + }, f) + + with pytest.raises(CLIConfigError) as exc_info: + resolve_config( + 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(bad_cfg), + cli_args_dict={} + ) + assert "Unknown configuration key(s)" in str(exc_info.value) + assert "unknown_bad_key" in str(exc_info.value) + + +def test_missing_required_keys_raises_error(): + with pytest.raises(CLIConfigError) as exc_info: + resolve_config( + 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': '/some/data'} + ) + assert "Missing required parameter(s)" in str(exc_info.value) + assert "model_path" in str(exc_info.value) + + +def test_invalid_integer_bounds_raises_error(): + with pytest.raises(CLIConfigError) as exc_info: + resolve_config( + command_name="labgym-cli train detector", + defaults=TRAIN_DETECTOR_DEFAULTS, + allowed_keys=ALLOWED_TRAIN_DETECTOR_KEYS, + required_keys=REQUIRED_TRAIN_DETECTOR_KEYS, + config_path=None, + cli_args_dict={ + 'path_to_annotation': 'a.json', + 'path_to_trainingimages': 'imgs/', + 'model_path': 'det/', + 'iteration_num': -100 + } + ) + 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-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': '/data', + 'model_path': '/model', + 'channel': 2 + } + ) + assert "Parameter 'channel' must be 1 or 3" in str(exc_info.value) + + +def test_invalid_network_type_raises_error(): + with pytest.raises(CLIConfigError) as exc_info: + resolve_config( + 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': '/data', + 'model_path': '/model', + 'network_type': 'nonexistent_network' + } + ) + assert "Invalid network_type 'nonexistent_network'" in str(exc_info.value) + + +def test_detector_training_does_not_require_categorizer_data(): + cli_args = { + 'path_to_annotation': 'annot.json', + 'path_to_trainingimages': 'images/', + 'model_path': 'models/detector', + } + resolved = resolve_config( + command_name="labgym-cli train detector", + defaults=TRAIN_DETECTOR_DEFAULTS, + allowed_keys=ALLOWED_TRAIN_DETECTOR_KEYS, + required_keys=REQUIRED_TRAIN_DETECTOR_KEYS, + config_path=None, + cli_args_dict=cli_args + ) + assert resolved['path_to_annotation'] == 'annot.json' + assert resolved['iteration_num'] == 200 + assert 'data_path' not in resolved + + +def test_user_path_expansion(): + cli_args = { + 'data_path': '~/my_dataset', + 'model_path': '~/my_model', + } + resolved = resolve_config( + 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=cli_args + ) + expected_home = os.path.expanduser('~') + assert resolved['data_path'].startswith(expected_home) + assert resolved['model_path'].startswith(expected_home) + assert not resolved['data_path'].startswith('~') + + +def test_cli_main_missing_config_returns_non_zero(): + exit_code = main(["train", "categorizer", "-c", "missing_file_does_not_exist.yaml"]) + assert exit_code == 2 + + +def test_cli_main_invalid_args_returns_code_2(): + exit_code = main(["infer", "--unknown-flag-1234"]) + assert exit_code == 2 + + +def test_booleans_rejected_for_integer_and_numeric_fields(): + with pytest.raises(CLIConfigError) as exc_info: + resolve_config( + 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', 'channel': True} + ) + assert "Parameter 'channel' must be 1 or 3" in str(exc_info.value) + + with pytest.raises(CLIConfigError) as exc_info: + resolve_config( + 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-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-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-cli infer' must be a positive integer" in str(exc_info.value) + + 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': ['v.mp4'], 'result_path': 'r', 'min_length': False} + ) + 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-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-cli infer' must be a positive integer" in str(exc_info.value) + + 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': ['v.mp4'], 'result_path': 'r', 'min_length': -5} + ) + 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-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-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-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_start': 100, 'ex_end': 50} + ) + assert "Parameter 'ex_end' (50) must be greater than or equal to 'ex_start' (100)" in str(exc_info.value) + + +def test_strings_rejected_where_lists_are_expected(tmp_path): + cfg = tmp_path / "bad_lists.yaml" + with open(cfg, 'w') as f: + yaml.dump({ + 'path_to_videos': ['v.mp4'], + 'result_path': 'r', + 'animal_kinds': "mouse" + }, f) + + 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=str(cfg), + cli_args_dict={} + ) + 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({ + 'data_path': 'd', + 'model_path': 'm', + 'aug_methods': "rotation" + }, f) + + with pytest.raises(CLIConfigError) as exc_info: + resolve_config( + 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-cli train categorizer' must be a list of strings" in str(exc_info.value) + + with open(cfg, 'w') as f: + yaml.dump({ + 'path_to_videos': ['v.mp4'], + 'result_path': 'r', + 'animal_kinds': [123] + }, f) + + 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=str(cfg), + cli_args_dict={} + ) + 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): + cfg = tmp_path / "bad_infer.yaml" + 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'], + 'result_path': 'r', + forbidden_key: True if 'background' in forbidden_key or 'color' in forbidden_key else 0 + }, f) + 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=str(cfg), + cli_args_dict={} + ) + 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() + param_file = cat_dir / "model_parameters.txt" + with open(param_file, "w") as f: + f.write("classnames,dim_conv,channel,time_step,network,inner_code,std,background_free,black_background,behavior_kind,social_distance,color_code\n") + f.write("groom,64,1,15,0,0,0,0,0,0,0,1\n") + f.write("walk,64,1,15,0,0,0,0,0,0,0,1\n") + + meta = load_categorizer_metadata(str(cat_dir)) + assert meta['classnames'] == ['groom', 'walk'] + assert meta['dim_conv'] == 64 + assert meta['channel'] == 1 + assert meta['length'] == 15 + assert meta['animation_analyzer'] is False + assert meta['include_bodyparts'] is True + assert meta['background_free'] is True + assert meta['black_background'] is True + assert meta['behavior_mode'] == 0 + assert 'groom' in meta['behaviornames_and_colors'] + assert 'walk' in meta['behaviornames_and_colors'] + + +def test_load_categorizer_metadata_missing_and_malformed(tmp_path): + with pytest.raises(CLIConfigError) as exc_info: + load_categorizer_metadata(str(tmp_path / "nonexistent")) + assert "Categorizer model directory not found" in str(exc_info.value) + + empty_dir = tmp_path / "empty_cat" + empty_dir.mkdir() + with pytest.raises(CLIConfigError) as exc_info: + load_categorizer_metadata(str(empty_dir)) + assert "parameters file not found" in str(exc_info.value) + + bad_param = empty_dir / "model_parameters.txt" + bad_param.write_text("invalid_column\n1\n") + with pytest.raises(CLIConfigError) as exc_info: + load_categorizer_metadata(str(empty_dir)) + assert "missing required field 'classnames'" in str(exc_info.value) + + missing_channel = empty_dir / "model_parameters.txt" + missing_channel.write_text("classnames,time_step,network,inner_code,std,background_free,black_background,behavior_kind,social_distance\ngroom,15,0,0,0,0,0,0,0\n") + with pytest.raises(CLIConfigError) as exc_info: + load_categorizer_metadata(str(empty_dir)) + assert "missing required field 'channel'" in str(exc_info.value) + + missing_dim = empty_dir / "model_parameters.txt" + missing_dim.write_text("classnames,channel,time_step,network,inner_code,std,background_free,black_background,behavior_kind,social_distance\ngroom,1,15,0,0,0,0,0,0,0\n") + with pytest.raises(CLIConfigError) as exc_info: + load_categorizer_metadata(str(empty_dir)) + assert "missing required architecture field 'dim_conv'" in str(exc_info.value) + + missing_tconv = empty_dir / "model_parameters.txt" + missing_tconv.write_text("classnames,channel,time_step,network,inner_code,std,background_free,black_background,behavior_kind,social_distance,color_code\ngroom,1,15,1,0,0,0,0,0,0,0\n") + with pytest.raises(CLIConfigError) as exc_info: + load_categorizer_metadata(str(empty_dir)) + assert "missing required architecture field 'dim_tconv'" in str(exc_info.value) + + +def test_load_detector_metadata(tmp_path): + det_dir = tmp_path / "my_detector" + det_dir.mkdir() + param_file = det_dir / "model_parameters.txt" + param_file.write_text(json.dumps({"animal_mapping": {"0": "mouse"}, "inferencing_framesize": 480})) + + meta = load_detector_metadata(str(det_dir)) + assert meta['animal_mapping'] == {"0": "mouse"} + assert meta['inferencing_framesize'] == 480 + + with pytest.raises(CLIConfigError) as exc_info: + load_detector_metadata(str(tmp_path / "nonexistent")) + assert "Detector model directory not found" in str(exc_info.value) + + bad_det = tmp_path / "bad_det" + bad_det.mkdir() + (bad_det / "model_parameters.txt").write_text("not json") + with pytest.raises(CLIConfigError) as exc_info: + load_detector_metadata(str(bad_det)) + assert "Error reading Detector model parameters" in str(exc_info.value) + + (bad_det / "model_parameters.txt").write_text(json.dumps({"inferencing_framesize": 480})) + with pytest.raises(CLIConfigError) as exc_info: + load_detector_metadata(str(bad_det)) + assert "missing required field 'animal_mapping'" in str(exc_info.value) + + (bad_det / "model_parameters.txt").write_text(json.dumps({"animal_mapping": {}, "inferencing_framesize": 480})) + with pytest.raises(CLIConfigError) as exc_info: + load_detector_metadata(str(bad_det)) + assert "'animal_mapping' must be a non-empty dictionary" in str(exc_info.value) + + (bad_det / "model_parameters.txt").write_text(json.dumps({"animal_mapping": {"0": "mouse"}})) + with pytest.raises(CLIConfigError) as exc_info: + load_detector_metadata(str(bad_det)) + assert "missing required field 'inferencing_framesize'" in str(exc_info.value) + + (bad_det / "model_parameters.txt").write_text(json.dumps({"animal_mapping": {"0": "mouse"}, "inferencing_framesize": -5})) + with pytest.raises(CLIConfigError) as exc_info: + load_detector_metadata(str(bad_det)) + assert "'inferencing_framesize' must be a positive integer" in str(exc_info.value) + + (bad_det / "model_parameters.txt").write_text('{"animal_mapping": {"0": "mouse"}, "inferencing_framesize": true}') + with pytest.raises(CLIConfigError) as exc_info: + load_detector_metadata(str(bad_det)) + assert "'inferencing_framesize' cannot be a boolean" in str(exc_info.value) + + +def test_resolve_media_paths(tmp_path): + v1 = tmp_path / "v1.mp4" + v1.write_text("video") + v2 = tmp_path / "v2.avi" + v2.write_text("video") + txt = tmp_path / "notes.txt" + txt.write_text("text") + + resolved = resolve_media_paths([str(tmp_path)], behavior_mode=0) + assert resolved == [str(v1), str(v2)] + + single = resolve_media_paths([str(v1)], behavior_mode=0) + assert single == [str(v1)] + + dup = resolve_media_paths([str(v1), str(v2), str(v1)], behavior_mode=0) + assert dup == [str(v1), str(v2)] + + with pytest.raises(CLIConfigError) as exc_info: + resolve_media_paths([str(txt)], behavior_mode=0) + assert "Unsupported video file format" in str(exc_info.value) + assert "notes.txt" in str(exc_info.value) + + with pytest.raises(CLIConfigError) as exc_info: + resolve_media_paths([str(tmp_path / "ghost.mp4")], behavior_mode=0) + assert "Specified media path does not exist" in str(exc_info.value) + + +def test_handle_infer_missing_detector_when_use_detector_true(tmp_path): + v = tmp_path / "v.mp4" + v.write_text("video") + out = tmp_path / "never_created" + exit_code = main(["infer", "--path-to-videos", str(v), "--result-path", str(out), "--use-detector"]) + assert exit_code == 2 + assert not out.exists() + + +def test_handle_infer_does_not_create_output_dir_on_failure(tmp_path): + txt = tmp_path / "notes.txt" + txt.write_text("notes") + out = tmp_path / "out_uncreated" + + exit_code = main(["infer", "--path-to-videos", str(txt), "--result-path", str(out)]) + assert exit_code == 2 + assert not out.exists() + + +def test_handle_infer_unknown_behavior_requested(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\ngroom,64,1,15,0,0,0,0,0,0,0,1\n") + v = tmp_path / "v.mp4" + v.write_text("video") + out = tmp_path / "out_uncreated_behavior" + + exit_code = main(["infer", "--path-to-videos", str(v), "--result-path", str(out), "--path-to-categorizer", str(cat_dir), "--behavior-to-include", "flying"]) + assert exit_code == 2 + assert not out.exists() + + +def test_handle_infer_e2e_animal_execution(tmp_path, capsys): + 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\ngroom,64,1,15,0,0,0,0,0,0,0,1\n") + v = tmp_path / "v_n1.mp4" + v.write_text("video") + out = tmp_path / "out" + + class FakeAnimal: + def __init__(self): + self.event_probability = {0: [['groom', 0.95]]} + self.all_time = [0.1] + def prepare_analysis(self, *a, **k): pass + 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): pass + + with patch('LabGym.analyzebehavior.AnalyzeAnimal', FakeAnimal), patch('LabGym.tools.plot_events'): + exit_code = main(["infer", "--path-to-videos", str(v), "--result-path", str(out), "--path-to-categorizer", str(cat_dir)]) + assert exit_code == 0 + captured = capsys.readouterr() + assert "Inference completed successfully" in captured.out + + +def test_handle_infer_e2e_detector_execution(tmp_path, capsys): + 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\ngroom,64,1,15,0,0,0,0,0,0,0,1\n") + 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_n1.mp4" + v.write_text("video") + out = tmp_path / "out" + + class FakeAnimalDetector: + def __init__(self): + self.event_probability = {'mouse': {0: [['groom', 0.95]]}} + self.all_time = [0.1] + def prepare_analysis(self, *a, **k): pass + 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): pass + + with patch('LabGym.analyzebehavior_dt.AnalyzeAnimalDetector', FakeAnimalDetector), patch('LabGym.tools.plot_events'): + exit_code = main([ + "infer", + "--path-to-videos", str(v), + "--result-path", str(out), + "--use-detector", + "--path-to-detector", str(det_dir), + "--path-to-categorizer", str(cat_dir) + ]) + assert exit_code == 0 + captured = capsys.readouterr() + assert "Inference completed successfully" in captured.out + + +def test_path_to_videos_rejects_empty_strings(): + 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/'} + ) + assert "Items in 'path_to_videos' must be non-empty string paths" in str(exc_info.value) + + 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': [' '], 'result_path': 'out/'} + ) + assert "Items in 'path_to_videos' must be non-empty string paths" in str(exc_info.value) + + +def test_handle_test_categorizer_validation_and_execution(tmp_path, capsys): + gt_dir = tmp_path / "groundtruth" + gt_dir.mkdir() + cat_dir = tmp_path / "cat_model" + cat_dir.mkdir() + param_file = cat_dir / "model_parameters.txt" + param_file.write_text("classnames,dim_conv,channel,time_step,network,inner_code,std,background_free,black_background,behavior_kind,social_distance,color_code\ngroom,64,1,15,0,0,0,0,0,0,0,1\n") + out_dir = tmp_path / "test_cat_out" + + exit_code = main(["test", "categorizer", "--groundtruth-path", str(tmp_path / "nonexistent"), "--model-path", str(cat_dir), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + dummy_file = tmp_path / "dummy_gt.txt" + dummy_file.write_text("file") + exit_code = main(["test", "categorizer", "--groundtruth-path", str(dummy_file), "--model-path", str(cat_dir), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + exit_code = main(["test", "categorizer", "--groundtruth-path", str(gt_dir), "--model-path", str(tmp_path / "nonexistent_model"), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + empty_model = tmp_path / "empty_model" + empty_model.mkdir() + exit_code = main(["test", "categorizer", "--groundtruth-path", str(gt_dir), "--model-path", str(empty_model), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + bad_param_dir = tmp_path / "bad_param_model" + bad_param_dir.mkdir() + (bad_param_dir / "model_parameters.txt").write_text("classnames,network,inner_code,background_free\ngroom,0,0,0\n") + exit_code = main(["test", "categorizer", "--groundtruth-path", str(gt_dir), "--model-path", str(bad_param_dir), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + missing_classes_dir = tmp_path / "missing_classes_model" + missing_classes_dir.mkdir() + (missing_classes_dir / "model_parameters.txt").write_text("time_step,network,inner_code,background_free\n15,0,0,0\n") + exit_code = main(["test", "categorizer", "--groundtruth-path", str(gt_dir), "--model-path", str(missing_classes_dir), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + with patch('LabGym.categorizer.Categorizers.test_categorizer') as mock_test: + exit_code = main(["test", "categorizer", "--groundtruth-path", str(gt_dir), "--model-path", str(cat_dir), "--result-path", str(out_dir)]) + assert exit_code == 0 + mock_test.assert_called_once_with(str(gt_dir), str(cat_dir), result_path=str(out_dir)) + assert out_dir.exists() + captured = capsys.readouterr() + assert "Categorizer testing completed successfully." in captured.out + + +def test_handle_test_detector_validation_and_execution(tmp_path, capsys): + anno_file = tmp_path / "annotations.json" + anno_file.write_text("{}") + img_dir = tmp_path / "test_images" + img_dir.mkdir() + det_dir = tmp_path / "det_model" + det_dir.mkdir() + (det_dir / "model_parameters.txt").write_text('{"animal_mapping": {"0": "mouse"}, "inferencing_framesize": 480}') + (det_dir / "config.yaml").write_text("MODEL:\n DEVICE: cpu\n") + (det_dir / "model_final.pth").write_text("weights") + out_dir = tmp_path / "test_det_out" + + exit_code = main(["test", "detector", "--path-to-annotation", str(anno_file), "--path-to-testingimages", str(img_dir), "--model-path", str(det_dir)]) + assert exit_code == 2 + + exit_code = main(["test", "detector", "--path-to-annotation", str(tmp_path / "ghost.json"), "--path-to-testingimages", str(img_dir), "--model-path", str(det_dir), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + exit_code = main(["test", "detector", "--path-to-annotation", str(img_dir), "--path-to-testingimages", str(img_dir), "--model-path", str(det_dir), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + exit_code = main(["test", "detector", "--path-to-annotation", str(anno_file), "--path-to-testingimages", str(tmp_path / "ghost_imgs"), "--model-path", str(det_dir), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + exit_code = main(["test", "detector", "--path-to-annotation", str(anno_file), "--path-to-testingimages", str(img_dir), "--model-path", str(tmp_path / "ghost_model"), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + missing_config_dir = tmp_path / "missing_config_det" + missing_config_dir.mkdir() + (missing_config_dir / "model_parameters.txt").write_text("{}") + (missing_config_dir / "model_final.pth").write_text("weights") + exit_code = main(["test", "detector", "--path-to-annotation", str(anno_file), "--path-to-testingimages", str(img_dir), "--model-path", str(missing_config_dir), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + missing_pth_dir = tmp_path / "missing_pth_det" + missing_pth_dir.mkdir() + (missing_pth_dir / "model_parameters.txt").write_text("{}") + (missing_pth_dir / "config.yaml").write_text("cfg") + exit_code = main(["test", "detector", "--path-to-annotation", str(anno_file), "--path-to-testingimages", str(img_dir), "--model-path", str(missing_pth_dir), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + missing_param_dir = tmp_path / "missing_param_det" + missing_param_dir.mkdir() + (missing_param_dir / "config.yaml").write_text("cfg") + (missing_param_dir / "model_final.pth").write_text("weights") + exit_code = main(["test", "detector", "--path-to-annotation", str(anno_file), "--path-to-testingimages", str(img_dir), "--model-path", str(missing_param_dir), "--result-path", str(out_dir)]) + assert exit_code == 2 + assert not out_dir.exists() + + with patch('LabGym.detector.Detector.test') as mock_test: + exit_code = main(["test", "detector", "--path-to-annotation", str(anno_file), "--path-to-testingimages", str(img_dir), "--model-path", str(det_dir), "--result-path", str(out_dir)]) + assert exit_code == 0 + mock_test.assert_called_once_with(str(anno_file), str(img_dir), str(det_dir), str(out_dir)) + assert out_dir.exists() + captured = capsys.readouterr() + assert "Detector testing completed successfully." in captured.out + + +def test_handle_test_detector_unreadable_file_fails_without_creating_out_dir(tmp_path): + anno_file = tmp_path / "annotations.json" + anno_file.write_text("{}") + img_dir = tmp_path / "test_images" + img_dir.mkdir() + det_dir = tmp_path / "det_model" + det_dir.mkdir() + (det_dir / "model_parameters.txt").write_text('{"animal_mapping": {"0": "mouse"}, "inferencing_framesize": 480}') + (det_dir / "config.yaml").write_text("MODEL:\n DEVICE: cpu\n") + (det_dir / "model_final.pth").write_text("weights") + out_dir = tmp_path / "test_det_out_unreadable" + + orig_open = open + + def mock_open_weights(file, *args, **kwargs): + if str(file).endswith("model_final.pth"): + raise PermissionError("Permission denied: unreadable weights") + return orig_open(file, *args, **kwargs) + + with patch("builtins.open", side_effect=mock_open_weights): + exit_code = main([ + "test", "detector", + "--path-to-annotation", str(anno_file), + "--path-to-testingimages", str(img_dir), + "--model-path", str(det_dir), + "--result-path", str(out_dir) + ]) + assert exit_code == 2 + assert not out_dir.exists() + + def mock_open_config(file, *args, **kwargs): + if str(file).endswith("config.yaml"): + raise OSError("I/O error reading config") + return orig_open(file, *args, **kwargs) + + with patch("builtins.open", side_effect=mock_open_config): + exit_code = main([ + "test", "detector", + "--path-to-annotation", str(anno_file), + "--path-to-testingimages", str(img_dir), + "--model-path", str(det_dir), + "--result-path", str(out_dir) + ]) + assert exit_code == 2 + assert not out_dir.exists() + + def mock_open_params(file, *args, **kwargs): + if str(file).endswith("model_parameters.txt"): + raise PermissionError("Permission denied: unreadable model parameters") + return orig_open(file, *args, **kwargs) + + with patch("builtins.open", side_effect=mock_open_params): + exit_code = main([ + "test", "detector", + "--path-to-annotation", str(anno_file), + "--path-to-testingimages", str(img_dir), + "--model-path", str(det_dir), + "--result-path", str(out_dir) + ]) + assert exit_code == 2 + assert not out_dir.exists() + + +def test_handle_train_categorizer_validation_and_execution(tmp_path, capsys): + data_dir = tmp_path / "behavior_data" + data_dir.mkdir() + model_dir = tmp_path / "cat_model" + dummy_file = tmp_path / "dummy.txt" + dummy_file.write_text("file") + + exit_code = main(["train", "categorizer", "--data-path", str(tmp_path / "nonexistent_data"), "--model-path", str(model_dir)]) + assert exit_code == 2 + assert not model_dir.exists() + + exit_code = main(["train", "categorizer", "--data-path", str(dummy_file), "--model-path", str(model_dir)]) + assert exit_code == 2 + assert not model_dir.exists() + + exit_code = main(["train", "categorizer", "--data-path", str(data_dir), "--model-path", str(model_dir)]) + assert exit_code == 2 + assert not model_dir.exists() + + (data_dir / "0_groom.jpg").write_text("image_content") + + exit_code = main(["train", "categorizer", "--data-path", str(data_dir), "--model-path", str(dummy_file)]) + assert exit_code == 2 + + exit_code = main(["train", "categorizer", "--data-path", str(data_dir), "--model-path", str(model_dir), "--out-path", str(dummy_file)]) + assert exit_code == 2 + assert not model_dir.exists() + + exit_code = main(["train", "categorizer", "--data-path", str(data_dir), "--model-path", str(model_dir), "--out-folder", str(dummy_file)]) + assert exit_code == 2 + assert not model_dir.exists() + + exit_code = main(["train", "categorizer", "--data-path", str(data_dir), "--model-path", str(model_dir), "--aug-methods", "bad_aug"]) + assert exit_code == 2 + assert not model_dir.exists() + + out_path = tmp_path / "reports" + with patch('LabGym.categorizer.Categorizers.train_combnet') as mock_train: + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--out-path", str(out_path), + "--network-type", "combnet", + "--aug-methods", "rotation", "vertical flipping" + ]) + assert exit_code == 0 + assert model_dir.exists() + assert out_path.exists() + mock_train.assert_called_once() + _, kwargs = mock_train.call_args + assert kwargs['aug_methods'] == ['random rotation', 'vertical flipping'] + captured = capsys.readouterr() + assert "Categorizer training completed successfully." in captured.out + + +def test_handle_train_categorizer_onfly_requires_subdirectories(tmp_path): + data_dir = tmp_path / "behavior_data_onfly" + data_dir.mkdir() + model_dir = tmp_path / "cat_model" + + with patch('LabGym.categorizer.Categorizers.train_combnet_onfly') as mock_train: + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--training-onfly" + ]) + assert exit_code == 2 + assert not model_dir.exists() + mock_train.assert_not_called() + + (data_dir / "train").mkdir() + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--training-onfly" + ]) + assert exit_code == 2 + assert not model_dir.exists() + mock_train.assert_not_called() + + (data_dir / "validation").mkdir() + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--training-onfly" + ]) + assert exit_code == 0 + assert model_dir.exists() + mock_train.assert_called_once() + + +def test_handle_train_categorizer_rejects_incompatible_combinations(tmp_path): + data_dir = tmp_path / "behavior_data" + data_dir.mkdir() + (data_dir / "0_groom.jpg").write_text("image") + (data_dir / "train").mkdir() + (data_dir / "validation").mkdir() + model_dir = tmp_path / "cat_model" + + with patch('LabGym.categorizer.Categorizers.train_combnet') as mock_c, \ + patch('LabGym.categorizer.Categorizers.train_combnet_onfly') as mock_co, \ + patch('LabGym.categorizer.Categorizers.train_pattern_recognizer') as mock_pr: + + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--training-onfly", + "--aug-methods", "rotation" + ]) + assert exit_code == 2 + assert not model_dir.exists() + mock_co.assert_not_called() + + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--training-onfly", + "--no-augvalid" + ]) + assert exit_code == 2 + assert not model_dir.exists() + mock_co.assert_not_called() + + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--training-onfly", + "--out-folder", str(tmp_path / "cache") + ]) + assert exit_code == 2 + assert not model_dir.exists() + mock_co.assert_not_called() + + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--network-type", "pattern_recognizer", + "--color-costar" + ]) + assert exit_code == 2 + assert not model_dir.exists() + mock_pr.assert_not_called() + + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--network-type", "combnet", + "--behavior-mode", "3" + ]) + assert exit_code == 2 + assert not model_dir.exists() + mock_c.assert_not_called() + + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--network-type", "animation_analyzer", + "--behavior-mode", "3" + ]) + assert exit_code == 2 + assert not model_dir.exists() + + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--network-type", "pattern_recognizer", + "--behavior-mode", "3" + ]) + assert exit_code == 0 + assert model_dir.exists() + mock_pr.assert_called_once() + + +def test_handle_train_categorizer_network_dispatch(tmp_path): + data_dir = tmp_path / "behavior_data" + data_dir.mkdir() + (data_dir / "0_groom.jpg").write_text("image") + (data_dir / "train").mkdir() + (data_dir / "validation").mkdir() + model_dir = tmp_path / "cat_model" + + with patch('LabGym.categorizer.Categorizers.train_pattern_recognizer') as mock_pr: + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--network-type", "pattern_recognizer" + ]) + assert exit_code == 0 + mock_pr.assert_called_once() + + with patch('LabGym.categorizer.Categorizers.train_pattern_recognizer_onfly') as mock_pr_onfly: + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--network-type", "pattern_recognizer", + "--training-onfly" + ]) + assert exit_code == 0 + mock_pr_onfly.assert_called_once() + + with patch('LabGym.categorizer.Categorizers.train_animation_analyzer') as mock_aa: + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--network-type", "animation_analyzer" + ]) + assert exit_code == 0 + mock_aa.assert_called_once() + + with patch('LabGym.categorizer.Categorizers.train_animation_analyzer_onfly') as mock_aa_onfly: + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--network-type", "animation_analyzer", + "--training-onfly" + ]) + assert exit_code == 0 + mock_aa_onfly.assert_called_once() + + with patch('LabGym.categorizer.Categorizers.train_combnet_onfly') as mock_cb_onfly: + exit_code = main([ + "train", "categorizer", + "--data-path", str(data_dir), + "--model-path", str(model_dir), + "--network-type", "combnet", + "--training-onfly" + ]) + assert exit_code == 0 + mock_cb_onfly.assert_called_once() + + +def test_handle_train_detector_validation_and_execution(tmp_path, capsys): + anno_file = tmp_path / "annotations.json" + anno_file.write_text(json.dumps({ + "categories": [{"id": 1, "name": "mouse"}], + "images": [{"id": 1, "file_name": "img.jpg"}], + "annotations": [] + })) + img_dir = tmp_path / "train_images" + img_dir.mkdir() + det_dir = tmp_path / "det_model" + dummy_file = tmp_path / "dummy.txt" + dummy_file.write_text("dummy") + + exit_code = main([ + "train", "detector", + "--path-to-annotation", str(tmp_path / "nonexistent.json"), + "--path-to-trainingimages", str(img_dir), + "--model-path", str(det_dir) + ]) + assert exit_code == 2 + assert not det_dir.exists() + + exit_code = main([ + "train", "detector", + "--path-to-annotation", str(img_dir), + "--path-to-trainingimages", str(img_dir), + "--model-path", str(det_dir) + ]) + assert exit_code == 2 + assert not det_dir.exists() + + bad_json = tmp_path / "bad.json" + bad_json.write_text("invalid json") + exit_code = main([ + "train", "detector", + "--path-to-annotation", str(bad_json), + "--path-to-trainingimages", str(img_dir), + "--model-path", str(det_dir) + ]) + assert exit_code == 2 + assert not det_dir.exists() + + exit_code = main([ + "train", "detector", + "--path-to-annotation", str(anno_file), + "--path-to-trainingimages", str(tmp_path / "nonexistent_imgs"), + "--model-path", str(det_dir) + ]) + assert exit_code == 2 + assert not det_dir.exists() + + exit_code = main([ + "train", "detector", + "--path-to-annotation", str(anno_file), + "--path-to-trainingimages", str(dummy_file), + "--model-path", str(det_dir) + ]) + assert exit_code == 2 + assert not det_dir.exists() + + exit_code = main([ + "train", "detector", + "--path-to-annotation", str(anno_file), + "--path-to-trainingimages", str(img_dir), + "--model-path", str(dummy_file) + ]) + assert exit_code == 2 + + existing_dir = tmp_path / "existing_det" + existing_dir.mkdir() + exit_code = main([ + "train", "detector", + "--path-to-annotation", str(anno_file), + "--path-to-trainingimages", str(img_dir), + "--model-path", str(existing_dir) + ]) + assert exit_code == 2 + + file_parent = tmp_path / "file_parent" + file_parent.write_text("file") + exit_code = main([ + "train", "detector", + "--path-to-annotation", str(anno_file), + "--path-to-trainingimages", str(img_dir), + "--model-path", str(file_parent / "det_model") + ]) + assert exit_code == 2 + + with patch('LabGym.detector.Detector.train') as mock_train: + exit_code = main([ + "train", "detector", + "--path-to-annotation", str(anno_file), + "--path-to-trainingimages", str(img_dir), + "--model-path", str(det_dir), + "--iteration-num", "500", + "--inference-size", "600" + ]) + assert exit_code == 0 + mock_train.assert_called_once_with( + str(anno_file), str(img_dir), str(det_dir), 500, 600 + ) + captured = capsys.readouterr() + assert "Detector training completed successfully." in captured.out + + +def test_handle_train_detector_annotation_validation(tmp_path): + img_dir = tmp_path / "train_images" + img_dir.mkdir() + det_dir = tmp_path / "det_model" + + invalid_annos = [ + {"images": [], "annotations": []}, + {"categories": [], "images": [], "annotations": []}, + {"categories": ["not_a_dict"], "images": [], "annotations": []}, + {"categories": [{"name": "mouse"}], "images": [], "annotations": []}, + {"categories": [{"id": True, "name": "mouse"}], "images": [], "annotations": []}, + {"categories": [{"id": "1", "name": "mouse"}], "images": [], "annotations": []}, + {"categories": [{"id": 1}], "images": [], "annotations": []}, + {"categories": [{"id": 1, "name": " "}], "images": [], "annotations": []}, + {"categories": [{"id": 1, "name": True}], "images": [], "annotations": []}, + {"categories": [{"id": 0, "name": "background"}], "images": [], "annotations": []}, + {"categories": [{"id": 1, "name": "mouse"}], "annotations": []}, + {"categories": [{"id": 1, "name": "mouse"}], "images": "not_a_list", "annotations": []}, + {"categories": [{"id": 1, "name": "mouse"}], "images": []}, + {"categories": [{"id": 1, "name": "mouse"}], "images": [], "annotations": {}}, + ] + + for idx, bad_data in enumerate(invalid_annos): + bad_anno_file = tmp_path / f"bad_anno_{idx}.json" + bad_anno_file.write_text(json.dumps(bad_data)) + + with patch('LabGym.detector.Detector.train') as mock_train: + exit_code = main([ + "train", "detector", + "--path-to-annotation", str(bad_anno_file), + "--path-to-trainingimages", str(img_dir), + "--model-path", str(det_dir) + ]) + assert exit_code == 2, f"Expected exit code 2 for case {idx}: {bad_data}" + assert not det_dir.exists(), f"Output dir should not be created for case {idx}" + mock_train.assert_not_called() + + +def test_train_rejects_irrelevant_cross_command_parameters(tmp_path): + cfg_cat = tmp_path / "cat_bad.yaml" + with open(cfg_cat, "w") as f: + yaml.dump({ + 'data_path': str(tmp_path), + 'model_path': str(tmp_path / 'model'), + 'path_to_annotation': 'anno.json' + }, f) + exit_code = main(["train", "categorizer", "-c", str(cfg_cat)]) + assert exit_code == 2 + + cfg_det = tmp_path / "det_bad.yaml" + with open(cfg_det, "w") as f: + yaml.dump({ + 'path_to_annotation': 'anno.json', + 'path_to_trainingimages': str(tmp_path), + 'model_path': str(tmp_path / 'model'), + 'data_path': str(tmp_path) + }, f) + exit_code = main(["train", "detector", "-c", str(cfg_det)]) + assert exit_code == 2 + + +def test_animal_number_scalar_and_structured_types_and_validation(): + cli_args = {'animal_number': '2'} + 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-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-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-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-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-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-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 = [ + True, + False, + 0, + -1, + "0", + "-5", + "abc", + {"mouse": 0}, + {"mouse": -1}, + {"mouse": True}, + {"mouse": "two"}, + {"": 2}, + {" ": 2}, + [1, 2], + ] + for bad_val in invalid_inputs: + with pytest.raises(CLIConfigError): + 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): + video = tmp_path / "vid.mp4" + video.write_bytes(b"vid") + out = tmp_path / "out" + + exit_code = main([ + "infer", + "--path-to-videos", str(video), + "--result-path", str(out), + "--animal-number", '{"mouse": 2}' + ]) + assert exit_code == 2 + assert not out.exists() + + cfg_file = tmp_path / "infer_non_det_mapping.yaml" + with open(cfg_file, "w") as f: + yaml.dump({ + "path_to_videos": [str(video)], + "result_path": str(out), + "animal_number": {"mouse": 2}, + "use_detector": False + }, f) + exit_code = main(["infer", "-c", str(cfg_file)]) + assert exit_code == 2 + assert not out.exists() + + +def test_headless_smoke_workflow_train_test_infer(tmp_path, capsys): + cat_train_data = tmp_path / "cat_data" + cat_train_data.mkdir() + (cat_train_data / "train1.jpg").write_bytes(b"image") + cat_model_dir = tmp_path / "trained_cat" + + det_imgs_dir = tmp_path / "det_imgs" + det_imgs_dir.mkdir() + (det_imgs_dir / "img1.png").write_bytes(b"image") + det_anno = tmp_path / "det_train.json" + det_anno.write_text(json.dumps({ + "categories": [{"id": 1, "name": "mouse"}], + "images": [{"id": 1, "file_name": "img1.png"}], + "annotations": [] + })) + det_model_dir = tmp_path / "trained_det" + + cat_gt_dir = tmp_path / "cat_gt" + cat_gt_dir.mkdir() + det_test_imgs = tmp_path / "det_test_imgs" + det_test_imgs.mkdir() + det_test_anno = tmp_path / "det_test.json" + det_test_anno.write_text(json.dumps({ + "categories": [{"id": 1, "name": "mouse"}], + "images": [{"id": 1, "file_name": "test1.png"}], + "annotations": [] + })) + + video_file = tmp_path / "video.mp4" + video_file.write_bytes(b"video") + infer_out = tmp_path / "infer_results" + + cat_meta_content = ( + "classnames,dim_conv,channel,time_step,network,inner_code,std,background_free,black_background,behavior_kind,social_distance,color_code\n" + "walk,64,1,15,0,0,0,0,0,0,0,1\n" + ) + + def fake_train_cat(*args, **kwargs): + cat_model_dir.mkdir(parents=True, exist_ok=True) + (cat_model_dir / "model_parameters.txt").write_text(cat_meta_content) + + with patch('LabGym.categorizer.Categorizers.train_combnet', side_effect=fake_train_cat): + code = main([ + "train", "categorizer", + "--data-path", str(cat_train_data), + "--model-path", str(cat_model_dir) + ]) + assert code == 0 + captured = capsys.readouterr() + assert "Categorizer training completed successfully." in captured.out + + def fake_train_det(*args, **kwargs): + det_model_dir.mkdir(parents=True, exist_ok=True) + (det_model_dir / "model_parameters.txt").write_text(json.dumps({"animal_mapping": {"0": "mouse"}, "inferencing_framesize": 480})) + (det_model_dir / "config.yaml").write_text("MODEL:\n DEVICE: cpu\n") + (det_model_dir / "model_final.pth").write_bytes(b"pth") + + with patch('LabGym.detector.Detector.train', side_effect=fake_train_det): + code = main([ + "train", "detector", + "--path-to-annotation", str(det_anno), + "--path-to-trainingimages", str(det_imgs_dir), + "--model-path", str(det_model_dir) + ]) + assert code == 0 + captured = capsys.readouterr() + assert "Detector training completed successfully." in captured.out + + with patch('LabGym.categorizer.Categorizers.test_categorizer') as mock_test_cat: + code = main([ + "test", "categorizer", + "--groundtruth-path", str(cat_gt_dir), + "--model-path", str(cat_model_dir), + "--result-path", str(tmp_path / "cat_eval") + ]) + assert code == 0 + mock_test_cat.assert_called_once() + captured = capsys.readouterr() + assert "Categorizer testing completed successfully." in captured.out + + with patch('LabGym.detector.Detector.test') as mock_test_det: + code = main([ + "test", "detector", + "--path-to-annotation", str(det_test_anno), + "--path-to-testingimages", str(det_test_imgs), + "--model-path", str(det_model_dir), + "--result-path", str(tmp_path / "det_eval") + ]) + assert code == 0 + mock_test_det.assert_called_once() + captured = capsys.readouterr() + assert "Detector testing completed successfully." in captured.out + + with patch('LabGym.analyzebehavior_dt.AnalyzeAnimalDetector') as mock_aad_cls: + instance = MagicMock() + instance.event_probability = {} + instance.all_time = [] + mock_aad_cls.return_value = instance + + code = main([ + "infer", + "--path-to-videos", str(video_file), + "--result-path", str(infer_out), + "--path-to-categorizer", str(cat_model_dir), + "--path-to-detector", str(det_model_dir), + "--use-detector" + ]) + assert code == 0 + instance.prepare_analysis.assert_called_once() + captured = capsys.readouterr() + assert "Inference completed successfully." in captured.out + + +def test_cli_subprocess_headless_execution(): + cmd = [ + sys.executable, + "-c", + "import sys, subprocess; " + "res = subprocess.run([sys.executable, '-m', 'LabGym.cli', '--help'], capture_output=True, text=True); " + "sys.exit(0 if (res.returncode == 0 and 'LabGym CLI' in res.stdout and res.stderr == '') else 1)" + ] + proc = subprocess.run(cmd, capture_output=True, text=True) + assert proc.returncode == 0 + + err_cmd = [ + sys.executable, + "-c", + "import sys, subprocess; " + "res = subprocess.run([sys.executable, '-m', 'LabGym.cli', 'invalid_subcmd'], capture_output=True, text=True); " + "sys.exit(0 if (res.returncode == 2 and 'invalid choice' in res.stderr and res.stdout == '') else 1)" + ] + proc_err = subprocess.run(err_cmd, capture_output=True, text=True) + assert proc_err.returncode == 0 + + no_wx_cmd = [ + sys.executable, + "-c", + "from LabGym import cli; import sys; " + "p = cli.build_parser(); " + "p.parse_args(['train', 'categorizer', '--data-path', 'd', '--model-path', 'm']); " + "sys.exit(0 if 'wx' not in sys.modules else 1)" + ] + 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"} + + +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 == "" + + +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_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" + 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] + diff --git a/LabGym_CLI_Guide.md b/LabGym_CLI_Guide.md new file mode 100644 index 00000000..5ee79305 --- /dev/null +++ b/LabGym_CLI_Guide.md @@ -0,0 +1,286 @@ +# LabGym Command Line Interface (CLI) Guide + +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-cli train categorizer` +* `labgym-cli train detector` +* `labgym-cli test categorizer` +* `labgym-cli test detector` +* `labgym-cli infer` + +Launch the desktop GUI with the separate `LabGym` command: +```bash +LabGym +``` + +### 3-Tier Precedence Hierarchy +Workflows can be driven purely by inline CLI flags, by a YAML workflow file (`-c` / `--config`), or a combination: +$$\text{Built-in Defaults} \quad\longrightarrow\quad \text{Workflow YAML } (\texttt{-c} \text{ / } \texttt{--config}) \quad\longrightarrow\quad \text{Inline CLI Overrides}$$ + +* Inline flags default to `None` so omitted flags never override YAML settings. +* Paired Boolean flags (e.g. `--use-detector` and `--no-use-detector`) allow explicit override in either direction while preserving YAML defaults when omitted. +* CLI options use kebab-case (`--data-path`), mapping directly to snake_case (`data_path`) in YAML and Python. + +### Workflow Configuration vs. Persistent Application Preferences +The `--config` / `-c` flag specifies a **per-command workflow (job) configuration file** written in YAML. + +* **Workflow Configuration (`--config`)**: A job-specific, hermetic YAML document defining the exact parameters, inputs, models, and outputs for a single headless execution. It is designed for reproducible scripted runs, automated analysis pipelines, and cluster submissions. +* **Persistent Application Preferences**: LabGym GUI settings or system-level preferences stored across sessions are **not** loaded, modified, or referenced by the headless CLI. The CLI operates completely independently of persistent GUI state, relying solely on built-in command defaults, the specified workflow YAML file, and explicit command-line flags. + +--- + +## 2. Command Reference + +### `labgym-cli train categorizer` +Headless training for behavior classification sub-networks (Pattern Recognizer, Animation Analyzer, or CombNet). + +* **Syntax**: + ```bash + labgym-cli train categorizer --config [inline-overrides] + ``` + +* **Required Parameters**: + * `--data-path` (`data_path`): Path to training examples dataset directory + * `--model-path` (`model_path`): Destination directory for the trained model + +* **Key Options**: + * `--network-type` (`network_type`): `combnet` (default), `pattern_recognizer`, `animation_analyzer`, or `combined_network` + * `--out-path` (`out_path`): Directory for training logs and reports + * `--out-folder` (`out_folder`): Cache directory for prepared frames + * `--dim-conv` (`dim_conv`): Input size for Pattern Recognizer (default: 64) + * `--dim-tconv` (`dim_tconv`): Input size for Animation Analyzer (default: 32) + * `--channel` (`channel`): Image channels, 1 or 3 (default: 1) + * `--time-step` (`time_step`): Frames per behavioral sequence (default: 15) + * `--level-conv` (`level_conv`): Complexity level for Pattern Recognizer 1–5 (default: 2) + * `--level-tconv` (`level_tconv`): Complexity level for Animation Analyzer 1–5 (default: 1) + * `--aug-methods` (`aug_methods`): List of augmentation methods (e.g. `"random rotation"`, `"horizontal flipping"`) + * `--augvalid` / `--no-augvalid`: Validate augmentation data (default: True) + * `--include-bodyparts` / `--no-include-bodyparts`: Include body part contours (default: True) + * `--std` (`std`): Standard deviation threshold parameter for body parts (default: 0.0) + * `--background-free` / `--no-background-free`: Exclude background from calculations (default: True) + * `--black-background` / `--no-black-background`: Use black background (default: True) + * `--behavior-mode` (`behavior_mode`): Mode 0 (standard), 1 (basic interactive), 2 (advanced interactive), 3 (static images) + * `--social-distance` (`social_distance`): Social interaction distance threshold (default: 0.0) + * `--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-cli train detector` +Headless training for Detectron2 object detection models. + +* **Syntax**: + ```bash + labgym-cli train detector --config [inline-overrides] + ``` + +* **Required Parameters**: + * `--path-to-annotation` (`path_to_annotation`): Path to COCO JSON annotation file + * `--path-to-trainingimages` (`path_to_trainingimages`): Directory containing training images + * `--model-path` (`model_path`): Destination directory for the trained detector + +* **Key Options**: + * `--iteration-num` (`iteration_num`): Number of training iterations (default: 200) + * `--inference-size` (`inference_size`): Image frame resizing dimension for inference (default: 480) + +### `labgym-cli test categorizer` +Headless evaluation of a trained behavior classifier against ground-truth data. + +* **Syntax**: + ```bash + labgym-cli test categorizer --config [inline-overrides] + ``` + +* **Required Parameters**: + * `--groundtruth-path` (`groundtruth_path`): Path to ground-truth testing dataset folder + * `--model-path` (`model_path`): Path to trained Categorizer directory + +* **Key Options**: + * `--result-path` (`result_path`): Directory to write evaluation metrics and confusion matrices + +### `labgym-cli test detector` +Headless evaluation of a trained object detector against annotated testing images. + +* **Syntax**: + ```bash + labgym-cli test detector --config [inline-overrides] + ``` + +* **Required Parameters**: + * `--path-to-annotation` (`path_to_annotation`): Path to COCO JSON annotation file + * `--path-to-testingimages` (`path_to_testingimages`): Directory containing test images + * `--model-path` (`model_path`): Path to trained Detector directory + * `--result-path` (`result_path`): Directory to write detection test results + +### `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-cli infer --config [inline-overrides] + ``` + +* **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. 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 + * `--path-to-detector` (`path_to_detector`): Path to trained Detector directory + * `--use-detector` / `--no-use-detector`: Enable or disable detector-based tracking (default: False) + +* **Analysis Options**: + * `--framewidth` (`framewidth`): Target image resizing width in pixels + * `--background-path` (`background_path`): Path to background reference image (for background subtraction) + * `--delta` (`delta`): Delta trigger threshold (default: 10000.0) + * `--animal-kinds` (`animal_kinds`): List of animal categories recognized by the detector + * `--animal-to-include` (`animal_to_include`): Specific animals to include in output reports + * `--behavior-to-include` (`behavior_to_include`): Behaviors to quantify (default: `['all']`) + * `--detector-batch` (`detector_batch`): Batch size for detector processing (default: 1) + * `--detection-threshold` (`detection_threshold`): Detection confidence threshold 0.0–1.0 (default: 0.0) + * `--animal-number` (`animal_number`): Total animal count (positive integer) for all inference modes, or animal-kind-to-count mapping (e.g. `{"mouse": 2, "fly": 1}`) when detector inference is enabled (`--use-detector` / `use_detector: true`). Structured mappings are rejected without detector inference. + * `--decode-animalnumber` / `--no-decode-animalnumber`: Extract animal counts from video filenames + * `--autofind-t` / `--no-autofind-t`: Automatically detect optical stimulation trigger start time (default: False) + * `--t` (`t`): Analysis start offset in seconds (default: 0.0) + * `--duration` (`duration`): Analysis duration in seconds (default: 0.0 = full video) + * `--decode-t` / `--no-decode-t`: Extract start time from video filenames + * `--ex-start` (`ex_start`): Extraction start frame number (default: 0) + * `--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) + * `--min-length` (`min_length`): Minimum behavior duration in frames + * `--show-legend` / `--no-show-legend`: Render behavior legends on output videos (default: True) + * `--normalize-distance` / `--no-normalize-distance`: Normalize distances by contour size (default: True) + * `--correct-id` / `--no-correct-id`: Apply ID correction heuristics (default: False) + * `--specific-behaviors` (`specific_behaviors`): Custom behavior definition mapping + +--- + +## 3. Configuration YAML Examples + +### Categorizer Training (`train_categorizer.yaml`) +```yaml +# labgym-cli train categorizer -c train_categorizer.yaml +data_path: "~/data/behavior_examples" +model_path: "~/models/categorizer_combnet" +network_type: "combnet" +out_path: "~/logs/categorizer_training" + +# Architecture dimensions +dim_conv: 64 +dim_tconv: 32 +channel: 1 +time_step: 15 +level_conv: 2 +level_tconv: 1 + +# Preprocessing & Augmentation +training_onfly: false +augvalid: true +include_bodyparts: true +std: 0.0 +background_free: true +black_background: true +behavior_mode: 0 +social_distance: 0.0 +``` + +### Detector Training (`train_detector.yaml`) +```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" +iteration_num: 1000 +inference_size: 480 +``` + +### Model Evaluation (`test_categorizer.yaml`) +```yaml +# labgym-cli test categorizer -c test_categorizer.yaml +groundtruth_path: "~/data/groundtruth_examples" +model_path: "~/models/categorizer_combnet" +result_path: "~/results/categorizer_eval" +``` + +### Detector Evaluation (`test_detector.yaml`) +```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" +result_path: "~/results/detector_eval" +``` + +### Behavioral Inference (`infer.yaml`) +```yaml +# labgym-cli infer -c infer.yaml +path_to_videos: + - "~/videos/session_1.mp4" + - "~/videos/session_2.mp4" +result_path: "~/results/inference_run_1" + +# Trained models +path_to_categorizer: "~/models/categorizer_combnet" +path_to_detector: "~/models/detector_mouse" +use_detector: true + +# Run parameters +detector_batch: 2 +animal_kinds: + - "mouse" +duration: 120.0 +show_legend: true +normalize_distance: true +``` + +--- + +## 4. High-Performance Computing (SLURM) Example + +Below is an example job script for submitting a headless training run on an HPC cluster: + +```bash +#!/bin/bash +#SBATCH --job-name=labgym_train +#SBATCH --output=logs/labgym_%j.out +#SBATCH --error=logs/labgym_%j.err +#SBATCH --time=04:00:00 +#SBATCH --partition=gpu +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=4 +#SBATCH --mem=16G + +module load python/3.10 +source ~/envs/labgym/bin/activate + +labgym-cli train categorizer \ + --config train_categorizer.yaml \ + --data-path ~/data/behavior_dataset \ + --model-path ~/models/combnet_run \ + --level-conv 3 +``` + +--- + +## 5. Exit Codes & Output Streams + +The LabGym CLI adheres to POSIX process exit conventions: + +* **Exit Code `0`**: Workflow succeeded. +* **Exit Code `1`**: Runtime scientific execution failure (e.g. underlying computation or model exception). +* **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/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/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 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 diff --git a/pyproject.toml b/pyproject.toml index 89d7d735..b70da498 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -77,6 +77,7 @@ Issues='http://github.com/umyelab/LabGym/issues' [project.scripts] LabGym='LabGym.__main__:main' +labgym-cli='LabGym.cli:main' [tool.pdm] distribution=true