Skip to content

Commit 840e3a0

Browse files
committed
[bugfix] Also reject negative and non-finite --weights
Address review: weights must be finite and non-negative, documented on ContentDetector and AdaptiveDetector. _weights_value returns the ScoreWeightsValue and lets get_value unwrap it.
1 parent 8c7184c commit 840e3a0

7 files changed

Lines changed: 40 additions & 6 deletions

File tree

‎scenedetect/_cli/config.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"""
1616

1717
import logging
18+
import math
1819
import os
1920
import os.path
2021
import typing as ty
@@ -221,6 +222,8 @@ def __init__(self, value: str | ContentDetector.Components):
221222
if not len(values) == 4:
222223
raise ValueError("Score weights must be specified as four numbers!")
223224
self._value = ContentDetector.Components(*(float(val) for val in values))
225+
if not all(math.isfinite(weight) and weight >= 0.0 for weight in self._value):
226+
raise ValueError("Weights must be finite and non-negative.")
224227
if not any(self._value):
225228
raise ValueError("At least one weight must be non-zero.")
226229

@@ -239,7 +242,8 @@ def from_config(config_value: str, default: "ScoreWeightsValue") -> "ScoreWeight
239242
except ValueError as ex:
240243
raise OptionParseFailure(
241244
"Score weights must be specified as four numbers in the form (H,S,L,E),"
242-
" e.g. (0.9, 0.2, 2.0, 0.5), with at least one non-zero."
245+
" e.g. (0.9, 0.2, 2.0, 0.5). Weights must be non-negative, with at least one"
246+
" non-zero."
243247
" Commas/brackets/slashes are ignored."
244248
) from ex
245249

‎scenedetect/_cli/context.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -185,13 +185,13 @@ def _kernel_size_value(kernel_size: int | None) -> KernelSizeValue | None:
185185
@staticmethod
186186
def _weights_value(
187187
weights: tuple[float, float, float, float] | None,
188-
) -> ContentDetector.Components | None:
189-
"""Validate `--weights` like the config file does, so all-zero weights give a usage error
188+
) -> ScoreWeightsValue | None:
189+
"""Validate `--weights` like the config file does, so invalid weights give a usage error
190190
instead of NaN frame scores."""
191191
if weights is None:
192192
return None
193193
try:
194-
return ScoreWeightsValue(ContentDetector.Components(*weights)).value
194+
return ScoreWeightsValue(ContentDetector.Components(*weights))
195195
except ValueError as ex:
196196
raise click.BadParameter(str(ex), param_hint="weights") from ex
197197

