diff --git a/CHANGELOG b/CHANGELOG index d873c51..5d5c623 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,7 @@ 0.11.2 - fix: `python -m chipstream.cli` failed with ModuleNotFoundError - fix: `chipstream-cli --recursive` silently did nothing when PATH_IN is a file + - fix: malformed `-ks`/`-kb`/`-kf`/`-kg` arguments of `chipstream-cli` caused tracebacks; values could not contain "=" and "None" was not accepted 0.11.1 - enh: don't show rounded 100% in CLI progress - setup: bump dcnum to 0.31.2 diff --git a/chipstream/cli/cli_valid.py b/chipstream/cli/cli_valid.py index cba4632..44dd8a1 100644 --- a/chipstream/cli/cli_valid.py +++ b/chipstream/cli/cli_valid.py @@ -1,7 +1,10 @@ import inspect +import types +import typing from typing import Any, get_type_hints import warnings +import click from dcnum.meta import ppid import dcnum.read import h5py @@ -9,6 +12,57 @@ from . import cli_common as cm +def convert_kwarg_value(key: str, + value: str, + dtype: Any, + option: str) -> Any: + """Convert a command-line keyword argument value to `dtype` + + The string "None" (case-insensitive) is converted to `None` if + `dtype` allows `None`. + + Raises + ------ + click.BadParameter + if the value cannot be converted + """ + if (value.lower() == "none" + and typing.get_origin(dtype) in {typing.Union, types.UnionType} + and type(None) in typing.get_args(dtype)): + return None + try: + return ppid.convert_to_dtype(value, dtype) + except (TypeError, ValueError) as e: + dtype_name = getattr(dtype, "__name__", str(dtype)) + raise click.BadParameter( + f"Invalid value '{value}' for keyword '{key}' " + f"(expected {dtype_name}): {e}", + param_hint=f"'{option}'") + + +def split_kwargs(args: list[str], option: str) -> list[tuple[str, str]]: + """Split command-line `KEY=VALUE` arguments into key-value pairs + + Only the first "=" separates the key from the value, so the + value may contain "=" (e.g. in a file path). + + Raises + ------ + click.BadParameter + if an argument has no "=" or an empty key + """ + pairs = [] + for arg in args or []: + key, sep, value = arg.partition("=") + key = key.strip() + if not sep or not key: + raise click.BadParameter( + f"Expected 'KEY=VALUE', got '{arg}'", + param_hint=f"'{option}'") + pairs.append((key, value)) + return pairs + + def validate_background_kwargs(bg_method, args): """Parse background keyword arguments""" # Get list of valid keyword arguments @@ -18,12 +72,15 @@ def validate_background_kwargs(bg_method, args): annot = get_type_hints(bg_cls.check_user_kwargs) # Convert the input args to key-value pairs kwargs = {} - for key, value in [a.split("=") for a in args]: + for key, value in split_kwargs(args, "-kb"): if key not in valid_kw: - raise ValueError(f"Invalid keyword '{key}' for {bg_method}. " - + f"Allowed keywords are {valid_kw}!") + raise click.BadParameter( + f"Invalid keyword '{key}' for '{bg_method}'. " + f"Allowed keywords are {valid_kw}!", + param_hint="'-kb'") # Convert to correct dtype (default to string) - kwargs[key] = ppid.convert_to_dtype(value, annot[key]) + kwargs[key] = convert_kwarg_value(key, value, annot.get(key, str), + "-kb") return kwargs @@ -37,13 +94,15 @@ def validate_feature_kwargs(args: list[str]) -> dict[str, Any]: annot = get_type_hints(feat_cls.get_events_from_masks) # Convert the input args to key-value pairs kwargs = {} - for key, value in [a.split("=") for a in args]: + for key, value in split_kwargs(args, "-kf"): if key in valid_kw: - kwargs[key] = ppid.convert_to_dtype(value, annot[key]) + kwargs[key] = convert_kwarg_value( + key, value, annot.get(key, str), "-kf") else: - raise ValueError( + raise click.BadParameter( f"Invalid keyword '{key}' for '{feat_code}'. " - f"Allowed keywords are {valid_kw}!") + f"Allowed keywords are {valid_kw}!", + param_hint="'-kf'") return kwargs @@ -53,13 +112,15 @@ def validate_gate_kwargs(args: list[str]) -> dict[str, Any]: annot = get_type_hints(cm.Gate.__init__) # Convert the input args to key-value pairs kwargs = {} - for key, value in [a.split("=") for a in args]: + for key, value in split_kwargs(args, "-kg"): if key in valid_kw: - kwargs[key] = ppid.convert_to_dtype(value, annot[key]) + kwargs[key] = convert_kwarg_value( + key, value, annot.get(key, str), "-kg") else: - raise ValueError( + raise click.BadParameter( f"Invalid keyword '{key}' for gating. " - f"Allowed keywords are {valid_kw} (and box filters)!") + f"Allowed keywords are {valid_kw} (and box filters)!", + param_hint="'-kg'") return kwargs @@ -116,14 +177,17 @@ def validate_segmentation_kwargs(seg_method, args): # Convert the input args to key-value pairs kwargs = {} kwargs_mask = {} - for key, value in [a.split("=") for a in args]: + for key, value in split_kwargs(args, "-ks"): if key in valid_kw_mask: - kwargs_mask[key] = ppid.convert_to_dtype(value, annot_mask[key]) + kwargs_mask[key] = convert_kwarg_value( + key, value, annot_mask.get(key, str), "-ks") elif key in valid_kw: - kwargs[key] = ppid.convert_to_dtype(value, annot[key]) + kwargs[key] = convert_kwarg_value( + key, value, annot.get(key, str), "-ks") else: - raise ValueError( - f"Invalid keyword '{key}' for {seg_method}. " - f"Allowed keywords are {valid_kw + valid_kw_mask}!") + raise click.BadParameter( + f"Invalid keyword '{key}' for '{seg_method}'. " + f"Allowed keywords are {valid_kw + valid_kw_mask}!", + param_hint="'-ks'") kwargs["kwargs_mask"] = kwargs_mask return kwargs diff --git a/tests/test_cli.py b/tests/test_cli.py index 58e8a0b..05ff4f1 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -13,7 +13,7 @@ import dcnum # noqa: E402 import chipstream # noqa: E402 -from chipstream.cli import cli_main # noqa: E402 +from chipstream.cli import cli_main, cli_valid # noqa: E402 @pytest.mark.parametrize("drain", [True, False]) @@ -156,6 +156,63 @@ def test_invalid_input_data_bad_format(cli_runner, tmp_path): assert result.stderr.count("Not a valid input file") +@pytest.mark.parametrize("args,message", [ + # missing "=" + [["-ks", "thresh"], "Expected 'KEY=VALUE', got 'thresh'"], + # missing key + [["-kb", "=5"], "Expected 'KEY=VALUE', got '=5'"], + # only the first "=" separates key and value + [["-ks", "thresh=1=2"], "Invalid value '1=2' for keyword 'thresh'"], + # unknown keywords + [["-ks", "peter=3"], "Invalid keyword 'peter' for 'thresh'"], + [["-kb", "peter=3"], "Invalid keyword 'peter' for 'sparsemed'"], + [["-kf", "peter=3"], "Invalid keyword 'peter' for 'legacy'"], + [["-kg", "peter=3"], "Invalid keyword 'peter' for gating"], + # invalid values + [["-kb", "kernel_size=abc"], "Invalid value 'abc' for keyword"], + [["-kf", "haralick=maybe"], "Invalid value 'maybe' for keyword"], + [["-kg", "size_thresh_mask=abc"], "Invalid value 'abc' for keyword"], + # None is only allowed if the keyword argument accepts None + [["-ks", "thresh=None"], "Invalid value 'None' for keyword"], +]) +def test_cli_kwargs_invalid(cli_runner, args, message): + path = retrieve_data( + "fmt-hdf5_cytoshot_full-features_legacy_allev_2023.zip") + result = cli_runner.invoke(cli_main.chipstream_cli, + [str(path), "--dry-run"] + args) + assert result.exit_code == 2 + assert result.stderr.count(f"Invalid value for '{args[0]}'") + assert result.stderr.count(message) + + +@pytest.mark.parametrize("value", ["None", "none", "10"]) +def test_cli_kwargs_none(cli_runner, value): + """The default "None" shown in the help string must be accepted""" + path = retrieve_data( + "fmt-hdf5_cytoshot_full-features_legacy_allev_2023.zip") + result = cli_runner.invoke(cli_main.chipstream_cli, + [str(path), "--dry-run", + "-kg", f"size_thresh_mask={value}"]) + assert result.exit_code == 0 + assert result.stdout.count("Gate ID:\tnorm:o=0^s=10") + + +def test_cli_kwargs_split_first_equal_sign(): + assert cli_valid.split_kwargs(["model_file=/path/a=b/m.dcnm", + "thresh=-3"], "-ks") == [ + ("model_file", "/path/a=b/m.dcnm"), + ("thresh", "-3"), + ] + + +def test_cli_kwargs_value_with_equal_sign(): + pytest.importorskip("torch") + kwargs = cli_valid.validate_segmentation_kwargs( + "torchmpo", ["model_file=/path/a=b/m.dcnm", "closing_disk=3"]) + assert kwargs["model_file"] == "/path/a=b/m.dcnm" + assert kwargs["kwargs_mask"] == {"closing_disk": 3} + + @pytest.mark.parametrize("limit_events,dcnum_mapping,dcnum_yield,f0", [ # this is the default ["0", "0", 36, 1],