From 3613c45c9d27ddb0bf3ec305e2a2ea91f81a0a9d Mon Sep 17 00:00:00 2001 From: Lenin Mookiah <2639584+leninworld@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:41:53 -0800 Subject: [PATCH 1/2] [feature] Add StatsManager.to_dict() for dict and pandas conversion (#507) --- scenedetect/stats_manager.py | 18 +++++++++++++ tests/test_stats_manager.py | 50 +++++++++++++++++++++++++++++++++++- website/pages/changelog.md | 1 + 3 files changed, 68 insertions(+), 1 deletion(-) diff --git a/scenedetect/stats_manager.py b/scenedetect/stats_manager.py index dc415f3c..3081547b 100644 --- a/scenedetect/stats_manager.py +++ b/scenedetect/stats_manager.py @@ -152,6 +152,24 @@ def metrics_exist(self, timecode: int | FrameTimecode, metric_keys: ty.Iterable[ """ return all([self._metric_exists(timecode, metric_key) for metric_key in metric_keys]) + def to_dict(self) -> dict[int | FrameTimecode, dict[str, ty.Any]]: + """Convert all stored metrics to a plain Python dictionary. + + Keys are stored keys: ``FrameTimecode`` for metrics set during detection, or 0-based + ``int`` frame numbers (e.g. from ``set_metrics(5, ...)`` or deprecated CSV loading). + A ``FrameTimecode`` hashes and compares equal to its 0-based ``frame_num``, so + ``result[5]`` (and ``DataFrame.loc[5]``) finds CFR frame 5. The CSV ``Frame Number`` + column is 1-based. Unlike ``save_to_csv()``, which skips int keys, this includes them. + + Example:: + + pandas.DataFrame.from_dict(stats_manager.to_dict(), orient="index") + + Returns: + Stored frame keys mapped to shallow copies of their metrics, in ascending order. + """ + return {key: dict(self._frame_metrics[key]) for key in sorted(self._frame_metrics)} + def is_save_required(self) -> bool: """Is Save Required: Checks if the stats have been updated since loading. diff --git a/tests/test_stats_manager.py b/tests/test_stats_manager.py index 5e7360ae..6ae891d8 100644 --- a/tests/test_stats_manager.py +++ b/tests/test_stats_manager.py @@ -27,12 +27,13 @@ """ import csv +from fractions import Fraction from pathlib import Path import pytest from scenedetect.backends.opencv import VideoStreamCv2 -from scenedetect.common import FrameTimecode +from scenedetect.common import FrameTimecode, Timecode from scenedetect.detectors import ContentDetector from scenedetect.scene_manager import SceneManager from scenedetect.stats_manager import ( @@ -73,6 +74,53 @@ def test_metrics(): ] +def test_to_dict(): + stats = StatsManager() + assert stats.to_dict() == {} + + frame_10 = FrameTimecode(10, 30.0) + frame_2 = FrameTimecode(2, 30.0) + first_frame_1 = FrameTimecode(Timecode(1000, Fraction(1, 30000)), 30.0) + second_frame_1 = FrameTimecode(Timecode(1001, Fraction(1, 30000)), 30.0) + assert first_frame_1.frame_num == second_frame_1.frame_num == 1 + assert first_frame_1 != second_frame_1 + + stats.set_metrics(frame_10, {"score": 10.0}) + stats.set_metrics(5, {"integer_key": 5.0}) + stats.set_metrics(frame_2, {"score": 2.0}) + stats.set_metrics(first_frame_1, {"score": 1.0, "first": 1.0}) + stats.set_metrics(second_frame_1, {"score": 1.1, "second": 1.0}) + + metrics = stats.to_dict() + keys = list(metrics) + assert keys == [first_frame_1, second_frame_1, frame_2, 5, frame_10] + assert keys[0] is first_frame_1 + assert keys[1] is second_frame_1 + assert keys[2] is frame_2 + assert type(keys[3]) is int + assert keys[4] is frame_10 + assert metrics[10] == {"score": 10.0} + assert metrics[5] == {"integer_key": 5.0} + assert metrics[first_frame_1] == {"score": 1.0, "first": 1.0} + assert metrics[second_frame_1] == {"score": 1.1, "second": 1.0} + + metrics[2]["score"] = 20.0 + assert stats.get_metrics(frame_2, ["score"]) == [2.0] + + +def test_to_dict_pandas(): + pandas = pytest.importorskip("pandas") + stats = StatsManager() + stats.set_metrics(FrameTimecode(4, 30.0), {"score": 4.0, "content": 0.4}) + stats.set_metrics(1, {"score": 1.0, "content": 0.1}) + + frame_metrics = pandas.DataFrame.from_dict(stats.to_dict(), orient="index") + + assert list(frame_metrics.index) == [1, 4] + assert list(frame_metrics.columns) == ["score", "content"] + assert frame_metrics.loc[4, "score"] == 4.0 + + def test_detector_metrics(test_video_file): """Test passing StatsManager to a SceneManager and using it for storing the frame metrics from a ContentDetector. diff --git a/website/pages/changelog.md b/website/pages/changelog.md index 3bb82505..cfd1ec4e 100644 --- a/website/pages/changelog.md +++ b/website/pages/changelog.md @@ -863,6 +863,7 @@ Major breaking release that overhauls how time is managed. Rather than assigning - [general] The root `pyproject.toml` is now `scenedetect` again (it had a development-only `scenedetect-core` name since 0.7.1). `pip install -e .` now installs the same distribution as PyPI. The `[opencv]` and `[opencv-headless]` extras of the development config were removed because `opencv-python` is now a declared dependency [#558](https://github.com/Breakthrough/PySceneDetect/issues/558) - [feature] Add `save-chapters` command to save scenes as chapters in FFmetadata format, which can be added to a video with ffmpeg without re-encoding. Also available as `write_scene_list_ffmetadata()` in the `scenedetect.output` module [#323](https://github.com/Breakthrough/PySceneDetect/issues/323) - [feature] Add `--stdin` to read the input video from a pipe, e.g. `ffmpeg -i input.mp4 -c copy -f matroska - | scenedetect --stdin detect-content list-scenes`. Requires the PyAV backend. `save-html` omits images, and commands that need to seek or refer to a source file (`split-video`, `save-images`, `save-fcp`, `save-otio`, `load-scenes`, `time -s`) are not supported [#189](https://github.com/Breakthrough/PySceneDetect/issues/189) [#434](https://github.com/Breakthrough/PySceneDetect/issues/434) + - [feature] Add `StatsManager.to_dict()` to get all stored metrics as a dict of shallow copies keyed by frame (`FrameTimecode`, which compares equal to its 0-based frame number, or `int`), e.g. for `pandas.DataFrame.from_dict(stats_manager.to_dict(), orient="index")` [#507](https://github.com/Breakthrough/PySceneDetect/issues/507) - [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 - [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) - [bugfix] `save-images` no longer takes the last image of a scene from the first frame of the next scene. `--frame-margin` is counted from the last frame of the scene again, as in v0.6 (`-m 0` now selects the last frame itself) From 6f8d3efb4e45292827f3eca9e100a1fa7fab41e1 Mon Sep 17 00:00:00 2001 From: Lenin Mookiah <2639584+leninworld@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:45:00 -0800 Subject: [PATCH 2/2] Address review: look up frames by key, drop pandas test, shorten changelog --- scenedetect/stats_manager.py | 5 ++--- tests/test_stats_manager.py | 13 ------------- website/pages/changelog.md | 2 +- 3 files changed, 3 insertions(+), 17 deletions(-) diff --git a/scenedetect/stats_manager.py b/scenedetect/stats_manager.py index 3081547b..498a02ee 100644 --- a/scenedetect/stats_manager.py +++ b/scenedetect/stats_manager.py @@ -157,9 +157,8 @@ def to_dict(self) -> dict[int | FrameTimecode, dict[str, ty.Any]]: Keys are stored keys: ``FrameTimecode`` for metrics set during detection, or 0-based ``int`` frame numbers (e.g. from ``set_metrics(5, ...)`` or deprecated CSV loading). - A ``FrameTimecode`` hashes and compares equal to its 0-based ``frame_num``, so - ``result[5]`` (and ``DataFrame.loc[5]``) finds CFR frame 5. The CSV ``Frame Number`` - column is 1-based. Unlike ``save_to_csv()``, which skips int keys, this includes them. + Frame numbers are estimates on VFR video (#569), so frames should be looked up using + these returned keys. Unlike ``save_to_csv()``, which skips int keys, this includes them. Example:: diff --git a/tests/test_stats_manager.py b/tests/test_stats_manager.py index 6ae891d8..d1e58975 100644 --- a/tests/test_stats_manager.py +++ b/tests/test_stats_manager.py @@ -108,19 +108,6 @@ def test_to_dict(): assert stats.get_metrics(frame_2, ["score"]) == [2.0] -def test_to_dict_pandas(): - pandas = pytest.importorskip("pandas") - stats = StatsManager() - stats.set_metrics(FrameTimecode(4, 30.0), {"score": 4.0, "content": 0.4}) - stats.set_metrics(1, {"score": 1.0, "content": 0.1}) - - frame_metrics = pandas.DataFrame.from_dict(stats.to_dict(), orient="index") - - assert list(frame_metrics.index) == [1, 4] - assert list(frame_metrics.columns) == ["score", "content"] - assert frame_metrics.loc[4, "score"] == 4.0 - - def test_detector_metrics(test_video_file): """Test passing StatsManager to a SceneManager and using it for storing the frame metrics from a ContentDetector. diff --git a/website/pages/changelog.md b/website/pages/changelog.md index cfd1ec4e..063b9434 100644 --- a/website/pages/changelog.md +++ b/website/pages/changelog.md @@ -863,7 +863,7 @@ Major breaking release that overhauls how time is managed. Rather than assigning - [general] The root `pyproject.toml` is now `scenedetect` again (it had a development-only `scenedetect-core` name since 0.7.1). `pip install -e .` now installs the same distribution as PyPI. The `[opencv]` and `[opencv-headless]` extras of the development config were removed because `opencv-python` is now a declared dependency [#558](https://github.com/Breakthrough/PySceneDetect/issues/558) - [feature] Add `save-chapters` command to save scenes as chapters in FFmetadata format, which can be added to a video with ffmpeg without re-encoding. Also available as `write_scene_list_ffmetadata()` in the `scenedetect.output` module [#323](https://github.com/Breakthrough/PySceneDetect/issues/323) - [feature] Add `--stdin` to read the input video from a pipe, e.g. `ffmpeg -i input.mp4 -c copy -f matroska - | scenedetect --stdin detect-content list-scenes`. Requires the PyAV backend. `save-html` omits images, and commands that need to seek or refer to a source file (`split-video`, `save-images`, `save-fcp`, `save-otio`, `load-scenes`, `time -s`) are not supported [#189](https://github.com/Breakthrough/PySceneDetect/issues/189) [#434](https://github.com/Breakthrough/PySceneDetect/issues/434) - - [feature] Add `StatsManager.to_dict()` to get all stored metrics as a dict of shallow copies keyed by frame (`FrameTimecode`, which compares equal to its 0-based frame number, or `int`), e.g. for `pandas.DataFrame.from_dict(stats_manager.to_dict(), orient="index")` [#507](https://github.com/Breakthrough/PySceneDetect/issues/507) + - [feature] Add `StatsManager.to_dict()` to get all frame metrics as a dict, e.g. for `pandas.DataFrame.from_dict(stats_manager.to_dict(), orient="index")` [#507](https://github.com/Breakthrough/PySceneDetect/issues/507) - [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 - [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) - [bugfix] `save-images` no longer takes the last image of a scene from the first frame of the next scene. `--frame-margin` is counted from the last frame of the scene again, as in v0.6 (`-m 0` now selects the last frame itself)