Skip to content

[feature] Add StatsManager.to_dict() for dict and pandas conversion (#507) - #636

Open
leninworld wants to merge 2 commits into
Breakthrough:mainfrom
leninworld:feature/507-stats-manager-to-dict
Open

leninworld wants to merge 2 commits into
Breakthrough:mainfrom
leninworld:feature/507-stats-manager-to-dict

Conversation

@leninworld

Copy link
Copy Markdown
Contributor

This PR addresses part of issue #507.

Who benefits: API users who analyse per-frame detector metrics (for example to pick a representative frame per scene, as in the issue) and want them in a dict or a pandas DataFrame without writing a stats CSV and reading it back.

This adds StatsManager.to_dict(), which returns every stored frame's metrics as a plain dict:

frame_metrics = pandas.DataFrame.from_dict(stats_manager.to_dict(), orient="index")
  • Keys are the frame keys as stored, in ascending order: FrameTimecode for metrics written during detection, or int 0-based frame numbers (from set_metrics(5, ...) or the deprecated load_from_csv). A FrameTimecode hashes and compares equal to its 0-based frame number, so result[5] and DataFrame.loc[5] find frame 5 of a constant frame rate video, and the DataFrame index prints as timecodes. The stats CSV Frame Number column stays 1-based.
  • Each frame's metrics dict is a shallow copy, so adding, removing or replacing values in the result doesn't change the StatsManager (nested mutable values, if any, stay shared).
  • I kept the stored keys instead of converting them to frame_num ints: on VFR video two PTS-based frames can round to the same frame_num, and converting would merge them and drop metrics. save_to_csv() writes both rows today, so this keeps the two in line. It also keeps int-keyed entries, which save_to_csv() skips.

I went with a conversion method rather than the full dict protocol: adding __len__ would make an empty StatsManager falsy, and that felt like a decision for the 0.8 API work (#591 also reworks this class), so the TODO above get_metrics is left as is. Happy to change the key type or move the changelog entry to 0.8 if you prefer.

Changelog entry added under 0.7.4 (TBD) in the Development section.

Tests: test_to_dict (empty manager, ordering of out-of-order keys, int and FrameTimecode keys, two VFR frames with the same frame_num kept apart, int lookup, shallow copies) and test_to_dict_pandas (DataFrame index, columns and .loc[4]; skipped when pandas isn't installed, since pandas isn't a test dependency). Both fail on main with AttributeError. With the resources branch, pytest gives 769 passed, 3 skipped (macOS, Python 3.12, pandas installed). ruff check, ruff format --check and pyright pass.

Refs #507

Comment thread scenedetect/stats_manager.py Outdated
Comment on lines +160 to +161
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``

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we remove the result[5] / DataFrame.loc[5] references, and say instead that frame numbers are estimates on VFR video (#569), so frames should be looked up by these keys?

Comment thread tests/test_stats_manager.py Outdated
assert stats.get_metrics(frame_2, ["score"]) == [2.0]


def test_to_dict_pandas():

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we drop this test? pandas isn't a dev dependency, so it always skips in CI. It's also not really a useful test for this library since the dict is what matters here.

Comment thread website/pages/changelog.md Outdated
- [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)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we shorten this to "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")"?

@leninworld

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All three are done in 6f8d3ef:

  • to_dict() docstring: dropped the result[5] / DataFrame.loc[5] lines; it now says frame numbers are estimates on VFR video (FrameTimecode.frame_num is inaccurate for VFR video #569), so frames should be looked up by the returned keys.
  • Removed test_to_dict_pandas.
  • Changelog entry shortened to the wording you gave.

Locally, tests/test_stats_manager.py gives 6 passed and 1 error; the error is only test_save_load_from_video, which needs tests/resources (not checked out here). Ruff check and format are clean.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants