diff --git a/scenedetect/stats_manager.py b/scenedetect/stats_manager.py index dc415f3c..498a02ee 100644 --- a/scenedetect/stats_manager.py +++ b/scenedetect/stats_manager.py @@ -152,6 +152,23 @@ 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). + 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:: + + 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..d1e58975 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,40 @@ 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_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..063b9434 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 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)