Skip to content

Commit 8c7184c

Browse files
EnesSoydanBreakthrough
authored andcommitted
[bugfix] Reject all-zero --weights instead of producing NaN frame scores
All-zero weights made ContentDetector divide by zero for every frame, so detect-content/detect-adaptive ran without finding any scenes. Reject them in ContentDetector, and give a usage error for -w and a config file error. Fixes #612
1 parent c5b0663 commit 8c7184c

6 files changed

Lines changed: 56 additions & 20 deletions

File tree

‎scenedetect/_cli/config.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,8 @@ def __init__(self, value: str | ContentDetector.Components):
221221
if not len(values) == 4:
222222
raise ValueError("Score weights must be specified as four numbers!")
223223
self._value = ContentDetector.Components(*(float(val) for val in values))
224+
if not any(self._value):
225+
raise ValueError("At least one weight must be non-zero.")
224226

225227
@property
226228
def value(self) -> ContentDetector.Components:
@@ -237,7 +239,8 @@ def from_config(config_value: str, default: "ScoreWeightsValue") -> "ScoreWeight
237239
except ValueError as ex:
238240
raise OptionParseFailure(
239241
"Score weights must be specified as four numbers in the form (H,S,L,E),"
240-
" e.g. (0.9, 0.2, 2.0, 0.5). Commas/brackets/slashes are ignored."
242+
" e.g. (0.9, 0.2, 2.0, 0.5), with at least one non-zero."
243+
" Commas/brackets/slashes are ignored."
241244
) from ex
242245

243246

‎scenedetect/_cli/context.py‎

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
ConfigRegistry,
2626
CropValue,
2727
KernelSizeValue,
28+
ScoreWeightsValue,
2829
)
2930
from scenedetect.backends import VideoStreamAv
3031
from scenedetect.common import MAX_FPS_DELTA, FrameTimecode
@@ -181,6 +182,19 @@ def _kernel_size_value(kernel_size: int | None) -> KernelSizeValue | None:
181182
"Kernel size must be an odd integer >= 3, or -1 for auto.", param_hint="kernel-size"
182183
) from ex
183184

185+
@staticmethod
186+
def _weights_value(
187+
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
190+
instead of NaN frame scores."""
191+
if weights is None:
192+
return None
193+
try:
194+
return ScoreWeightsValue(ContentDetector.Components(*weights)).value
195+
except ValueError as ex:
196+
raise click.BadParameter(str(ex), param_hint="weights") from ex
197+
184198
def parse_timecode(self, value: str | None, correct_pts: bool = False) -> FrameTimecode | None:
185199
"""Parses a user input string into a FrameTimecode assuming the given framerate. If `value`
186200
is None it will be passed through without processing.
@@ -388,17 +402,10 @@ def get_detect_content_params(
388402
"""Get a dict containing user options to construct a ContentDetector with."""
389403
min_scene_len_frames = self._resolve_min_scene_len("detect-content", min_scene_len)
390404

391-
if weights is not None:
392-
try:
393-
weights = ContentDetector.Components(*weights)
394-
except ValueError as ex:
395-
if DEBUG_MODE:
396-
raise
397-
logger.debug(str(ex))
398-
raise click.BadParameter(str(ex), param_hint="weights") from None
399-
400405
return {
401-
"weights": self.config.get_value("detect-content", "weights", weights),
406+
"weights": self.config.get_value(
407+
"detect-content", "weights", self._weights_value(weights)
408+
),
402409
"kernel_size": self.config.get_value(
403410
"detect-content", "kernel-size", self._kernel_size_value(kernel_size)
404411
),
@@ -422,17 +429,11 @@ def get_detect_adaptive_params(
422429

423430
min_scene_len_frames = self._resolve_min_scene_len("detect-adaptive", min_scene_len)
424431

425-
if weights is not None:
426-
try:
427-
weights = ContentDetector.Components(*weights)
428-
except ValueError as ex:
429-
if DEBUG_MODE:
430-
raise
431-
logger.debug(str(ex))
432-
raise click.BadParameter(str(ex), param_hint="weights") from None
433432
return {
434433
"adaptive_threshold": self.config.get_value("detect-adaptive", "threshold", threshold),
435-
"weights": self.config.get_value("detect-adaptive", "weights", weights),
434+
"weights": self.config.get_value(
435+
"detect-adaptive", "weights", self._weights_value(weights)
436+
),
436437
"kernel_size": self.config.get_value(
437438
"detect-adaptive", "kernel-size", self._kernel_size_value(kernel_size)
438439
),

‎scenedetect/detectors/content_detector.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,8 @@ def __init__(
132132
self._weights: ContentDetector.Components = weights
133133
if luma_only:
134134
self._weights = ContentDetector.LUMA_ONLY_WEIGHTS
135+
if not any(self._weights):
136+
raise ValueError("At least one weight must be non-zero.")
135137
self._kernel: numpy.ndarray | None = None
136138
if kernel_size is not None:
137139
if kernel_size < 3 or kernel_size % 2 == 0:

‎tests/test_cli.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,26 @@ def test_cli_kernel_size_config_file_rejects_one(tmp_path: Path, command: str):
463463
assert any("odd integer >= 3" in message for _, message in ex.value.init_log)
464464

465465

466+
@pytest.mark.parametrize("command", ["detect-content", "detect-adaptive"])
467+
def test_cli_weights_rejects_all_zero(command: str):
468+
"""All-zero weights must give a usage error instead of NaN frame scores (#612)."""
469+
exit_code, output = invoke_cli(
470+
["-i", DEFAULT_VIDEO_PATH, command, "-w", "0", "0", "0", "0", "time", "-e", "1"]
471+
)
472+
assert exit_code != 0
473+
assert "At least one weight must be non-zero." in output
474+
475+
476+
@pytest.mark.parametrize("command", ["detect-content", "detect-adaptive"])
477+
def test_cli_weights_config_file_rejects_all_zero(tmp_path: Path, command: str):
478+
"""A config file with all-zero weights must be rejected when loading (#612)."""
479+
config_path = tmp_path.joinpath("config.cfg")
480+
config_path.write_text(f"[{command}]\nweights = 0, 0, 0, 0\n")
481+
with pytest.raises(ConfigLoadFailure) as ex:
482+
ConfigRegistry(str(config_path))
483+
assert any("non-zero" in message for _, message in ex.value.init_log)
484+
485+
466486
@pytest.mark.parametrize(
467487
"cli_args",
468488
[

‎tests/test_detectors.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,3 +292,12 @@ def test_adaptive_detector_min_scene_len_uses_target_frame():
292292

293293
cut_frames = [cut.frame_num for cut in cuts]
294294
assert cut_frames == [100, 140]
295+
296+
297+
@pytest.mark.parametrize("detector_type", [ContentDetector, AdaptiveDetector])
298+
def test_detector_rejects_all_zero_weights(detector_type):
299+
"""All-zero weights would make every frame score NaN (#612)."""
300+
with pytest.raises(ValueError, match="At least one weight must be non-zero"):
301+
detector_type(weights=ContentDetector.Components(0.0, 0.0, 0.0, 0.0))
302+
# luma_only overrides weights, so this is still valid.
303+
detector_type(weights=ContentDetector.Components(0.0, 0.0, 0.0, 0.0), luma_only=True)

‎website/pages/changelog.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -864,3 +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)

0 commit comments

Comments
 (0)