‎scenedetect/detectors/adaptive_detector.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@ def __init__(
5858
calculates frame score based on `weights`/`luma_only`/`kernel_size`.
5959
weights: Weight to place on each component when calculating frame score
6060
(`content_val` in a statsfile, the value `threshold` is compared against).
61-
If omitted, the default ContentDetector weights are used.
61+
If omitted, the default ContentDetector weights are used. Each weight must be
62+
finite and non-negative, and at least one must be non-zero.
6263
luma_only: If True, only considers changes in the luminance channel of the video.
6364
Equivalent to specifying `weights` as
6465
:attr:`~scenedetect.detectors.content_detector.ContentDetector.LUMA_ONLY_WEIGHTS`.

‎scenedetect/detectors/content_detector.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ def __init__(
118118
str (e.g. ``"0.6s"``, ``"00:00:00.600"``).
119119
weights: Weight to place on each component when calculating frame score
120120
(`content_val` in a statsfile, the value `threshold` is compared against).
121+
Each weight must be finite and non-negative, and at least one must be non-zero.
121122
luma_only: If True, only considers changes in the luminance channel of the video.
122123
Equivalent to specifying `weights` as
123124
:attr:`~scenedetect.detectors.content_detector.ContentDetector.LUMA_ONLY_WEIGHTS`.
@@ -132,6 +133,8 @@ def __init__(
132133
self._weights: ContentDetector.Components = weights
133134
if luma_only:
134135
self._weights = ContentDetector.LUMA_ONLY_WEIGHTS
136+
if not all(math.isfinite(weight) and weight >= 0.0 for weight in self._weights):
137+
raise ValueError("Weights must be finite and non-negative.")
135138
if not any(self._weights):
136139
raise ValueError("At least one weight must be non-zero.")
137140
self._kernel: numpy.ndarray | None = None

‎tests/test_cli.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,25 @@ def test_cli_weights_config_file_rejects_all_zero(tmp_path: Path, command: str):
483483
assert any("non-zero" in message for _, message in ex.value.init_log)
484484

485485

486+
@pytest.mark.parametrize("command", ["detect-content", "detect-adaptive"])
487+
@pytest.mark.parametrize("bad_weight", ["-1", "nan", "inf"])
488+
def test_cli_weights_rejects_negative_or_non_finite(command: str, bad_weight: str):
489+
exit_code, output = invoke_cli(
490+
["-i", DEFAULT_VIDEO_PATH, command, "-w", "1", "1", bad_weight, "0", "time", "-e", "1"]
491+
)
492+
assert exit_code != 0
493+
assert "Weights must be finite and non-negative." in output
494+
495+
496+
@pytest.mark.parametrize("command", ["detect-content", "detect-adaptive"])
497+
def test_cli_weights_config_file_rejects_negative(tmp_path: Path, command: str):
498+
config_path = tmp_path.joinpath("config.cfg")
499+
config_path.write_text(f"[{command}]\nweights = 1, 1, -1, 0\n")
500+
with pytest.raises(ConfigLoadFailure) as ex:
501+
ConfigRegistry(str(config_path))
502+
assert any("non-negative" in message for _, message in ex.value.init_log)
503+
504+
486505
@pytest.mark.parametrize(
487506
"cli_args",
488507
[

‎tests/test_detectors.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,3 +301,10 @@ def test_detector_rejects_all_zero_weights(detector_type):
301301
detector_type(weights=ContentDetector.Components(0.0, 0.0, 0.0, 0.0))
302302
# luma_only overrides weights, so this is still valid.
303303
detector_type(weights=ContentDetector.Components(0.0, 0.0, 0.0, 0.0), luma_only=True)
304+
305+
306+
@pytest.mark.parametrize("detector_type", [ContentDetector, AdaptiveDetector])
307+
@pytest.mark.parametrize("bad_weight", [-1.0, float("nan"), float("inf")])
308+
def test_detector_rejects_negative_or_non_finite_weights(detector_type, bad_weight: float):
309+
with pytest.raises(ValueError, match="Weights must be finite and non-negative"):
310+
detector_type(weights=ContentDetector.Components(1.0, 1.0, bad_weight, 0.0))

‎website/pages/changelog.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -864,4 +864,4 @@ Development
864864
- [bugfix] The CLI now exits with 1 when no frames could be read from the input video, or seeking to the `time -s`/`--start` time fails, instead of 0
865865
- [bugfix] `--kernel-size`/`-k` values the detectors cannot use (even numbers, 1, 0 and negatives other than -1) now give a usage error instead of a traceback, and `-k -1` now means auto, like the config file. A config file with `kernel-size = 1` is now an error [#604](https://github.com/Breakthrough/PySceneDetect/issues/604)
866866
- [bugfix] Out of range values for `detect-adaptive --frame-window` (below 1) and `save-images` `--num-images` (below 1), `--scale`, `--height` and `--width` (negative) now give a usage error instead of a traceback, and the same values are rejected in a config file [#609](https://github.com/Breakthrough/PySceneDetect/issues/609)
867-
- [bugfix] `detect-content` / `detect-adaptive` `--weights` set to all zeros (also in a config file) now give an error instead of NaN frame scores and no detected scenes, and `ContentDetector` / `AdaptiveDetector` raise a `ValueError` for them [#612](https://github.com/Breakthrough/PySceneDetect/issues/612)
867+
- [bugfix] `detect-content` / `detect-adaptive` `--weights` set to all zeros, or with a negative or non-finite weight (also in a config file), now give an error instead of NaN frame scores and no detected scenes, and `ContentDetector` / `AdaptiveDetector` raise a `ValueError` for them [#612](https://github.com/Breakthrough/PySceneDetect/issues/612)

0 commit comments

Comments
 (0)