diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index cc59c62d..9079822b 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -16,6 +16,7 @@ workflows: '.github/workflows/check-docs.yml': - 'actions/checkout@v7.0.1' - 'actions/setup-python@v7.1.0' + - 'actions/upload-artifact@v7.0.2' '.github/workflows/codeql.yml': - 'actions/checkout@v7.0.1' - 'github/codeql-action@v4.39.3' diff --git a/.github/workflows/check-docs.yml b/.github/workflows/check-docs.yml index b74db10c..cb27f184 100644 --- a/.github/workflows/check-docs.yml +++ b/.github/workflows/check-docs.yml @@ -40,10 +40,7 @@ jobs: - name: Install Dependencies run: | - python -m pip install --upgrade pip build wheel virtualenv - pip install .[docs,website] - pip install -r packaging/windows/requirements.txt - + pip install ".[docs,pyav,moviepy]" -r website/requirements.txt - name: Check CLI Documentation shell: bash @@ -61,7 +58,23 @@ jobs: run: | sphinx-build -W --keep-going -b html docs docs/_build/html - - name: Build MkDocs Website (--strict) + - name: Build Website (--strict) + shell: bash + run: | + python website/build.py --strict + + - name: Check Responsive Layout & Capture Screenshots shell: bash run: | - mkdocs build --strict -f website/mkdocs.yml + python website/check_layout.py \ + --sphinx-dir docs/_build/html \ + --screenshots "${RUNNER_TEMP}/website-screenshots" + + - name: Upload Website Screenshots + if: always() + uses: actions/upload-artifact@v7.0.2 + with: + name: website-screenshots + path: ${{ runner.temp }}/website-screenshots/ + if-no-files-found: ignore + retention-days: 14 diff --git a/.github/workflows/generate-docs.yml b/.github/workflows/generate-docs.yml index 0a42776a..8e0a89f5 100644 --- a/.github/workflows/generate-docs.yml +++ b/.github/workflows/generate-docs.yml @@ -10,8 +10,13 @@ on: - 'docs/**' - 'scenedetect/**' - 'scenedetect.cfg' + - 'website/pages/docs.md' workflow_dispatch: +concurrency: + group: gh-pages + cancel-in-progress: false + jobs: update_docs: runs-on: ubuntu-latest @@ -36,32 +41,38 @@ jobs: cache: 'pip' - name: Set Destination (Releases) - if: ${{ contains(github.ref_name, 'releases') }} + if: ${{ startsWith(github.ref, 'refs/heads/releases/') }} + shell: bash + env: + REF_NAME: ${{ github.ref_name }} run: | - echo "scenedetect_docs_dest=$(echo ${{ github.ref_name }} | cut -b 10-)" >> "$GITHUB_ENV" + echo "scenedetect_docs_dest=${REF_NAME#releases/}" >> "$GITHUB_ENV" - name: Set Destination (Head) - if: ${{ contains(github.ref_name, 'main') }} + if: ${{ github.ref == 'refs/heads/main' }} + shell: bash run: | echo "scenedetect_docs_dest=head" >> "$GITHUB_ENV" - name: Check Destination if: ${{ env.scenedetect_docs_dest == '' }} + shell: bash run: | echo "Failing build: destination must be set!" + exit 1 - name: Setup Environment run: | - python -m pip install --upgrade pip build wheel virtualenv - pip install .[docs] - pip install -r packaging/windows/requirements.txt + pip install ".[docs,pyav,moviepy]" git config --global user.name github-actions git config --global user.email github-actions@github.com - name: Check CLI Documentation shell: bash + env: + PYTHONDONTWRITEBYTECODE: "1" run: | - python docs/generate_cli_docs.py + python -B docs/generate_cli_docs.py if [[ $(git status --porcelain=1 -- docs | wc -l) -ne 0 ]]; then git --no-pager diff -- docs echo 'CLI documentation is out of date: the generated docs do not match the output of docs/generate_cli_docs.py!' @@ -70,29 +81,45 @@ jobs: fi - name: Generate Docs + shell: bash + env: + PYTHONDONTWRITEBYTECODE: "1" run: | - sphinx-build -b html docs build + sphinx-build -b html -d "${RUNNER_TEMP}/doctrees" docs "${RUNNER_TEMP}/docs-build" - name: Update gh-pages Branch + shell: bash + env: + DOCS_DEST: ${{ env.scenedetect_docs_dest }} run: | git fetch origin gh-pages git checkout gh-pages - git rm "docs/${{ env.scenedetect_docs_dest }}" -r -f --ignore-unmatch - git add build/ - git mv build "docs/${{ env.scenedetect_docs_dest }}" + git clean -ffdx + git rm "docs/${DOCS_DEST}" -r -f --ignore-unmatch + mkdir -p "docs/${DOCS_DEST}" + cp -a "${RUNNER_TEMP}/docs-build/." "docs/${DOCS_DEST}/" + git add -A "docs/${DOCS_DEST}" - name: Update Latest if: ${{ env.scenedetect_docs_dest == env.scenedetect_docs_latest }} + shell: bash + env: + DOCS_DEST: ${{ env.scenedetect_docs_dest }} run: | git rm "docs/latest" -r -f --ignore-unmatch - mkdir -p latest - cp -r -f "docs/${{ env.scenedetect_docs_dest }}" docs/latest - git add docs/latest - echo "scenedetect_docs_dest='${{ env.scenedetect_docs_dest }} (latest)'" >> "$GITHUB_ENV" + cp -a "docs/${DOCS_DEST}" docs/latest + git add -A docs/latest + echo "scenedetect_docs_dest=${DOCS_DEST} (latest)" >> "$GITHUB_ENV" - name: Commit and Push + shell: bash + env: + DOCS_DEST: ${{ env.scenedetect_docs_dest }} + TRIGGER_ACTOR: ${{ github.triggering_actor }} run: | - git commit -a -m "[docs] @${{ github.triggering_actor }}: Generate Documentation" \ - -m "Source: ${{ github.ref_name }} (${{ github.sha }})" \ - -m "Destination: ${{ env.scenedetect_docs_dest }}" - git push + if ! git diff --quiet || ! git diff --cached --quiet; then + git commit -a -m "[docs] @${TRIGGER_ACTOR}: Generate Documentation" \ + -m "Source: ${GITHUB_REF_NAME} (${GITHUB_SHA})" \ + -m "Destination: ${DOCS_DEST}" + git push + fi diff --git a/.github/workflows/generate-website.yml b/.github/workflows/generate-website.yml index 406ef7ed..5ce2e8f7 100644 --- a/.github/workflows/generate-website.yml +++ b/.github/workflows/generate-website.yml @@ -1,13 +1,31 @@ - name: Generate Website on: push: branches: - main + - 'website/**' paths: - 'website/**' + - 'docs/LATEST_VERSION' + - 'docs/_ext/doc_versions.py' + - '.github/workflows/generate-website.yml' workflow_dispatch: + inputs: + target: + description: 'Deployment target on gh-pages' + required: false + default: 'auto' + type: choice + options: + - auto + - staging + - production + - clear-staging + +concurrency: + group: gh-pages + cancel-in-progress: false jobs: update_site: @@ -19,36 +37,97 @@ jobs: steps: - uses: actions/checkout@v7.0.1 + - name: Resolve Deployment Target + shell: bash + env: + INPUT_TARGET: ${{ inputs.target || 'auto' }} + run: | + if [[ "${INPUT_TARGET}" == "auto" ]]; then + if [[ "${GITHUB_REF}" == "refs/heads/main" ]]; then + target="production" + else + target="staging" + fi + else + target="${INPUT_TARGET}" + fi + + if [[ "$target" == "production" ]] && [[ "${GITHUB_REF}" != "refs/heads/main" ]] && [[ "${GITHUB_REF}" != refs/heads/releases/* ]]; then + echo "Refusing production deployment from non-release ref: ${GITHUB_REF}" >&2 + exit 1 + fi + + if [[ "$target" == "staging" ]]; then + base_path="/staging" + else + base_path="" + fi + + echo "deploy_target=${target}" >> "$GITHUB_ENV" + echo "site_base_path=${base_path}" >> "$GITHUB_ENV" + echo "Resolved target=${target} (base_path='${base_path}')" + - name: Set up Python 3.12 + if: env.deploy_target != 'clear-staging' uses: actions/setup-python@v7.1.0 with: python-version: '3.12' - cache: 'pip' - name: Install Dependencies + if: env.deploy_target != 'clear-staging' run: | - python -m pip install --upgrade pip build wheel virtualenv - pip install .[website] + python -m pip install -r website/requirements.txt - - name: Generate Website + - name: Generate Website (--strict) + if: env.deploy_target != 'clear-staging' + shell: bash run: | - mkdocs build -f website/mkdocs.yml + python -B website/build.py \ + --strict \ + --base-path "${SITE_BASE_PATH}" \ + --out-dir "${RUNNER_TEMP}/site-build" + env: + PYTHONDONTWRITEBYTECODE: "1" + SITE_BASE_PATH: ${{ env.site_base_path }} - - name: Update Website + - name: Update gh-pages Branch + shell: bash run: | git fetch origin gh-pages git checkout gh-pages - git rm * -r -f --ignore-unmatch - git checkout HEAD -- .nojekyll - git checkout HEAD -- CNAME - git checkout HEAD -- docs/ - git rm docs/index.html --ignore-unmatch - git add website/build/ - git mv website/build/* . -f -k - git mv website/build/docs/index.html docs/index.html -k - git rm website/build/* -r -f --ignore-unmatch + git clean -ffdx + + if [[ "${DEPLOY_TARGET}" == "production" ]]; then + # Replace root site while preserving .nojekyll, CNAME, versioned Sphinx + # /docs/* trees, and any active /staging/ preview (cleared on demand via + # workflow_dispatch target=clear-staging). + git rm -r -f --ignore-unmatch * + git checkout HEAD -- .nojekyll CNAME docs/ + if git cat-file -e HEAD:staging 2>/dev/null; then + git checkout HEAD -- staging/ + fi + cp -a "${RUNNER_TEMP}/site-build/." . + git add -A + elif [[ "${DEPLOY_TARGET}" == "staging" ]]; then + git rm -r -f --ignore-unmatch staging + mkdir -p staging + cp -a "${RUNNER_TEMP}/site-build/." staging/ + git add -A staging + elif [[ "${DEPLOY_TARGET}" == "clear-staging" ]]; then + git rm -r -f --ignore-unmatch staging + else + echo "Unknown deploy_target: ${DEPLOY_TARGET}" >&2 + exit 1 + fi + git config --global user.name github-actions git config --global user.email github-actions@github.com - git commit -a -m "[docs] @${{ github.triggering_actor }}: Generate Website" \ - -m "Commit: ${{ github.sha }}" - git push + if ! git diff --quiet || ! git diff --cached --quiet; then + git commit -a -m "[docs] @${TRIGGER_ACTOR}: Generate Website (${DEPLOY_TARGET})" \ + -m "Source: ${GITHUB_REF_NAME} (${GITHUB_SHA})" \ + -m "Target: ${DEPLOY_TARGET}" + git push + fi + env: + DEPLOY_TARGET: ${{ env.deploy_target }} + TRIGGER_ACTOR: ${{ github.triggering_actor }} diff --git a/RELEASE-PLAN.md b/RELEASE-PLAN.md index bcd86ce7..6bacc6bf 100644 --- a/RELEASE-PLAN.md +++ b/RELEASE-PLAN.md @@ -17,8 +17,8 @@ Optional: version referenced below as `X.Y[.Z]` - replace with the real version - [ ] Docstring examples all run correctly, nothing references removed or deprecated symbols. - [ ] Changelog has release notes for major/minor release, all features, breaking changes, bug fixes, and known issues are documented. - [ ] `website/pages/download.md` updated with the new version / installer link / release date. -- [ ] `website/pages/changelog.md`: move the release changes from the **Development** section at the bottom to the top. -- [ ] `website/pages/index.md`: Latest release version and date updated. +- [ ] `website/pages/changelog.md`: move the release changes from the **Development** section at the bottom to the top (`website/build.py` derives the homepage release date from this heading). +- [ ] Verify homepage version and date (`docs/LATEST_VERSION` + `website/pages/changelog.md` parsed by `website/build.py`) match `website/pages/download.md`. ## 3. Tests @@ -55,8 +55,9 @@ Optional: version referenced below as `X.Y[.Z]` - replace with the real version - [ ] Dispatch `release.yml` (Release Orchestrator) with the release tag while the Github release is still a **draft**. It runs the verify-then-publish ladder (MSI install/upgrade test -> TestPyPI -> publish Github release -> PyPI -> Docker), verifying each stage before the next; `verify-only` stops before anything goes public. See the header of `release.yml` for details. - [ ] Verify both projects: https://pypi.org/project/scenedetect/ and https://pypi.org/project/scenedetect-headless/. -- [ ] Deploy website: `generate-website.yml` +- [ ] Deploy website: dispatch `generate-website.yml` with `target=production` (or push to `main`). - [ ] Deploy docs: `generate-docs.yml` +- [ ] Fast-forward the `latest` branch to the tagged release commit (`git push origin vX.Y[.Z]:refs/heads/latest`) so stable GitHub links (`/blob/latest/scenedetect.cfg`) track the new release. - [ ] Merge release branch back into `main`, verify `docs/LATEST_VERSION` is correct - [ ] [Manually dispatch `generate-docs.yml`](https://github.com/Breakthrough/PySceneDetect/actions/workflows/generate-docs.yml) against `releases/X.Y` to update www.scenedetect.com/docs/latest - [ ] Smoke-test PyPI release: in a fresh venv, `pip install scenedetect==X.Y.Z`; CLI launches and `scenedetect --version` looks correct. @@ -71,3 +72,17 @@ Optional: version referenced below as `X.Y[.Z]` - replace with the real version - **Branching model**: work spans multiple commits on `releases/X.Y[.Z]`; the final one gets the `vX.Y[.Z]` tag which gates the release-test workflow. A passing release-test is a hard prerequisite for publishing. - **Version consistency** is enforced in two places (`__init__.py`, `PySceneDetect.aip`). The `static` job of `release-test.yml` checks `__init__.py` against the tag and verifies the changelog has a matching `## PySceneDetect X.Y` heading; the installer parity is checked by `scripts/pre_release.py --release`. - **Changelog convention**: the in-development section lives at the *bottom* of `website/pages/changelog.md` under the "Development" heading - don't move it to the top. + +### Special Branch Naming Scheme + +| Pattern | Purpose | Automated CI / Triggers | +| --- | --- | --- | +| `main` | Active development / integration branch | Full test suite, `docs/head`, production website, Docker `main` | +| `latest` | Fast-forwarding pointer to the latest stable release commit | Stable GitHub file URLs (`/blob/latest/scenedetect.cfg`); does not trigger release/`v*` workflows or AppVeyor | +| `releases/` | Release stabilization & maintenance branches (e.g. `releases/0.7.3`) | Full test suite, `docs/` + `docs/latest`, AppVeyor (on `v*` tags) | +| `website/` | Website redesign / content branches (e.g. `website/redesign`) | Auto-deploys staging preview to `scenedetect.com/staging/` via `generate-website.yml` (`'website/**'`) | +| `feature/` | New features / detectors (e.g. `feature/color-detector`) | PR checks only | +| `issue/-` | Issue-linked fixes / work (e.g. `issue/512-description`) | PR checks only | +| `fix/` | Standalone bug fixes without a linked issue number | PR checks only | +| `docs/` | Reference documentation / style updates (non-staging) | PR checks only | +| `gh-pages`, `resources` | Infrastructure branches (published site/docs; test video fixtures) | Automated deploy target / test fixture store | diff --git a/THIRD-PARTY.md b/THIRD-PARTY.md index 959c2e4f..03538d84 100644 --- a/THIRD-PARTY.md +++ b/THIRD-PARTY.md @@ -14,16 +14,16 @@ In no particular order: ----------------------------------------------------------------------- > click [Copyright (C) 2017, Armin Ronacher]: - This software uses OpenCV; see thirdparty/LICENSE-CLICK or visit: - [ http://click.pocoo.org/license/ ] + This software uses click; see thirdparty/LICENSE-CLICK or visit: + [ https://click.palletsprojects.com/en/stable/license/ ] > NumPy [Copyright (C) 2005-2016, Numpy Developers]: - This software uses Numpy; see thirdparty/LICENSE-NUMPY or visit: - [ http://www.numpy.org/license.html ] + This software uses NumPy; see thirdparty/LICENSE-NUMPY or visit: + [ https://numpy.org/doc/stable/license.html ] > OpenCV [Copyright (C) 2017, Itseez]: This software uses OpenCV; see thirdparty/LICENSE-OPENCV or visit: - [ http://opencv.org/license.html ] + [ https://opencv.org/license/ ] > PyAV [Copyright (C) 2017, Mike Boers and others]: This software uses PyAV; see thirdparty/LICENSE-PYAV or visit: @@ -42,10 +42,14 @@ In no particular order: This software uses tqdm; see thirdparty/LICENSE-TQDM or visit: [ https://github.com/tqdm/tqdm/blob/master/LICENCE ] -> MoviePy [ Copyright (C) 2015 Zulko ] - This software uses tqdm; see thirdparty/LICENSE-TQDM or visit: +> MoviePy [Copyright (C) 2015 Zulko]: + This software uses MoviePy; see thirdparty/LICENSE-MOVIEPY or visit: [ https://github.com/Zulko/moviepy/blob/master/LICENCE.txt ] +> platformdirs [Copyright (C) The platformdirs developers]: + This software uses platformdirs; visit: + [ https://github.com/tox-dev/platformdirs/blob/main/LICENSE ] + ----------------------------------------------------------------------- This software may also invoke FFmpeg or mkvmerge, if available. If required, @@ -61,7 +65,7 @@ Certain distributions of PySceneDetect may include ffmpeg. See thirdparty/LICENSE-FFMPEG file or visit [ https://ffmpeg.org ] FFmpeg is a trademark of Fabrice Bellard -mkvmerge is Copyright (C) 2005-2016, Matroska +mkvmerge is part of MKVToolNix by Moritz Bunkus (GNU General Public License v2) Windows distributions may include a compiled Python distribution. For license information regarding the distributed version of Python, see the diff --git a/docs/_ext/doc_versions.py b/docs/_ext/doc_versions.py new file mode 100644 index 00000000..88fc130a --- /dev/null +++ b/docs/_ext/doc_versions.py @@ -0,0 +1,65 @@ +# Copyright (C) 2026 Brandon Castellano . +# PySceneDetect is licensed under the BSD 3-Clause License; see the +# included LICENSE file, or visit one of the above pages for details. +"""Shared documentation version list loader for Sphinx (docs/conf.py) and website/build.py.""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any + +_DOC_LINK_RE = re.compile(r"^-\s*\[([^\]]+)\]\(/docs/([^/]+)/\)") + + +def _entry(slug: str, label: str, group: str) -> dict[str, Any]: + """One version entry. Only the legacy group uses a different page layout.""" + return {"slug": slug, "label": label, "group": group, "same_layout": group != "legacy"} + + +def load_doc_versions( + repo_dir: Path, fallback_version: str = "" +) -> tuple[str, list[dict[str, Any]]]: + """Load (latest_version, version_entries) from docs/LATEST_VERSION and website/pages/docs.md.""" + latest_file = repo_dir / "docs" / "LATEST_VERSION" + latest_ver = ( + latest_file.read_text(encoding="utf-8").strip().lstrip("v") + if latest_file.is_file() + else fallback_version.lstrip("v") + ) + + stable_slugs: list[str] = [] + legacy_slugs: list[str] = [] + docs_md = repo_dir / "website" / "pages" / "docs.md" + if docs_md.is_file(): + section = "" + for raw_line in docs_md.read_text(encoding="utf-8").splitlines(): + line = raw_line.strip() + if line.startswith("## "): + section = line[3:].strip().lower() + continue + match = _DOC_LINK_RE.match(line) + if not match: + continue + slug = match.group(2).strip() + if slug in {"latest", "head"}: + continue + if section == "legacy": + legacy_slugs.append(slug) + else: + stable_slugs.append(slug) + + if not stable_slugs and latest_ver: + stable_slugs = [latest_ver, "0.7"] + if not legacy_slugs: + legacy_slugs = ["0.6.7"] + + entries = [ + _entry("latest", f"v{latest_ver} (latest)", "channel"), + _entry("head", "dev (head)", "channel"), + ] + # Avoid duplicating `latest` as a separate row when it is the current stable release. + entries += [_entry(slug, f"v{slug}", "release") for slug in stable_slugs if slug != latest_ver] + if legacy_slugs: + entries.append(_entry(legacy_slugs[0], f"v{legacy_slugs[0]} (legacy)", "legacy")) + return latest_ver, entries diff --git a/docs/_ext/section_sidebar.py b/docs/_ext/section_sidebar.py index 32aebba3..406826a9 100644 --- a/docs/_ext/section_sidebar.py +++ b/docs/_ext/section_sidebar.py @@ -6,8 +6,8 @@ The root document has one named toctree per section. For every page inside a section, the sidebar template gets ``section_toctree()``, which renders that section's toctree fully expanded (other pages to the section's ``maxdepth``, the current page to ``current_maxdepth``), -plus ``sidebar_section`` and ``sidebar_sections`` for a switch between sections. The root -document itself renders every labelled section's tree, each pruned to +plus ``sidebar_section`` and ``sidebar_sections`` so templates can highlight the active section +in the top bar. The root document itself renders every top-level section's tree, each pruned to ``section_sidebar_root_depth`` (by default the section's ``maxdepth``). Pages in no section (genindex, search, py-modindex) and the singlehtml builder fall back to the regular global toctree. @@ -15,15 +15,13 @@ Configure with ``section_sidebar_sections`` in conf.py:: section_sidebar_sections = { - "clitoc": ("CLI", "cli", 2, 2), # toctree name: (label, landing doc, depth, cur depth) - "reftoc": (None, None, 2, 2), # no label: every page in the section is a small link + "clitoc": (True, 2, 3), # toctree name: (show_on_root, depth, current-page depth) + "reftoc": (False, 2, 2), # standalone page: show only current page's headings } section_sidebar_root_depth = {"apitoc": 1} # on the root document: page titles only -A section whose label is ``None`` is not part of the switch; the template gets its pages as -``sidebar_section_docs[name]`` (a list of ``(title, docname)``) and draws them as a row of -smaller links. Its tree is only drawn on its own pages, and then holds just the current page's -headings, since the row already lists the pages. +A section with ``show_on_root=False`` is omitted from the root document's sidebar tree. Its tree +is only drawn on its own pages, and then holds just the current page's headings. ``section_sidebar_summary`` trims what a page contributes to the tree when it is NOT the current page: only entries (at any depth) whose text matches one of the glob patterns are @@ -122,8 +120,8 @@ def _prune_depth(top: nodes.list_item, maxdepth: int) -> None: def _keep_current_headings(tree: nodes.Element) -> None: """Replace the section's page list with the headings of the current page, one level up. - For sections without a switch label: the link row under the switch already lists their - pages, so the tree repeats neither the current page's title nor its siblings. + For standalone sections (``show_on_root=False``), the top bar already links to the page, + so the sidebar lists only the current page's headings under an "On this page" caption. """ for top in list(tree.findall(nodes.list_item)): if "toctree-l1" not in top["classes"] or not top.get("iscurrent"): @@ -172,7 +170,7 @@ def _prune_tree( def _add_section_toctree(app: Sphinx, pagename: str, templatename, context, doctree) -> None: sections = app.config.section_sidebar_sections if app.builder.name == "singlehtml": - # Everything is one page: the switch would link to itself, so hide it. + # Everything is one page: fall back to the global toctree instead of per-section trees. sections = {} node = _section_toctree_node(app, pagename) if sections else None names = node.parent.get("names", []) if node is not None else [] @@ -185,10 +183,9 @@ def _add_section_toctree(app: Sphinx, pagename: str, templatename, context, doct root_nodes.append((name, root_node)) context["sidebar_section"] = section context["sidebar_sections"] = sections - context["sidebar_section_docs"] = _section_docs(app, sections) if sections else {} def render(name: str, toctree_node: addnodes.toctree) -> str: - _, _, maxdepth, current_maxdepth = sections[name] + show_on_root, maxdepth, current_maxdepth = sections[name] current_maxdepth = app.config.section_sidebar_page_depth.get(pagename, current_maxdepth) tree = TocTree(app.env).resolve( pagename, @@ -201,11 +198,11 @@ def render(name: str, toctree_node: addnodes.toctree) -> str: ) if tree is None: return "" - # The switch and link row above the tree already name the sections; the toctree - # caption would only repeat them (the captions still head the global toctree used by - # the fallback pages and the singlehtml build). - for child in [c for c in tree.children if isinstance(c, nodes.title)]: - tree.remove(child) + # The top bar names the active section on section pages; keep the toctree caption only on + # the root page (where every section's tree is listed sequentially) and in fallback builds. + if pagename != app.env.config.root_doc: + for child in [c for c in tree.children if isinstance(c, nodes.title)]: + tree.remove(child) root_depth = app.config.section_sidebar_root_depth if pagename == app.env.config.root_doc and name in root_depth: # The root page has no current entry; one depth for every page, no summaries. @@ -217,7 +214,7 @@ def render(name: str, toctree_node: addnodes.toctree) -> str: for docname, patterns in app.config.section_sidebar_summary.items() } _prune_tree(tree, maxdepth, current_maxdepth, summary) - if sections[name][0] is None: + if not show_on_root: _keep_current_headings(tree) return app.builder.render_partial(tree)["fragment"] @@ -231,19 +228,6 @@ def section_toctree() -> str: context["section_toctree"] = section_toctree -def _section_docs(app: Sphinx, sections: dict) -> dict[str, list[tuple[str, str]]]: - """(title, docname) of every page listed by each section's toctree, in order.""" - env = app.env - docs: dict[str, list[tuple[str, str]]] = {} - for node in env.get_doctree(env.config.root_doc).findall(addnodes.toctree): - name = next((n for n in node.parent.get("names", []) if n in sections), None) - if name is not None: - docs[name] = [ - (env.titles[d].astext(), d) for d in node["includefiles"] if d in env.titles - ] - return docs - - def _check_config(app: Sphinx, env) -> None: """Warn about summary / depth entries that name pages or sections which do not exist.""" configured = set(app.config.section_sidebar_summary) diff --git a/docs/_static/pyscenedetect.css b/docs/_static/pyscenedetect.css index cf1d0147..2dd54544 100644 --- a/docs/_static/pyscenedetect.css +++ b/docs/_static/pyscenedetect.css @@ -33,60 +33,22 @@ padding-top: 12px; } -/* Per-section sidebar: CLI | Python API switch and the expanded section tree. */ -div.sphinxsidebar nav.section-switch { - font-size: 1.2em; - margin: 0.5em 0 1em 0; -} -/* No captions over the trees (the switch names them); on the index page, where every - section's tree is listed, space separates one tree from the next. */ -div.sphinxsidebarwrapper > ul + ul { - margin-top: 1.2em; -} -div.sphinxsidebar nav.section-switch a.current { - font-weight: bold; - border-bottom: 2px solid #004B6B; -} -div.sphinxsidebar nav.section-switch .sep { - color: #AAA; - margin: 0 0.4em; -} -div.sphinxsidebar ul li.toctree-l3 > a, -div.sphinxsidebar ul li.toctree-l4 > a { - font-size: 0.9em; -} /* Long constant names (MAX_CONSECUTIVE_DECODE_FAILURES) must wrap inside the sidebar. */ div.sphinxsidebar code span.pre { white-space: normal; overflow-wrap: anywhere; } -/* Pages that span both halves (Examples): a row of smaller links under the switch. */ -div.sphinxsidebar nav.section-switch span.section-links { - display: block; - font-size: 0.75em; - margin-top: 0.4em; -} -div.sphinxsidebar nav.section-switch span.section-links::before { - content: "\2192\00a0"; -} -div.sphinxsidebar nav.section-switch span.section-links a { - white-space: nowrap; /* "Migration Guide (v0.7)" wraps as a whole, not at "(v0.7)" */ -} -div.sphinxsidebar nav.section-switch span.section-links a.current { - font-weight: bold; - border-bottom: none; -} - /* CLI <-> Python API cross-links: compact "See also" boxes with the title inline. */ div.body div.admonition.seealso { - padding: 8px 14px; - margin: 12px 0; + padding: 0.6rem 0.95rem; + margin: 0.9rem 0; } div.body div.admonition.seealso p.admonition-title { display: inline; - font-size: 1em; - font-weight: bold; + font-family: var(--psd-font-sans); + font-size: 0.94rem; + font-weight: 600; line-height: inherit; margin: 0 0.4em 0 0; } @@ -103,21 +65,58 @@ div.body div.admonition.seealso ul { div.surfaces { display: grid; grid-template-columns: 1fr 1fr; - gap: 0 2em; - margin: 1em 0; + gap: 1.25rem 1.75rem; + margin: 1.15rem 0 1.5rem 0; } div.surfaces div.surface { min-width: 0; + padding: 1rem 1.15rem; + border: 1px solid var(--psd-border); + border-radius: 0.55rem; + background: var(--psd-surface); +} +div.body div.surfaces div.surface p.rubric { + font-family: var(--psd-font-heading); + font-size: 1.12rem; + font-weight: 700; + margin: 0 0 0.65rem 0; + padding-bottom: 0.4rem; + border-bottom: 1px solid var(--psd-border); + color: var(--psd-fg); +} +div.body div.surfaces ul { + list-style: none; + margin: 0; + padding: 0; } -div.surfaces div.surface p.rubric { - font-size: 1.2em; - margin: 0 0 0.3em 0; +div.body div.surfaces div.surface > ul > li + li { + margin-block-start: 0.35rem; } -div.surfaces div.surface > ul { - margin-left: 1.2em; +div.body div.surfaces div.surface li > ul { + list-style: none; + margin: 0.2rem 0 0.45rem 0.3rem; + padding-inline-start: 0.8rem; + border-inline-start: 1px solid var(--psd-border); } -div.surfaces div.surface li > ul { - margin: 0.1em 0 0.3em 1.4em; +div.body div.surfaces li + li { + margin-block-start: 0.2rem; +} +div.body div.surfaces li p { + margin: 0; + line-height: 1.5; +} +div.body div.surfaces div.surface > ul > li > p > a { + font-weight: 500; +} +div.body div.surfaces li > p > strong:only-child { + display: inline-block; + font-family: var(--psd-font-sans); + font-size: 0.74rem; + font-weight: 700; + letter-spacing: 0.045em; + text-transform: uppercase; + color: var(--psd-muted); + margin-block: 0.18rem 0.04rem; } div.surfaces li li a { white-space: nowrap; @@ -132,7 +131,7 @@ div.surfaces li li a { table.detector-options, table.config-keys { width: 100%; - font-size: 0.9em; + font-size: 0.9rem; } div.table-scroll { overflow-x: auto; @@ -153,9 +152,9 @@ table.config-keys { div.body div.admonition.seealso a { white-space: nowrap; } -/* Long inline code (config file paths) and URLs wrap instead of widening the page. The 980px +/* Long inline code (config file paths) and URLs wrap instead of widening the page. The 1120px bound matches the fluid-width query below. */ -@media screen and (max-width: 980px) { +@media screen and (max-width: 1120px) { div.body code.literal span.pre, div.body a.reference.external { white-space: normal; @@ -163,32 +162,986 @@ div.body div.admonition.seealso a { } } -/* alabaster fixes the page at 940px and only goes fluid below 876px; fill the gap. */ -@media screen and (min-width: 876px) and (max-width: 980px) { +@media screen and (max-width: 875px) { + div.surfaces { + grid-template-columns: 1fr; + } +} +@media screen and (max-width: 700px) { + /* Too narrow for four columns: keep the table readable and let its container scroll. */ + div.table-scroll table.detector-options { + min-width: 560px; + } +} + +/* ========================================================================== + Harmonized Modern-Web Theme Layer (Unified Noto Sans + Style A Tokens) + ========================================================================== */ + +@media (prefers-reduced-motion: no-preference) { + @view-transition { + navigation: auto; + } +} + +:root { + --psd-bg: light-dark(oklch(99.2% 0.002 250), oklch(15.5% 0.012 255)); + --psd-surface: light-dark(oklch(96.8% 0.005 250), oklch(19.5% 0.015 255)); + --psd-surface-elevated: light-dark(oklch(100% 0 0), oklch(22% 0.016 255)); + --psd-fg: light-dark(oklch(21% 0.02 255), oklch(94% 0.008 250)); + --psd-muted: light-dark(oklch(44% 0.02 255), oklch(72% 0.015 250)); + --psd-border: light-dark(oklch(87.5% 0.01 250), oklch(29.5% 0.018 255)); + --psd-brand: light-dark(oklch(44% 0.12 248), oklch(75% 0.12 240)); + --psd-code-bg: light-dark(oklch(96.2% 0.006 250), oklch(13.5% 0.012 255)); + + --psd-syn-kw: light-dark(oklch(38% 0.14 295), oklch(78% 0.14 295)); + --psd-syn-fn: light-dark(oklch(38% 0.13 240), oklch(79% 0.12 235)); + --psd-syn-str: light-dark(oklch(38% 0.12 155), oklch(78% 0.13 155)); + --psd-syn-num: light-dark(oklch(42% 0.13 45), oklch(80% 0.13 65)); + + --psd-warn: light-dark(oklch(58% 0.15 70), oklch(78% 0.15 75)); + --psd-danger: light-dark(oklch(52% 0.19 25), oklch(72% 0.18 25)); + --psd-success: light-dark(oklch(45% 0.14 150), oklch(76% 0.15 150)); + + --psd-font-sans: "Noto Sans", "Segoe UI", system-ui, -apple-system, BlinkMacSystemFont, sans-serif; + --psd-font-heading: var(--psd-font-sans); + --psd-font-mono: "JetBrains Mono", "Cascadia Code", "Cascadia Mono", "Consolas", ui-monospace, monospace; + + color-scheme: light dark; + accent-color: var(--psd-brand); + &:has(> head > meta[name="color-scheme"][content="dark"]) { + color-scheme: dark; + } + &:has(> head > meta[name="color-scheme"][content="light"]) { + color-scheme: light; + } +} + +html { + scroll-padding-block-start: 4.5rem; +} + +body { + background-color: var(--psd-bg); + color: var(--psd-fg); + font-family: var(--psd-font-sans); + font-size-adjust: from-font; + font-size: 1rem; + line-height: 1.72; + text-align: start; + margin: 0; +} + +@supports not (font-size-adjust: from-font) { + body { + line-height: 1.75; + } +} + +a:focus-visible, +button:focus-visible, +input:focus-visible { + outline: 2px solid var(--psd-brand); + outline-offset: 2px; +} + +.psd-sr-only { + position: absolute; + clip-path: inset(50%); + overflow: hidden; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + border: 0; + white-space: nowrap; +} + +/* Harmonized top bar with backlink to scenedetect.com and version switcher */ +header.psd-topbar { + position: sticky; + inset-block-start: 0; + z-index: 30; + background: color-mix(in oklab, var(--psd-bg) 90%, transparent); + backdrop-filter: blur(8px); + border-block-end: 1px solid var(--psd-border); + font-family: var(--psd-font-sans); + font-size: 0.875rem; +} +.psd-topbar-inner { + max-inline-size: 1080px; + margin-inline: auto; + padding: 0.55rem 1.5rem; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem 1rem; + box-sizing: border-box; +} +.psd-topbar-nav { + display: flex; + align-items: center; + gap: 0.35rem 1.1rem; + flex-wrap: wrap; +} +.psd-topbar-nav a { + color: var(--psd-muted); + text-decoration: none; + border-bottom: none; + font-weight: 500; + padding-block: 0.15rem; +} +.psd-topbar-nav a:hover { + color: var(--psd-fg); +} +.psd-topbar-nav a.psd-backlink { + color: var(--psd-fg); + font-weight: 600; +} +.psd-topbar-nav a.current { + color: var(--psd-brand); + font-weight: 600; + border-block-end: 2px solid var(--psd-brand); +} +.psd-sep { + color: var(--psd-border); +} +.psd-topbar-meta { + display: flex; + align-items: center; + gap: 0.65rem; +} + +/* Version switcher button + top-layer popover */ +.psd-version-switcher { + position: relative; + display: inline-flex; + align-items: center; +} +.psd-version-btn { + display: inline-flex; + align-items: center; + gap: 0.35rem; + min-block-size: 2rem; + padding: 0.22rem 0.65rem; + border: 1px solid var(--psd-border); + border-radius: 99rem; + background: var(--psd-surface); + color: var(--psd-fg); + font-family: var(--psd-font-mono); + font-size: 0.78rem; + font-weight: 500; + line-height: 1.25; + white-space: nowrap; + cursor: pointer; + transition: background-color 120ms ease-out, border-color 120ms ease-out, color 120ms ease-out; +} +.psd-version-btn:hover { + background: color-mix(in oklab, var(--psd-fg) 6%, var(--psd-surface)); + border-color: color-mix(in oklab, var(--psd-fg) 25%, var(--psd-border)); +} +.psd-version-btn[aria-expanded="true"] { + background: color-mix(in oklab, var(--psd-brand) 12%, var(--psd-surface)); + border-color: var(--psd-brand); + color: var(--psd-brand); +} +.psd-version-chevron { + flex: none; + color: var(--psd-muted); + transition: transform 150ms ease-out, color 120ms ease-out; +} +.psd-version-btn[aria-expanded="true"] .psd-version-chevron { + transform: rotate(180deg); + color: currentColor; +} +.psd-version-menu { + min-inline-size: 13rem; + max-inline-size: min(18rem, calc(100dvw - 1rem)); + max-block-size: min(24rem, calc(100dvh - 4rem)); + padding: 0.35rem; + border: 1px solid var(--psd-border); + border-radius: 0.55rem; + background: var(--psd-surface-elevated); + color: var(--psd-fg); + box-shadow: 0 12px 30px oklch(0% 0 0 / 0.18); + overflow-y: auto; + overscroll-behavior: contain; + box-sizing: border-box; + transform-origin: top right; +} +.psd-version-menu:not(:is(:popover-open, .\:popover-open)) { + display: none; +} +.psd-version-menu[popover]:is(:popover-open, .\:popover-open) { + display: block; +} +@supports (position-area: block-end) { + .psd-version-menu { + inset: auto; + margin: 0.35rem 0 0 0; + height: auto; + position-area: block-end span-inline-start; + position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline; + } +} +@supports not (position-area: block-end) { + .psd-version-menu { + position: fixed; + inset: auto; + margin: 0; + height: auto; + } +} +@media (prefers-reduced-motion: no-preference) { + .psd-version-menu[popover]:is(:popover-open, .\:popover-open) { + animation: psd-menu-in 130ms ease-out both; + } +} +@keyframes psd-menu-in { + from { + opacity: 0; + scale: 0.96; + } +} +.psd-version-list { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 0.12rem; +} +.psd-version-divider { + block-size: 1px; + background: var(--psd-border); + margin: 0.25rem 0.2rem; +} +.psd-version-list a { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.6rem; + min-block-size: 1.95rem; + padding: 0.28rem 0.6rem; + border-radius: 0.38rem; + color: var(--psd-fg); + text-decoration: none; + border-bottom: none; + font-family: var(--psd-font-mono); + font-size: 0.8rem; + line-height: 1.35; + box-sizing: border-box; +} +.psd-version-list a.psd-version-all { + font-family: var(--psd-font-sans); + font-size: 0.82rem; + font-weight: 500; + color: var(--psd-muted); +} +.psd-version-list a:hover, +.psd-version-list a:focus-visible { + background: color-mix(in oklab, var(--psd-brand) 12%, var(--psd-surface)); + color: var(--psd-brand); + text-decoration: none; +} +.psd-version-list a[aria-current="true"] { + background: color-mix(in oklab, var(--psd-brand) 12%, var(--psd-surface)); + color: var(--psd-brand); + font-weight: 600; +} +.psd-version-check { + flex: none; + opacity: 0; +} +.psd-version-list a[aria-current="true"] .psd-version-check { + opacity: 1; +} + +.psd-theme-toggle { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + min-inline-size: 2rem; + min-block-size: 2rem; + padding: 0; + border: 1px solid var(--psd-border); + border-radius: 0.4rem; + background: var(--psd-surface); + color: var(--psd-fg); + cursor: pointer; +} +@media (pointer: coarse) { + .psd-version-btn, + .psd-theme-toggle { + min-inline-size: 2.5rem; + min-block-size: 2.5rem; + } +} +.psd-theme-toggle:hover { + background: color-mix(in oklab, var(--psd-fg) 8%, var(--psd-surface)); + color: var(--psd-brand); +} +.psd-theme-toggle .psd-icon-moon { + display: block; +} +.psd-theme-toggle .psd-icon-sun, +.psd-theme-toggle .psd-label-light { + display: none; +} +:root:has(> head > meta[name="color-scheme"][content="dark"]) .psd-theme-toggle .psd-icon-moon, +:root:has(> head > meta[name="color-scheme"][content="dark"]) .psd-theme-toggle .psd-label-dark { + display: none; +} +:root:has(> head > meta[name="color-scheme"][content="dark"]) .psd-theme-toggle .psd-icon-sun { + display: block; +} +:root:has(> head > meta[name="color-scheme"][content="dark"]) .psd-theme-toggle .psd-label-light { + display: inline; +} +@media (prefers-color-scheme: dark) { + :root:not(:has(> head > meta[name="color-scheme"][content="light"])) .psd-theme-toggle .psd-icon-moon, + :root:not(:has(> head > meta[name="color-scheme"][content="light"])) .psd-theme-toggle .psd-label-dark { + display: none; + } + :root:not(:has(> head > meta[name="color-scheme"][content="light"])) .psd-theme-toggle .psd-icon-sun { + display: block; + } + :root:not(:has(> head > meta[name="color-scheme"][content="light"])) .psd-theme-toggle .psd-label-light { + display: inline; + } +} +.psd-gh-link { + display: inline-flex; + align-items: center; + gap: 0.35rem; + color: var(--psd-fg); + text-decoration: none; + font-weight: 500; +} +.psd-gh-link:hover { + color: var(--psd-brand); + text-decoration: none; +} + +/* Main document shell & editorial serif headings */ +div.document { + width: 1080px; + margin: 1.75rem auto 0 auto; +} +div.documentwrapper { + background: transparent; +} +div.bodywrapper { + margin: 0 0 0 255px; +} +div.body { + color: var(--psd-fg); + background: transparent; + max-width: 730px; + font-size: 1rem; + line-height: 1.72; +} +div.body h1, +div.body h2, +div.body h3, +div.body h4 { + font-family: var(--psd-font-heading); + font-size-adjust: from-font; + font-weight: 600; + line-height: 1.25; + color: var(--psd-fg); + text-wrap: balance; +} +div.body h1 { + font-size: 2.02rem; + font-weight: 700; + letter-spacing: -0.018em; + margin: 0 0 0.75rem 0; +} +div.body h2 { + font-size: 1.52rem; + letter-spacing: -0.01em; + padding-bottom: 0.3rem; + border-bottom: 1px solid var(--psd-border); + margin: 2rem 0 0.75rem 0; +} +div.body h3 { + font-size: 1.24rem; + margin: 1.6rem 0 0.55rem 0; +} +div.body h4 { + font-size: 1.08rem; + margin: 1.25rem 0 0.45rem 0; +} +div.body h1 code, +div.body h2 code, +div.body h3 code, +div.body h4 code { + font-size: 0.84em; + font-weight: 600; +} +div.body p, +div.body dd, +div.body li { + line-height: 1.72; + text-wrap: pretty; +} +div.body li + li { + margin-block-start: 0.28rem; +} +hr { + border-color: var(--psd-border); +} +div.sphinxsidebar hr { + color: var(--psd-border); + background: var(--psd-border); +} + +/* Body links & clickable monospace hover feedback */ +div.body a, +div.body a:visited { + color: var(--psd-brand); + border-bottom: none; + text-decoration: underline; + text-decoration-color: color-mix(in oklab, var(--psd-brand) 42%, transparent); + text-underline-offset: 0.2em; +} +div.body a:hover { + color: var(--psd-brand); + border-bottom: none; + text-decoration-color: var(--psd-brand); + text-decoration-thickness: 1.5px; +} +div.body a.headerlink { + color: var(--psd-muted); + text-decoration: none; + border-bottom: none; +} +div.body a.headerlink:hover { + color: var(--psd-fg); + background: var(--psd-surface); + text-decoration: none; +} + +/* Sidebar logo, search, TOC scale, larger monospace, & unmistakable row hover */ +div.sphinxsidebar { + width: 255px; + font-family: var(--psd-font-sans); + font-size: 0.92rem; + line-height: 1.5; +} +.psd-logo-light { + display: block; + max-width: 185px; + height: auto; +} +.psd-logo-dark { + display: none; + max-width: 185px; + height: auto; +} +:root:has(> head > meta[name="color-scheme"][content="dark"]) .psd-logo-light { display: none; } +:root:has(> head > meta[name="color-scheme"][content="dark"]) .psd-logo-dark { display: block; } +@media (prefers-color-scheme: dark) { + :root:not(:has(> head > meta[name="color-scheme"][content="light"])) .psd-logo-light { display: none; } + :root:not(:has(> head > meta[name="color-scheme"][content="light"])) .psd-logo-dark { display: block; } +} + +div.sphinxsidebar p.psd-sidebar-subtitle { + font-size: 0.82rem; + color: var(--psd-muted); + margin: 0.35rem 0 0.9rem 0; +} +div.sphinxsidebar h3, +div.sphinxsidebar h4 { + font-family: var(--psd-font-sans); + font-size: 0.85rem; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--psd-muted); + margin: 1rem 0 0.35rem 0.45rem; +} +div.sphinxsidebar p.caption { + font-family: var(--psd-font-sans); + font-size: 0.74rem; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--psd-muted); + margin: 1.15rem 0 0.3rem 0.5rem; +} +div.sphinxsidebar nav.psd-sidebar-toc > p.caption:first-child { + margin-top: 0.65rem; +} +div.sphinxsidebar ul { + list-style: none; + margin: 0.35rem 0; + padding: 0; +} +div.sphinxsidebar ul ul { + list-style: none; + margin: 0.12rem 0 0.28rem 0.6rem; + padding-inline-start: 0.55rem; + border-inline-start: 1px solid var(--psd-border); +} +div.sphinxsidebar li { + color: var(--psd-muted); + margin-block: 0.08rem; +} +div.sphinxsidebar a { + color: var(--psd-muted); + text-decoration: none; + border-bottom: none; +} +div.sphinxsidebar ul li > a, +div.sphinxsidebar ul li.toctree-l1 > a, +div.sphinxsidebar ul li.toctree-l2 > a, +div.sphinxsidebar ul li.toctree-l3 > a, +div.sphinxsidebar ul li.toctree-l4 > a { + display: block; + padding: 0.22rem 0.5rem; + border-radius: 0.35rem; + font-size: 0.9rem; + line-height: 1.42; + color: var(--psd-muted); + text-decoration: none; + border-bottom: none; + transition: background-color 110ms ease-out, color 110ms ease-out; +} +div.sphinxsidebar ul li.toctree-l1 > a { + font-size: 0.94rem; + font-weight: 500; + color: var(--psd-fg); +} +div.sphinxsidebar ul li.toctree-l3 > a, +div.sphinxsidebar ul li.toctree-l4 > a { + font-size: 0.88rem; +} +div.sphinxsidebar ul li.current > a { + color: var(--psd-fg); + font-weight: 600; +} +div.sphinxsidebar ul li.current > a.current { + color: var(--psd-brand); + background: color-mix(in oklab, var(--psd-brand) 12%, var(--psd-surface)); + font-weight: 600; +} +div.sphinxsidebar ul li > a:hover, +div.sphinxsidebar ul li > a:focus-visible { + color: var(--psd-brand); + background: color-mix(in oklab, var(--psd-brand) 13%, var(--psd-surface)); + border-bottom: none; + text-decoration: none; +} +div.sphinxsidebar p.logo a, +div.sphinxsidebar p.logo a:hover { + background: transparent; + border: none; +} +/* TOC monospace: larger x-height, uncramped (no inner border box), inherits hover color */ +div.sphinxsidebar code, +div.sphinxsidebar tt, +div.sphinxsidebar a code, +div.sphinxsidebar a code span.pre { + font-family: var(--psd-font-mono); + font-size: 0.96em; + font-size-adjust: from-font; + background: transparent; + border: none; + padding: 0; + color: inherit; +} + +.psd-searchbox { + margin-bottom: 0.85rem; +} +.psd-searchbox input[type="search"] { + width: 100%; + box-sizing: border-box; + padding: 0.44rem 0.65rem; + border: 1px solid var(--psd-border); + border-radius: 0.4rem; + background: var(--psd-surface); + color: var(--psd-fg); + font-family: inherit; + font-size: 0.875rem; +} +.psd-searchbox input[type="search"]::placeholder { + color: var(--psd-muted); +} + +/* Code blocks, inline literals, Pygments tokens, & sphinx-copybutton */ +div.highlight, .highlight { + background: transparent; +} +.highlight .hll { + background-color: color-mix(in oklab, var(--psd-brand) 16%, var(--psd-code-bg)); +} +div.body pre { + background: var(--psd-code-bg); + color: var(--psd-fg); + border: 1px solid var(--psd-border); + border-radius: 0.45rem; + padding: 0.9rem 1.05rem; + font-family: var(--psd-font-mono); + font-size: 0.875rem; + line-height: 1.62; + overflow-x: auto; +} +div.body code, +div.body tt, +div.body code.xref, +div.body div.admonition code.xref { + font-family: var(--psd-font-mono); + font-size-adjust: from-font; + background: var(--psd-surface); + color: var(--psd-fg); + border: 1px solid var(--psd-border); + border-radius: 0.25rem; + padding: 0.08em 0.34em; + font-size: 0.88em; +} +@supports not (font-size-adjust: from-font) { + div.body code, + div.body tt, + div.body code.xref, + :is(div.body, .related) a[href*="#command-"] > span.std-ref, + :is(div.body, .related) a[href*="#config-"] > span.std-ref { + font-size: 0.86em; + } +} +:is(div.body, div.body div.admonition, .related) a :is(code, tt, code.xref), +:is(div.body, .related) a[href*="#command-"] > span.std-ref, +:is(div.body, .related) a[href*="#config-"] > span.std-ref { + font-family: var(--psd-font-mono); + font-size: 0.88em; + font-weight: 500; + font-size-adjust: from-font; + color: var(--psd-brand); + background: color-mix(in oklab, var(--psd-brand) 6%, var(--psd-surface)); + border: 1px solid color-mix(in oklab, var(--psd-brand) 30%, var(--psd-border)); + border-radius: 0.25rem; + padding: 0.08em 0.34em; + transition: background-color 110ms ease-out, border-color 110ms ease-out, color 110ms ease-out; +} +:is(div.body, div.body div.admonition, .related) a:is(:hover, :focus-visible) :is(code, tt, code.xref), +:is(div.body, .related) a[href*="#command-"]:is(:hover, :focus-visible) > span.std-ref, +:is(div.body, .related) a[href*="#config-"]:is(:hover, :focus-visible) > span.std-ref { + color: var(--psd-brand); + background: color-mix(in oklab, var(--psd-brand) 18%, var(--psd-surface)); + border-color: var(--psd-brand); + text-decoration: underline; + text-decoration-thickness: 1.5px; + text-underline-offset: 0.18em; +} +div.body pre code { + background: transparent; + border: none; + padding: 0; + font-size: inherit; +} + +/* Accessible light/dark Pygments token overrides via :root custom properties */ +.highlight .k, .highlight .kc, .highlight .kd, .highlight .kn, +.highlight .kp, .highlight .kr, .highlight .ow, .highlight .nb, +.highlight .bp, .highlight .ne, .highlight .cp { + color: var(--psd-syn-kw); +} +.highlight .nf, .highlight .fm, .highlight .nc, .highlight .nn, +.highlight .nt, .highlight .nl, .highlight .kt, .highlight .no { + color: var(--psd-syn-fn); +} +.highlight .s, .highlight .sa, .highlight .sb, .highlight .sc, +.highlight .dl, .highlight .sd, .highlight .s2, .highlight .se, +.highlight .sh, .highlight .si, .highlight .sx, .highlight .sr, +.highlight .s1, .highlight .ss, .highlight .na { + color: var(--psd-syn-str); +} +.highlight .m, .highlight .mb, .highlight .mf, .highlight .mh, +.highlight .mi, .highlight .mo, .highlight .il, .highlight .gp, +.highlight .nv, .highlight .vc, .highlight .vg, .highlight .vi, .highlight .vm { + color: var(--psd-syn-num); +} +.highlight .c, .highlight .ch, .highlight .cm, +.highlight .cpf, .highlight .c1, .highlight .cs { + color: var(--psd-muted); + background: transparent; +} +.highlight .o, .highlight .p, .highlight .go, .highlight .nd { + color: var(--psd-fg); +} + +/* sphinx-copybutton styling against --psd-code-bg */ +.highlight button.copybtn { + background-color: var(--psd-surface); + color: var(--psd-muted); + border: 1px solid var(--psd-border); +} +.highlight button.copybtn:hover { + background-color: color-mix(in oklab, var(--psd-fg) 10%, var(--psd-surface)); + color: var(--psd-fg); + border-color: color-mix(in oklab, var(--psd-fg) 25%, var(--psd-border)); +} +.highlight button.copybtn:active { + background-color: color-mix(in oklab, var(--psd-fg) 18%, var(--psd-surface)); +} +.highlight button.copybtn:focus-visible { + opacity: 1; + outline: 2px solid var(--psd-brand); + outline-offset: 2px; +} +.highlight button.copybtn.success { + border-color: var(--psd-success); + color: var(--psd-success); +} +.o-tooltip--left::after { + background: var(--psd-surface); + color: var(--psd-fg); + border: 1px solid var(--psd-border); +} + +/* API signatures, tables, admonitions, & footer */ +dt:target, div.viewcode-block:target { + background: color-mix(in oklab, var(--psd-brand) 16%, var(--psd-surface)); +} +span.highlighted { + background-color: color-mix(in oklab, var(--psd-warn) 32%, var(--psd-surface)); + color: var(--psd-fg); + border-radius: 0.2rem; + padding: 0 0.15em; +} +table.indextable tr.cap { + background-color: var(--psd-surface); + color: var(--psd-fg); +} +div.genindex-jumpbox, +div.modindex-jumpbox { + border-top: 1px solid var(--psd-border); + border-bottom: 1px solid var(--psd-border); +} +dl.py > dt.sig { + background: var(--psd-surface); + border-inline-start: 3px solid var(--psd-brand); + padding: 0.45rem 0.75rem; + border-radius: 0 0.35rem 0.35rem 0; + overflow-wrap: anywhere; +} +dl.py > dt.sig span.pre { + white-space: pre-wrap; +} +table.docutils { + border-collapse: collapse; + border: 1px solid var(--psd-border); + box-shadow: none; +} +table.docutils th, table.docutils td { + border: 1px solid var(--psd-border); + padding: 0.48rem 0.68rem; +} +table.docutils th { + background: var(--psd-surface); + color: var(--psd-fg); +} +table.footnote, div.topic { + background: var(--psd-surface); + border-color: var(--psd-border); +} +div.body div.admonition { + background: var(--psd-surface); + border: 1px solid var(--psd-border); + border-inline-start: 3px solid var(--psd-brand); + border-radius: 0.4rem; + box-shadow: none; +} +div.body div.admonition.warning, +div.body div.admonition.caution, +div.body div.admonition.attention { + border-inline-start-color: var(--psd-warn); +} +div.body div.admonition.danger, +div.body div.admonition.error { + border-inline-start-color: var(--psd-danger); +} +div.admonition p.admonition-title, +div.body p.admonition-title { + font-family: var(--psd-font-sans); + color: var(--psd-fg); + font-size: 1rem; + font-weight: 600; + line-height: 1.4; +} +.related { + color: var(--psd-muted); +} +.related.top, .related.bottom { + border-color: var(--psd-border); +} +.related a, +.related a:visited { + color: var(--psd-brand); + border-bottom: none; + text-decoration: underline; + text-decoration-color: color-mix(in oklab, var(--psd-brand) 42%, transparent); + text-underline-offset: 0.2em; +} +.related a:hover { + color: var(--psd-brand); + border-bottom: none; + text-decoration-color: var(--psd-brand); + text-decoration-thickness: 1.5px; +} +div.footer { + width: 1080px; + color: var(--psd-muted); + border-top: 1px solid var(--psd-border); + padding-top: 1rem; + margin-top: 2.5rem; +} +.psd-footer-inner { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem 1.25rem; +} +.psd-footer-links { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.35rem 1rem; +} +div.footer a, +div.footer a:visited { + color: var(--psd-muted); + border-bottom: none; + text-decoration: none; +} +div.footer a:hover { + color: var(--psd-brand); + text-decoration: underline; +} + +/* Responsive fluid layout below 1120px and mobile <= 875px */ +@media screen and (min-width: 876px) and (max-width: 1120px) { div.document, div.footer { + max-inline-size: 100%; width: auto; - margin-left: 20px; - margin-right: 20px; + margin-inline: 1.25rem; } } -@media screen and (max-width: 875px) { - div.surfaces { - grid-template-columns: 1fr; +@media (max-width: 875px) { + body { + padding: 0; + } + .psd-topbar-inner, + div.document, + div.footer { + max-inline-size: 100%; + width: auto; + padding-inline: 1rem; + box-sizing: border-box; } - /* The sidebar is drawn as a dark block at the bottom of the page. */ - div.sphinxsidebar code, - div.sphinxsidebar code span.pre { - color: #DDD; + div.document { + margin-block-start: 1.25rem; + } + div.documentwrapper, + div.bodywrapper, + div.body { + max-inline-size: 100%; + min-inline-size: 0; + width: auto; + margin: 0; + box-sizing: border-box; + } + div.documentwrapper { background: transparent; } - div.sphinxsidebar nav.section-switch a.current { - border-bottom-color: #DDD; + div.body { + padding: 0; + overflow-wrap: anywhere; + } + div.body :not(pre) > code span.pre { + white-space: pre-wrap; + } + div.body table.docutils { + display: block; + max-inline-size: 100%; + overflow-x: auto; + } + div.sphinxsidebar { + max-inline-size: 100%; + width: auto; + margin: 2rem 0 1.5rem 0; + padding: 1rem; + box-sizing: border-box; + background: var(--psd-surface); + color: var(--psd-fg); + border: 1px solid var(--psd-border); + border-radius: 0.5rem; + } + div.sphinxsidebar h3, + div.sphinxsidebar h4, + div.sphinxsidebar p.caption { + color: var(--psd-muted); + } + div.sphinxsidebar p, + div.sphinxsidebar h3 a { + color: var(--psd-fg); + } + div.sphinxsidebar ul li > a { + color: var(--psd-fg); + } + div.sphinxsidebar p.psd-sidebar-subtitle { + color: var(--psd-muted); + } + div.sphinxsidebar ul li.current > a.current { + color: var(--psd-brand); + background: color-mix(in oklab, var(--psd-brand) 14%, var(--psd-bg)); + } + div.sphinxsidebar ul li > a:hover, + div.sphinxsidebar ul li > a:focus-visible { + color: var(--psd-brand); + background: color-mix(in oklab, var(--psd-brand) 14%, var(--psd-bg)); } } -@media screen and (max-width: 700px) { - /* Too narrow for four columns: keep the table readable and let its container scroll. */ - div.table-scroll table.detector-options { - min-width: 560px; + +/* Forced Colors Mode (Windows High Contrast) safe boundaries */ +@media (forced-colors: active) { + header.psd-topbar { + border-block-end: 1px solid CanvasText; + } + .psd-topbar-nav a.current { + border-block-end: 2px solid Highlight; + } + .psd-version-btn, + .psd-version-menu, + .psd-theme-toggle, + .psd-searchbox input[type="search"], + div.body pre, + div.body div.admonition, + table.docutils, + table.docutils th, + table.docutils td, + .highlight button.copybtn { + border: 1px solid CanvasText; + } + dl.py > dt.sig, + div.body div.admonition { + border-inline-start: 3px solid Highlight; + } + div.sphinxsidebar ul li.current > a.current, + .psd-version-list a[aria-current="true"] { + outline: 2px solid Highlight; + outline-offset: -2px; + } + span.highlighted { + background-color: Mark; + color: MarkText; } } diff --git a/docs/_static/pyscenedetect_logo_small_darkmode.png b/docs/_static/pyscenedetect_logo_small_darkmode.png new file mode 100644 index 00000000..5b080af2 Binary files /dev/null and b/docs/_static/pyscenedetect_logo_small_darkmode.png differ diff --git a/docs/_templates/about.html b/docs/_templates/about.html new file mode 100644 index 00000000..7d983b75 --- /dev/null +++ b/docs/_templates/about.html @@ -0,0 +1,7 @@ + +

Reference Manual · {{ release }}

diff --git a/docs/_templates/layout.html b/docs/_templates/layout.html new file mode 100644 index 00000000..49247f46 --- /dev/null +++ b/docs/_templates/layout.html @@ -0,0 +1,332 @@ +{%- extends "!layout.html" %} + +{%- block extrahead %} + + + + + +{%- if builder != 'singlehtml' %} + + +{%- endif %} + + {{ super() }} +{%- endblock %} + +{%- block header %} +{%- set psd_page_rel = '' if pagename == root_doc else (pagename ~ '.html') %} +
+
+ +
+
+ +
+ +
+
+ + + + GitHub + +
+
+
+{%- endblock %} + +{%- block footer %} + +{%- endblock %} diff --git a/docs/_templates/navigation.html b/docs/_templates/navigation.html index 7da16877..522d5513 100644 --- a/docs/_templates/navigation.html +++ b/docs/_templates/navigation.html @@ -1,33 +1,15 @@ -{#- Per-section sidebar: `sidebar_section`, `sidebar_sections`, `sidebar_section_docs` and - `section_toctree()` are set by docs/_ext/section_sidebar.py. -#} -{%- if sidebar_sections %} - -{%- endif %} +{#- Per-section sidebar: `sidebar_section`, `sidebar_sections`, and `section_toctree()` + are set by docs/_ext/section_sidebar.py. Top-level section links live in `.psd-topbar`. -#} {%- set section_tree = section_toctree() if sidebar_sections else "" %} {%- if section_tree %} + {%- else %}

{{ _('Navigation') }}

{{ toctree(maxdepth=2, includehidden=theme_sidebar_includehidden, collapse=theme_sidebar_collapse) }} {%- endif %} -{% if theme_extra_nav_links %} -
-
    - {% for text, uri in theme_extra_nav_links.items() %} -
  • {{ text }}
  • - {% endfor %} -
-{% endif %} \ No newline at end of file +{# The line break before this comment is part of the rendered sidebar. #} diff --git a/docs/_templates/searchbox.html b/docs/_templates/searchbox.html new file mode 100644 index 00000000..76af5983 --- /dev/null +++ b/docs/_templates/searchbox.html @@ -0,0 +1,7 @@ +{%- if pagename != "search" and builder != "singlehtml" %} + + + +{%- endif %} diff --git a/docs/api.rst b/docs/api.rst index b9bbd733..2e199af4 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -5,31 +5,31 @@ .. seealso:: For the ``scenedetect`` command, see the :doc:`CLI reference `. -The `scenedetect` API is easy to integrate with most application workflows, while also being highly extensible. See the `Usage`_ section below for some common use cases and integrations. The `scenedetect` package is organized into several sub-modules: +The ``scenedetect`` API integrates into Python applications and supports custom detectors and video backends. See `Usage`_ below for common examples. The ``scenedetect`` package is organized into these submodules: - * :ref:`Functions `: high-level functions like :func:`scenedetect.detect() ` to quickly analyze a video with any :ref:`detection algorithm ` (:ref:`example `) and get a list of timecode pairs as a result + * :ref:`Functions `: high-level functions such as :func:`scenedetect.detect() ` to analyze a video with any :ref:`detector ` (:ref:`example `) and return a list of timecode pairs - * :doc:`api/detectors`: detection algorithms: + * :doc:`api/detectors`: built-in detectors: - * :class:`AdaptiveDetector `: finds fast cuts using rolling average of HSL changes + * :class:`AdaptiveDetector `: finds fast cuts using a rolling average of HSV content changes - * :class:`ContentDetector `: detects fast cuts using weighted average of HSV changes + * :class:`ContentDetector `: finds fast cuts using a weighted average of HSV color and optional edge changes - * :class:`ThresholdDetector `: finds fades in/out using average pixel intensity changes in RGB + * :class:`HashDetector `: finds fast cuts using perceptual image hashing - * :class:`HistogramDetector `: finds fast cuts using HSV histogram changes + * :class:`HistogramDetector `: finds fast cuts using Y-channel (brightness) histogram changes in YUV - * :class:`HashDetector `: finds fast cuts using perceptual image hashing + * :class:`ThresholdDetector `: finds fades in and out using average RGB pixel brightness - * :doc:`api/output`: Output formats: + * :doc:`api/output`: output helpers: - * :func:`split_video_ffmpeg ` and :func:`split_video_mkvmerge ` split a video based on the detected scenes + * :func:`split_video_ffmpeg ` and :func:`split_video_mkvmerge ` split a video into clips for each detected scene - * :func:`save_images ` can save an arbitrary number of images from each scene + * :func:`save_images ` saves still frames from each scene - * :func:`write_scene_list ` can be used to save scene/cut info as CSV, :func:`write_scene_list_html ` for HTML + * :func:`write_scene_list ` writes scene lists as CSV, :func:`write_scene_list_html ` writes HTML reports, and additional helpers export EDL, Final Cut Pro XML, OpenTimelineIO, and FFmetadata chapters - * :doc:`api/backends`: PySceneDetect supports multiple libraries as an input backend: + * :doc:`api/backends`: modular video input backends: * OpenCV: :class:`VideoStreamCv2 ` @@ -37,30 +37,30 @@ The `scenedetect` API is easy to integrate with most application workflows, whil * MoviePy: :class:`VideoStreamMoviePy ` - * Multiple videos can be treated as a single continuous stream using :class:`VideoStreamConcat ` (e.g. ``open_video(["part1.mp4", "part2.mp4"])``) + * Multiple videos can be read as one continuous stream with :class:`VideoStreamConcat ` (for example, ``open_video(["part1.mp4", "part2.mp4"])``) - * :doc:`api/common`: common functionality such as :class:`FrameTimecode ` for timecode handling + * :doc:`api/common`: common types such as :class:`FrameTimecode ` for timecode handling - * :doc:`api/scene_manager`: the :class:`SceneManager ` coordinates performing scene detection on a video with one or more detectors + * :doc:`api/scene_manager`: :class:`SceneManager ` runs scene detection on a video with one or more detectors - * :doc:`api/detector`: the interface (:class:`SceneDetector `) that detectors must implement to be compatible with PySceneDetect + * :doc:`api/detector`: the :class:`SceneDetector ` base class for custom detectors - * :doc:`api/video_stream`: the interface (:class:`VideoStream `) that video backends must implement to be compatible with PySceneDetect + * :doc:`api/video_stream`: the :class:`VideoStream ` base class for custom video backends - * :doc:`api/stats_manager`: the :class:`StatsManager ` allows you to store detection metrics for each frame and save them to CSV for further analysis + * :doc:`api/stats_manager`: :class:`StatsManager ` stores per-frame detection metrics and writes them to a CSV stats file * :doc:`api/platform`: logging and utility functions -Most types/functions are also available directly from the `scenedetect` package to make imports simpler. +Most common types and functions can be imported directly from the top-level ``scenedetect`` package. .. warning:: - The PySceneDetect API is still under development. It is recommended that you pin the `scenedetect` version in your requirements to below the next major release: + The PySceneDetect API may change before v1.0. Pin ``scenedetect`` to a minor release in your dependencies: .. code:: python - scenedetect~=0.7 + scenedetect~=0.7.0 .. _scenedetect-usage: @@ -68,7 +68,7 @@ Most types/functions are also available directly from the `scenedetect` package Usage ----- -PySceneDetect makes it very easy to find scene transitions in a video with the :func:`scenedetect.detect` function: +Find scene cuts in a video with :func:`scenedetect.detect`: .. code:: python @@ -78,9 +78,9 @@ PySceneDetect makes it very easy to find scene transitions in a video with the : for (scene_start, scene_end) in scenes: print(f"{scene_start}-{scene_end}") -``scenes`` now contains a list of :class:`FrameTimecode ` pairs representing the start/end of each scene. Note that you can set ``show_progress=True`` when calling :func:`detect ` to display a progress bar with estimated time remaining. +``scenes`` is a list of :class:`FrameTimecode ` pairs giving the start and end of each scene. Pass ``show_progress=True`` to :func:`detect ` to show a progress bar with estimated time remaining. -Here, we use :mod:`ContentDetector ` to detect fast cuts. There are :ref:`many detector types ` which can be used to find fast cuts and fades in/out. PySceneDetect can also export scene data in various formats, and can :ref:`split the input video ` automatically if `ffmpeg` is available: +This example uses :class:`ContentDetector ` to find fast cuts. You can choose from several :ref:`detectors ` for fast cuts and fades. PySceneDetect can also export scene lists in several formats and :ref:`split the input video ` when ``ffmpeg`` is installed: .. code:: python @@ -88,7 +88,7 @@ Here, we use :mod:`ContentDetector ` to scene_list = detect("my_video.mp4", ContentDetector()) split_video_ffmpeg("my_video.mp4", scene_list) -More tasks, each shown as a command and as Python, are on the :doc:`examples` page. For advanced workflows, start with the :ref:`SceneManager `. Logging is covered under :ref:`Platform & Logging `. +See :doc:`examples` for more tasks shown as both CLI commands and Python code. For advanced workflows, start with :ref:`SceneManager `. Logging is covered under :ref:`Platform & Logging `. .. _scenedetect-functions: diff --git a/docs/api/migration_guide.rst b/docs/api/migration_guide.rst index 26694c41..3c7015e0 100644 --- a/docs/api/migration_guide.rst +++ b/docs/api/migration_guide.rst @@ -5,7 +5,7 @@ Migration Guide (v0.7) ---------------------- -PySceneDetect v0.7 is a major release that overhauls timestamp handling to support variable framerate (VFR) videos. While the high-level :func:`scenedetect.detect` workflow is largely unchanged, several internal APIs have been restructured. This guide covers the changes needed to update applications from v0.6 to v0.7. +PySceneDetect v0.7 is a major release that updates timestamp handling to support variable frame rate (VFR) videos. While the high-level :func:`scenedetect.detect` workflow is largely unchanged, several internal APIs changed. This guide lists the updates needed when migrating from v0.6 to v0.7. The minimum supported Python version is now **Python 3.10**. @@ -81,7 +81,7 @@ The ``frame_num`` parameter (``int``) has been replaced with ``timecode`` (:clas def process_frame(self, timecode: FrameTimecode, frame_img) -> List[FrameTimecode]: ... -The same change applies to ``post_process()``. Using units of time instead of frame numbers is critical for temporal accuracy. If you need the frame number, use ``timecode.frame_num`` to convert the timecode to an integer. +The same change applies to ``post_process()``. Using timecodes instead of frame numbers keeps timing accurate on VFR video. Use ``timecode.frame_num`` if you need an integer frame number. ``SceneDetector`` is Now Abstract ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -139,12 +139,12 @@ Access :attr:`~scenedetect.common.FrameTimecode.frame_num`, :attr:`~scenedetect. rate * 0.5 # 14.985... (float, mixed arithmetic) f"{float(rate):.3f}" # '29.970' (explicit cast for format spec) -The legacy ``framerate`` property (one word, returns ``float``) is retained as a deprecated alias and will emit a ``DeprecationWarning`` in a future release. Migrate to ``frame_rate``; cast with ``float(...)`` at the call site if you specifically need a ``float``. +The legacy ``framerate`` property (one word, returns ``float``) is retained as a deprecated alias and emits a ``DeprecationWarning`` (scheduled for removal in v0.9). Migrate to ``frame_rate``; cast with ``float(...)`` at the call site if you specifically need a ``float``. Renamed Method: ``equal_framerate()`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -:meth:`~scenedetect.common.FrameTimecode.equal_framerate` has been renamed to :meth:`~scenedetect.common.FrameTimecode.equal_frame_rate` for consistency with the :attr:`~scenedetect.common.FrameTimecode.frame_rate` property. The legacy ``equal_framerate()`` method is retained as a deprecated alias and will emit a ``DeprecationWarning`` in a future release. The new form additionally accepts a ``Fraction`` or another ``FrameTimecode`` (in addition to ``float``). +:meth:`~scenedetect.common.FrameTimecode.equal_framerate` has been renamed to :meth:`~scenedetect.common.FrameTimecode.equal_frame_rate` for consistency with the :attr:`~scenedetect.common.FrameTimecode.frame_rate` property. The legacy ``equal_framerate()`` method is retained as a deprecated alias and emits a ``DeprecationWarning`` (scheduled for removal in v0.9). The new form additionally accepts a ``Fraction`` or another ``FrameTimecode`` (in addition to ``float``). Removed Methods ^^^^^^^^^^^^^^^ @@ -152,11 +152,11 @@ Removed Methods - ``previous_frame()`` - removed, use ``FrameTimecode(tc.frame_num - 1, tc)`` instead (passing a ``FrameTimecode`` as the ``fps`` argument reuses its rate) -Framerate and Timestamp Changes -------------------------------- +Frame Rate and Timestamp Changes +-------------------------------- -Rational Framerates -^^^^^^^^^^^^^^^^^^^ +Rational Frame Rates +^^^^^^^^^^^^^^^^^^^^ :attr:`~scenedetect.video_stream.VideoStream.frame_rate` now returns a ``Fraction`` instead of ``float``. Common NTSC rates (23.976, 29.97, 59.94) are automatically detected from float values: @@ -170,7 +170,7 @@ Rational Framerates ``frame_rate`` Keyword Argument ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -The ``framerate`` keyword argument has been renamed to ``frame_rate`` on :func:`~scenedetect.open_video` and on every backend constructor (:class:`~scenedetect.backends.opencv.VideoStreamCv2`, :class:`~scenedetect.backends.opencv.VideoCaptureAdapter`, :class:`~scenedetect.backends.pyav.VideoStreamAv`, :class:`~scenedetect.backends.moviepy.VideoStreamMoviePy`). The new form accepts ``float | Fraction | None``. The legacy ``framerate`` keyword is retained as a deprecated alias and will emit a ``DeprecationWarning`` in a future release; if both are supplied, ``frame_rate`` takes precedence. +The ``framerate`` keyword argument has been renamed to ``frame_rate`` on :func:`~scenedetect.open_video` and on every backend constructor (:class:`~scenedetect.backends.opencv.VideoStreamCv2`, :class:`~scenedetect.backends.opencv.VideoCaptureAdapter`, :class:`~scenedetect.backends.pyav.VideoStreamAv`, :class:`~scenedetect.backends.moviepy.VideoStreamMoviePy`). The new form accepts ``float | Fraction | None``. The legacy ``framerate`` keyword is retained as a deprecated alias and emits a ``DeprecationWarning`` (scheduled for removal in v0.9); if both are supplied, ``frame_rate`` takes precedence. .. code:: python @@ -199,7 +199,7 @@ The ``StatsManager`` methods :meth:`~scenedetect.stats_manager.StatsManager.get_ ``SceneDetector`` Annotation Fixes ---------------------------------- -:meth:`~scenedetect.detector.SceneDetector.post_process` now declares its parameter as ``timecode: FrameTimecode`` (previously typed as ``int``). The method already received a ``FrameTimecode`` at runtime and concrete detectors (e.g. ``ThresholdDetector``, ``ContentDetector``) already used the ``FrameTimecode`` type - only the abstract-base-class annotation was inconsistent. No call-site changes are needed; this just brings the signature into agreement with the documented and actual behavior. +:meth:`~scenedetect.detector.SceneDetector.post_process` now declares its parameter as ``timecode: FrameTimecode`` (previously typed as ``int``). The method already received a ``FrameTimecode`` at runtime and built-in detectors (such as ``ThresholdDetector`` and ``ContentDetector``) already used ``FrameTimecode``. Only the abstract base class annotation differed; no call-site changes are needed. ``SceneManager.detect_scenes()`` Time Arguments diff --git a/docs/api/platform.rst b/docs/api/platform.rst index 72ee3223..4a3757e5 100644 --- a/docs/api/platform.rst +++ b/docs/api/platform.rst @@ -14,7 +14,7 @@ Platform & Logging Logging ------- -PySceneDetect outputs messages to a logger named ``pyscenedetect`` which does not have any default handlers. You can use :func:`scenedetect.init_logger ` with ``show_stdout=True`` or specify a log file (verbosity can also be specified) to attach some common handlers, or use ``logging.getLogger("pyscenedetect")`` and attach log handlers manually. +PySceneDetect writes log messages to the ``pyscenedetect`` logger, which has no default handlers. Call :func:`scenedetect.init_logger ` with ``show_stdout=True`` or a log file path to attach standard handlers, or configure ``logging.getLogger("pyscenedetect")`` directly. .. seealso:: CLI: :option:`-v/--verbosity `, :option:`-l/--logfile `, :option:`-q/--quiet ` diff --git a/docs/cli.rst b/docs/cli.rst index 8b898c62..219e2009 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -561,7 +561,7 @@ Options ------------------------------------------------------------------------ -.. seealso:: Python API: *no Python API equivalent* | Config file: :ref:`[load-scenes] ` +.. seealso:: Python API: *none (CLI only)* | Config file: :ref:`[load-scenes] ` Load scenes from CSV instead of detecting. Can be used with CSV generated by :ref:`list-scenes `. Scenes are loaded using the specified column as cut locations (frame number or timecode). @@ -870,7 +870,7 @@ Options ------------------------------------------------------------------------ -.. seealso:: Python API: *no Python API equivalent* | Config file: :ref:`[save-keyframes] ` +.. seealso:: Python API: *none (CLI only)* | Config file: :ref:`[save-keyframes] ` Save detected cuts using keyframe format v1. @@ -946,7 +946,7 @@ Options ------------------------------------------------------------------------ -.. seealso:: Python API: *no Python API equivalent* | Config file: :ref:`[save-qp] ` +.. seealso:: Python API: *none (CLI only)* | Config file: :ref:`[save-qp] ` Save cuts as keyframes (I-frames) for video encoding. diff --git a/docs/cli/backends.rst b/docs/cli/backends.rst index 63039f42..f22f1d9b 100644 --- a/docs/cli/backends.rst +++ b/docs/cli/backends.rst @@ -2,12 +2,12 @@ .. _cli-backends: *********************************************************************** -Video Backends +Video Backends (CLI) *********************************************************************** -PySceneDetect supports multiple backends for video input. Some can be configured by using :ref:`a config file `. Installed backends can be verified by running ``scenedetect version``. +PySceneDetect supports modular video input backends. You can configure backend options in a :ref:`config file `. Run ``scenedetect version`` to see which backends are installed. -Note that the `scenedetect` command output is generated as a post-processing step, after scene detection completes. Most commands require the ability for the input to be replayed, and preferably it should also support seeking. Network streams and other input types are supported with certain backends, however integration with live streams requires use of the Python API. +The ``scenedetect`` command generates outputs after scene detection finishes. Most output commands require an input that you can replay, and preferably seek. Some backends support network streams and other input types, but live streams require the Python API. .. _cli-backend-opencv: @@ -19,13 +19,13 @@ OpenCV .. seealso:: Python API: :class:`~scenedetect.backends.opencv.VideoStreamCv2` | Config file: :ref:`[backend-opencv] ` *[Default]* -The `OpenCV `_ backend (usually `opencv-python `_) uses OpenCV's ``VideoCapture`` for video input. Can be used by specifying ``-b opencv`` via command line, or setting ``backend = opencv`` under the ``[global]`` section of your :ref:`config file `. +The `OpenCV `_ backend (usually `opencv-python `_) uses OpenCV's ``VideoCapture`` to decode video. Select it with ``-b opencv`` on the command line, or set ``backend = opencv`` under ``[global]`` in your :ref:`config file `. -It is mostly reliable and fast, although can occasionally run into issues processing videos with multiple audio tracks or small amounts of frame corruption. You can use a custom version of the ``cv2`` package, or install either the `opencv-python` or `opencv-python-headless` packages from `pip`. +OpenCV is fast and reliable for most files, though it can occasionally fail on videos with multiple audio tracks or minor frame corruption. You can use ``opencv-python``, ``opencv-python-headless``, or a custom ``cv2`` build. -The OpenCV backend also supports image sequences as inputs (e.g. ``frame%02d.jpg`` if you want to load frame001.jpg, frame002.jpg, frame003.jpg...). Make sure to specify the framerate manually (``-f``/``--frame-rate``) to ensure accurate timing calculations. +The OpenCV backend also supports image sequences (for example, ``frame%03d.jpg`` to load ``frame001.jpg``, ``frame002.jpg``, ``frame003.jpg``, and so on). Set the frame rate manually with ``-f`` / ``--frame-rate`` so timecodes are accurate. -Variable framerate (VFR) video is supported. Scene detection uses PTS-derived timestamps from ``CAP_PROP_POS_MSEC`` for accurate timecodes. Seeking compensates for OpenCV's average-fps-based internal seek approximation, so output timecodes remain accurate across the full video. +Variable frame rate (VFR) video is supported. Scene detection uses PTS-derived timestamps from ``CAP_PROP_POS_MSEC`` for accurate timecodes. Seeking compensates for OpenCV's average-fps seek approximation so output timecodes stay accurate across the full video. .. _cli-backend-pyav: @@ -36,11 +36,11 @@ PyAV .. seealso:: Python API: :class:`~scenedetect.backends.pyav.VideoStreamAv` | Config file: :ref:`[backend-pyav] ` -The `PyAV `_ backend (`av package `_) is a more robust backend that handles multiple audio tracks and frame decode errors gracefully. +The `PyAV `_ backend (`av package `_) handles multiple audio tracks and frame decode errors more reliably than OpenCV. -Variable framerate (VFR) video is fully supported. PyAV uses native PTS timestamps directly from the container, giving the most accurate timecodes for VFR content. +Variable frame rate (VFR) video is fully supported. PyAV reads native PTS timestamps directly from the video container, giving the most accurate timecodes for VFR content. -This backend can be used by specifying ``-b pyav`` via command line, or setting ``backend = pyav`` under the ``[global]`` section of your :ref:`config file `. +Select this backend with ``-b pyav`` on the command line, or set ``backend = pyav`` under ``[global]`` in your :ref:`config file `. .. _cli-backend-moviepy: @@ -51,12 +51,12 @@ MoviePy .. seealso:: Python API: :class:`~scenedetect.backends.moviepy.VideoStreamMoviePy` -MoviePy launches ffmpeg as a subprocess, and can be used with various types of inputs. If the input supports seeking it should work fine with most operations, for example, image sequences or AviSynth scripts. +MoviePy runs ``ffmpeg`` as a subprocess and supports many input types. Inputs that support seeking, such as image sequences or AviSynth scripts, work with most commands. .. warning:: - The MoviePy backend is still under development and is not included with current Windows distribution. To enable MoviePy support, you must install PySceneDetect using `python` and `pip`. + The MoviePy backend is experimental and is not included in the Windows installer. To use it, install PySceneDetect with ``pip`` (``pip install "scenedetect[moviepy]"``). - Variable framerate (VFR) video is **not supported**. MoviePy assumes a fixed framerate, so timecodes for VFR content will be inaccurate. Use the PyAV or OpenCV backend instead. + Variable frame rate (VFR) video is **not supported**. MoviePy assumes a constant frame rate, so timecodes for VFR content will be inaccurate. Use the PyAV or OpenCV backend instead. -This backend can be used by specifying ``-b moviepy`` via command line, or setting ``backend = moviepy`` under the ``[global]`` section of your :ref:`config file `. +Select this backend with ``-b moviepy`` on the command line, or set ``backend = moviepy`` under ``[global]`` in your :ref:`config file `. diff --git a/docs/cli/config_file.rst b/docs/cli/config_file.rst index f265b270..c7ba1ceb 100644 --- a/docs/cli/config_file.rst +++ b/docs/cli/config_file.rst @@ -5,27 +5,27 @@ Configuration File *********************************************************************** -A configuration file path can be specified using the ``-c``/``--config`` argument. PySceneDetect also looks for a config file named `scenedetect.cfg` in one of the following locations: +Specify a config file with ``-c`` / ``--config``. If you do not pass ``-c``, PySceneDetect looks for ``scenedetect.cfg`` in one of these locations: * Windows: * ``C:/Users/%USERNAME%/AppData/Local/PySceneDetect/scenedetect.cfg`` * Linux: * ``~/.config/PySceneDetect/scenedetect.cfg`` - * ``$XDG_CONFIG_HOME/scenedetect.cfg`` + * ``$XDG_CONFIG_HOME/PySceneDetect/scenedetect.cfg`` - * Mac: - * ``~/Library/Preferences/PySceneDetect/scenedetect.cfg`` + * macOS: + * ``~/Library/Application Support/PySceneDetect/scenedetect.cfg`` -Run ``scenedetect --help`` to see the exact path on your system which will be used. Values set on the command line take precedence over those set in the config file. Most (but not all) command line parameters can be set using a configuration file, and some options can *only* be set using a config file. The :ref:`Sections ` reference below lists every key with its default and the matching command-line option. Note that lines starting with a ``#`` are comments and will be ignored. +Run ``scenedetect --help`` to see the exact path on your system. Command-line options override values in the config file. Most CLI options can be set in a config file, and some options are config-file only. The :ref:`Sections ` reference below lists every key, its default value, and its matching CLI option. Lines starting with ``#`` are comments and are ignored. -The syntax of a configuration file is: +The syntax of a config file is: .. code:: ini [command] option_a = value - #comment + # comment option_b = 1 @@ -60,6 +60,6 @@ Sample File Sections ======================================================================= -Every section of the config file, its keys and defaults, and the part of the ``scenedetect.cfg`` template that documents them. The complete template can be `downloaded from Github `_ and used as a config file as-is (every key is commented out). Values shown in the template are the defaults, or an example where the default is unset. +Every section of the config file, its keys and defaults, and the matching part of the ``scenedetect.cfg`` template. You can `download the complete template from GitHub `_ and use it directly (every key is commented out). Values shown in the template are defaults, or examples where the default is unset. .. include:: config_sections.inc diff --git a/docs/cli/config_sections.inc b/docs/cli/config_sections.inc index da5db4eb..b8b4710e 100644 --- a/docs/cli/config_sections.inc +++ b/docs/cli/config_sections.inc @@ -5,7 +5,7 @@ [global] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Options of the :doc:`scenedetect ` command; detectors and commands inherit ``min-scene-len`` and ``output`` from here. +Options of the :ref:`scenedetect ` command; detectors and commands inherit ``min-scene-len`` and ``output`` from here. .. list-table:: :class: config-keys diff --git a/docs/cli_index.inc b/docs/cli_index.inc index ebc2ca75..07dee69b 100644 --- a/docs/cli_index.inc +++ b/docs/cli_index.inc @@ -1,11 +1,44 @@ .. NOTE: This file is auto-generated by docs/generate_cli_docs.py and should not be modified. -- :doc:`scenedetect Command ` +- :ref:`scenedetect ` Command - :ref:`Usage ` - :ref:`Options ` - - :ref:`Detectors `: :ref:`detect-adaptive `, :ref:`detect-content `, :ref:`detect-hash `, :ref:`detect-hist `, :ref:`detect-threshold ` - - :ref:`Commands `: :ref:`list-scenes `, :ref:`load-scenes `, :ref:`save-chapters `, :ref:`save-edl `, :ref:`save-fcp `, :ref:`save-html `, :ref:`save-images `, :ref:`save-keyframes `, :ref:`save-otio `, :ref:`save-qp `, :ref:`split-video `, :ref:`time ` + - :ref:`Detectors ` + + - **Fast Cuts** + + - :ref:`detect-adaptive ` + - :ref:`detect-content ` + - :ref:`detect-hash ` + - :ref:`detect-hist ` + + - **Other** + + - :ref:`detect-threshold ` + + - :ref:`Commands ` + + - **Splitting & Images** + + - :ref:`split-video ` + - :ref:`save-images ` + + - **Scene Lists & Exports** + + - :ref:`list-scenes ` + - :ref:`save-html ` + - :ref:`save-edl ` + - :ref:`save-fcp ` + - :ref:`save-otio ` + - :ref:`save-chapters ` + - :ref:`save-qp ` + - :ref:`save-keyframes ` + + - **Input & Timing** + + - :ref:`time ` + - :ref:`load-scenes ` - :doc:`cli/config_file` - :doc:`cli/backends` diff --git a/docs/conf.py b/docs/conf.py index 98b10750..9a3f91a2 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,40 +1,37 @@ # # Configuration file for the Sphinx documentation builder. # -# This file does only contain a selection of the most common options. For a -# full list see the documentation: -# http://www.sphinx-doc.org/en/master/config +# Only the html and singlehtml builders are used. # -- Path setup -------------------------------------------------------------- -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# import os import sys +from pathlib import Path sys.path.insert(0, os.path.abspath("..")) sys.path.insert(0, os.path.abspath("_ext")) +from doc_versions import load_doc_versions + from scenedetect import __version__ as scenedetect_version +_REPO_DIR = Path(__file__).resolve().parent.parent +_psd_latest_version, _psd_doc_versions = load_doc_versions( + _REPO_DIR, fallback_version=scenedetect_version.split("-dev")[0] +) + # -- Project information ----------------------------------------------------- project = "PySceneDetect" copyright = "2014, Brandon Castellano" author = "Brandon Castellano" -# The short X.Y version version = scenedetect_version -# The full version, including alpha/beta/rc tags release = scenedetect_version # -- General configuration --------------------------------------------------- -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. extensions = [ "sphinx.ext.napoleon", "sphinx.ext.autodoc", @@ -53,141 +50,59 @@ # instead of `AdaptiveDetector.process_frame()`) so they fit in the sidebar. toc_object_entries_show_parents = "hide" -# Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# -# source_suffix = ['.rst', '.md'] +# Treat bare single-backtick text (`scenedetect`, `ffmpeg`, parameter names in docstrings) +# as inline code literals instead of docutils' default italic title-reference role. +default_role = "literal" + source_suffix = ".rst" -# The root toctree document. root_doc = "index" -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. language = "en" -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This pattern also affects html_static_path and html_extra_path . exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] -# The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # -- Options for HTML output ------------------------------------------------- -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] html_css_files = ["pyscenedetect.css"] html_favicon = "_static/favicon.ico" -# Custom sidebar templates, must be a dictionary that maps document names -# to template names. -# -# The default sidebars (for documents that don't match any pattern) are -# defined by theme itself. Builtin themes are using these templates by -# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', -# 'searchbox.html']``. -# -# html_sidebars = {} -# # The section tree is long, so the search box goes above it. html_sidebars = {"**": ["about.html", "searchbox.html", "navigation.html"]} -# -- Options for HTMLHelp output --------------------------------------------- - -# Output file base name for HTML help builder. -htmlhelp_basename = "PySceneDetectdoc" - -# -- Options for LaTeX output ------------------------------------------------ - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - (root_doc, "PySceneDetect.tex", "PySceneDetect Documentation", "Brandon Castellano", "manual"), -] - -# -- Options for manual page output ------------------------------------------ - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [(root_doc, "pyscenedetect", "PySceneDetect Documentation", [author], 1)] - -# -- Options for Texinfo output ---------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "PySceneDetect", - "PySceneDetect Documentation", - author, - "PySceneDetect", - "Python API and `scenedetect` command reference.", - "Miscellaneous", - ), -] - # -- Theme ------------------------------------------------- -# TODO: Consider switching to sphinx_material. - html_theme = "alabaster" html_theme_options = { - "sidebar_width": "235px", - "description": f"Version: [{release}]", + "page_width": "1080px", + "sidebar_width": "255px", "show_relbar_bottom": True, - "show_relbar_top": False, - "github_user": "Breakthrough", - "github_repo": "PySceneDetect", - "github_type": "star", - "tip_bg": "#f0f6fa", - "tip_border": "#c2dcf2", - "hint_bg": "#f0faf0", - "hint_border": "#d3ebdc", - "warn_bg": "#f5ebd0", - "warn_border": "#f2caa2", - "attention_bg": "#f5dcdc", - "attention_border": "#ffaaaa", - "logo": "pyscenedetect_logo.png", - "logo_name": False, + "font_family": '"Noto Sans", "Segoe UI", system-ui, -apple-system, sans-serif', + "head_font_family": '"Noto Sans", "Segoe UI", system-ui, -apple-system, sans-serif', + "code_font_family": ( + '"JetBrains Mono", "Cascadia Code", "Cascadia Mono", "Consolas", ui-monospace, monospace' + ), +} + +html_context = { + "psd_doc_versions": _psd_doc_versions, + "psd_latest_version": _psd_latest_version, } -# Options for docs/_ext/section_sidebar.py: toctree `:name:` in index.rst -> (switch label, -# landing page, depth for other pages in the section, depth for the current page). The -# Examples page spans both halves, so it is its own one-page section drawn as a smaller link. +# Options for docs/_ext/section_sidebar.py: toctree `:name:` in index.rst -> (show_on_root, +# depth for other pages in the section, depth for the current page). The Examples page spans +# both halves, so it is its own one-page section showing only its on-page headings. section_sidebar_sections = { - "clitoc": ("CLI", "cli", 2, 3), - "apitoc": ("Python API", "api", 2, 4), - # No label: the pages of this section are drawn as a row of smaller links. - "reftoc": (None, None, 2, 2), + "clitoc": (True, 2, 3), + "apitoc": (True, 2, 4), + # Standalone page: omitted from the root sidebar, shows only the current page's headings. + "reftoc": (False, 2, 2), } # The index page shows every labelled section; keep the API tree to page titles there (the # CLI tree keeps its default depth of 2, which is only 12 entries). diff --git a/docs/examples.rst b/docs/examples.rst index fd8f659c..536da624 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -122,7 +122,8 @@ Python: Set a Minimum Scene Length -------------------------- -Cuts closer together than this are ignored. On the command line +Cuts closer than this length are suppressed or merged into adjacent scenes (depending on the +detector and ``filter_mode``). On the command line :option:`-m/--min-scene-len ` applies to every detector and defaults to ``0.6s``; in Python each detector takes ``min_scene_len`` and defaults to ``15`` frames. @@ -144,7 +145,7 @@ Analyze Only Part of the Video ------------------------------ Skip the first 10 seconds and stop after one minute. Times can be given as frames (``100``), -seconds (``10s``) or timecodes (``00:01:00``). +seconds (``10s``), or timecodes (``00:01:00``). Command line: @@ -163,8 +164,7 @@ Python: Save Per-Frame Statistics ------------------------- -Write the metric each detector computes for every frame to a CSV file, to help choose a -threshold. +Write each detector's per-frame metrics to a CSV stats file to help choose a threshold. Command line: diff --git a/docs/generate_cli_docs.py b/docs/generate_cli_docs.py index 6e1e99e1..ac6578fd 100644 --- a/docs/generate_cli_docs.py +++ b/docs/generate_cli_docs.py @@ -65,10 +65,6 @@ INDENT = " " * 4 -PAGE_SEP = "*" * 72 -TITLE_SEP = "=" * 72 -HEADING_SEP = "-" * 72 - GENERATED_NOTE = ".. NOTE: This file is auto-generated by docs/generate_cli_docs.py and should not be modified.\n" OPTION_HELP_OVERRIDES = { @@ -356,8 +352,7 @@ class Counterpart: } CLI_ONLY = "*CLI only*" -NO_API = "*no Python API equivalent*" -API_ONLY = "*Python API only*" +NO_API = "*none (CLI only)*" # Group that `check_concordance` adds inferred rows to, and the warning it prints for each. INFERRED_GROUP = "No row" @@ -491,15 +486,6 @@ def format_api(entry: Counterpart) -> str: return "" if entry.inferred else CLI_ONLY -def format_cli(entry: Counterpart, options: dict[str, click.Parameter]) -> str: - if entry.command: - return f":ref:`{entry.command} `" - if entry.option: - display, target = option_flags(options[entry.option]) - return f":option:`{display} <{target}>`" - return entry.cli or API_ONLY - - def table_row(first: str, *rest: str) -> str: """One `list-table` row; empty cells get no trailing whitespace.""" return f" * - {first}\n" + "".join(f" - {cell}".rstrip() + "\n" for cell in rest) @@ -528,7 +514,9 @@ def generate_global_option_table(options: dict[str, click.Parameter]) -> StrGene for name in options: entry = counterpart_for(option=name) assert entry is not None - yield table_row(format_cli(entry, options), format_config(entry.config), format_api(entry)) + display, target = option_flags(options[name]) + cli = f":option:`{display} <{target}>`" + yield table_row(cli, format_config(entry.config), format_api(entry)) yield "\n" @@ -616,19 +604,20 @@ def add_link(_match: re.Match, command: str = command) -> str: return s -def generate_title(s: str, level: int = 0, len: int = 72) -> StrGenerator: +def generate_title(s: str, level: int = 0) -> StrGenerator: yield "\n" if level == 0: - yield TITLE_LEVELS[level] * len + "\n" + yield TITLE_LEVELS[level] * 72 + "\n" yield s + "\n" - yield TITLE_LEVELS[level] * len + "\n\n" + yield TITLE_LEVELS[level] * 72 + "\n\n" -@dataclass -class ReplaceWithReference: - range: tuple[int, int] - ref: str - ref_type: str +def split_commands(commands: list[str]) -> tuple[list[str], list[str]]: + """Split the commands into the `detect-*` commands and the others. Only the second list + leaves out the info commands.""" + detectors = [c for c in commands if c.startswith("detect-")] + others = [c for c in commands if not c.startswith("detect-") and c not in INFO_COMMANDS] + return detectors, others def transform_backquotes(s: str) -> str: @@ -636,7 +625,7 @@ def transform_backquotes(s: str) -> str: def add_backquotes(match: re.Match) -> str: - return f"``{match.string[match.start() : match.end()]}``" + return f"``{match.group(0)}``" def add_backquotes_with_refs(refs: set[str]) -> ty.Callable[[str], str]: @@ -644,13 +633,10 @@ def add_backquotes_with_refs(refs: set[str]) -> ty.Callable[[str], str]: references to any found options.""" def _add_backquotes(s: re.Match) -> str: - to_add: str = s.string[s.start() : s.end()] - flag = re.search(r"-+[\w-]+[^\.\=\s\/]*", to_add) - if flag is not None and flag.string[flag.start() : flag.end()] in refs: + flag = re.search(r"-+[\w-]+[^\.\=\s\/]*", s.group(0)) + if flag is not None and flag.group(0) in refs: # add cross reference - cross_ref = flag.string[flag.start() : flag.end()] - option = s.string[s.start() : s.end()] - return f":option:`{option} <{cross_ref}>`" + return f":option:`{s.group(0)} <{flag.group(0)}>`" else: return add_backquotes(s) @@ -798,41 +784,23 @@ def generate_command_help( def generate_subcommands(ctx: click.Context, commands: list[str]) -> StrGenerator: - processed = set() - for info_command in INFO_COMMANDS: assert info_command in commands - processed.add(info_command) + detectors, output_commands = split_commands(commands) yield "\n.. _cli-detectors:\n" yield from generate_title("Detectors", 1) - detectors = [command for command in commands if command.startswith("detect-")] for detector in detectors: yield from generate_command_help(ctx, ctx.command.get_command(ctx, detector), ctx.info_name) - processed.add(detector) yield "\n.. _cli-commands:\n" yield from generate_title("Commands", 1) - output_commands = [ - command - for command in commands - if (not command.startswith("detect-") and command not in INFO_COMMANDS) - ] for command in output_commands: yield from generate_command_help(ctx, ctx.command.get_command(ctx, command), ctx.info_name) - processed.add(command) yield INFO_COMMAND_OVERRIDE - assert set(commands) == processed - - -def create_help() -> tuple[str, list[str]]: - ctx = click.Context(scenedetect, info_name=scenedetect.name) - commands: list[str] = ctx.command.list_commands(ctx) - commands = list( - filter(lambda command: not ctx.command.get_command(ctx, command).hidden, commands) - ) +def create_help(ctx: click.Context, commands: list[str]) -> str: # ctx.to_info_dict lacks metavar so we have to use the context directly. actions = [ generate_title("``scenedetect`` Command", level=0), @@ -842,26 +810,75 @@ def create_help() -> tuple[str, list[str]]: lines = [] for action in actions: lines.extend(action) - return "".join(lines), commands + return "".join(lines) + + +CLI_INDEX_DETECTOR_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("Fast Cuts", ("detect-adaptive", "detect-content", "detect-hash", "detect-hist")), + ("Other", ("detect-threshold",)), +) + +CLI_INDEX_COMMAND_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("Splitting & Images", ("split-video", "save-images")), + ( + "Scene Lists & Exports", + ( + "list-scenes", + "save-html", + "save-edl", + "save-fcp", + "save-otio", + "save-chapters", + "save-qp", + "save-keyframes", + ), + ), + ("Input & Timing", ("time", "load-scenes")), +) + + +def _format_cli_index_groups( + available: list[str], + groups: tuple[tuple[str, tuple[str, ...]], ...], +) -> str: + """Format a grouped, logically ordered nested RST bullet list of CLI command refs.""" + available_set = set(available) + grouped: list[tuple[str, list[str]]] = [] + placed: set[str] = set() + for label, members in groups: + present = [c for c in members if c in available_set] + if present: + grouped.append((label, present)) + placed.update(present) + unplaced = [c for c in available if c not in placed] + if unplaced: + if grouped and grouped[-1][0] == "Other": + grouped[-1][1].extend(unplaced) + else: + grouped.append(("Other", unplaced)) + + lines: list[str] = [] + for label, members in grouped: + lines.append(f"\n{INDENT}- **{label}**\n\n") + for cmd in members: + lines.append(f"{INDENT} - :ref:`{cmd} `\n") + return "".join(lines) def generate_cli_index(commands: list[str]) -> str: """Nested link list of the CLI reference, included by the index page.""" - detectors = [c for c in commands if c.startswith("detect-")] - others = [c for c in commands if not c.startswith("detect-") and c not in INFO_COMMANDS] + detectors, others = split_commands(commands) return "".join( [ GENERATED_NOTE + "\n", - "- :doc:`scenedetect Command `\n\n", + "- :ref:`scenedetect ` Command\n\n", " - :ref:`Usage `\n", " - :ref:`Options `\n", - " - :ref:`Detectors `: " - + ", ".join(f":ref:`{c} `" for c in detectors) - + "\n", - " - :ref:`Commands `: " - + ", ".join(f":ref:`{c} `" for c in others) - + "\n\n", - "- :doc:`cli/config_file`\n", + " - :ref:`Detectors `\n", + _format_cli_index_groups(detectors, CLI_INDEX_DETECTOR_GROUPS), + "\n - :ref:`Commands `\n", + _format_cli_index_groups(others, CLI_INDEX_COMMAND_GROUPS), + "\n- :doc:`cli/config_file`\n", "- :doc:`cli/backends`\n", ] ) @@ -904,10 +921,10 @@ def generate_detector_options(ctx: click.Context, command_name: str) -> str: for opt in command.params: if not isinstance(opt, click.Option): continue - long = next((o for o in opt.opts if o.startswith("--")), None) - if long is None: + key = option_key(opt) + if key is None: raise SystemExit(f"{where}: option {opt.opts} has no long name") - key = long[2:] + long = f"--{key}" same_name = key.replace("-", "_") param = spec.renames.get(long, same_name) if param not in params: @@ -993,8 +1010,20 @@ def generate_detector_options(ctx: click.Context, command_name: str) -> str: ) +def write_text(path: str, text: str): + """Write an ASCII output file with LF line endings. Leave the file alone if it already has + the same text apart from line endings, so that a CRLF checkout stays unchanged.""" + assert text.isascii(), path + if os.path.exists(path): + with open(path, "rb") as f: + if f.read().replace(b"\r\n", b"\n") == text.encode(): + return + with open(path, "wb") as f: + f.write(text.encode()) + + def write_detector_options(ctx: click.Context, commands: list[str]): - detectors = [c for c in commands if c.startswith("detect-")] + detectors, _ = split_commands(commands) if sorted(detectors) != sorted(DETECTOR_OPTIONS): raise SystemExit( f"generate_cli_docs.py: DETECTOR_OPTIONS {sorted(DETECTOR_OPTIONS)} does not match " @@ -1002,10 +1031,10 @@ def write_detector_options(ctx: click.Context, commands: list[str]): ) os.makedirs(DETECTOR_OPTIONS_DIR, exist_ok=True) for command in detectors: - text = generate_detector_options(ctx, command) - assert text.isascii(), command - with open(os.path.join(DETECTOR_OPTIONS_DIR, f"{command}.inc"), "wb") as f: - f.write(text.encode()) + write_text( + os.path.join(DETECTOR_OPTIONS_DIR, f"{command}.inc"), + generate_detector_options(ctx, command), + ) @dataclass @@ -1123,7 +1152,7 @@ def config_section_pointer(section: str) -> str: """One sentence linking a config section to the command or backend it configures.""" if section == "global": return ( - "Options of the :doc:`scenedetect ` command; detectors and " + "Options of the :ref:`scenedetect ` command; detectors and " "commands inherit ``min-scene-len`` and ``output`` from here." ) entry = counterpart_for(command=section) @@ -1176,9 +1205,7 @@ def write_config_sections( text += "".join( generate_config_section(ctx, sections[s]) for s in config_section_order(commands) ) - assert text.isascii() - with open(CONFIG_SECTIONS_PATH, "wb") as f: - f.write(text.encode()) + write_text(CONFIG_SECTIONS_PATH, text) def main(): @@ -1190,16 +1217,12 @@ def main(): check_concordance(visible, options) template = parse_template(TEMPLATE_PATH) check_template(template) - help, commands = create_help() + help = create_help(ctx, visible) check_reverse_links() - with open(CLI_INDEX_PATH, "wb") as f: - f.write(generate_cli_index(commands).encode()) - write_detector_options(ctx, commands) - write_config_sections(ctx, commands, template) - help = patch_help(help, commands) - help = GENERATED_NOTE + help - with open("docs/cli.rst", "wb") as f: - f.write(help.encode()) + write_text(CLI_INDEX_PATH, generate_cli_index(visible)) + write_detector_options(ctx, visible) + write_config_sections(ctx, visible, template) + write_text("docs/cli.rst", GENERATED_NOTE + patch_help(help, visible)) if __name__ == "__main__": diff --git a/docs/index.rst b/docs/index.rst index 307be028..1bf43dfb 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -2,7 +2,7 @@ Copyright (C) 2014 Brandon Castellano. All rights reserved. ####################################################################### -PySceneDetect Documentation +PySceneDetect Reference Manual ####################################################################### PySceneDetect finds scene changes in video (fast cuts and fades) and can split the video, save @@ -36,18 +36,17 @@ The same from Python: scenes = detect("video.mp4", AdaptiveDetector()) split_video_ffmpeg("video.mp4", scenes) -``scenes`` is a list of ``(start, end)`` timecode pairs. More :doc:`examples`, each done both -ways, cover images, CSV output, detector tuning and more; see :ref:`SceneManager -` for advanced workflows. +``scenes`` is a list of ``(start, end)`` timecode pairs. See :doc:`examples` for side-by-side CLI +and Python examples (saving images, CSV output, tuning detectors, and more), or +:ref:`SceneManager ` for advanced workflows. ======================================================================= Reference ======================================================================= -Most features exist on both sides. The :doc:`examples` page shows each task done both ways, -and every page links to its counterpart on the other side: each command to the function or -class that does the same, and each detector to a table of its options, config file keys and -constructor parameters. +Most features work in both the CLI and the Python API. The :doc:`examples` page shows each task +both ways, and each reference page links to its counterpart across CLI commands, config file keys, +and Python functions or classes. .. The toctrees are hidden so that the singlehtml build does not inline every document into the two columns; the sidebar extension reads them by their :name:. @@ -65,12 +64,41 @@ constructor parameters. .. rubric:: Python API - :doc:`api` - - :doc:`api/detectors`: :class:`~scenedetect.detectors.adaptive_detector.AdaptiveDetector`, - :class:`~scenedetect.detectors.content_detector.ContentDetector`, - :class:`~scenedetect.detectors.hash_detector.HashDetector`, - :class:`~scenedetect.detectors.histogram_detector.HistogramDetector`, - :class:`~scenedetect.detectors.threshold_detector.ThresholdDetector` + + - :func:`~scenedetect.detect` + - :func:`~scenedetect.open_video` + + - :doc:`api/detectors` + + - **Fast Cuts** + + - :class:`~scenedetect.detectors.adaptive_detector.AdaptiveDetector` + - :class:`~scenedetect.detectors.content_detector.ContentDetector` + - :class:`~scenedetect.detectors.hash_detector.HashDetector` + - :class:`~scenedetect.detectors.histogram_detector.HistogramDetector` + + - **Other** + + - :class:`~scenedetect.detectors.threshold_detector.ThresholdDetector` + - :doc:`api/output` + + - **Splitting & Images** + + - :func:`~scenedetect.output.split_video_ffmpeg` + - :func:`~scenedetect.output.split_video_mkvmerge` + - :func:`~scenedetect.output.save_images` + + - **Scene Lists & Exports** + + - :func:`~scenedetect.output.write_scene_list` + - :func:`~scenedetect.output.write_scene_list_html` + - :func:`~scenedetect.output.write_scene_list_edl` + - :func:`~scenedetect.output.write_scene_list_fcpx` + - :func:`~scenedetect.output.write_scene_list_fcp7` + - :func:`~scenedetect.output.write_scene_list_otio` + - :func:`~scenedetect.output.write_scene_list_ffmetadata` + - :doc:`api/backends` - :doc:`api/common` - :doc:`api/scene_manager` @@ -113,9 +141,9 @@ constructor parameters. examples -Found a problem in the docs? Raise an issue on +Found a problem in the docs? Open an issue on `the PySceneDetect issue tracker `_. -Development happens on Github at +Development happens on GitHub at `github.com/Breakthrough/PySceneDetect `_. ======================================================================= diff --git a/pyproject.toml b/pyproject.toml index 29246a1c..326d463f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -67,7 +67,6 @@ dev = [ "pytest-rerunfailures", ] docs = ["Sphinx==7.0.1", "sphinx-copybutton==0.5.2"] -website = ["mkdocs==1.5.2", "jinja2>=3.1.6"] [project.urls] Homepage = "https://www.scenedetect.com" diff --git a/scenedetect.cfg b/scenedetect.cfg index 00f3dc87..58d2b3cc 100644 --- a/scenedetect.cfg +++ b/scenedetect.cfg @@ -8,9 +8,9 @@ # Windows: C:/Users/%USERNAME%/AppData/Local/PySceneDetect/scenedetect.cfg # # Linux: ~/.config/PySceneDetect/scenedetect.cfg -# $XDG_CONFIG_HOME/scenedetect.cfg +# $XDG_CONFIG_HOME/PySceneDetect/scenedetect.cfg # -# Mac: ~/Library/Preferences/PySceneDetect/scenedetect.cfg +# macOS: ~/Library/Application Support/PySceneDetect/scenedetect.cfg # # Run `scenedetect --help` to see the exact path on your system which will be # used (it will be listed under the help text for the -c/--config option). diff --git a/scripts/generate_assets.py b/scripts/generate_assets.py index 7cac1df3..edbec0c8 100644 --- a/scripts/generate_assets.py +++ b/scripts/generate_assets.py @@ -41,6 +41,7 @@ class LogoOutput(NamedTuple): width: int height: int source: Path + darkmode: bool = False # Colors matching the SVG design @@ -104,11 +105,22 @@ class LogoOutput(NamedTuple): REPO_DIR / "docs" / "_static" / "pyscenedetect_logo_small.png", 300, 141, LOGO_BG_SVG ), LogoOutput( - REPO_DIR / "website" / "pages" / "img" / "pyscenedetect_logo.png", 640, 300, LOGO_BG_SVG + REPO_DIR / "docs" / "_static" / "pyscenedetect_logo_small_darkmode.png", + 462, + 217, + LOGO_SVG, + darkmode=True, ), LogoOutput( REPO_DIR / "website" / "pages" / "img" / "pyscenedetect_logo_small.png", 462, 217, LOGO_SVG ), + LogoOutput( + REPO_DIR / "website" / "pages" / "img" / "pyscenedetect_logo_small_darkmode.png", + 462, + 217, + LOGO_SVG, + darkmode=True, + ), ] SVG_FOR_SIZE: dict[int, Path] = { @@ -184,13 +196,24 @@ def render_svg(inkscape: str, svg: Path, output: Path, width: int, height: int): ) -def render_logos(inkscape: str): +def render_logos(inkscape: str, work_dir: Path): """Render the logo SVG to all required PNG outputs.""" print("Rendering logo PNGs...") + dark_svg: Path | None = None for entry in LOGO_OUTPUTS: rel_path = entry.path.relative_to(REPO_DIR) - print(f" {rel_path} ({entry.width}x{entry.height}) [source: {entry.source.name}]...") - render_svg(inkscape, entry.source, entry.path, entry.width, entry.height) + source = entry.source + if entry.darkmode: + if dark_svg is None: + dark_svg = work_dir / f"{source.stem}_darkmode.svg" + dark_svg.write_text( + source.read_text(encoding="utf-8").replace("#2a3545", "#e0e8f0"), + encoding="utf-8", + ) + source = dark_svg + mode = " (darkmode)" if entry.darkmode else "" + print(f" {rel_path} ({entry.width}x{entry.height}) [source: {entry.source.name}{mode}]...") + render_svg(inkscape, source, entry.path, entry.width, entry.height) print(f" Done ({len(LOGO_OUTPUTS)} files).") @@ -394,7 +417,7 @@ def main(): for dest in FAVICON_OUTPUTS: shutil.copy2(ICO_PATH, dest) print(f" {dest.relative_to(REPO_DIR)}") - render_logos(inkscape) + render_logos(inkscape, Path(work)) print("Rendering installer branding (static assets)...") render_installer_static(inkscape, Path(work)) print("Rendering installer JPGs...") diff --git a/website/build.py b/website/build.py new file mode 100644 index 00000000..d07774f0 --- /dev/null +++ b/website/build.py @@ -0,0 +1,1091 @@ +# +# PySceneDetect: Python-Based Video Scene Detector +# ------------------------------------------------------------------- +# [ Site: https://scenedetect.com ] +# [ Docs: https://scenedetect.com/docs/ ] +# [ Github: https://github.com/Breakthrough/PySceneDetect/ ] +# +# Copyright (C) 2026 Brandon Castellano . +# PySceneDetect is licensed under the BSD 3-Clause License; see the +# included LICENSE file, or visit one of the above pages for details. +# +"""Static site builder, link verifier, and preview server for scenedetect.com.""" + +from __future__ import annotations + +import argparse +import html +import html.parser +import http.server +import json +import posixpath +import re +import shutil +import struct +import sys +import urllib.parse +from dataclasses import dataclass, field +from datetime import datetime +from pathlib import Path +from typing import Any + +import jinja2 +import markdown +from markupsafe import Markup +from pygments import highlight +from pygments.formatters import HtmlFormatter +from pygments.lexers import get_lexer_by_name + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "docs" / "_ext")) + +from doc_versions import load_doc_versions # type: ignore[import-not-found] + +WEBSITE_DIR = Path(__file__).resolve().parent +REPO_DIR = WEBSITE_DIR.parent + +SITE_URL = "https://www.scenedetect.com" +REPO_URL = "https://github.com/Breakthrough/PySceneDetect" +PYPI_URL = "https://pypi.org/project/scenedetect/" +DEFAULT_RELEASE_DATE = "November 8, 2026" +DEFAULT_DESCRIPTION = ( + "Fast, frame-accurate video scene detection and splitting tool in Python " + "with a command-line interface and Python API." +) + +PAGES_DIR = WEBSITE_DIR / "pages" +IMG_SRC_DIR = PAGES_DIR / "img" +THEME_DIR = WEBSITE_DIR / "theme" +BUILD_DIR = WEBSITE_DIR / "build" + + +@dataclass(frozen=True) +class PageSpec: + """One page of the site. + + The sidebar shows `title`. The top bar shows `nav_label`, or `title` if `nav_label` is empty. + """ + + slug: str + title: str + nav_label: str = "" + is_primary: bool = False + description: str = DEFAULT_DESCRIPTION + + @property + def label(self) -> str: + return self.nav_label or self.title + + @property + def is_home(self) -> bool: + return self.slug == "" + + @property + def src_name(self) -> str: + return f"{self.slug or 'index'}.md" + + @property + def url_path(self) -> str: + return "/" if self.is_home else f"/{self.slug}/" + + @property + def out_rel_path(self) -> Path: + return Path("index.html") if self.is_home else Path(self.slug) / "index.html" + + +NAV_GROUPS: list[tuple[str, list[PageSpec]]] = [ + ( + "PySceneDetect", + [ + PageSpec( + "", + "Home", + is_primary=True, + description=DEFAULT_DESCRIPTION, + ), + PageSpec( + "features", + "Features", + is_primary=True, + description=( + "Explore PySceneDetect features: five built-in scene detectors, " + "video splitting, still-frame previews, and timeline export formats." + ), + ), + PageSpec( + "download", + "Download", + is_primary=True, + description=( + "Install PySceneDetect via pip, uv, pipx, Windows 64-bit MSI/ZIP builds, " + "or the official Docker container image." + ), + ), + PageSpec( + "changelog", + "Changelog", + description=( + "Release history, new features, bug fixes, and upgrade notes for PySceneDetect." + ), + ), + ], + ), + ( + "Guides", + [ + PageSpec( + "docs", + "Documentation Versions", + description=( + "Browse stable, development, and legacy PySceneDetect CLI and Python API " + "reference manuals." + ), + ), + PageSpec( + "cli", + "Command-Line Interface", + "CLI", + is_primary=True, + description=( + "Get started with the scenedetect command-line interface: examples, " + "detectors, video splitting, config files, and threshold tuning." + ), + ), + PageSpec( + "api", + "Python API", + is_primary=True, + description=( + "Learn how PySceneDetect's built-in detectors work and how to build " + "custom scene detectors using the Python API." + ), + ), + PageSpec( + "benchmarks", + "Benchmarks", + is_primary=True, + description=( + "Accuracy benchmarks and parameter sweeps for PySceneDetect detectors " + "on BBC Planet Earth, AutoShot, and ClipShots datasets." + ), + ), + ], + ), + ( + "Community", + [ + PageSpec( + "faq", + "Frequently Asked Questions", + "FAQ", + is_primary=True, + description=( + "Answers to common PySceneDetect questions on installation, OpenCV, " + "threshold tuning, variable frame rate video, and video splitting." + ), + ), + PageSpec( + "contributing", + "Contributing & Support", + "Contributing", + description=( + "How to report bugs, contribute code, and support PySceneDetect development." + ), + ), + PageSpec( + "projects", + "Projects & Research", + "Projects", + description=( + "Open-source projects, academic papers, and similar video shot-boundary " + "detection tools related to PySceneDetect." + ), + ), + PageSpec( + "copyright", + "License & Copyright", + "License", + description=( + "PySceneDetect BSD 3-Clause license agreement and third-party software " + "licenses." + ), + ), + ], + ), +] + +PAGES: list[PageSpec] = [page for _, group in NAV_GROUPS for page in group] +KNOWN_SLUGS: set[str] = {page.slug for page in PAGES} + +# Legacy URLs merged into consolidated pages -> (target path, link label). +LEGACY_REDIRECTS: dict[str, tuple[str, str]] = { + "gallery": ("/projects/#projects-using-pyscenedetect", "Projects & Research"), + "literature": ("/projects/#research-and-literature", "Projects & Research"), + "similar": ("/projects/#similar-programs", "Projects & Research"), + "supporting": ("/contributing/#project-support-and-credits", "Contributing & Support"), +} + +HERO_SNIPPETS: list[tuple[str, str, str, str, str]] = [ + ( + "python", + "Python API", + "AdaptiveDetector", + "python", + ( + "from scenedetect import (\n" + " detect, AdaptiveDetector, split_video_ffmpeg,\n" + ")\n\n" + "# Find scene cuts and split the video with ffmpeg\n" + 'scenes = detect("goldeneye.mp4", AdaptiveDetector())\n' + 'split_video_ffmpeg("goldeneye.mp4", scenes)\n' + ), + ), + ( + "cli", + "Command Line", + "scenedetect", + "bash", + ( + "# Split a video at each detected cut\n" + "scenedetect -i goldeneye.mp4 split-video\n\n" + "# Export a CSV scene list, still frames, and an HTML report\n" + "scenedetect -i goldeneye.mp4 list-scenes save-images save-html\n" + ), + ), + ( + "docker", + "Docker", + "ghcr.io", + "bash", + ( + "# CLI, ffmpeg, mkvmerge, PyAV, and MoviePy in one container\n" + 'docker run --rm -v "$(pwd):/files" \\\n' + " ghcr.io/breakthrough/pyscenedetect \\\n" + " -i /files/goldeneye.mp4 split-video -o /files\n" + ), + ), +] + +SPHINX_ABS_RE = re.compile(r"^/docs/(?:latest|head|\d+\.\d+(?:\.\d+)?)(?:/.*)?$") +IMG_PATH_RE = re.compile(r"^(?:\./|\.\./|/)*img/(.+)$") +ATTR_RE = re.compile( + r"""([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?""" +) +EXTERNAL_SCHEMES = ("http://", "https://", "mailto:", "tel:", "data:", "javascript:") + + +@dataclass +class TocItem: + """Right-hand 'On this page' anchor entry.""" + + id: str + title: str + children: list[TocItem] = field(default_factory=list) + + +def strip_tags(fragment: str) -> str: + """Remove HTML tags and unescape entities into collapsed plain text.""" + no_tags = re.sub(r"<[^>]+>", " ", fragment) + unescaped = html.unescape(no_tags).replace("\xa0", " ") + return re.sub(r"\s+", " ", unescaped).strip() + + +def get_image_dimensions(img_path: Path) -> tuple[int, int] | None: + """Read intrinsic (width, height) in pixels for local PNG and SVG assets.""" + data = img_path.read_bytes() + suffix = img_path.suffix.lower() + + if suffix == ".png" and len(data) >= 24 and data[:8] == b"\x89PNG\r\n\x1a\n": + width, height = struct.unpack(">II", data[16:24]) + return int(width), int(height) + + if suffix == ".svg": + head_txt = data[:4096].decode("utf-8", errors="ignore") + svg_match = re.search(r"]*>", head_txt, re.IGNORECASE | re.DOTALL) + if svg_match: + svg_tag = svg_match.group(0) + w_px = _parse_svg_length(svg_tag, "width") + h_px = _parse_svg_length(svg_tag, "height") + if w_px and h_px: + return w_px, h_px + + return None + + +def _parse_svg_length(svg_tag: str, attr_name: str) -> int | None: + """Parse an SVG width/height attribute (px, pt, or unitless) to integer pixels.""" + match = re.search( + rf'\b{attr_name}\s*=\s*["\']\s*([\d.]+)\s*(px|pt|)?\s*["\']', + svg_tag, + re.IGNORECASE, + ) + if not match: + return None + val = float(match.group(1)) + if (match.group(2) or "").lower() == "pt": + val *= 96.0 / 72.0 + return max(1, round(val)) + + +def normalize_base_path(raw: str) -> str: + """Normalize an optional URL base path (e.g. 'staging/' -> '/staging', '/' -> '').""" + cleaned = raw.strip().strip("/") + return f"/{cleaned}" if cleaned else "" + + +def rewrite_internal_href(href: str, base_path: str = "") -> str: + """Normalize Markdown and relative internal links to site-root paths.""" + raw = href.strip() + if not raw or raw.startswith(("#", *EXTERNAL_SCHEMES)): + return href + + path_part, sep, frag = raw.partition("#") + suffix = f"#{frag}" if sep else "" + clean_path = path_part.split("?", 1)[0] + + if SPHINX_ABS_RE.match(clean_path): + return href + + img_match = IMG_PATH_RE.match(clean_path) + if img_match: + return f"{base_path}/img/{img_match.group(1)}{suffix}" + + if clean_path.endswith(".md"): + stem = posixpath.basename(clean_path)[:-3] + if stem == "index": + return f"{base_path}/{suffix}" + if stem in KNOWN_SLUGS: + return f"{base_path}/{stem}/{suffix}" + if stem in LEGACY_REDIRECTS: + target_path, _ = LEGACY_REDIRECTS[stem] + return f"{base_path}{target_path}" + + slug_candidate = clean_path.strip("/") + if slug_candidate in KNOWN_SLUGS: + target = f"{base_path}/" if slug_candidate == "" else f"{base_path}/{slug_candidate}/" + return f"{target}{suffix}" + if slug_candidate in LEGACY_REDIRECTS: + target_path, _ = LEGACY_REDIRECTS[slug_candidate] + return f"{base_path}{target_path}" + + return href + + +def _parse_attrs(attr_str: str) -> list[tuple[str, str | None]]: + """Parse HTML tag attributes preserving order.""" + attrs: list[tuple[str, str | None]] = [] + for match in ATTR_RE.finditer(attr_str): + name = match.group(1) + if match.group(2) is not None: + val: str | None = match.group(2) + elif match.group(3) is not None: + val = match.group(3) + elif match.group(4) is not None: + val = match.group(4) + else: + val = None + attrs.append((name, val)) + return attrs + + +def _format_attrs(attrs: list[tuple[str, str | None]]) -> str: + """Serialize HTML tag attributes cleanly.""" + parts: list[str] = [] + for name, val in attrs: + if val is None: + parts.append(name) + else: + escaped = html.escape(html.unescape(val), quote=True) + parts.append(f'{name}="{escaped}"') + return (" " + " ".join(parts)) if parts else "" + + +def postprocess_html( + rendered_html: str, + img_dims: dict[str, tuple[int, int]], + base_path: str = "", +) -> str: + """Apply accessibility, CLS, code-block, table, and link transforms.""" + + def _normalize_pre(match: re.Match[str]) -> str: + attrs = _parse_attrs(match.group(1)) + if not any(k.lower() == "tabindex" for k, _ in attrs): + attrs.append(("tabindex", "0")) + inner = re.sub(r"^(\s*)", r"\1", match.group(2), count=1) + return f"{inner}" + + out = re.sub( + r"]*)>(.*?)", _normalize_pre, rendered_html, flags=re.DOTALL | re.IGNORECASE + ) + + out = _wrap_tables_with_regions(out) + + def _rewrite_anchor(match: re.Match[str]) -> str: + attrs = _parse_attrs(match.group(1)) + new_attrs = [ + ( + k, + rewrite_internal_href(v, base_path) if k.lower() == "href" and v is not None else v, + ) + for k, v in attrs + ] + return f"" + + out = re.sub(r"]*)>", _rewrite_anchor, out, flags=re.IGNORECASE) + + def _rewrite_img(match: re.Match[str]) -> str: + attrs = _parse_attrs(match.group(1)) + attr_map = {k.lower(): v for k, v in attrs} + src = attr_map.get("src") or "" + local_img_name: str | None = None + + if src and not src.startswith(EXTERNAL_SCHEMES): + clean_src = src.split("#", 1)[0].split("?", 1)[0] + img_match = IMG_PATH_RE.match(clean_src) + if img_match: + local_img_name = img_match.group(1) + src = f"{base_path}/img/{local_img_name}" + + rebuilt = [("src", src) if k.lower() == "src" else (k, v) for k, v in attrs] + filled = {k.lower() for k, v in attrs if v} + + if local_img_name and local_img_name in img_dims: + w, h = img_dims[local_img_name] + if "width" not in filled: + rebuilt.append(("width", str(w))) + if "height" not in filled: + rebuilt.append(("height", str(h))) + + if "loading" not in filled and attr_map.get("fetchpriority") != "high": + rebuilt.append(("loading", "lazy")) + + return f"" + + return re.sub(r"]*?)\s*/?>", _rewrite_img, out, flags=re.IGNORECASE) + + +def _upgrade_table_semantics(table_html: str) -> str: + """Ensure semantics inside .""" + + def _scope_thead(match: re.Match[str]) -> str: + def _add_col_scope(th_match: re.Match[str]) -> str: + attrs = _parse_attrs(th_match.group(1)) + if not any(k.lower() == "scope" for k, _ in attrs): + attrs.insert(0, ("scope", "col")) + return f"" + + return re.sub(r"]*)>", _add_col_scope, match.group(0), flags=re.IGNORECASE) + + return re.sub( + r"]*>.*?", + _scope_thead, + table_html, + flags=re.DOTALL | re.IGNORECASE, + ) + + +def _wrap_tables_with_regions(html_text: str) -> str: + """Wrap every in an accessible scrollable .table-wrapper named by preceding heading.""" + token_re = re.compile( + r"(]*>.*?)|(]*>.*?
)", + re.DOTALL | re.IGNORECASE, + ) + last_heading = "Data table" + pieces: list[str] = [] + pos = 0 + + for match in token_re.finditer(html_text): + pieces.append(html_text[pos : match.start()]) + pos = match.end() + if match.group(1): + h_text = strip_tags(match.group(1)) + if h_text: + last_heading = h_text + pieces.append(match.group(1)) + elif match.group(2): + upgraded = _upgrade_table_semantics(match.group(2)) + label = html.escape(last_heading, quote=True) + pieces.append( + f'
{upgraded}
' + ) + + pieces.append(html_text[pos:]) + return "".join(pieces) + + +def extract_toc(html_text: str) -> list[TocItem]: + """Extract h2 and nested h3 headings from final article HTML for 'On this page'.""" + items: list[TocItem] = [] + heading_re = re.compile(r"]*)>(.*?)", re.DOTALL | re.IGNORECASE) + for match in heading_re.finditer(html_text): + level = int(match.group(1)) + attrs = dict(_parse_attrs(match.group(2))) + hid = attrs.get("id") or "" + title = strip_tags(match.group(3)) + if not hid or not title: + continue + if level == 2 or not items: + items.append(TocItem(id=hid, title=title)) + else: + items[-1].children.append(TocItem(id=hid, title=title)) + return items + + +def extract_search_entries( + spec: PageSpec, + html_text: str, + base_path: str = "", +) -> list[dict[str, str]]: + """Chunk a page's HTML by h1/h2/h3 sections for instant client-side jump search.""" + heading_re = re.compile(r"]*)>(.*?)", re.DOTALL | re.IGNORECASE) + matches = list(heading_re.finditer(html_text)) + entries: list[dict[str, str]] = [] + page_url = f"{base_path}{spec.url_path}" + + for idx, match in enumerate(matches): + level = int(match.group(1)) + attrs = dict(_parse_attrs(match.group(2))) + hid = attrs.get("id") or "" + sec_title = strip_tags(match.group(3)) or spec.title + start = match.end() + end = matches[idx + 1].start() if idx + 1 < len(matches) else len(html_text) + chunk_text = strip_tags(html_text[start:end]) + url = page_url if (level == 1 and idx == 0) or not hid else f"{page_url}#{hid}" + entries.append( + { + "title": spec.title, + "section": sec_title, + "url": url, + "text": chunk_text[:600], + } + ) + + if spec.is_home: + entries.insert( + 0, + { + "title": "Home", + "section": "Overview & Quickstart", + "url": f"{base_path}/", + "text": ( + "Fast, frame-accurate scene cut detection for video. Detect fast cuts and " + "fades. pip install scenedetect AdaptiveDetector ContentDetector HashDetector " + "HistogramDetector ThresholdDetector split-video ffmpeg mkvmerge Docker." + ), + }, + ) + + return entries + + +def render_hero_tabs() -> list[dict[str, str]]: + """Pre-highlight the 3 interactive quickstart code tabs with Pygments.""" + formatter = HtmlFormatter(nowrap=True) + tabs: list[dict[str, str]] = [] + for tab_id, label, hint, lang, code in HERO_SNIPPETS: + highlighted = highlight(code, get_lexer_by_name(lang), formatter).rstrip("\n") + tabs.append( + { + "id": tab_id, + "label": label, + "hint": hint, + "html": highlighted, + } + ) + return tabs + + +def load_release_date(pages_dir: Path, version: str) -> str: + """Parse the release date for `version` from changelog.md, falling back to default.""" + changelog_path = pages_dir / "changelog.md" + if changelog_path.is_file() and version: + pattern = re.compile( + rf"^###\s+(?:PySceneDetect\s+)?{re.escape(version)}\s*\(([^)]+)\)", + re.MULTILINE, + ) + match = pattern.search(changelog_path.read_text(encoding="utf-8")) + if match: + candidate = match.group(1).strip() + try: + datetime.strptime(candidate, "%B %d, %Y") + return candidate + except ValueError: + pass + return DEFAULT_RELEASE_DATE + + +def _validate_out_dir(out_dir: Path) -> Path: + """Resolve `out_dir` and refuse to overwrite protected repository directories.""" + resolved_out = out_dir.resolve() + protected = { + REPO_DIR.resolve(), + WEBSITE_DIR.resolve(), + PAGES_DIR.resolve(), + THEME_DIR.resolve(), + } + if resolved_out in protected or any(resolved_out in p.parents for p in protected): + raise ValueError(f"Refusing to overwrite protected directory: {resolved_out}") + return resolved_out + + +def build_site(base_path: str = "", out_dir: Path = BUILD_DIR) -> None: + """Cleanly generate out_dir from website/pages/ and website/theme/.""" + base_path = normalize_base_path(base_path) + out_dir = _validate_out_dir(out_dir) + if out_dir.exists(): + shutil.rmtree(out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + assets_out = out_dir / "assets" + assets_out.mkdir(parents=True, exist_ok=True) + shutil.copy2(THEME_DIR / "site.css", assets_out / "site.css") + shutil.copy2(THEME_DIR / "site.js", assets_out / "site.js") + + shutil.copytree(IMG_SRC_DIR, out_dir / "img") + shutil.copy2(IMG_SRC_DIR / "favicon.ico", out_dir / "favicon.ico") + + img_dims: dict[str, tuple[int, int]] = {} + for img_file in IMG_SRC_DIR.iterdir(): + if img_file.is_file(): + dims = get_image_dimensions(img_file) + if dims is not None: + img_dims[img_file.name] = dims + + latest_ver, doc_versions = load_doc_versions(REPO_DIR) + release_date = load_release_date(PAGES_DIR, latest_ver) + rel_dt = datetime.strptime(release_date, "%B %d, %Y") + + site_ctx = { + "url": SITE_URL, + "base_path": base_path, + "repo_url": REPO_URL, + "pypi_url": PYPI_URL, + "version": f"v{latest_ver}", + "release_date_short": f"{rel_dt:%b} {rel_dt.day}, {rel_dt.year}", + } + + env = jinja2.Environment( + loader=jinja2.FileSystemLoader(str(THEME_DIR)), + autoescape=jinja2.select_autoescape(["html", "xml"]), + trim_blocks=True, + lstrip_blocks=True, + ) + base_tmpl = env.get_template("base.html") + home_tmpl = env.get_template("home.html") + not_found_tmpl = env.get_template("404.html") + + md = markdown.Markdown( + extensions=[ + "fenced_code", + "codehilite", + "tables", + "toc", + "attr_list", + "admonition", + "sane_lists", + ], + extension_configs={ + "codehilite": {"guess_lang": False, "css_class": "codehilite"}, + }, + ) + + hero_tabs = render_hero_tabs() + search_index: list[dict[str, str]] = [] + + for idx, spec in enumerate(PAGES): + md.reset() + raw_md = (PAGES_DIR / spec.src_name).read_text(encoding="utf-8") + processed_html = postprocess_html(md.convert(raw_md), img_dims, base_path) + toc_items = extract_toc(processed_html) + search_index.extend(extract_search_entries(spec, processed_html, base_path)) + + prev_spec = PAGES[idx - 1] if idx > 0 else None + next_spec = PAGES[idx + 1] if idx + 1 < len(PAGES) else None + + page_ctx = { + "html_title": ( + "PySceneDetect | Video Scene Cut Detection & Analysis" + if spec.is_home + else f"{spec.title} | PySceneDetect" + ), + "description": spec.description, + "slug": spec.slug, + "canonical_path": spec.url_path, + "content": Markup(processed_html), + "toc": toc_items, + "prev_page": ( + {"title": prev_spec.title, "href": f"{base_path}{prev_spec.url_path}"} + if prev_spec + else None + ), + "next_page": ( + {"title": next_spec.title, "href": f"{base_path}{next_spec.url_path}"} + if next_spec + else None + ), + "edit_url": f"{REPO_URL}/blob/main/website/pages/{spec.src_name}", + } + + tmpl = home_tmpl if spec.is_home else base_tmpl + rendered_page = tmpl.render( + site=site_ctx, + page=page_ctx, + hero_tabs=hero_tabs, + nav_groups=NAV_GROUPS, + pages=PAGES, + ) + + out_file = out_dir / spec.out_rel_path + out_file.parent.mkdir(parents=True, exist_ok=True) + out_file.write_text(rendered_page, encoding="utf-8") + + rendered_404 = not_found_tmpl.render( + site=site_ctx, + page={ + "html_title": "Page Not Found | PySceneDetect", + "description": DEFAULT_DESCRIPTION, + "slug": None, + "canonical_path": None, + }, + nav_groups=NAV_GROUPS, + pages=PAGES, + ) + (out_dir / "404.html").write_text(rendered_404, encoding="utf-8") + + for old_slug, (target_path, target_label) in LEGACY_REDIRECTS.items(): + href = f"{base_path}{target_path}" + canonical = f"{SITE_URL}{target_path.split('#', 1)[0]}" + safe_href = html.escape(href, quote=True) + safe_canonical = html.escape(canonical, quote=True) + safe_label = html.escape(target_label) + stub = ( + "\n" + '\n' + "\n" + ' \n' + " Redirecting | PySceneDetect\n" + ' \n' + f' \n' + f' \n' + "\n" + "\n" + "

Redirecting...

\n" + f'

This page moved to {safe_label}.

\n' + "\n" + "\n" + ) + stub_file = out_dir / old_slug / "index.html" + stub_file.parent.mkdir(parents=True, exist_ok=True) + stub_file.write_text(stub, encoding="utf-8") + + (out_dir / "search_index.json").write_text( + json.dumps(search_index, ensure_ascii=True, separators=(",", ":")), + encoding="utf-8", + ) + (out_dir / "versions.json").write_text( + json.dumps( + {"latest": latest_ver, "versions": doc_versions}, + ensure_ascii=True, + separators=(",", ":"), + ), + encoding="utf-8", + ) + + sitemap_lines = [ + '', + '', + *(f" {SITE_URL}{spec.url_path}" for spec in PAGES), + "", + ] + (out_dir / "sitemap.xml").write_text("\n".join(sitemap_lines) + "\n", encoding="utf-8") + + +class _PageInspector(html.parser.HTMLParser): + """Collect element IDs, headings, links, and asset references from built HTML.""" + + def __init__(self) -> None: + super().__init__() + self.ids: set[str] = set() + self.h1_count = 0 + self.links: list[str] = [] + self.assets: list[tuple[str, str]] = [] + self.imgs_missing_alt: list[str] = [] + self.imgs_missing_dims: list[str] = [] + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + attr_dict = dict(attrs) + elem_id = attr_dict.get("id") + if elem_id: + self.ids.add(elem_id) + if tag == "h1": + self.h1_count += 1 + if tag == "a": + href = attr_dict.get("href") + if href is not None: + self.links.append(href) + elif tag == "img": + src = attr_dict.get("src") or "" + if src: + self.assets.append(("img", src)) + if "alt" not in attr_dict or attr_dict["alt"] is None: + self.imgs_missing_alt.append(src or "") + if ( + src + and not src.startswith(EXTERNAL_SCHEMES) + and (not attr_dict.get("width") or not attr_dict.get("height")) + ): + self.imgs_missing_dims.append(src) + elif tag == "link": + rel = (attr_dict.get("rel") or "").lower() + href = attr_dict.get("href") + if href and rel != "canonical": + self.assets.append(("link", href)) + elif tag == "script": + src = attr_dict.get("src") + if src: + self.assets.append(("script", src)) + + +def _strip_base_path(site_path: str, base_path: str) -> str | None: + """Strip base_path prefix from a resolved site path, or return None if missing.""" + if not base_path: + return site_path + if site_path == base_path: + return "/" + prefix = f"{base_path}/" + if site_path.startswith(prefix): + return site_path[len(base_path) :] + return None + + +def verify_build(base_path: str = "", build_dir: Path = BUILD_DIR) -> list[str]: + """Strictly validate routes, internal links, #fragment anchors, and asset paths.""" + base_path = normalize_base_path(base_path) + errors: list[str] = [] + required_files = [ + *(build_dir / spec.out_rel_path for spec in PAGES), + *(build_dir / slug / "index.html" for slug in LEGACY_REDIRECTS), + build_dir / "404.html", + build_dir / "assets" / "site.css", + build_dir / "assets" / "site.js", + build_dir / "favicon.ico", + build_dir / "search_index.json", + build_dir / "versions.json", + build_dir / "sitemap.xml", + ] + for req in required_files: + if not req.is_file(): + errors.append(f"Missing expected output file: {req}") + + html_files = sorted(build_dir.rglob("*.html")) + inspectors: dict[Path, _PageInspector] = {} + for html_file in html_files: + parser = _PageInspector() + parser.feed(html_file.read_text(encoding="utf-8")) + inspectors[html_file] = parser + rel_label = html_file.relative_to(build_dir).as_posix() + if parser.h1_count != 1: + errors.append(f"{rel_label}: expected exactly 1

, found {parser.h1_count}") + for bad_img in parser.imgs_missing_alt: + errors.append(f"{rel_label}: missing alt attribute ({bad_img})") + for bad_dim in parser.imgs_missing_dims: + errors.append(f"{rel_label}: local missing width/height ({bad_dim})") + + for html_file, parser in inspectors.items(): + rel_file = html_file.relative_to(build_dir) + rel_label = rel_file.as_posix() + parent_posix = rel_file.parent.as_posix() + base_url_dir = f"{base_path}/" if parent_posix == "." else f"{base_path}/{parent_posix}/" + + for href in parser.links: + if not href or href.startswith(EXTERNAL_SCHEMES): + continue + if href.startswith("#"): + frag = urllib.parse.unquote(href[1:]) + if frag and frag not in parser.ids: + errors.append(f"{rel_label}: broken same-page anchor '{href}'") + continue + + path_part, sep, frag = href.partition("#") + path_part = path_part.split("?", 1)[0] + site_path = _resolve_site_path(base_url_dir, path_part) + + if SPHINX_ABS_RE.match(site_path): + continue + + local_site_path = _strip_base_path(site_path, base_path) + if local_site_path is None: + errors.append( + f"{rel_label}: internal link '{href}' missing base_path '{base_path}' " + f"(resolved to '{site_path}')" + ) + continue + + target_file = _map_site_path_to_file(local_site_path, build_dir) + if target_file is None or not target_file.is_file(): + errors.append( + f"{rel_label}: broken internal link '{href}' (resolved to '{site_path}')" + ) + continue + + if sep and frag and target_file in inspectors: + decoded_frag = urllib.parse.unquote(frag) + if decoded_frag not in inspectors[target_file].ids: + target_label = target_file.relative_to(build_dir).as_posix() + errors.append( + f"{rel_label}: broken fragment '{href}' " + f"(id '{decoded_frag}' not found in {target_label})" + ) + + for tag_name, src in parser.assets: + if src.startswith(EXTERNAL_SCHEMES): + continue + clean_src = src.split("#", 1)[0].split("?", 1)[0] + site_path = _resolve_site_path(base_url_dir, clean_src) + local_site_path = _strip_base_path(site_path, base_path) + if local_site_path is None: + errors.append( + f"{rel_label}: <{tag_name}> asset '{src}' missing base_path '{base_path}' " + f"(resolved to '{site_path}')" + ) + continue + target_file = build_dir / local_site_path.lstrip("/") + if not target_file.is_file(): + errors.append( + f"{rel_label}: missing <{tag_name}> asset '{src}' (resolved to '{site_path}')" + ) + + return errors + + +def _resolve_site_path(base_url_dir: str, path_part: str) -> str: + """Resolve a root-relative or page-relative URL path into a normalized site path.""" + if path_part.startswith("/"): + norm = posixpath.normpath(path_part) + if path_part.endswith("/") and not norm.endswith("/"): + norm += "/" + return norm + + joined = posixpath.normpath(posixpath.join(base_url_dir, path_part)) + is_dir_ref = path_part in {".", "./", "..", "../"} or path_part.endswith("/") + if is_dir_ref and not joined.endswith("/"): + joined += "/" + return joined + + +def _map_site_path_to_file(site_path: str, build_dir: Path = BUILD_DIR) -> Path | None: + """Map a normalized site path (e.g. '/cli/') to an existing file path in build_dir.""" + stripped = site_path.lstrip("/") + if site_path.endswith("/"): + return (build_dir / stripped / "index.html") if stripped else (build_dir / "index.html") + candidate = build_dir / stripped + if candidate.is_dir(): + return candidate / "index.html" + return candidate + + +def serve_site(port: int, base_path: str = "", build_dir: Path = BUILD_DIR) -> None: + """Serve build_dir locally on 127.0.0.1: with custom 404.html handling.""" + base_path = normalize_base_path(base_path) + + class PreviewHandler(http.server.SimpleHTTPRequestHandler): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, directory=str(build_dir), **kwargs) + + def do_GET(self) -> None: + if base_path and self.path in {"/", base_path}: + self.send_response(302) + self.send_header("Location", f"{base_path}/") + self.end_headers() + return + if base_path: + parsed = urllib.parse.urlsplit(self.path) + local_path = _strip_base_path(parsed.path, base_path) + if local_path is None: + self.send_error(404) + return + self.path = urllib.parse.urlunsplit( + ("", "", local_path, parsed.query, parsed.fragment) + ) + super().do_GET() + + def send_error( + self, + code: int, + message: str | None = None, + explain: str | None = None, + ) -> None: + not_found_path = build_dir / "404.html" + if code == 404 and not_found_path.is_file(): + body = not_found_path.read_bytes() + self.send_response(404) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + super().send_error(code, message, explain) + + server = http.server.ThreadingHTTPServer(("127.0.0.1", port), PreviewHandler) + mount = f"{base_path}/" if base_path else "/" + print(f"Serving {build_dir} at http://127.0.0.1:{port}{mount} (Ctrl+C to stop)") + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nStopped preview server.") + finally: + server.server_close() + + +def main(argv: list[str] | None = None) -> int: + """CLI entry point for building, strictly validating, and serving scenedetect.com.""" + parser = argparse.ArgumentParser(description="Build the PySceneDetect static website.") + parser.add_argument( + "--base-path", + default="", + help="Optional URL path prefix (e.g. '/staging' for scenedetect.com/staging/).", + ) + parser.add_argument( + "--out-dir", + type=Path, + default=BUILD_DIR, + help="Output directory for generated static files (default: website/build).", + ) + parser.add_argument( + "--strict", + action="store_true", + help="Verify all expected routes, internal links, #fragment anchors, and assets.", + ) + parser.add_argument( + "--serve", + nargs="?", + const=8000, + type=int, + metavar="PORT", + help="Build and serve output locally on 127.0.0.1:PORT (default: 8000).", + ) + args = parser.parse_args(argv) + base_path = normalize_base_path(args.base_path) + out_dir = args.out_dir.resolve() + + build_site(base_path=base_path, out_dir=out_dir) + prefix_note = f" (base_path={base_path})" if base_path else "" + print(f"Built {len(PAGES)} pages + 404 + search index into {out_dir}{prefix_note}") + + if args.strict: + errors = verify_build(base_path=base_path, build_dir=out_dir) + if errors: + for err in errors: + print(f"[STRICT ERROR] {err}", file=sys.stderr) + print(f"Strict check failed with {len(errors)} error(s).", file=sys.stderr) + return 1 + print("Strict verification passed (all routes, anchors, and assets verified).") + + if args.serve is not None: + serve_site(args.serve, base_path=base_path, build_dir=out_dir) + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/website/check_layout.py b/website/check_layout.py new file mode 100644 index 00000000..fb642e2d --- /dev/null +++ b/website/check_layout.py @@ -0,0 +1,1001 @@ +# +# PySceneDetect: Python-Based Video Scene Detector +# ------------------------------------------------------------------- +# [ Site: https://scenedetect.com ] +# [ Docs: https://scenedetect.com/docs/ ] +# [ Github: https://github.com/Breakthrough/PySceneDetect/ ] +# +# Copyright (C) 2026 Brandon Castellano . +# PySceneDetect is licensed under the BSD 3-Clause License; see the +# included LICENSE file, or visit one of the above pages for details. +# +"""Zero-dependency headless Chromium layout verifier and screenshot generator.""" + +from __future__ import annotations + +import argparse +import base64 +import contextlib +import hashlib +import http.server +import json +import os +import posixpath +import shutil +import socket +import struct +import subprocess +import sys +import tempfile +import threading +import time +import urllib.parse +import urllib.request +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +WEBSITE_DIR = Path(__file__).resolve().parent +DEFAULT_BUILD_DIR = WEBSITE_DIR / "build" + +DEVICE_SCALE_FACTOR = 2.0 +SPHINX_PREFIX = "/docs/head/" + +VIEWPORTS: list[tuple[str, int, int, bool]] = [ + ("Mobile 320x568", 320, 568, True), + ("Mobile 375x812", 375, 812, True), + ("Mobile 390x844", 390, 844, True), + ("Tablet 768x1024", 768, 1024, True), + ("Desktop 1280x800", 1280, 800, False), +] + +# Screenshot devices: width, height, mobile. +DEVICES: dict[str, tuple[int, int, bool]] = { + "desktop": (1280, 800, False), + "mobile": (390, 844, True), + "mobile-320": (320, 568, True), +} + +SPHINX_SAMPLE_PAGES: tuple[str, ...] = ( + "index.html", + "cli.html", + "api.html", + "api/detectors.html", + "examples.html", +) + +AUDIT_JS_TEMPLATE = """ +(() => { + const vw = __EXPECTED_VW__; + const docScrollW = document.documentElement.scrollWidth; + const overflows = []; + if (docScrollW > vw + 1) { + for (const el of document.querySelectorAll('*')) { + const style = getComputedStyle(el); + if (style.display === 'none' || style.visibility === 'hidden') continue; + const r = el.getBoundingClientRect(); + const unclippedScroll = + (style.overflowX === 'visible' || style.overflowX === '') && + el.clientWidth > 0 && + el.scrollWidth > el.clientWidth + 1 && + el !== document.documentElement && + el !== document.body; + if ((r.width > 0 && r.right > vw + 0.5) || unclippedScroll) { + let p = el.parentElement; + let clipped = false; + while (p && p !== document.documentElement) { + const ox = getComputedStyle(p).overflowX; + if (ox === 'auto' || ox === 'scroll' || ox === 'hidden' || ox === 'clip') { + if (p.getBoundingClientRect().right <= vw + 0.5) { + clipped = true; + break; + } + } + p = p.parentElement; + } + if (!clipped) { + overflows.push({ + tag: el.tagName.toLowerCase(), + cls: (el.className && typeof el.className === 'string') ? el.className : '', + right: Math.round(r.right * 10) / 10, + width: Math.round(Math.max(r.width, el.scrollWidth) * 10) / 10, + text: (el.textContent || '').trim().slice(0, 40) + }); + } + } + } + if (overflows.length === 0) { + const cands = []; + for (const el of document.querySelectorAll('*')) { + const r = el.getBoundingClientRect(); + if (r.width > 0 && r.right > vw - 18 && el.children.length <= 2) { + cands.push({ + tag: el.tagName.toLowerCase(), + cls: (el.className && typeof el.className === 'string') ? el.className : '', + right: Math.round(r.right * 10) / 10, + width: Math.round(r.width * 10) / 10, + text: (el.textContent || '').trim().slice(0, 40) + }); + } + } + cands.sort((a, b) => b.right - a.right); + overflows.push(...cands.slice(0, 6)); + } + } + + const header = document.querySelector('.site-header, .psd-topbar'); + const isWide = header ? header.classList.contains('is-wide') : null; + const selectors = [ + '.brand-link', + '.menu-button', + '.search-trigger', + '.theme-toggle', + '.icon-link', + '.psd-brand', + '.psd-version-btn', + '.psd-theme-toggle' + ]; + const controls = []; + for (const sel of selectors) { + const el = document.querySelector(sel); + if (!el) continue; + const cs = getComputedStyle(el); + if (cs.display === 'none' || cs.visibility === 'hidden') continue; + const r = el.getBoundingClientRect(); + controls.push({ + sel, + isButton: sel !== '.brand-link' && sel !== '.psd-brand', + w: Math.round(r.width * 10) / 10, + h: Math.round(r.height * 10) / 10, + left: Math.round(r.left * 10) / 10, + right: Math.round(r.right * 10) / 10 + }); + } + + let headerOverlap = false; + for (let i = 0; i < controls.length; i++) { + for (let j = i + 1; j < controls.length; j++) { + const a = controls[i]; + const b = controls[j]; + if (Math.max(a.left, b.left) < Math.min(a.right, b.right) - 0.5) { + headerOverlap = true; + } + } + } + + return { + docScrollW, + isWide, + headerOverlap, + controls, + overflows: overflows.slice(0, 6) + }; +})() +""" + + +def find_browser(explicit: str | None = None) -> Path: + """Locate a local Chrome, Chromium, or Edge executable across Linux, macOS, and Windows.""" + candidates: list[str] = [] + if explicit: + candidates.append(explicit) + env_bin = os.environ.get("CHROME_BIN") + if env_bin: + candidates.append(env_bin) + + for binary_name in ( + "google-chrome", + "google-chrome-stable", + "chromium", + "chromium-browser", + "microsoft-edge", + "microsoft-edge-stable", + "msedge", + ): + found = shutil.which(binary_name) + if found: + candidates.append(found) + + if sys.platform == "win32": + for root_var in ("ProgramFiles", "ProgramFiles(x86)", "LocalAppData"): + root = os.environ.get(root_var) + if root: + candidates.append( + str(Path(root) / "Google" / "Chrome" / "Application" / "chrome.exe") + ) + candidates.append( + str(Path(root) / "Microsoft" / "Edge" / "Application" / "msedge.exe") + ) + elif sys.platform == "darwin": + candidates.extend( + [ + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", + "/Applications/Chromium.app/Contents/MacOS/Chromium", + ] + ) + + for cand in candidates: + path = Path(cand) + if path.is_file(): + return path + + raise FileNotFoundError( + "No Chrome, Chromium, or Edge binary found. Pass --browser PATH or set CHROME_BIN." + ) + + +class SimpleWS: + """Minimal RFC 6455 WebSocket client over stdlib socket for local CDP JSON-RPC.""" + + def __init__(self, ws_url: str) -> None: + parsed = urllib.parse.urlparse(ws_url) + host = parsed.hostname or "127.0.0.1" + port = parsed.port or 80 + path = parsed.path or "/" + if parsed.query: + path += f"?{parsed.query}" + + self.sock = socket.create_connection((host, port), timeout=20.0) + key = base64.b64encode(os.urandom(16)).decode("ascii") + req = ( + f"GET {path} HTTP/1.1\r\n" + f"Host: {host}:{port}\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + f"Sec-WebSocket-Key: {key}\r\n" + "Sec-WebSocket-Version: 13\r\n\r\n" + ) + self.sock.sendall(req.encode("ascii")) + buf = b"" + while b"\r\n\r\n" not in buf: + chunk = self.sock.recv(4096) + if not chunk: + raise RuntimeError("WebSocket handshake closed prematurely") + buf += chunk + header, self._leftover = buf.split(b"\r\n\r\n", 1) + if b"101" not in header.splitlines()[0]: + raise RuntimeError(f"WebSocket handshake failed: {header.decode('latin1')}") + expected = base64.b64encode( + hashlib.sha1((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()).digest() + ) + if expected not in header: + raise RuntimeError("Invalid Sec-WebSocket-Accept") + self._next_id = 1 + self.events: list[dict[str, Any]] = [] + + def _recv_exact(self, n: int) -> bytes: + out = bytearray() + if self._leftover: + take = min(n, len(self._leftover)) + out.extend(self._leftover[:take]) + self._leftover = self._leftover[take:] + while len(out) < n: + chunk = self.sock.recv(max(4096, n - len(out))) + if not chunk: + raise RuntimeError("WebSocket closed while reading frame") + need = n - len(out) + out.extend(chunk[:need]) + if len(chunk) > need: + self._leftover += chunk[need:] + return bytes(out) + + def send_text(self, text: str) -> None: + payload = text.encode("utf-8") + mask = os.urandom(4) + header = bytearray([0x81]) + length = len(payload) + if length < 126: + header.append(0x80 | length) + elif length < 65536: + header.append(0x80 | 126) + header.extend(struct.pack(">H", length)) + else: + header.append(0x80 | 127) + header.extend(struct.pack(">Q", length)) + header.extend(mask) + masked = bytes(b ^ mask[i & 3] for i, b in enumerate(payload)) + self.sock.sendall(bytes(header) + masked) + + def recv_frame(self) -> str: + while True: + b1, b2 = self._recv_exact(2) + opcode = b1 & 0x0F + masked = bool(b2 & 0x80) + length = b2 & 0x7F + if length == 126: + length = struct.unpack(">H", self._recv_exact(2))[0] + elif length == 127: + length = struct.unpack(">Q", self._recv_exact(8))[0] + mask_key = self._recv_exact(4) if masked else b"" + data = self._recv_exact(length) + if masked: + data = bytes(b ^ mask_key[i & 3] for i, b in enumerate(data)) + if opcode == 0x8: + raise RuntimeError("WebSocket closed by server") + if opcode == 0x9: + pong = bytearray([0x8A, 0x80 | len(data)]) + m = os.urandom(4) + pong.extend(m) + pong.extend(bytes(b ^ m[i & 3] for i, b in enumerate(data))) + self.sock.sendall(bytes(pong)) + continue + if opcode == 0x1: + return data.decode("utf-8") + + def call(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]: + msg_id = self._next_id + self._next_id += 1 + self.send_text(json.dumps({"id": msg_id, "method": method, "params": params or {}})) + while True: + raw = self.recv_frame() + msg = json.loads(raw) + if msg.get("id") == msg_id: + if "error" in msg: + raise RuntimeError(f"CDP error on {method}: {msg['error']}") + return msg.get("result", {}) + self.events.append(msg) + + def close(self) -> None: + with contextlib.suppress(OSError): + self.sock.close() + + +def _resolve_mounted_file(root_dir: Path, rel_posix: str) -> Path | None: + """Safely resolve a URL path fragment inside root_dir without directory traversal.""" + norm = posixpath.normpath("/" + rel_posix.lstrip("/")).lstrip("/") + candidate = (root_dir / norm).resolve() if norm else (root_dir / "index.html").resolve() + root_resolved = root_dir.resolve() + if candidate != root_resolved and root_resolved not in candidate.parents: + return None + if candidate.is_dir(): + index_file = candidate / "index.html" + return index_file if index_file.is_file() else None + return candidate if candidate.is_file() else None + + +def start_local_server( + build_dir: Path, + sphinx_dir: Path | None, + http_errors: list[str], +) -> tuple[http.server.ThreadingHTTPServer, int]: + """Serve build_dir at / (plus optional sphinx_dir at /docs/head/ & /docs/latest/).""" + + class MultiMountHandler(http.server.SimpleHTTPRequestHandler): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, directory=str(build_dir), **kwargs) + + def log_message(self, fmt: str, *args: Any) -> None: + pass + + def _locate_target(self, url_path: str) -> Path | None: + if sphinx_dir is not None: + for mount in ("/docs/head", "/docs/latest"): + if url_path == mount or url_path.startswith(mount + "/"): + sub = url_path[len(mount) :] + return _resolve_mounted_file(sphinx_dir, sub or "/index.html") + + return _resolve_mounted_file(build_dir, url_path) + + def do_GET(self) -> None: + url_path = urllib.parse.unquote(urllib.parse.urlsplit(self.path).path) + target = self._locate_target(url_path) + if target is None: + if url_path != "/404.html" and not url_path.endswith("/favicon.ico"): + http_errors.append(f"HTTP 404 for local request: {url_path}") + not_found = build_dir / "404.html" + if not_found.is_file(): + body = not_found.read_bytes() + self.send_response(404) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + else: + self.send_error(404) + return + + ctype = self.guess_type(str(target)) + data = target.read_bytes() + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), MultiMountHandler) + port = int(server.server_address[1]) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, port + + +def get_free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + +def eval_js(cdp: SimpleWS, expr: str) -> Any: + res = cdp.call( + "Runtime.evaluate", + {"expression": expr, "returnByValue": True, "awaitPromise": True}, + ) + if "exceptionDetails" in res: + raise RuntimeError(f"JS eval exception: {res['exceptionDetails']}") + return res.get("result", {}).get("value") + + +def navigate(cdp: SimpleWS, url: str) -> None: + cdp.events.clear() + cdp.call("Page.navigate", {"url": url}) + deadline = time.time() + 10.0 + while time.time() < deadline: + if eval_js(cdp, "document.readyState") == "complete": + break + time.sleep(0.04) + eval_js( + cdp, + "new Promise(r => requestAnimationFrame(() => " + "requestAnimationFrame(() => setTimeout(r, 35))))", + ) + + +def set_viewport( + cdp: SimpleWS, + width: int, + height: int, + mobile: bool, + scheme: str, +) -> None: + cdp.call( + "Emulation.setDeviceMetricsOverride", + { + "width": width, + "height": height, + "deviceScaleFactor": DEVICE_SCALE_FACTOR, + "mobile": mobile, + }, + ) + cdp.call( + "Emulation.setTouchEmulationEnabled", + {"enabled": True, "maxTouchPoints": 5} if mobile else {"enabled": False}, + ) + cdp.call( + "Emulation.setEmulatedMedia", + {"features": [{"name": "prefers-color-scheme", "value": scheme}]}, + ) + + +def click_point(cdp: SimpleWS, x: float, y: float) -> None: + cdp.call( + "Input.dispatchMouseEvent", + {"type": "mousePressed", "x": x, "y": y, "button": "left", "clickCount": 1}, + ) + cdp.call( + "Input.dispatchMouseEvent", + {"type": "mouseReleased", "x": x, "y": y, "button": "left", "clickCount": 1}, + ) + + +def save_screenshot(cdp: SimpleWS, out_path: Path) -> None: + data_b64 = cdp.call("Page.captureScreenshot", {"format": "png"})["data"] + out_path.write_bytes(base64.b64decode(data_b64)) + + +def discover_routes(build_dir: Path, sphinx_dir: Path | None) -> list[str]: + """Collect all built website HTML routes plus representative Sphinx routes when provided.""" + routes: list[str] = [] + for html_file in sorted(build_dir.rglob("*.html")): + if 'http-equiv="refresh"' in html_file.read_text(encoding="utf-8", errors="ignore"): + continue + rel = html_file.relative_to(build_dir).as_posix() + if rel == "index.html": + routes.append("/") + elif rel.endswith("/index.html"): + slug = rel[: -len("/index.html")] + routes.append(f"/{slug}/") + else: + routes.append(f"/{rel}") + + routes.sort(key=lambda r: (0 if r == "/" else 1, r)) + + if sphinx_dir is not None: + for sample in SPHINX_SAMPLE_PAGES: + if (sphinx_dir / sample).is_file(): + routes.append(f"{SPHINX_PREFIX}{sample}") + + return routes + + +def click_selector(cdp: SimpleWS, selector: str) -> None: + """Click the centre of the first element that matches selector.""" + pt = eval_js( + cdp, + f"(() => {{ const r = document.querySelector({json.dumps(selector)})" + ".getBoundingClientRect(); " + "return {x: r.left + r.width / 2, y: r.top + r.height / 2}; })()", + ) + click_point(cdp, pt["x"], pt["y"]) + + +def popover_state(cdp: SimpleWS, element_id: str) -> dict[str, Any]: + """Return whether the popover is open, plus its left and right bounds.""" + return eval_js( + cdp, + f"""(() => {{ + const m = document.getElementById({json.dumps(element_id)}); + const r = m.getBoundingClientRect(); + return {{ + open: m.matches(':popover-open'), + left: Math.round(r.left), + right: Math.round(r.right) + }}; + }})()""", + ) + + +class BrowserLaunchError(RuntimeError): + """Raised when the headless browser does not expose a CDP endpoint.""" + + +@contextlib.contextmanager +def launch_browser(browser_bin: Path) -> Iterator[str]: + """Start a headless browser and yield the CDP WebSocket URL of its first page.""" + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + ws_url: str | None = None + proc: subprocess.Popen[bytes] | None = None + profile_dir: Path | None = None + stderr_log = "" + + for _attempt in range(2): + cdp_port = get_free_port() + profile_dir = Path(tempfile.mkdtemp(prefix="psd-layout-cdp-")) + stderr_path = profile_dir / "browser-stderr.log" + browser_cmd = [ + str(browser_bin), + "--headless=new", + "--disable-gpu", + "--no-first-run", + "--no-default-browser-check", + "--disable-extensions", + "--disable-background-networking", + "--disable-sync", + "--disable-crash-reporter", + "--password-store=basic", + "--use-mock-keychain", + "--no-proxy-server", + "--window-size=1280,900", + f"--user-data-dir={profile_dir}", + "--remote-debugging-address=127.0.0.1", + f"--remote-debugging-port={cdp_port}", + ] + if sys.platform.startswith("linux"): + browser_cmd.extend(["--no-sandbox", "--disable-dev-shm-usage", "--disable-dbus"]) + browser_cmd.append("about:blank") + + with stderr_path.open("wb") as err_fh: + proc = subprocess.Popen(browser_cmd, stdout=subprocess.DEVNULL, stderr=err_fh) + + deadline = time.time() + 25.0 + while time.time() < deadline: + if proc.poll() is not None: + break + try: + with opener.open(f"http://127.0.0.1:{cdp_port}/json", timeout=1.0) as resp: + targets = json.loads(resp.read().decode("utf-8")) + for target in targets: + if target.get("type") == "page" and target.get("webSocketDebuggerUrl"): + ws_url = str(target["webSocketDebuggerUrl"]) + break + if ws_url: + break + except Exception: + time.sleep(0.15) + + if ws_url: + break + + proc.kill() + with contextlib.suppress(Exception): + proc.wait(timeout=5) + with contextlib.suppress(OSError): + stderr_log = stderr_path.read_text(encoding="utf-8", errors="replace")[-1500:] + shutil.rmtree(profile_dir, ignore_errors=True) + + if not ws_url or proc is None or profile_dir is None: + raise BrowserLaunchError( + "Timed out waiting for headless browser CDP endpoint.\n" + f"Browser stderr tail:\n{stderr_log}" + ) + + try: + yield ws_url + finally: + proc.kill() + with contextlib.suppress(Exception): + proc.wait(timeout=5) + shutil.rmtree(profile_dir, ignore_errors=True) + + +def _wait_for_search_hits(cdp: SimpleWS, query: str) -> dict[str, Any]: + """Type query into #search-input and poll briefly until search_index.json renders hits.""" + eval_js( + cdp, + f"""(() => {{ + const input = document.getElementById('search-input'); + input.value = {json.dumps(query)}; + input.dispatchEvent(new Event('input', {{ bubbles: true }})); + }})()""", + ) + deadline = time.time() + 2.0 + state: dict[str, Any] = {} + while time.time() < deadline: + state = eval_js( + cdp, + """(() => { + const dlg = document.getElementById('search-dialog'); + const r = dlg.getBoundingClientRect(); + const hits = [...document.querySelectorAll('.search-hit')].map( + a => a.getAttribute('href') + ); + return { + open: dlg.open, + left: Math.round(r.left), + right: Math.round(r.right), + top: Math.round(r.top), + bottom: Math.round(r.bottom), + hitCount: hits.length, + topHit: hits[0] || null + }; + })()""", + ) + if state.get("hitCount", 0) > 0: + break + time.sleep(0.05) + return state + + +def _open_mobile_menu(cdp: SimpleWS) -> None: + click_selector(cdp, ".menu-button") + time.sleep(0.1) + + +def _open_search(query: str) -> Callable[[SimpleWS], None]: + def action(cdp: SimpleWS) -> None: + eval_js(cdp, "document.querySelector('.search-trigger').click()") + _wait_for_search_hits(cdp, query) + + return action + + +def _open_version_menu(cdp: SimpleWS) -> None: + click_selector(cdp, ".psd-version-btn") + time.sleep(0.12) + + +# Each row: file name, route, device, colour scheme, optional action before the shot. +SHOTS: list[tuple[str, str, str, str, Callable[[SimpleWS], None] | None]] = [ + ("desktop-home-light.png", "/", "desktop", "light", None), + ("desktop-home-dark.png", "/", "desktop", "dark", None), + ("desktop-features-light.png", "/features/", "desktop", "light", None), + ("desktop-download-dark.png", "/download/", "desktop", "dark", None), + ("desktop-cli-light.png", "/cli/", "desktop", "light", None), + ("desktop-benchmarks-dark.png", "/benchmarks/", "desktop", "dark", None), + ("desktop-projects-light.png", "/projects/", "desktop", "light", None), + ("mobile-home-light.png", "/", "mobile", "light", None), + ("mobile-home-dark.png", "/", "mobile", "dark", None), + ("mobile-320-home-dark.png", "/", "mobile-320", "dark", None), + ("mobile-cli-dark.png", "/cli/", "mobile", "dark", None), + ("mobile-benchmarks-light.png", "/benchmarks/", "mobile", "light", None), + ("mobile-download-light.png", "/download/", "mobile", "light", None), + ("mobile-404-light.png", "/404.html", "mobile", "light", None), + ("mobile-menu-open.png", "/", "mobile", "light", _open_mobile_menu), + ("mobile-search-open.png", "/", "mobile", "dark", _open_search("save-otio")), + ("desktop-search-open.png", "/", "desktop", "dark", _open_search("AdaptiveDetector")), + ("sphinx-desktop-home-dark.png", "/docs/head/index.html", "desktop", "dark", None), + ("sphinx-desktop-cli-light.png", "/docs/head/cli.html", "desktop", "light", None), + ( + "sphinx-mobile-cli-versions-dark.png", + "/docs/head/cli.html", + "mobile", + "dark", + _open_version_menu, + ), + ("sphinx-mobile-detectors-light.png", "/docs/head/api/detectors.html", "mobile", "light", None), +] + + +def capture_curated_pack( + cdp: SimpleWS, + base_url: str, + sphinx_dir: Path | None, + shots_dir: Path, +) -> int: + """Capture the screenshot pack from SHOTS and return the number of PNG files written.""" + shots_dir.mkdir(parents=True, exist_ok=True) + count = 0 + for filename, route, device, scheme, before in SHOTS: + is_sphinx = route.startswith(SPHINX_PREFIX) + if is_sphinx and ( + sphinx_dir is None or not (sphinx_dir / route[len(SPHINX_PREFIX) :]).is_file() + ): + continue + width, height, mobile = DEVICES[device] + set_viewport(cdp, width, height, mobile, scheme) + navigate(cdp, f"{base_url}{route}") + if before is not None: + before(cdp) + save_screenshot(cdp, shots_dir / filename) + count += 1 + return count + + +def audit_page( + cdp: SimpleWS, vp_name: str, route: str, width: int, is_mobile: bool, base_url: str +) -> list[str]: + """Load one route at the current viewport and return its layout failure messages.""" + navigate(cdp, f"{base_url}{route}") + issues: list[str] = [] + + for ev in cdp.events: + if ev.get("method") == "Runtime.exceptionThrown": + issues.append(f"[JS EXCEPTION] {vp_name} {route}: {ev.get('params')}") + + info = eval_js(cdp, AUDIT_JS_TEMPLATE.replace("__EXPECTED_VW__", str(width))) + if info["docScrollW"] > width + 1: + issues.append( + f"[OVERFLOW] {vp_name} {route}: " + f"scrollWidth={info['docScrollW']} > {width}; " + f"offenders={info['overflows']}" + ) + if info["headerOverlap"]: + issues.append(f"[HEADER OVERLAP] {vp_name} {route}: controls={info['controls']}") + + if not route.startswith(SPHINX_PREFIX): + if width <= 768 and info["isWide"]: + issues.append(f"[NAVBAR] {vp_name} {route}: expected collapsed menu, got is-wide=True") + if width >= 1280 and not info["isWide"]: + issues.append( + f"[NAVBAR] {vp_name} {route}: expected inline wide nav, got is-wide=False" + ) + + for ctrl in info["controls"]: + if ctrl["left"] < -1 or ctrl["right"] > width + 1: + issues.append( + f"[CLIPPED CONTROL] {vp_name} {route}: {ctrl['sel']} bounds " + f"[{ctrl['left']}, {ctrl['right']}] outside [0, {width}]" + ) + if is_mobile and ctrl["isButton"] and (ctrl["w"] < 36 or ctrl["h"] < 36): + issues.append( + f"[TOUCH TARGET] {vp_name} {route}: {ctrl['sel']} is " + f"{ctrl['w']}x{ctrl['h']}px (< 36px)" + ) + return issues + + +def run_checks( + cdp: SimpleWS, + base_url: str, + routes: list[str], + sphinx_dir: Path | None, + screenshots_dir: Path | None, + http_errors: list[str], +) -> tuple[list[str], int]: + """Run all viewport and interactive checks. Return the failures and the viewport check count.""" + failures: list[str] = [] + total_checks = 0 + cdp.call("Page.enable") + cdp.call("Runtime.enable") + + print(f"Auditing {len(routes)} routes across {len(VIEWPORTS)} viewports...") + + for vp_name, width, height, is_mobile in VIEWPORTS: + set_viewport(cdp, width, height, is_mobile, "light") + vp_failures: list[str] = [] + for route in routes: + total_checks += 1 + vp_failures.extend(audit_page(cdp, vp_name, route, width, is_mobile, base_url)) + failures.extend(vp_failures) + print(f" {vp_name:18} -> {len(routes)} routes checked (issues: {len(vp_failures)})") + + # Interactive mobile component checks on the home page (390x844) + set_viewport(cdp, 390, 844, True, "light") + navigate(cdp, f"{base_url}/") + + tabs_ok = eval_js( + cdp, + """(() => { + const cli = document.getElementById('hero-tab-cli'); + const docker = document.getElementById('hero-tab-docker'); + const py = document.getElementById('hero-tab-python'); + if (!cli || !docker || !py) return false; + cli.click(); + const cOk = !document.getElementById('hero-panel-cli').hidden; + docker.click(); + const dOk = !document.getElementById('hero-panel-docker').hidden; + py.click(); + const noOverflow = document.documentElement.scrollWidth <= window.innerWidth + 1; + return cOk && dOk && noOverflow; + })()""", + ) + if not tabs_ok: + failures.append("[INTERACTIVE] Hero quickstart tabs failed on /") + + install_tabs_ok = eval_js( + cdp, + """(() => { + const pip = document.getElementById('install-tab-pip'); + const uv = document.getElementById('install-tab-uv'); + const pipx = document.getElementById('install-tab-pipx'); + if (!pip || !uv || !pipx) return false; + uv.click(); + const uOk = !document.getElementById('install-panel-uv').hidden + && Boolean(document.getElementById('install-panel-pip').hidden); + pipx.click(); + const pOk = !document.getElementById('install-panel-pipx').hidden + && Boolean(document.getElementById('install-panel-uv').hidden); + pip.click(); + const noOverflow = document.documentElement.scrollWidth <= window.innerWidth + 1; + return uOk && pOk && noOverflow; + })()""", + ) + if not install_tabs_ok: + failures.append("[INTERACTIVE] Install method tabs failed on /") + + theme_res = eval_js( + cdp, + """(() => { + const beforeBg = getComputedStyle(document.body).backgroundColor; + document.querySelector('.theme-toggle').click(); + const afterBg = getComputedStyle(document.body).backgroundColor; + const meta = document.querySelector('meta[name="color-scheme"]').content; + localStorage.removeItem('color-scheme'); + document.querySelector('meta[name="color-scheme"]').content = 'light dark'; + return { changed: beforeBg !== afterBg, meta }; + })()""", + ) + if not theme_res.get("changed") or theme_res.get("meta") != "dark": + failures.append(f"[INTERACTIVE] Theme toggle failed: {theme_res}") + + _open_mobile_menu(cdp) + menu_state = popover_state(cdp, "site-menu") + if not menu_state["open"] or menu_state["left"] < 0 or menu_state["right"] > 390: + failures.append(f"[INTERACTIVE] Mobile menu popover geometry invalid: {menu_state}") + click_point(cdp, 15, 500) + time.sleep(0.1) + if eval_js(cdp, "document.getElementById('site-menu').matches(':popover-open')"): + failures.append("[INTERACTIVE] Mobile menu popover did not light-dismiss on outside tap") + + eval_js(cdp, "document.querySelector('.search-trigger').click()") + search_state = _wait_for_search_hits(cdp, "save-otio") + top_hit = search_state.get("topHit") or "" + if ( + not search_state.get("open") + or search_state.get("hitCount", 0) == 0 + or not top_hit.startswith("/") + or search_state.get("left", -1) < 0 + or search_state.get("right", 999) > 390 + ): + failures.append(f"[INTERACTIVE] Mobile search modal check failed: {search_state}") + backdrop_y = min(820, int(search_state.get("bottom", 400)) + 40) + click_point(cdp, 195, backdrop_y) + time.sleep(0.1) + if eval_js(cdp, "document.getElementById('search-dialog').open"): + failures.append("[INTERACTIVE] Mobile search modal did not dismiss on backdrop tap") + + if sphinx_dir is not None and (sphinx_dir / "cli.html").is_file(): + navigate(cdp, f"{base_url}{SPHINX_PREFIX}cli.html") + _open_version_menu(cdp) + vmenu = popover_state(cdp, "psd-version-menu") + if not vmenu["open"] or vmenu["left"] < 0 or vmenu["right"] > 390: + failures.append(f"[INTERACTIVE] Sphinx version switcher failed: {vmenu}") + + for err in http_errors: + failures.append(f"[LOCAL ASSET] {err}") + + if screenshots_dir is not None: + print(f"Capturing screenshot pack into {screenshots_dir} ...") + shot_count = capture_curated_pack(cdp, base_url, sphinx_dir, screenshots_dir) + print(f"Wrote {shot_count} screenshots to {screenshots_dir}") + + return failures, total_checks + + +def run_audit( + build_dir: Path, + sphinx_dir: Path | None, + screenshots_dir: Path | None, + browser_bin: Path, +) -> int: + """Run headless responsive layout audit and optional screenshot generation.""" + if not build_dir.is_dir(): + print(f"[ERROR] Build directory does not exist: {build_dir}", file=sys.stderr) + return 1 + if sphinx_dir is not None and not sphinx_dir.is_dir(): + print(f"[ERROR] Sphinx directory does not exist: {sphinx_dir}", file=sys.stderr) + return 1 + + routes = discover_routes(build_dir, sphinx_dir) + if not routes: + print(f"[ERROR] No HTML files found in {build_dir}", file=sys.stderr) + return 1 + + http_errors: list[str] = [] + server, http_port = start_local_server(build_dir, sphinx_dir, http_errors) + base_url = f"http://127.0.0.1:{http_port}" + + try: + with launch_browser(browser_bin) as ws_url: + cdp = SimpleWS(ws_url) + try: + print(f"Using browser: {browser_bin}") + failures, total_checks = run_checks( + cdp, base_url, routes, sphinx_dir, screenshots_dir, http_errors + ) + finally: + cdp.close() + except BrowserLaunchError as exc: + print(f"[ERROR] {exc}", file=sys.stderr) + return 1 + finally: + server.shutdown() + server.server_close() + + if failures: + print(f"\nLayout verification FAILED with {len(failures)} issue(s):", file=sys.stderr) + for item in failures: + print(f" - {item}", file=sys.stderr) + return 1 + + print( + f"Layout verification passed ({total_checks} viewport checks " + "+ interactive flows, 0 issues)." + ) + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Verify PySceneDetect responsive website layout and capture screenshots." + ) + parser.add_argument( + "--build-dir", + type=Path, + default=DEFAULT_BUILD_DIR, + help="Built website directory (default: website/build).", + ) + parser.add_argument( + "--sphinx-dir", + type=Path, + default=None, + help="Optional built Sphinx HTML directory mounted at /docs/head/ and /docs/latest/.", + ) + parser.add_argument( + "--screenshots", + type=Path, + default=None, + help="Optional output directory for PNG screenshots.", + ) + parser.add_argument( + "--browser", + default=None, + help="Optional path to Chrome, Chromium, or Edge executable.", + ) + args = parser.parse_args(argv) + + try: + browser_bin = find_browser(args.browser) + except FileNotFoundError as exc: + print(f"[ERROR] {exc}", file=sys.stderr) + return 1 + + return run_audit( + build_dir=args.build_dir.resolve(), + sphinx_dir=args.sphinx_dir.resolve() if args.sphinx_dir else None, + screenshots_dir=args.screenshots.resolve() if args.screenshots else None, + browser_bin=browser_bin, + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/website/mkdocs.yml b/website/mkdocs.yml deleted file mode 100644 index e7981472..00000000 --- a/website/mkdocs.yml +++ /dev/null @@ -1,47 +0,0 @@ -# PySceneDetect Website (https://www.scenedetect.com) -# Copyright (C) 2014 Brandon Castellano . -site_name: PySceneDetect -site_description: "Website and documentation for PySceneDetect, a program to automatically detect scene cuts and split videos. Written in Python, and also provides Python API in addition to command-line interface for use within other programs." -site_author: "Brandon Castellano" -docs_dir: "pages" -site_dir: "build" -repo_url: https://github.com/Breakthrough/PySceneDetect -edit_uri: 'blob/main/website/pages/' -repo_name: "PySceneDetect on Github" -copyright: 'Copyright © 2014 Brandon Castellano. All rights reserved.
Licensed under BSD 3-Clause (see the LICENSE file for details).' -theme: - name: readthedocs - logo: img/pyscenedetect_logo_small.png - favicon: img/favicon.ico - custom_dir: overrides -# Google Analytics is injected manually via overrides/main.html (the top-level -# `google_analytics` option was deprecated and removed from MkDocs). - -nav: -- 'PySceneDetect': - - 'Home': 'index.md' - - 'Features': 'features.md' - - 'Download': 'download.md' - - 'Changelog': 'changelog.md' -- 'Reference:': - - 'Documentation': 'docs.md' - - 'Command-Line': 'cli.md' - - 'Python API': 'api.md' - - 'Benchmarks': 'benchmarks.md' -- 'Support:': - - 'FAQ': 'faq.md' - - 'Bugs & Contributing': 'contributing.md' - - 'Development & Support': 'supporting.md' -- 'Resources': - - 'Project Gallery': 'gallery.md' - - 'Similar Projects': 'similar.md' - - 'Research & Literature': 'literature.md' - - 'License & Copyright': 'copyright.md' - -markdown_extensions: [fenced_code] - -extra_css: - - style.css - -extra_javascript: - - js/helper.js diff --git a/website/overrides/404.html b/website/overrides/404.html deleted file mode 100644 index 7b608acb..00000000 --- a/website/overrides/404.html +++ /dev/null @@ -1,42 +0,0 @@ -{% extends "base.html" %} - -{% block title %}Page Not Found{% endblock %} - -{% block content %} -

Page Not Found

-

This page does not exist.

- - -{% endblock %} \ No newline at end of file diff --git a/website/overrides/main.html b/website/overrides/main.html deleted file mode 100644 index f1413372..00000000 --- a/website/overrides/main.html +++ /dev/null @@ -1,22 +0,0 @@ -{% extends "base.html" %} - -{% block site_name %} -{% if page.is_index %} - -{% else %} - -{% endif %} - - -{% endblock %} - -{% block extrahead %} - -{% endblock %} diff --git a/website/pages/api.md b/website/pages/api.md index 90013ec7..cbe5908b 100644 --- a/website/pages/api.md +++ b/website/pages/api.md @@ -1,81 +1,79 @@ +# Python API -# API Reference +The complete Python API reference is in the [Reference Manual](/docs/latest/api.html). See [Documentation Versions](docs.md) for older releases. -The Python API is documented using Sphinx and [can be found here](docs.md). +## Detectors -# Scene Detection Algorithms +This page describes how each built-in detector works, along with its key CLI options and default values. -This page discusses the scene detection methods/algorithms available for use in PySceneDetect, including details describing the operation of the detection method, as well as relevant command-line arguments and recommended values. +### Adaptive detector -## Content-Aware Detector +The adaptive detector (`AdaptiveDetector` / `detect-adaptive`, default in the CLI) scores adjacent frames the same way as `ContentDetector`, then compares each frame's score against a rolling average of nearby frames. This reduces false cuts during fast camera movement. -The content-aware scene detector (`detect-content`) detects [jump cuts](https://en.wikipedia.org/wiki/Jump_cut) in the input video. This is typically what people think of as "cuts" between scenes in a movie - given two adjacent frames, do they belong to the same scene? The content-aware scene detector finds areas where the *difference* between two subsequent frames exceeds the threshold value that is set (a good value to start with is `--threshold 27`). +Default settings: `--threshold 3.0`, `--frame-window 2`, `--min-content-val 15.0`. See [`detect-adaptive`](/docs/latest/cli.html#detect-adaptive) and [`AdaptiveDetector`](/docs/latest/api/detectors.html#adaptivedetector) for details. -Internally, this detector functions by converting the colorspace of each decoded frame from [RGB](https://en.wikipedia.org/wiki/RGB_color_space) into [HSV](https://en.wikipedia.org/wiki/HSL_and_HSV). It then takes the average difference across all channels (or optionally just the *value* channel) from frame to frame. When this exceeds a set threshold, a scene change is triggered. +### Content detector -`detect-content` also has edge detection, which can be enabled by providing a set of 4 numbers in the form (*delta_hue*, *delta_sat*, *delta_lum*, *delta_edges*). Changes in edges are typically larger than the other components, so threshold may need to be increased accordingly. For example, `-w 1.0 0.5 1.0 0.2 -t 32` is a good starting point to use with edge detection. The default weights are `--weights 1.0 1.0 1.0 0.0` which does not include edges, but this may change in the future. +The content detector (`ContentDetector` / `detect-content`) finds fast cuts between scenes. It converts each frame from [RGB](https://en.wikipedia.org/wiki/RGB_color_space) to [HSV](https://en.wikipedia.org/wiki/HSL_and_HSV), computes the average difference across hue, saturation, and value (brightness) between adjacent frames, and records a cut when that score exceeds `--threshold` (default: `27.0`). -See [the documentation for detect-content](https://www.scenedetect.com/docs/latest/cli.html#detect-content) for details. +You can also enable edge detection by passing four weights (`delta_hue`, `delta_sat`, `delta_lum`, `delta_edges`). Edge differences are usually larger than color differences, so raise the threshold when enabling edges (for example, `-w 1.0 0.5 1.0 0.2 -t 32`). The default weights are `--weights 1.0 1.0 1.0 0.0` (edges disabled). -## Adaptive Content Detector +See [`detect-content`](/docs/latest/cli.html#detect-content) and [`ContentDetector`](/docs/latest/api/detectors.html#contentdetector) for details. -The adaptive content detector (`detect-adaptive`) compares the difference in content between adjacent frames similar to `detect-content` but instead using a rolling average of adjacent frame changes. This helps mitigate false detections where there is fast camera motion. +### Perceptual hash detector -## Threshold Detector +The perceptual hash detector (`HashDetector` / `detect-hash`) computes a perceptual hash (`phash`, based on [imagehash](https://github.com/JohannesBuchner/imagehash)) for each frame and compares adjacent hashes using normalized Hamming distance. When the distance exceeds `--threshold` (default: `0.35`, with `--size 8` and `--lowpass 2`), it records a cut. -The threshold-based scene detector (`detect-threshold`) is how most traditional scene detection methods work (e.g. the `ffmpeg blackframe` filter), by comparing the intensity/brightness of the current frame with a set threshold, and triggering a scene cut/break when this value crosses the threshold. In PySceneDetect, this value is computed by averaging the R, G, and B values for every pixel in the frame, yielding a single floating point number representing the average pixel value (from 0.0 to 255.0). +Because `phash` converts frames to grayscale first, `HashDetector` ignores color changes when brightness stays constant. It is fast even without downscaling. See [Looks Like It](https://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html) for a visual explanation of perceptual hashing. -## Histogram Detector +See [`detect-hash`](/docs/latest/cli.html#detect-hash) and [`HashDetector`](/docs/latest/api/detectors.html#hashdetector) for details. -The scene change detection algorithm uses histograms of the Y channel in the YCbCr color space to detect scene changes, which helps mitigate issues caused by lighting variations. Each frame of the video is converted from its original color space to the YCbCr color space. The Y channel, which represents luminance, is extracted from the YCbCr color space. This helps in focusing on intensity variations rather than color variations. A histogram of the Y channel is computed using the specified number of bins (--bins/-b). The histogram is normalized to ensure that it can be consistently compared with histograms from other frames. The normalized histogram of the current frame is compared with the normalized histogram of the previous frame using the correlation method (cv2.HISTCMP_CORREL). A scene change is detected if the correlation between the histograms of consecutive frames is below the specified threshold (--threshold/-t). This indicates a significant change in luminance, suggesting a scene change. +### Histogram detector -## Perceptual Hash Detector +The histogram detector (`HistogramDetector` / `detect-hist`) finds fast cuts using brightness histograms. It converts each frame to the YUV color space, extracts the Y (luminance) channel, and builds a normalized histogram with `--bins` bins (default: `128`). -The perceptual hash detector (`detect-hash`) calculates a hash for a frame and compares that hash to the previous frame's hash. If the hashes differ by more than the defined threshold, then a scene change is recorded. The hashing algorithm used for this detector is an implementation of `phash` from the [imagehash](https://github.com/JohannesBuchner/imagehash) library. In practice, this detector works similarly to `detect-content` in that it picks up large differences between adjacent frames. One important note is that the hashing algorithm converts the frames to grayscale, so this detector is insensitive to changes in colors if the brightness remains constant. In general, this algorithm is very computationally efficient compared to `detect-content` or `detect-adaptive`, especially if downscaling is not used. See [here](https://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html) for an overview of how a perceptual hashing algorithm can be used for detecting similarity (or otherwise) of images and a visual depiction of the algorithm. +Adjacent frame histograms are compared using correlation (`cv2.HISTCMP_CORREL`). When the difference exceeds `--threshold` (default: `0.20`), the detector records a cut. Focusing on luminance makes this detector less sensitive to pure color shifts. +See [`detect-hist`](/docs/latest/cli.html#detect-hist) and [`HistogramDetector`](/docs/latest/api/detectors.html#histogramdetector) for details. -# Creating New Detection Algorithms +### Threshold detector -All scene detection algorithms must inherit from [the base `SceneDetector` class](https://www.scenedetect.com/docs/latest/api/detector.html). Note that the current SceneDetector API is under development and expected to change somewhat before v1.0 is released, so make sure to pin your `scenedetect` dependency to the correct API version (e.g. `scenedetect < 0.6`, `scenedetect < 0.7`, etc...). +The threshold detector (`ThresholdDetector` / `detect-threshold`) finds fades to and from black, similar to the `ffmpeg blackframe` filter. It averages the R, G, and B values of every pixel in each frame to get a brightness score from `0.0` to `255.0`, and records fade events when that score crosses `--threshold` (default: `12.0`). -Creating a new scene detection method can be as simple as implementing the `process_frame` function, and optionally `post_process`: +See [`detect-threshold`](/docs/latest/cli.html#detect-threshold) and [`ThresholdDetector`](/docs/latest/api/detectors.html#thresholddetector) for details. + +## Creating Custom Detectors + +Custom detectors must inherit from [`SceneDetector`](/docs/latest/api/detector.html). Because the `SceneDetector` interface may change before v1.0, pin your dependency to a minor version (for example, `scenedetect~=0.7.0`). + +To create a detector, implement `process_frame` and, if needed, `post_process`: ```python -import typing as ty import numpy as np from scenedetect import FrameTimecode, SceneDetector class CustomDetector(SceneDetector): - """CustomDetector class to implement a scene detection algorithm.""" + """Example custom scene detector.""" def process_frame( self, timecode: FrameTimecode, - frame_im: np.ndarray, - ) -> ty.List[FrameTimecode]: - # Return a list of timecodes where we found cuts (either on this frame or previously). + frame_img: np.ndarray, + ) -> list[FrameTimecode]: + # Return a list of cut timecodes found on this frame or earlier. return [] - def post_process(self, timecode: FrameTimecode) -> ty.List[FrameTimecode]: - # Called after the last frame has been read to handle pending events. + def post_process(self, timecode: FrameTimecode) -> list[FrameTimecode]: + # Called after the last frame to emit any pending cuts. return [] ``` -`process_frame` is called on every frame in the input video, which will be called after the final frame of the video is passed to `process_frame`. This may be useful for multi-pass algorithms, or detectors which are waiting on some condition but still wish to output an event on the final frame. - -For example, a detector may output at most 1 cuts for every call to `process_frame`, it may output the entire scene list in `post_process`, or a combination of both. Note that the latter will not work in cases where a live video stream or camera input device is being used. See the [API documentation for the `SceneDetector` class](https://www.scenedetect.com/docs/latest/api/detector.html#scenedetect.scene_detector.SceneDetector) for details. Alternatively, you can call `help(SceneDetector)` from a Python REPL. For examples of actual detection algorithm implementations, see the source files in the `scenedetect/detectors/` directory (e.g. `threshold_detector.py`, `content_detector.py`). - -Processing is done by calling the `process_frame(...)` function for all frames in the video, followed by `post_process(...)` (optional) after the final frame. Scene cuts are detected and added to the passed list object in both cases. - -`process_frame(...)` is called for each frame in sequence, passing the following arguments: - -- `frame_num`: the number of the current frame being processed -- `frame_img`: frame returned video file or stream (accessible as NumPy array) -- `frame_metrics`: dictionary for memoizing results of detection algorithm calculations for quicker subsequent analyses (if possible) -- `scene_list`: List containing the frame numbers where all scene cuts/breaks occur in the video. +PySceneDetect calls `process_frame(timecode, frame_img)` for every frame in sequence: -`post_process(...)` is called **after** the final frame has been processed, to allow for any stored scene cuts to be written *if required* (e.g. in the case of the `ThresholdDetector`). +- `timecode`: `FrameTimecode` of the current frame. +- `frame_img`: decoded video frame as a NumPy `ndarray`. -You may also want to look into the implementation of current detectors to understand how frame metrics are saved/loaded to/from a [`StatsManager`](https://www.scenedetect.com/docs/latest/api/stats_manager.html) for caching and allowing values to be written to a stats file for users to graph and find trends in to tweak detector options. Also see the documentation for the [`SceneManager`](https://www.scenedetect.com/docs/latest/api/scene_manager.html) for details. +After the final frame, PySceneDetect calls `post_process(timecode)` so multi-pass detectors or detectors waiting on an end condition (such as `ThresholdDetector`) can emit remaining cuts. Both methods return a list of `FrameTimecode` cut locations. Note that detectors that emit cuts only in `post_process` will not report cuts live on continuous streams. +To save or reuse frame metrics in a CSV stats file, integrate with [`StatsManager`](/docs/latest/api/stats_manager.html). See the built-in detectors in [`scenedetect/detectors/`](https://github.com/Breakthrough/PySceneDetect/tree/main/scenedetect/detectors), [`SceneDetector`](/docs/latest/api/detector.html#scenedetect.detector.SceneDetector), and [`SceneManager`](/docs/latest/api/scene_manager.html) for working examples. diff --git a/website/pages/benchmarks.md b/website/pages/benchmarks.md index 9b8f9198..5424b0ca 100644 --- a/website/pages/benchmarks.md +++ b/website/pages/benchmarks.md @@ -1,107 +1,112 @@ - # Benchmarks -PySceneDetect's detectors are benchmarked for accuracy against public -shot-boundary-detection corpora. Scoring follows the -[TRECVID-SBD convention](https://www-nlpir.nist.gov/projects/tv2007/pastdata/shot_boundary.07.html) -(greedy 1-to-1 nearest-neighbor matching with a configurable frame tolerance for hard cuts; -point-in-interval matching for fades), so numbers are comparable to published results. -The benchmark harness, datasets, and full raw results live in -[`benchmark/`](https://github.com/Breakthrough/PySceneDetect/tree/main/benchmark) on GitHub. +PySceneDetect's detectors are tested for accuracy against three public shot-boundary detection datasets. Scoring follows the [TRECVID-SBD convention](https://trecvid.nist.gov/) (greedy 1-to-1 nearest-neighbor matching with a configurable frame tolerance for hard cuts, and point-in-interval matching for fades), so results can be compared directly with published research. The benchmark code, dataset loaders, and result summaries ([`README.md`](https://github.com/Breakthrough/PySceneDetect/blob/main/benchmark/README.md), [`SWEEP_REPORT.md`](https://github.com/Breakthrough/PySceneDetect/blob/main/benchmark/SWEEP_REPORT.md)) are in [`benchmark/`](https://github.com/Breakthrough/PySceneDetect/tree/main/benchmark) on GitHub. -Three datasets are used, chosen to cover very different content: +The three datasets cover different types of video: - - **BBC Planet Earth** - 11 long-form broadcast episodes (hard cuts only) - - **AutoShot** - short-form web/user-generated clips (hard cuts only) - - **ClipShots** - 500 short web clips with hard cuts *and* typed gradual transitions +- **BBC Planet Earth**: 11 long-form broadcast episodes (hard cuts only). +- **AutoShot**: short web and user-generated clips (hard cuts only). +- **ClipShots**: 500 short web clips with hard cuts and gradual transitions. -## Accuracy at default settings +## Accuracy at Default Settings -Grouped bar chart of hard-cut F1 score per detector and dataset at default settings. AdaptiveDetector leads on BBC (92) and AutoShot (74); HistogramDetector trails, dropping to 20 on ClipShots. +Grouped bar chart of hard-cut F1 score per detector and dataset at default settings. AdaptiveDetector leads on BBC (92) and AutoShot (74); HistogramDetector trails, dropping to 20 on ClipShots. -Hard cuts, strict frame-exact matching (tolerance 0). F1 cells are shaded by score. +Hard cuts with exact frame matching (tolerance 0). F1 cells are shaded by score. -These results were measured with the v0.7 defaults. In v0.7.2 the `HistogramDetector` and -`HashDetector` defaults changed to the swept-best values listed under -[Parameter sweeps](#parameter-sweeps); the tables below will be regenerated with the new defaults. +The tables below show scores with the v0.7 defaults. Version 0.7.2 changed the `HistogramDetector` and `HashDetector` defaults to the tuned values in [Parameter Sweeps](#parameter-sweeps). ### BBC Planet Earth - - - - - - + + + + + + + + + +
DetectorRecallPrecisionF1
AdaptiveDetector87.1296.5591.59
ContentDetector84.7088.7786.69
HashDetector92.3075.5683.10
HistogramDetector89.8472.0379.96
ThresholdDetector *0.060.700.11
DetectorRecallPrecisionF1
AdaptiveDetector87.1296.5591.59
ContentDetector84.7088.7786.69
HashDetector92.3075.5683.10
HistogramDetector89.8472.0379.96
ThresholdDetector *0.060.700.11
### AutoShot - - - - - - + + + + + + + + + +
DetectorRecallPrecisionF1
AdaptiveDetector70.5977.4673.86
ContentDetector63.4976.1969.26
HashDetector56.4876.1164.84
HistogramDetector63.2753.2357.82
ThresholdDetector *0.7538.641.47
DetectorRecallPrecisionF1
AdaptiveDetector70.5977.4673.86
ContentDetector63.4976.1969.26
HashDetector56.4876.1164.84
HistogramDetector63.2753.2357.82
ThresholdDetector *0.7538.641.47
### ClipShots (hard cuts) - - - - - - + + + + + + + + + +
DetectorRecallPrecisionF1
AdaptiveDetector85.9741.2555.75
ContentDetector81.9342.3655.84
HashDetector81.3430.1443.98
HistogramDetector72.2011.4719.80
ThresholdDetector *0.080.580.14
DetectorRecallPrecisionF1
AdaptiveDetector85.9741.2555.75
ContentDetector81.9342.3655.84
HashDetector81.3430.1443.98
HistogramDetector72.2011.4719.80
ThresholdDetector *0.080.580.14
### ClipShots (fades) - - - - - - + + + + + + + + + +
DetectorRecallPrecisionF1
AdaptiveDetector13.6598.1223.96
ContentDetector26.0398.0441.14
HashDetector18.7794.5331.33
HistogramDetector69.6781.9975.33
ThresholdDetector *5.6999.2410.77
DetectorRecallPrecisionF1
AdaptiveDetector13.6598.1223.96
ContentDetector26.0398.0441.14
HashDetector18.7794.5331.33
HistogramDetector69.6781.9975.33
ThresholdDetector *5.6999.2410.77
-\* ThresholdDetector detects fades to/from black, not shot-to-shot transitions; near-zero -hard-cut scores are expected. Included for completeness. +\* `ThresholdDetector` detects fades to and from black, not hard cuts, so near-zero hard-cut scores are expected. It is included here for completeness. -## Parameter sweeps +## Parameter Sweeps -Beyond the default values, a sweep over each detector's key parameters shows how -accuracy per dataset changes: +Sweeping each detector's main parameters shows how accuracy changes across datasets: -Four small-multiple line charts showing hard-cut F1 at 1-frame tolerance versus threshold for detect-content, detect-adaptive, detect-hash, and detect-hist. Each panel has one line per dataset with a dot at that dataset's optimum; BBC and AutoShot peak at lower thresholds than ClipShots in most panels. +Four small-multiple line charts showing hard-cut F1 at 1-frame tolerance versus threshold for detect-content, detect-adaptive, detect-hash, and detect-hist. Each panel has one line per dataset with a dot at that dataset's optimum; BBC and AutoShot peak at lower thresholds than ClipShots in most panels. -Dots mark each dataset's optimum within the shown parameter slice. Long-form broadcast content (BBC) -generally prefers lower thresholds than short web clips (ClipShots), so the defaults aim for a -robust middle ground. +Dots mark the highest score for each dataset in the tested range. Long-form broadcast video (BBC) generally works best at lower thresholds than short web clips (ClipShots), so default settings aim for a balanced middle ground. -Grouped bar chart of hard-cut F1 at 1-frame tolerance after parameter tuning. Bars show the best single cross-dataset parameter set per detector and dataset, a black tick marks the v0.7 default, and a dot marks each dataset's own optimum. HistogramDetector shows the largest gap between default and tuned scores, most dramatically on ClipShots (20 vs 48); for ContentDetector and AdaptiveDetector on BBC the default tick sits slightly above the tuned bar. +Grouped bar chart of hard-cut F1 at 1-frame tolerance after parameter tuning. Bars show the best single cross-dataset parameter set per detector and dataset, a black tick marks the v0.7 default, and a dot marks each dataset's own optimum. HistogramDetector shows the largest gap between default and tuned scores, most dramatically on ClipShots (20 vs 48); for ContentDetector and AdaptiveDetector on BBC the default tick sits slightly above the tuned bar. Scored by mean hard-cut F1 at 1-frame tolerance across all three datasets: - - - - - - +
DetectorBest mean F1Best parametersv0.7.2 defaultv0.7 default
AdaptiveDetector76.3adaptive_threshold=3.5, window_width=3, min_scene_len=0.6sadaptive_threshold=3.0, window_width=2adaptive_threshold=3.0, window_width=2
ContentDetector73.4threshold=31, min_scene_len=0.6sthreshold=27threshold=27
HashDetector69.8threshold=0.35, size=8threshold=0.35, size=8threshold=0.395, size=16
HistogramDetector66.3threshold=0.20, bins=128threshold=0.20, bins=128threshold=0.05, bins=256
+ + + + + + + + +
DetectorBest mean F1Best parametersv0.7.2 defaultv0.7 default
AdaptiveDetector76.3adaptive_threshold=3.5, window_width=3, min_scene_len=0.6sadaptive_threshold=3.0, window_width=2adaptive_threshold=3.0, window_width=2
ContentDetector73.4threshold=31, min_scene_len=0.6sthreshold=27threshold=27
HashDetector69.8threshold=0.35, size=8threshold=0.35, size=8threshold=0.395, size=16
HistogramDetector66.3threshold=0.20, bins=128threshold=0.20, bins=128threshold=0.05, bins=256
-Full per-dataset breakdowns are in -[`benchmark/SWEEP_REPORT.md`](https://github.com/Breakthrough/PySceneDetect/blob/main/benchmark/SWEEP_REPORT.md). +Full per-dataset breakdowns are in [`benchmark/SWEEP_REPORT.md`](https://github.com/Breakthrough/PySceneDetect/blob/main/benchmark/SWEEP_REPORT.md). -## Benchmarking +## Running Benchmarks -See [`benchmark/README.md`](https://github.com/Breakthrough/PySceneDetect/blob/main/benchmark/README.md) -for dataset download instructions and usage. +See [`benchmark/README.md`](https://github.com/Breakthrough/PySceneDetect/blob/main/benchmark/README.md) for dataset setup instructions and full usage: ```bash # Score one detector on one dataset: diff --git a/website/pages/changelog.md b/website/pages/changelog.md index 958e5040..9e1d1532 100644 --- a/website/pages/changelog.md +++ b/website/pages/changelog.md @@ -1,5 +1,5 @@ -# Releases +# Changelog ## PySceneDetect 0.7 @@ -50,9 +50,9 @@ PySceneDetect 0.7.2 ships improved defaults for the histogram and perceptual has #### CLI Changes - - [improvement] `HistogramDetector` (`detect-hist`) default `threshold` changed from 0.05 to 0.20 and default `bins` from 256 to 128, calibrated from the [benchmarks](https://www.scenedetect.com/benchmarks/). Output for this detector will change if you are not setting both parameters explicitly. [#559](https://github.com/Breakthrough/PySceneDetect/issues/559) + - [improvement] `HistogramDetector` (`detect-hist`) default `threshold` changed from 0.05 to 0.20 and default `bins` from 256 to 128, calibrated from the [benchmarks](benchmarks.md). Output for this detector will change if you are not setting both parameters explicitly. [#559](https://github.com/Breakthrough/PySceneDetect/issues/559) - Use `detect-hist -t 0.05 -b 256` or `HistogramDetector(threshold=0.05, bins=256)` to restore the previous behavior. - - [improvement] `HashDetector` (`detect-hash`) default `threshold` changed from 0.395 to 0.35 and default `size` from 16 to 8, calibrated from the [benchmarks](https://www.scenedetect.com/benchmarks/). Output for this detector will change if you are not setting both parameters explicitly. [#559](https://github.com/Breakthrough/PySceneDetect/issues/559) + - [improvement] `HashDetector` (`detect-hash`) default `threshold` changed from 0.395 to 0.35 and default `size` from 16 to 8, calibrated from the [benchmarks](benchmarks.md). Output for this detector will change if you are not setting both parameters explicitly. [#559](https://github.com/Breakthrough/PySceneDetect/issues/559) - Use `detect-hash -t 0.395 -s 16` or `HashDetector(threshold=0.395, size=16)` to restore the previous behavior. - [improvement] `detect-threshold` now ignores fade-outs shorter than `0.1s` by default. Use `--min-out-length 0` to restore the previous behavior. The API default remains `0` [#278](https://github.com/Breakthrough/PySceneDetect/issues/278) - [feature] Added `save-keyframes` command to export detected cuts using `# keyframe format v1` for Aegisub-compatible tools [#534](https://github.com/Breakthrough/PySceneDetect/issues/534). Frame numbers are currently approximate for VFR input [#569](https://github.com/Breakthrough/PySceneDetect/issues/569) @@ -102,21 +102,21 @@ PySceneDetect 0.7.1 adds support for concatenating multiple videos, along with s - [general] `scenedetect` and `scenedetect-headless` are unchanged: they continue to ship the full program (library + CLI) with `opencv-python` / `opencv-python-headless` respectively. Both packages provide the same `scenedetect` module (install or depend only one) - [feature] Official Docker images are now published to the GitHub Container Registry with the full CLI, all backends, and external tools (ffmpeg, mkvmerge) included, thanks [@FNGarvin](https://github.com/FNGarvin) [#537](https://github.com/Breakthrough/PySceneDetect/pull/537) - - Example usage (process a video in the current directory): -```bash -docker run --rm -v "$(pwd):/files" ghcr.io/breakthrough/pyscenedetect -i /files/video.mp4 detect-adaptive split-video -o /files -``` + - Example usage (process a video in the current directory): + + docker run --rm -v "$(pwd):/files" ghcr.io/breakthrough/pyscenedetect -i /files/video.mp4 detect-adaptive split-video -o /files + - [general] The Windows distribution now bundles OpenCV 5.0, PyAV 18, and FFmpeg 8.1.2. The Windows and Docker builds also override Pillow to 12.3.0 for upstream security fixes ([moviepy#2553](https://github.com/Zulko/moviepy/issues/2553)) #### General - - [general] Benchmark results are now published on the website ([scenedetect.com/benchmarks](https://www.scenedetect.com/benchmarks/)), including accuracy at default settings and parameter sweep curves for each detector + - [general] Benchmark results are now published on the website ([scenedetect.com/benchmarks](benchmarks.md)), including accuracy at default settings and parameter sweep curves for each detector ### 0.7 (May 3, 2026) PySceneDetect 0.7 is a **major breaking release** which overhauls how timestamps are handled. This allows PySceneDetect to properly process variable framerate (VFR) videos. A significant amount of technical debt has been addressed, including removal of deprecated or overly complicated APIs. -Care was taken to minimize changes for most common API uses, however more advanced use cases may run into breaking changes. Please review [the Migration Guide](https://www.scenedetect.com/docs/0.7/api/migration_guide.html) when updating from v0.6. Minimum supported Python version is now **Python 3.10**. +Care was taken to minimize changes for most common API uses, however more advanced use cases may run into breaking changes. Please review [the Migration Guide](/docs/0.7/api/migration_guide.html) when updating from v0.6. Minimum supported Python version is now **Python 3.10**. #### CLI Changes @@ -189,7 +189,7 @@ Care was taken to minimize changes for most common API uses, however more advanc **Removals:** - * Remove deprecated module `scenedetect.video_manager`, use [the `scenedetect.open_video()` function](https://www.scenedetect.com/docs/head/api.html#scenedetect.open_video) instead + * Remove deprecated module `scenedetect.video_manager`, use [the `scenedetect.open_video()` function](/docs/0.7/api.html#scenedetect.open_video) instead * Remove deprecated parameters `base_timecode` and `video_manager` from various functions * Remove deprecated `SceneManager.get_event_list()` method * Remove deprecated `AdaptiveDetector.get_content_val()` method (use `StatsManager` instead) @@ -246,7 +246,7 @@ PySceneDetect v0.6.6 introduces new output formats, which improve compatibility - [bugfix] Fix crash when using `split-video` with `-m`/`--mkvmerge` option [#473](https://github.com/Breakthrough/PySceneDetect/issues/473) - [bugfix] Fix incorrect default filename template for `split-video` command with `-m`/`--mkvmerge` option - [bugfix] Fix inconsistent filenames when using `split_video_mkvmerge()` - - [bugfix] Ensure auto-rotation is always enabled for `VideoStreamCv2` as workaround for (opencv#26795)[https://github.com/opencv/opencv/issues/26795] + - [bugfix] Ensure auto-rotation is always enabled for `VideoStreamCv2` as workaround for [opencv#26795](https://github.com/opencv/opencv/issues/26795) - [general] The `export-html` command is now deprecated, use `save-html` instead - [general] Updates to Windows distributions: - av 13.1.0 -> 14.2.0 @@ -294,14 +294,14 @@ This release brings crop support, performance improvements to save-images, lots #### Python Distribution Changes * *v0.6.5.1* - Fix compatibility issues with PyAV 14+ [#466](https://github.com/Breakthrough/PySceneDetect/issues/466) - * *v0.6.5.2* - Fix for `AttributeError: module 'cv2' has no attribute 'Mat'` [#468](https://github.com/Breakthrough/PySceneDetect/issues/466) + * *v0.6.5.2* - Fix for `AttributeError: module 'cv2' has no attribute 'Mat'` [#468](https://github.com/Breakthrough/PySceneDetect/issues/468) ### 0.6.4 (June 10, 2024) Includes new histogram and perceptual hash based detectors (thanks @wjs018 and @ash2703), adds flash filter to content detector, and includes various bugfixes. Below shows the scores of the new detectors normalized against `detect-content` for comparison on a difficult segment with 3 cuts: -comparison of new detector scores +comparison of new detector scores Feedback on the new detection methods and their default values is most welcome. Thanks to everyone who contributed for their help and support! @@ -351,8 +351,7 @@ In addition to some performance improvements with the `load-scenes` command, thi - [bugfix] Ensure correct string conversion behavior for `FrameTimecode` when rounding is enabled [#354](https://github.com/Breakthrough/PySceneDetect/issues/354) - [bugfix] Fix `AdaptiveDetector` not respecting `min_scene_len` for the first scene - [feature] Add `output_dir` argument to `split_video_ffmpeg` and `split_video_mkvmerge` functions to set output directory [#298](https://github.com/Breakthrough/PySceneDetect/issues/298) - - [feature] Add `formatter` argument to `split_video_ffmpeg` to allow formatting filenames via callback [#359](https://github.com/ - Breakthrough/PySceneDetect/issues/359) + - [feature] Add `formatter` argument to `split_video_ffmpeg` to allow formatting filenames via callback [#359](https://github.com/Breakthrough/PySceneDetect/issues/359) - [general] The `frame_img` argument to `SceneDetector.process_frame()` is now required - [general] Remove `TimecodeValue` from `scenedetect.frame_timecode` (use `typing.Union[int, float, str]`) - [general] Remove `MotionDetector` and `scenedetect.detectors.motion_detector` module (will be reintroduced after `SceneDetector` interface is stable) @@ -366,13 +365,13 @@ In addition to some performance improvements with the `load-scenes` command, thi ### 0.6.2 (July 23, 2023) -Includes new [`load-scenes` command](https://www.scenedetect.com/docs/0.6.2/cli.html#load-scenes), ability to specify a default detector, PyAV 10 support, and several bugfixes. Minimum supported Python version is now **Python 3.7**. +Includes new [`load-scenes` command](/docs/0.6.2/cli.html#load-scenes), ability to specify a default detector, PyAV 10 support, and several bugfixes. Minimum supported Python version is now **Python 3.7**. **Command-Line Changes:** - - [feature] Add [`load-scenes` command](https://www.scenedetect.com/docs/0.6.2/cli.html#load-scenes) to load cuts from `list-scenes` CSV output [#235](https://github.com/Breakthrough/PySceneDetect/issues/235) + - [feature] Add [`load-scenes` command](/docs/0.6.2/cli.html#load-scenes) to load cuts from `list-scenes` CSV output [#235](https://github.com/Breakthrough/PySceneDetect/issues/235) - [feature] Use `detect-adaptive` by default if a detector is not specified [#329](https://github.com/Breakthrough/PySceneDetect/issues/329) - - Default detector can be set by [config file](https://www.scenedetect.com/docs/latest/cli/config_file.html) with the `default-detector` option under `[global]` + - Default detector can be set by [config file](/docs/latest/cli/config_file.html) with the `default-detector` option under `[global]` - [bugfix] Fix `-d`/`--duration` and `-e`/`--end` options of `time` command consuming one extra frame [#307](https://github.com/Breakthrough/PySceneDetect/issues/307) - [bugfix] Fix incorrect end timecode for final scene when last frame of video is a new scene [#307](https://github.com/Breakthrough/PySceneDetect/issues/307) - [bugfix] Expand `$VIDEO_NAME` before creating output directory for `-f`/`--filename` option of `split-video`, now allows absolute paths @@ -384,7 +383,7 @@ Includes new [`load-scenes` command](https://www.scenedetect.com/docs/0.6.2/cli. **General:** - - [feature] Add ability to specify method (floor/ceiling) when creating [`ThresholdDetector`](https://www.scenedetect.com/docs/0.6.2/api/detectors.html#scenedetect.detectors.threshold_detector.ThresholdDetector), allows fade to white detection [#143](https://github.com/Breakthrough/PySceneDetect/issues/143) + - [feature] Add ability to specify method (floor/ceiling) when creating [`ThresholdDetector`](/docs/0.6.2/api/detectors.html#scenedetect.detectors.threshold_detector.ThresholdDetector), allows fade to white detection [#143](https://github.com/Breakthrough/PySceneDetect/issues/143) - [general] Minimum supported Python version is now **Python 3.7** - [general] Add support for PyAV 10.0 [#292](https://github.com/Breakthrough/PySceneDetect/issues/292) - [general] Use platformdirs package instead of appdirs [#309](https://github.com/Breakthrough/PySceneDetect/issues/309) @@ -402,7 +401,7 @@ Includes new [`load-scenes` command](https://www.scenedetect.com/docs/0.6.2/cli. #### Project Updates - - Website and documentation is now hosted on Github Pages, documentation can be found at [scenedetect.com/docs](https://www.scenedetect.com/docs) + - Website and documentation is now hosted on GitHub Pages, documentation can be found at [scenedetect.com/docs](docs.md) - Windows and Linux builds are now done on Github Actions, add OSX builds as well - Build matrix has been updated to support Python 3.7 through 3.11 for all operating systems for Python distributions - Windows portable builds have been moved to Github Actions, signed builds/installer is still done on Appveyor @@ -418,24 +417,24 @@ Includes [MoviePy support](https://github.com/Zulko/moviepy), edge detection cap **Command-Line Changes:** - [feature] Add `moviepy` backend wrapping the MoviePy package, uses `ffmpeg` binary on the system for video decoding - - [feature] Edge detection can now be enabled with `detect-content` and `detect-adaptive` to improve accuracy in some cases, especially under lighting changes, see [new `-w`/`--weights` option](http://scenedetect.com/projects/Manual/en/latest/cli/detectors.html#detect-content) for more information + - [feature] Edge detection can now be enabled with `detect-content` and `detect-adaptive` to improve accuracy in some cases, especially under lighting changes, see [new `-w`/`--weights` option](/docs/0.6.1/cli/detectors.html#detect-content) for more information - A good starting point is to place 100% weight on the change in a frame's hue, 50% on saturation change, 100% on luma (brightness) change, and 25% on change in edges, with a threshold of 32: `detect-adaptive -w 1.0 0.5 1.0 0.25` - - Edge differences are typically larger than other components, so you may need to increase `-t`/`--threshold` higher when increasing the edge weight (the last component) with `detect-content, for example: + - Edge differences are typically larger than other components, so you may need to increase `-t`/`--threshold` higher when increasing the edge weight (the last component) with `detect-content`, for example: `detect-content -w 1.0 0.5 1.0 0.25 -t 32` - May be enabled by default in the future once it has been more thoroughly tested, further improvements for `detect-content` are being investigated as well (e.g. motion compensation, flash suppression) - Short-form of `detect-content` option `--frame-window` has been changed from `-w` to `-f` to accommodate this change - [enhancement] Progress bar now displays number of detections while processing, no longer conflicts with log message output - [enhancement] When using ffmpeg to split videos, `-map 0` has been added to the default arguments so other audio tracks are also included when present ([#271](https://github.com/Breakthrough/PySceneDetect/issues/271)) - [enhancement] Add `-a` flag to `version` command to print more information about versions of dependencies/tools being used - - [enhancement] The resizing method used used for frame downscaling or resizing can now be set using [a config file](http://scenedetect.com/projects/Manual/en/latest/cli/config_file.html), see `[global]` option `downscale-method` and `[save-images]` option `scale-method` + - [enhancement] The resizing method used for frame downscaling or resizing can now be set using [a config file](/docs/0.6.1/cli/config_file.html), see `[global]` option `downscale-method` and `[save-images]` option `scale-method` - [other] Linear interpolation is now used as the default downscaling method (previously was nearest neighbor) for improved edge detection accuracy - [other] Add `-c`/`--min-content-val` argument to `detect-adaptive`, deprecate `-d`/`--min-delta-hsv` **General:** - [general] Recommend `detect-adaptive` over `detect-content` - - [feature] Add new backend `VideoStreamMoviePy` using the MoviePy package` + - [feature] Add new backend `VideoStreamMoviePy` using the MoviePy package - [feature] Add edge detection to `ContentDetector` and `AdaptiveDetector` ([#35](https://github.com/Breakthrough/PySceneDetect/issues/35)) - Add ability to specify content score weights of hue, saturation, luma, and edge differences between frames - Default remains as `1.0, 1.0, 1.0, 0.0` so there is no change in behavior @@ -446,20 +445,20 @@ Includes [MoviePy support](https://github.com/Zulko/moviepy), edge detection cap - [bugfix] Fix a named argument that was incorrect ([#299](https://github.com/Breakthrough/PySceneDetect/issues/299)) - [enhancement] Add optional `start_time`, `end_time`, and `start_in_scene` arguments to `scenedetect.detect()` ([#282](https://github.com/Breakthrough/PySceneDetect/issues/282)) - [enhancement] Add `-map 0` option to default arguments of `split_video_ffmpeg` to include all audio tracks by default ([#271](https://github.com/Breakthrough/PySceneDetect/issues/271)) - - [docs] Add example for [using a callback](http://scenedetect.com/projects/Manual/en/v0.6.1/api/scene_manager.html#usage) ([#273](https://github.com/Breakthrough/PySceneDetect/issues/273)) + - [docs] Add example for [using a callback](/docs/0.6.1/api/scene_manager.html#usage) ([#273](https://github.com/Breakthrough/PySceneDetect/issues/273)) - [enhancement] Add new `VideoCaptureAdapter` to make existing `cv2.VideoCapture` objects compatible with a `SceneManager` ([#276](https://github.com/Breakthrough/PySceneDetect/issues/276)) - - Primary use case is for handling input devices/webcams and gstreamer pipes, [see updated examples](http://scenedetect.com/projects/Manual/en/latest/api/backends.html#devices-cameras-pipes) + - Primary use case is for handling input devices/webcams and gstreamer pipes, [see updated examples](/docs/0.6.1/api/backends.html#devices-cameras-pipes) - Files, image sequences, and network streams/URLs should continue to use `VideoStreamCv2` - [api] The `SceneManager` methods `get_cut_list()` and `get_event_list()` are deprecated, along with the `base_timecode` argument - [api] The `base_timecode` argument of `get_scenes_from_cuts()` in `scenedetect.stats_manager` is deprecated (the signature of this function has been changed accordingly) - - [api] Rename `AdaptiveDetector` constructor parameter `min_delta_hsv` to `min_content_val + - [api] Rename `AdaptiveDetector` constructor parameter `min_delta_hsv` to `min_content_val` - [general] The default `crf` for `split_video_ffmpeg` has been changed from 21 to 22 to match command line default - [enhancement] Add `interpolation` property to `SceneManager` to allow setting method of frame downscaling, use linear interpolation by default (previously nearest neighbor) - [enhancement] Add `interpolation` argument to `save_images` to allow setting image resize method (default remains bicubic) ### 0.6 (May 29, 2022) -PySceneDetect v0.6 is a **major breaking change** including better performance, configuration file support, and a more ergonomic API. The new **minimum Python version is now 3.6**. See the [Migration Guide](https://scenedetect.com/projects/Manual/en/latest/api/migration_guide.html) for information on how to port existing applications to the new API. Most users will see performance improvements after updating, and changes to the command-line are not expected to break most workflows. +PySceneDetect v0.6 is a **major breaking change** including better performance, configuration file support, and a more ergonomic API. The new **minimum Python version is now 3.6**. See the [Migration Guide](/docs/0.6.1/api/migration_guide.html) for information on how to port existing applications to the new API. Most users will see performance improvements after updating, and changes to the command-line are not expected to break most workflows. The main goals of v0.6 are reliability and performance. To achieve this required several breaking changes. The video input API was refactored, and *many* technical debt items were addressed. This should help the eventual transition to the first planned stable release (v1.0) where the goal is an improved scene detection API. @@ -470,10 +469,10 @@ Both the Windows installer and portable distributions now include signed executa **Overview:** * Major performance improvements on multicore systems - * [Configuration file support](http://scenedetect.com/projects/Manual/en/latest/cli/config_file.html) via command line option or user settings folder + * [Configuration file support](/docs/0.6.1/cli/config_file.html) via command line option or user settings folder * Support for multiple video backends, PyAV is now supported in addition to OpenCV * Breaking API changes to `VideoManager` (replaced with `VideoStream`), `StatsManager`, and `save_images()` - * See the [Migration Guide](https://scenedetect.com/projects/Manual/en/latest/api/migration_guide.html) for details on how to update from v0.5.x + * See the [Migration Guide](/docs/0.6.1/api/migration_guide.html) for details on how to update from v0.5.x * A backwards compatibility layer has been added to prevent most applications from breaking, will be removed in a future release * Support for Python 2.7 has been dropped, minimum supported Python version is 3.6 * Support for OpenCV 2.x has been dropped, minimum OpenCV version is 3.x @@ -481,7 +480,7 @@ Both the Windows installer and portable distributions now include signed executa **Command-Line Changes:** - * Configuration files are now supported, [see documentation for details](http://scenedetect.com/projects/Manual/en/latest/cli/config_file.html) + * Configuration files are now supported, [see documentation for details](/docs/0.6.1/cli/config_file.html) * Can specify config file path with `-c`/`--config`, or create a `scenedetect.cfg` file in your user config folder * Frame numbers are now 1-based, aligning with most other tools (e.g. `ffmpeg`) and video editors ([#265](https://github.com/Breakthrough/PySceneDetect/issues/265)) * Start/end *frame numbers* of adjacent scenes no longer overlap ([#264](https://github.com/Breakthrough/PySceneDetect/issues/265)) @@ -512,8 +511,8 @@ Both the Windows installer and portable distributions now include signed executa **API Changes:** - * New `detect()` function performs scene detection on a video path, [see example here](http://scenedetect.com/projects/Manual/en/latest/api.html#quickstart) - * New `open_video()` function to handle video input, [see example here](http://scenedetect.com/projects/Manual/en/latest/api.html#example) + * New `detect()` function performs scene detection on a video path, [see example here](/docs/0.6.1/api.html#quickstart) + * New `open_video()` function to handle video input, [see example here](/docs/0.6.1/api.html#example) * `split_video_ffmpeg()` and `split_video_mkvmerge()` now take a single path as input * `save_images()` no longer accepts `downscale_factor` * Use `scale` or `height`/`width` arguments to resize images @@ -652,7 +651,7 @@ Both the Windows installer and portable distributions now include signed executa * [bugfix] fix `detect-threshold` crash when using statsfile ([#122](https://github.com/Breakthrough/PySceneDetect/issues/122)) * [bugfix] fix `save-images` command under Python 2.7 ([#174](https://github.com/Breakthrough/PySceneDetect/issues/174), thanks @santiagodemierre) - * [bugfix] gracefully exit and show link to FAQ when number of scenes is too large to split with mkvmerge on Windows (see [#164](https://github.com/Breakthrough/PySceneDetect/issues/164, thanks @alexboydray) + * [bugfix] gracefully exit and show link to FAQ when number of scenes is too large to split with mkvmerge on Windows (see [#164](https://github.com/Breakthrough/PySceneDetect/issues/164), thanks @alexboydray) * [enhancement] Improved seeking performance, greatly improves performance of the `time` and `save-images` commands ([#98](https://github.com/Breakthrough/PySceneDetect/issues/98) and [PR #163](https://github.com/Breakthrough/PySceneDetect/pull/163) - thanks @obroomhall) * [enhancement] improve `detect-threshold` performance when min-percent is less than 50% * [bugfix] Fixed issue where video loading would fail silently due to multiple audio tracks ([#179](https://github.com/Breakthrough/PySceneDetect/issues/179)) @@ -722,14 +721,14 @@ Both the Windows installer and portable distributions now include signed executa ### 0.5 (August 31, 2018) * **major** release, includes stable Python API with examples and updated documentation - * numerous changes to command-line interface with addition of sub-commands (see [the new manual](http://manual.scenedetect.com) for updated usage information) + * numerous changes to command-line interface with addition of sub-commands (see [the new manual](docs.md) for updated usage information) * [feature] videos are now split using `ffmpeg` by default, resulting in frame-perfect cuts (can still use `mkvmerge` by specifying the `-c`/`--copy` argument to the `split-video` command) * [enhance] image filename numbers are now consistent with those of split video scenes (PR #39, thanks [@e271828-](https://github.com/Breakthrough/PySceneDetect/pull/39)) * [enhance] 5-10% improvement in processing performance due to reduced memory copy operations (PR #40, thanks [@elcombato](https://github.com/Breakthrough/PySceneDetect/pull/40)) * [enhance] updated exception handling to raise proper standard exceptions (PR #37, thanks [@talkain](https://github.com/Breakthrough/PySceneDetect/pull/37)) * several fixes to the documentation, including improper dates and outdated CLI arguments (PR #26 and #, thanks [@elcombato](https://github.com/Breakthrough/PySceneDetect/pull/26), and [@colelawrence](https://github.com/Breakthrough/PySceneDetect/pull/33)) * *numerous* other PRs and issues/bug reports that have been fixed - there are too many to list individually here, so I want to extend a big thank you to **everyone** who contributed to making this release better - * [enhance] add Sphinx-generated API documentation (available at: http://manual.scenedetect.com) + * [enhance] add Sphinx-generated API documentation (available at [scenedetect.com/docs](docs.md)) * [project] move from BSD 2-clause to 3-clause license @@ -853,10 +852,9 @@ Both the Windows installer and portable distributions now include signed executa ---------------------------------------------------------------- -Development -========================================================== +## Development -## PySceneDetect 0.8 (TBD) +### PySceneDetect 0.8 (TBD) - [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) diff --git a/website/pages/cli.md b/website/pages/cli.md index 40092343..673f3add 100644 --- a/website/pages/cli.md +++ b/website/pages/cli.md @@ -1,23 +1,22 @@ +# Command-Line Interface -# PySceneDetect CLI - -See [the documentation](../docs/latest/) for a complete reference to the `scenedetect` command with more examples. +See the [Reference Manual](/docs/latest/cli.html) for a complete list of `scenedetect` commands and options. ## Quickstart -Split input video on each fast cut using `ffmpeg`: +Split a video at each fast cut using `ffmpeg`: ```bash scenedetect -i video.mp4 split-video ``` -Save some frames from each cut: +Save still frames from each scene: ```bash scenedetect -i video.mp4 save-images ``` -Skip the first 10 seconds of the input video: +Skip the first 10 seconds of the video: ```bash scenedetect -i video.mp4 time -s 10s @@ -25,183 +24,171 @@ scenedetect -i video.mp4 time -s 10s ## Example -As a concrete example to become familiar with PySceneDetect, let's use the following short clip from the James Bond movie, GoldenEye (Copyright © 1995 MGM): - -[https://www.youtube.com/watch?v=OMgIPnCnlbQ](https://www.youtube.com/watch?v=OMgIPnCnlbQ) +This walkthrough uses a short clip from the James Bond film *GoldenEye* (Copyright © 1995 MGM): -You can [download the clip from here](https://github.com/Breakthrough/PySceneDetect/raw/refs/heads/resources/tests/resources/goldeneye.mp4) (right-click and save the video in your working directory as `goldeneye.mp4`). +- [Watch the clip on YouTube](https://www.youtube.com/watch?v=OMgIPnCnlbQ) +- [Download `goldeneye.mp4`](https://github.com/Breakthrough/PySceneDetect/raw/refs/heads/resources/tests/resources/goldeneye.mp4) (right-click and save it in your working directory as `goldeneye.mp4`) -Let's split this scene into clips on each fast cut. This means we need to use content-aware detection mode (`detect-content`) or adaptive mode (`detect-adaptive`). If the video instead contains fade-in/fade-out transitions you want to find, you can use `detect-threshold` instead. If no detector is specified, `detect-adaptive` will be used by default. +To split this clip on each fast cut, use the adaptive detector (`detect-adaptive`) or the content detector (`detect-content`). To detect fades to and from black instead, use `detect-threshold`. When you do not specify a detector, PySceneDetect uses `detect-adaptive` by default. -Let's first save a scene list in CSV format and generate some images of each scene to check the output: +Start by saving a CSV scene list and preview images for each scene: ```bash scenedetect --input goldeneye.mp4 detect-adaptive list-scenes save-images ``` -Running the above command, in the working directory, you should see a file `goldeneye-Scenes.csv`, as well as individual frames for the start/middle/end of each scene starting with `goldeneye-Scene-001-01.jpg`. The results should appear as follows: - - -| Scene # | Start Time | Preview | -| ------------ | ------------- | ------------- | -| 1 | 00:00:00.000 | | -| 2 | 00:00:03.754 | | -| 3 | 00:00:08.759 | | -| 4 | 00:00:10.802 | | -| 5 | 00:00:15.599 | | -| 6 | 00:00:27.110 | | -| 7 | 00:00:34.117 | | -| 8 | 00:00:36.536 | | -| ... | ... | ... | -| 18 | 00:01:06.316 | | -| 19 | 00:01:10.779 | | -| 20 | 00:01:18.036 | | -| 21 | 00:01:19.913 | | -| 22 | 00:01:21.999 | | - +This command creates `goldeneye-Scenes.csv` and three preview images per scene in your working directory (starting with `goldeneye-Scene-001-01.jpg`). The output matches the scenes below: + +| Scene # | Start Time | Preview | +| --- | --- | --- | +| 1 | 00:00:00.000 | GoldenEye scene 1 preview | +| 2 | 00:00:03.754 | GoldenEye scene 2 preview | +| 3 | 00:00:08.759 | GoldenEye scene 3 preview | +| 4 | 00:00:10.802 | GoldenEye scene 4 preview | +| 5 | 00:00:15.599 | GoldenEye scene 5 preview | +| 6 | 00:00:27.110 | GoldenEye scene 6 preview | +| 7 | 00:00:34.117 | GoldenEye scene 7 preview | +| 8 | 00:00:36.536 | GoldenEye scene 8 preview | +| ... | ... | ... | +| 18 | 00:01:06.316 | GoldenEye scene 18 preview | +| 19 | 00:01:10.779 | GoldenEye scene 19 preview | +| 20 | 00:01:18.036 | GoldenEye scene 20 preview | +| 21 | 00:01:19.913 | GoldenEye scene 21 preview | +| 22 | 00:01:21.999 | GoldenEye scene 22 preview | ## Splitting Video into Clips -The `split-video` command can be used to automatically split the input video using `ffmpeg` or `mkvmerge`. For example: +Use the `split-video` command to split the input video with `ffmpeg` or `mkvmerge`: ```bash scenedetect -i goldeneye.mp4 split-video ``` -Type `scenedetect split-video --help` for a full list of options which can be specified for video splitting, including high quality mode (`-hq/--high-quality`) or copy mode (`-c/--copy`). +By default, `split-video` re-encodes each clip with `ffmpeg` for frame-accurate cuts. You can adjust encoding quality with `-hq` / `--high-quality` (near-lossless), `-p` / `--preset`, and `-crf` / `--rate-factor`. -You can also specify `-h` / `--high-quality` to produces near lossless results, or `-p`/`--preset` and `-crf`/`--rate-factor` (call `scenedetect help split-video` for details). If either `-c`/`--copy` or `-m`/`--mkvmerge` is specified, codec copying mode is used, at the expense of frame accurate cuts. Optionally, you can also specify the x264 `-p`/`--preset` and `-crf`/`--rate-factor` (see `scenedetect split-video --help` for details). +For faster splitting without re-encoding, pass `-c` / `--copy` (uses `ffmpeg` stream copy) or `-m` / `--mkvmerge` (uses `mkvmerge`). Stream copy splits only on keyframes, so clip boundaries may not be frame-accurate. Run `scenedetect split-video --help` for all options. +## Detectors -## Detection Methods +PySceneDetect includes five detectors: -PySceneDetect can look for fades in/out using `detect-threshold` (comparing each frame to a set black level) or find fast cuts using `detect-content` (compares each frame looking for changes in content). There also is `detect-adaptive`, which uses the same scoring as `detect-content`, but compares the ratio of each frame score to its neighbors. +- `detect-adaptive` (default): finds fast cuts by comparing each frame's content score against a rolling average of nearby frames. +- `detect-content`: finds fast cuts by comparing differences in HSV color and optional edges between adjacent frames. +- `detect-hash`: finds fast cuts by comparing perceptual hashes of adjacent frames. +- `detect-hist`: finds fast cuts by comparing Y-channel (brightness) histograms of adjacent frames. +- `detect-threshold`: finds fades to and from black by comparing average frame brightness against a threshold. -Each mode has slightly different parameters, and is described in detail below. Most detector parameters can also be [set with a config file](https://www.scenedetect.com/docs/latest/cli/config_file.html). +Most detector options can also be set in a [config file](/docs/latest/cli/config_file.html). -In general, use `detect-threshold` mode if you want to detect scene boundaries using fades/cuts in/out to black. If the video uses a lot of fast cuts between content, and has no well-defined scene boundaries, you should use the `detect-adaptive` or `detect-content` modes. Once you know what detection mode to use, you can try the parameters recommended below, or generate a statistics file (using the `-s` / `--stats` flag) in order to determine the correct parameters - specifically, the proper threshold value. +Use `detect-adaptive` or `detect-content` for videos with fast cuts between scenes. Use `detect-threshold` for videos separated by fades to black. If the default settings miss cuts or report false cuts, generate a stats file with `-s` / `--stats` to choose a better threshold. +### Adaptive detector -### Content-Aware Detection +`detect-adaptive` compares each frame's `content_val` score against the average of nearby frames and records the ratio in the stats file under `adaptive_ratio (w=2)` (the `w=` suffix matches `--frame-window`). This reduces false cuts during fast camera movement. Adjust the window size with `--frame-window` and the minimum content score with `--min-content-val`. -Unlike threshold mode, content-aware mode looks at the *difference* between each pair of adjacent frames, triggering a scene break when this difference exceeds the threshold value. +### Content detector -The optimal threshold can be determined by generating a stats file (`-s`), opening it with a spreadsheet editor (e.g. Excel), and examining the `content_val` column ([example](img/goldeneye-stats.png)). This value should be very small between similar frames, and grow large when a big change in content is noticed (look at the values near frame numbers/times where you know a scene change occurs). The threshold value should be set so that most scenes fall below the threshold value, and scenes where changes occur should *exceed* the threshold value (thus triggering a scene change). +`detect-content` measures the difference between each pair of adjacent frames and records a cut when the difference exceeds the threshold (default: `27.0`). +To find the best threshold, generate a stats file with `-s`, open it in a spreadsheet editor, and check the `content_val` column ([example](img/goldeneye-stats.png)). This value stays low within a scene and spikes when the scene changes. Choose a threshold above normal motion scores and below the spikes at real cuts. -### Threshold Detection +### Threshold detector -Threshold-based mode is what most traditional scene detection programs use, which looks at the average intensity of the *current* frame, triggering a scene break when the intensity falls below the threshold (or crosses back upwards). The default threshold when using the `detect-threshold` is `12` (e.g. `detect-threshold` is the same as `detect-threshold --threshold 12` when the `-t` / `--threshold` option is not supplied), which is a good value to try when detecting fade outs to black on most videos. +`detect-threshold` measures the average RGB brightness of each frame (from `0.0` to `255.0`) and records a fade event when brightness crosses the threshold. The default threshold is `12.0`: ```bash -scenedetect -i my_video.mp4 -s my_video.stats.mp4 detect-threshold +scenedetect -i video.mp4 -s video.stats.csv detect-threshold ``` ```bash -scenedetect -i my_video.mp4 -s my_video.stats.mp4 detect-threshold -t 20 +scenedetect -i video.mp4 -s video.stats.csv detect-threshold -t 20 ``` -Using values for threshold less than `8` may cause problems with some videos, especially those encoded at lower bitrates or with limited dynamic range. - -The optimal threshold can be determined by generating a statsfile (`-s`), opening it with a spreadsheet editor (e.g. Excel), and examining the `delta_rgb` column. These values represent the average intensity of the pixels for that particular frame (taken by averaging the R, G, and B values over the whole frame). The threshold value should be set so that the average intensity of most frames in content scenes lie above the threshold value, and scenes where scene changes/breaks occur should fall *under* the threshold value (thus triggering a scene change). - +Thresholds below `8.0` can cause missed detections on videos with low bitrates or limited brightness range. -### Adaptive Detection +To tune the threshold, generate a stats file with `-s` and inspect the `average_rgb` column in a spreadsheet editor. Choose a threshold below the brightness of normal scenes and above the dark fade frames. -The `detect-adaptive` mode compares each frame's score as calculated by `detect-content` with its neighbors. This score is what forms the `adaptive_ratio` metric in the statsfile. You can also configure the amount of neighboring frames via the `frame-window` option, as well as the minimum change in `content_val` score using `min-content-val`. +## Detector Options +You can configure detector options on the [command line](/docs/latest/cli.html#detectors) or in a [config file](/docs/latest/cli/config_file.html). -## Detection Parameters - -Detectors take a variety of parameters, which can be [configured via command-line](https://www.scenedetect.com/docs/latest/cli.html#detectors) or by [using a config file](https://www.scenedetect.com/docs/latest/cli/config_file.html). If the default parameters do not produce correct results, you can generate a stats file using the `-s` / `--stats` option. - -For example, with `detect-content`, if the default threshold of `27` does not produce correct results, we can determine the proper threshold by first generating a stats file: +If the default threshold does not give the results you want, generate a stats file first: ```bash scenedetect --input goldeneye.mp4 --stats goldeneye.stats.csv detect-adaptive ``` -We can then plot the values of the `content_val` column: +Then plot the `content_val` or `adaptive_ratio (w=2)` column from `goldeneye.stats.csv`: goldeneye.mp4 statistics graph -The peaks in values correspond to the scene breaks in the input video. In some cases the threshold may need to be raised or lowered accordingly. +Peaks in the graph match the scene cuts in the video. For fast-cut detectors, raise the threshold to reduce false cuts or lower it to catch missed cuts. For `detect-threshold`, do the opposite: raise `-t` to catch more fades or lower it to reduce false detections. ## Saving Image Previews of Detected Scenes -PySceneDetect can automatically save the beginning and ending frame of each detected scene by using the `save-images` command. If present, the first and last frames of each scene will be saved in the current working directory, using the filename of the input video. - -Files marked `00` represent the starting frame of the scene, and those marked `01` represent the last frame (e.g. `testvideo.mp4.Scene-4-01.jpg`). By default, two images are generated. - -Coming soon: If more are specified via the `-n` flag, they will start from `00` (the first frame) and be evenly spaced throughout the scene until the last frame, which will be numbered `N-1`. - - -## Improving Processing Speed/Performance - -The following arguments are global program options, and need to be applied before any commands (e.g. `detect-content`, `list-scenes`). They can be used to achieve performance gains for some source material with a variable loss of accuracy. +Use `save-images` to save still frames from each detected scene in your working directory (or the folder set with `-o` / `--output`). -Assuming the input video is of a high enough resolution, a significant performance gain can be achieved by sub-sampling (down-scaling) the input image by a specific integer factor (2x, 3x, 4x, 5x...). This is applied automatically to some degree based on the input video size, but can be overridden manually with the `-d` / `--downscale` option. +By default, `save-images` saves three JPEG images per scene (start, middle, and end), numbered `01`, `02`, and `03` (for example, `goldeneye-Scene-001-01.jpg`). Use `-n` / `--num-images` to choose a different fixed count per scene, or `-i` / `--interval` to save one image per time interval so longer scenes produce more images. Run `scenedetect save-images --help` for format, size, and quality options. -This factor represents how many pixels are "skipped" in both the x- and y- directions, effectively down-scaling the image (using nearest-neighbor sampling) by the factor specified (the new resolution being `W/factor x H/factor` if the old resolution is `W x H`). +## Improving Processing Speed -Another method that can be used to gain a performance boost is frame skipping. This method, however, severely reduces frame-accurate scene cuts, so it should only be used with high FPS material (ideally > 60 FPS), at low values (try not to exceed a value of `1` or `2` if using `-fs` / `--frame-skip`), in cases where this is acceptable. Using the frame skip option also disallows the use of a stats file, which offsets the speed gain if the same video needs to be processed multiple times (e.g. to determine the optimal threshold). +These global options go before any command (such as `detect-adaptive` or `list-scenes`). They speed up processing at the cost of some accuracy: -The option still remains, however, for the set of cases where it is still required. For example, if we skip every other frame (e.g. using `--frame-skip 1`), the processing speed should roughly double. +- **Downscaling (`-d` / `--downscale`)**: shrinks each frame by an integer factor (`2`, `3`, `4`, and so on) before analysis. By default, PySceneDetect picks a downscale factor automatically based on video resolution. Pass `-d 1` to disable downscaling, or a higher integer to process frames faster. +- **Frame skipping (`-fs` / `--frame-skip`)**: skips `N` frames after every processed frame. For example, `--frame-skip 1` processes every second frame and roughly doubles speed. -If set too large, enough frames may be skipped each time that the threshold is met during every iteration, continually triggering scene changes. This is because frame skipping essentially raises the threshold between frames in the same scene (making them more likely to appear as *cuts*) while not affecting the threshold between frames of different scenes. +Frame skipping reduces cut accuracy. You cannot use it together with a stats file (`-s` / `--stats`). Because skipped frames increase the difference between adjacent processed frames, large values can cause false cuts even inside the same scene. Use `-fs` only on high-frame-rate video (above 60 FPS) with small values such as `1` or `2`. -This makes the two harder to distinguish, and can cause additional false scene cuts to be detected. While this can be compensated for by raising the threshold value, this increases the probability of missing a real/true scene cut - thus, the use of the `-fs` / `--frame-skip` option is discouraged. +## Seeking, Duration, and Start / End Times +Use the `time` command to analyze only part of a video. It accepts three options: -## Seeking, Duration, and Setting Start / Stop Times +- `-s` / `--start`: where to begin detection. +- `-e` / `--end`: where to stop detection. +- `-d` / `--duration`: how much video to process after the start time. -Specifying the `time` command allows control over what portion of the video PySceneDetect processes. The `time` command accepts three options: start time (`-s` / `-start`), end time (`-e` / `-end`), and duration (`-d` / `--duration`). Specifying both end time and duration is redundant, and in this case, duration overrides end time. Timecodes can be given in seconds (`100.0`), frames (no decimal place, `100`), or timecode as `HH:MM:SS[.nnn]` (`12:34:56.789`). +Set either `--end` or `--duration`, not both. You can write times in seconds (`100.0` or `100s`), frames (`100`), or `HH:MM:SS[.nnn]` timecode (`00:05:00.000`). -For example, let's say we have a video shot at 30 FPS, and want to analyze only the segment from the 5 to the 6.5 minute mark in the video (we want to analyze the 90 seconds [2700 frames] between 00:05:00 and 00:06:30). The following commands are all thus equivalent in this regard (assuming we are using the content detector): +For a 30 FPS video, all four commands below analyze the same 90-second segment (2700 frames) between `00:05:00` and `00:06:30`: ```bash -scenedetect -i my_video.mp4 time --start 00:05:00 --end 00:06:30 +scenedetect -i video.mp4 time --start 00:05:00 --end 00:06:30 ``` ```bash -scenedetect -i my_video.mp4 time --start 300s --end 390s +scenedetect -i video.mp4 time --start 300s --end 390s ``` ```bash -scenedetect -i my_video.mp4 time --start 300s --duration 90s +scenedetect -i video.mp4 time --start 300s --duration 90s ``` ```bash -scenedetect -i my_video.mp4 time --start 300s --duration 2700 +scenedetect -i video.mp4 time --start 300s --duration 2700 ``` -This demonstrates the different timecode formats, interchanging end time with duration and vice-versa, and precedence of setting duration over end time. - - ## Config File -A configuration file path can be specified using the `-c`/`--config` argument. PySceneDetect also looks for a config file named `scenedetect.cfg` in one of the following locations: - - * Windows: - * `C:/Users/%USERNAME%/AppData/Local/PySceneDetect/scenedetect.cfg` - - * Linux: - * `~/.config/PySceneDetect/scenedetect.cfg` - * `$XDG_CONFIG_HOME/scenedetect.cfg` +Pass a config file path with `-c` / `--config`. If you do not pass `-c`, PySceneDetect checks for `scenedetect.cfg` in your platform's default user config folder: - * Mac: - * `~/Library/Preferences/PySceneDetect/scenedetect.cfg` +- Windows: + - `C:/Users/%USERNAME%/AppData/Local/PySceneDetect/scenedetect.cfg` +- Linux: + - `~/.config/PySceneDetect/scenedetect.cfg` + - `$XDG_CONFIG_HOME/PySceneDetect/scenedetect.cfg` +- macOS: + - `~/Library/Application Support/PySceneDetect/scenedetect.cfg` -Run `scenedetect --help` to see the exact path on your system which will be used (it will be listed under the help text for the -c/--config option). You can [click here to download a `scenedetect.cfg` config file](https://raw.githubusercontent.com/Breakthrough/PySceneDetect/v0.6.4-release/scenedetect.cfg) to use as a template. Note that lines starting with a `#` are comments and will be ignored. The `scenedetect.cfg` template file is also available in the folder where PySceneDetect is installed. +Run `scenedetect --help` to see the exact path on your system under the `-c` / `--config` help text. You can [download the `scenedetect.cfg` template from GitHub](https://github.com/Breakthrough/PySceneDetect/blob/latest/scenedetect.cfg), or copy it from the PySceneDetect installation folder when using the Windows builds. Lines starting with `#` are comments and are ignored. -Specifying a config file path using -c/--config overrides the user config file. Specifying values on the command line will override those values in the config file. +Options passed on the command line override values in the config file, and `-c` / `--config` overrides the default user config file. -The syntax of a configuration file is: +Config files use INI syntax: ```ini [command] option_a = value -#comment +# comment option_b = 1 ``` @@ -219,7 +206,7 @@ weights = 1.0 0.5 1.0 0.2 [split-video] preset = slow rate-factor = 17 -# Don't need to use quotes even if filename contains spaces +# Quotes are not needed even if the filename contains spaces filename = $VIDEO_NAME-Clip-$SCENE_NUMBER [save-images] @@ -228,38 +215,28 @@ quality = 80 num-images = 3 ``` -See the `scenedetect.cfg` file in the location you installed PySceneDetect or [download it from Github](https://raw.githubusercontent.com/Breakthrough/PySceneDetect/v0.6.4-release/scenedetect.cfg) for a complete listing of all configuration options. +See the [Configuration File Reference](/docs/latest/cli/config_file.html) or [the `scenedetect.cfg` template on GitHub](https://github.com/Breakthrough/PySceneDetect/blob/latest/scenedetect.cfg) for every available key. +## Video Splitting Requirements -##   Video Splitting Requirements - -PySceneDetect can use either `ffmpeg` or `mkvmerge` to split videos automatically. - -By default, when specifying the `split-video` command, `ffmpeg` will be used to split the video. If the `-c`/`--copy` option is also set (e.g. `split-video --copy`), `mkvmerge` will be used to split the video instead. +PySceneDetect uses `ffmpeg` or `mkvmerge` to split videos: +- `split-video` (default): uses `ffmpeg` and re-encodes for frame-accurate splits. +- `split-video -c` / `--copy`: uses `ffmpeg` in stream-copy mode. +- `split-video -m` / `--mkvmerge`: uses `mkvmerge` in stream-copy mode. ### FFmpeg -You can download `ffmpeg` from: [https://ffmpeg.org/download.html](https://ffmpeg.org/download.html) - -Note that Linux users should use a package manager (e.g. `sudo apt-get install ffmpeg`). Windows users may require additional steps in order for PySceneDetect to detect `ffmpeg` - see the section Manually Enabling `split-video` Support below for details. - +Download `ffmpeg` from [FFmpeg](https://ffmpeg.org/download.html). On Linux, install it with your package manager (for example, `sudo apt-get install ffmpeg`). On Windows, the PySceneDetect builds bundle `ffmpeg`; otherwise follow the steps below. ### mkvmerge -You can download and install `mkvmerge` as part of the mkvtoolnix package from: -[https://mkvtoolnix.download/downloads.html](https://mkvtoolnix.download/downloads.html) - -Note that Windows users should use the installer/setup, and Linux users should use their system package manager, otherwise PySceneDetect may not be able to find `mkvmerge`. If this is the case, see the section below to enable support for the `split-video --copy` command manually. - - -### Enabling `split-video` Support - -If PySceneDetect cannot find the respective tool installed on your system, you have three options: - - 1. Place the tool in the same location that PySceneDetect is installed (e.g. copy and paste mkvmerge.exe into the same place scenedetect.exe is located). This is the easiest solution for most users. +Download `mkvmerge` as part of [MKVToolNix](https://mkvtoolnix.download/downloads.html). Use the installer on Windows or your system package manager on Linux so PySceneDetect can find `mkvmerge` automatically. - 2. Add the directory where you installed ffmpeg/mkvmerge to your system's PATH environment variable, ensuring that you can use the ffmpeg/mkvmerge command from any terminal/command prompt. This is the best solution for advanced users. +### Enabling `split-video` support - 3. Place the tool in a location already in your system's PATH variable (e.g. C:/Windows). This is not recommended, but may be the only solution on systems without administrative rights. +If PySceneDetect cannot find `ffmpeg` or `mkvmerge`, use one of these approaches: +1. Add the folder containing `ffmpeg` or `mkvmerge` to your system `PATH` environment variable so it works from any terminal (recommended). +2. Copy `ffmpeg` or `mkvmerge` into the same folder where `scenedetect` is installed (on Windows with `pip`, typically `C:\PythonXY\Scripts`) if you prefer not to edit `PATH`. +3. Copy the executable into a folder already on `PATH` if neither of the above is possible. diff --git a/website/pages/contributing.md b/website/pages/contributing.md index 7e3f55d9..d561a149 100644 --- a/website/pages/contributing.md +++ b/website/pages/contributing.md @@ -1,48 +1,66 @@ +# Contributing & Support -##   Bug Reports +## Reporting Bugs -Bugs, issues, features, and improvements to PySceneDetect are handled through [the issue tracker on Github](https://github.com/Breakthrough/PySceneDetect/issues). If you run into any bugs using PySceneDetect, please [create a new issue](https://github.com/Breakthrough/PySceneDetect/issues/new/choose). +Report bugs and request features on [the PySceneDetect issue tracker on GitHub](https://github.com/Breakthrough/PySceneDetect/issues). Before [opening a new issue](https://github.com/Breakthrough/PySceneDetect/issues/new/choose), search [existing issues](https://github.com/Breakthrough/PySceneDetect/issues?q=) to check for known fixes or workarounds. Adding reproduction details to an existing report is also helpful. -Try to [find an existing issue](https://github.com/Breakthrough/PySceneDetect/issues?q=) before creating a new one, as there may be a workaround posted there. Additional information is also helpful for existing reports. +## Contributing Code -##   Contributing to Development +PySceneDetect development takes place at [github.com/Breakthrough/PySceneDetect](https://github.com/Breakthrough/PySceneDetect). Pull requests are welcome. When possible, link each pull request to an entry on [the issue tracker](https://github.com/Breakthrough/PySceneDetect/issues?q=). -Development of PySceneDetect happens on [github.com/Breakthrough/PySceneDetect](https://github.com/Breakthrough/PySceneDetect). Pull requests are accepted and encouraged. Where possible, PRs should be submitted with a dedicated entry in [the issue tracker](https://github.com/Breakthrough/PySceneDetect/issues?q=). Issues and features are typically grouped into version milestones. +Before submitting a pull request, check that your changes meet these requirements: -The following checklist covers the basics of pre-submission requirements: +- All unit tests pass (`pytest`). +- Linting and formatting checks pass (`ruff check` and `ruff format`). +- New public APIs include type hints and docstrings with `Arguments:` / `Returns:` sections. - - Code passes all unit tests (run `pytest`) - - Code passes static analysis and formatting checks (`ruff check` and `ruff format`) - - Follows the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html) +When working on repository branches, use a descriptive prefix matching the change: `feature/`, `issue/-`, `fix/`, `docs/`, or `website/` for website updates. -Note that PySceneDetect is released under the BSD 3-Clause license, and submitted code should comply with this license (see [License & Copyright Information](copyright.md) for details). +PySceneDetect is released under the BSD 3-Clause License, and all submitted code must comply with this license (see [License & Copyright](copyright.md)). -##   Features That Need Help +## Features That Need Help -The following is a "wishlist" of features which PySceneDetect eventually should have, but does not currently due to lack of resources. Anyone who is able to contribute in any capacity to these items is encouraged to do so by starting a dialogue by opening a new issue on Github as per above. +These areas are open for community contributions. Open an issue on GitHub to discuss an approach before writing a large change. -### Flash Suppression +### Flash suppression -Some detection methods struggle with bright flashes and fast camera movement. The detection pipeline has some filters in place to deal with these cases, but there are still drawbacks. We are actively seeking methods which can improve both performance and accuracy in these cases. +Bright flashes and fast camera movement can still trigger false cuts in some videos. Contributions that improve both accuracy and speed for these cases are welcome. -### Automatic Thresholding +### Automatic thresholding -The `detect-content` command requires a manual threshold to be set currently. Methods to use peak detection to dynamically determine when scene cuts occur would allow for the program to work with a much wider amount of material without requiring manual tuning, but would require statistical analysis. +`detect-content` currently requires a fixed threshold. Peak-detection methods that estimate a threshold automatically (for example, `--threshold=auto`) would reduce manual tuning across diverse videos. -Ideally, this would be something like `-threshold=auto` as a default. +### Dissolve detection -### Dissolve Detection +Detection accuracy on slow dissolves varies with transition length and detector settings. Better dissolve detection with low performance overhead remains an open problem. -Depending on the length of the dissolve and parameters being used, detection accuracy for these types of cuts can vary widely. A method to improve accuracy with minimal performance loss is an open problem. +### New detectors -### Advanced Strategies +Research and prototypes for faster or more accurate detectors are always welcome. -Research into detection methods and performance are ongoing. All contributions in this regard are most welcome. +### Graphical user interface (GUI) -### GUI - -A graphical user interface will be crucial for making PySceneDetect approachable by a wider audience. There have been several suggested designs, but nothing concrete has been developed yet. Any proposed solution for the GUI should work across Windows, Linux, and OSX. +A cross-platform GUI for Windows, Linux, and macOS would make PySceneDetect easier for non-technical users. No official GUI has been built yet. ### Localization -PySceneDetect currently is not localized for other languages. Anyone who can help improve how localization can be approached for development material is encouraged to contribute in any way possible. Whether it is the GUI program, the command line interface, or documentation, localization will allow PySceneDetect to be used by much more users in their native languages. \ No newline at end of file +PySceneDetect is currently available only in English. Contributions to support localization in the CLI, documentation, or a future GUI will help more people use PySceneDetect in their own language. + +## Project Support and Credits + +PySceneDetect is built and distributed with help from the tools, services, and contributors below. Listing these services gives credit for their support and does not imply endorsement. + +### Tools and services + +- [GitHub](https://github.com/): Git hosting, website hosting, code review, issue tracking, and CI builds. +- [AppVeyor](https://www.appveyor.com/): Windows portable and MSI builds. +- [Advanced Installer](https://www.advancedinstaller.com/): Windows MSI installer packaging. +- [SignPath](https://signpath.io/): free code signing for Windows builds. + +### Community contributions + +Thank you to everyone who has submitted bug reports, feature requests, documentation fixes, and pull requests. You can view the contributor list on [the GitHub contributors page](https://github.com/Breakthrough/PySceneDetect/graphs/contributors). + +### Donations + +PySceneDetect does not accept monetary donations. The best ways to support the project are reporting bugs, improving docs, and contributing code. If you can offer tools, hosting, or testing resources that help development, open an issue on GitHub or reach out through [bcastell.com/contact](https://bcastell.com/contact/). diff --git a/website/pages/copyright.md b/website/pages/copyright.md index d522083c..86a19eb6 100644 --- a/website/pages/copyright.md +++ b/website/pages/copyright.md @@ -1,3 +1,4 @@ +# License & Copyright ## PySceneDetect License Agreement @@ -38,53 +39,59 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ``` +## Third-Party Software Licenses -## Ancillary Software Licenses - -This section contains links to the license agreements for all third-party software libraries used and distributed with PySceneDetect. You can find copies of all the relevant license agreements referenced below if you installed a copy of PySceneDetect by looking at the LICENSE files in the installation directory. +This section lists license links for third-party libraries used by or distributed with PySceneDetect. Windows builds include copies of bundled third-party licenses in the `thirdparty/` folder (also available in `scenedetect/_thirdparty/` in the source repository). ----------------------------------------------------------------------- +### Click + +- Copyright (C) 2017, Armin Ronacher. +- License: [https://click.palletsprojects.com/en/stable/license/](https://click.palletsprojects.com/en/stable/license/) -### click +### MoviePy - - Copyright (C) 2017, Armin Ronacher. - - URL: http://click.pocoo.org/license/ +- Copyright (C) 2015, Zulko. +- License: [https://github.com/Zulko/moviepy/blob/master/LICENCE.txt](https://github.com/Zulko/moviepy/blob/master/LICENCE.txt) ### NumPy - - Copyright (C) 2005-2016, NumPy Developers. - - URL: http://www.numpy.org/license.html +- Copyright (C) 2005-2016, NumPy Developers. +- License: [https://numpy.org/doc/stable/license.html](https://numpy.org/doc/stable/license.html) ### OpenCV - - Copyright (C) 2017, Itseez. - - URL: http://opencv.org/license.html +- Copyright (C) 2017, Itseez. +- License: [https://opencv.org/license/](https://opencv.org/license/) + +### platformdirs + +- Copyright (C) The platformdirs developers. +- License: [https://github.com/tox-dev/platformdirs/blob/main/LICENSE](https://github.com/tox-dev/platformdirs/blob/main/LICENSE) ### PyAV - - Copyright (C) 2017, Mike Boers and others - - URL: https://github.com/PyAV-Org/PyAV/blob/main/LICENSE.txt + +- Copyright (C) 2017, Mike Boers and others. +- License: [https://github.com/PyAV-Org/PyAV/blob/main/LICENSE.txt](https://github.com/PyAV-Org/PyAV/blob/main/LICENSE.txt) ### simpletable - - Copyright (C) 2014-2019, Matheus Vieira Portela and others - - URL: https://github.com/matheusportela/simpletable/blob/master/LICENSE +- Copyright (C) 2014-2019, Matheus Vieira Portela and others. +- License: [https://github.com/matheusportela/simpletable/blob/master/LICENSE](https://github.com/matheusportela/simpletable/blob/master/LICENSE) ### tqdm - - Copyright (C) 2013-2018, Casper da Costa-Luis, Google Inc., and Noam Yorav-Raphael. - - URL: https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE - +- Copyright (C) 2013-2018, Casper da Costa-Luis, Google Inc., and Noam Yorav-Raphael. +- License: [https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE](https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE) ----------------------------------------------------------------------- ### FFmpeg and mkvmerge -This software may also invoke mkvmerge or FFmpeg, if available. +PySceneDetect may also invoke `ffmpeg` or `mkvmerge` if they are installed. FFmpeg is a trademark of Fabrice Bellard. -mkvmerge is Copyright (C) 2005-2016, Matroska. - -Certain distributions of PySceneDetect may include ffmpeg. See the -thirdparty/LICENSE-FFMPEG file or visit [ https://ffmpeg.org ]. +`mkvmerge` is part of [MKVToolNix](https://mkvtoolnix.download/) by Moritz Bunkus, licensed under the GNU General Public License v2. +Windows builds and the Docker image bundle `ffmpeg` (the Docker image also includes `mkvmerge`). In Windows builds, see `thirdparty/LICENSE-FFMPEG` or visit [ffmpeg.org](https://ffmpeg.org). diff --git a/website/pages/docs.md b/website/pages/docs.md index 407efe94..c30a05a8 100644 --- a/website/pages/docs.md +++ b/website/pages/docs.md @@ -1,24 +1,25 @@ +# Documentation Versions -# Documentation +Select a version below to open the PySceneDetect Reference Manual (CLI and Python API). Most users should start with [latest](/docs/latest/). ## Stable - * [latest](latest/) - * [v0.7.3](0.7.3/) - * [v0.7.2](0.7.2/) - * [v0.7.1](0.7.1/) - * [v0.7](0.7/) +- [latest](/docs/latest/) +- [v0.7.3](/docs/0.7.3/) +- [v0.7.2](/docs/0.7.2/) +- [v0.7.1](/docs/0.7.1/) +- [v0.7](/docs/0.7/) ## Development - * [head](head/) +- [head](/docs/head/) ## Legacy - * [v0.6.7](0.6.7/) - * [v0.6.6](0.6.6/) - * [v0.6.5](0.6.5/) - * [v0.6.4](0.6.4/) - * [v0.6.3](0.6.3/) - * [v0.6.2](0.6.2/) - * [v0.6.1](0.6.1/) +- [v0.6.7](/docs/0.6.7/) +- [v0.6.6](/docs/0.6.6/) +- [v0.6.5](/docs/0.6.5/) +- [v0.6.4](/docs/0.6.4/) +- [v0.6.3](/docs/0.6.3/) +- [v0.6.2](/docs/0.6.2/) +- [v0.6.1](/docs/0.6.1/) diff --git a/website/pages/download.md b/website/pages/download.md index 77b01c85..1559d51d 100644 --- a/website/pages/download.md +++ b/website/pages/download.md @@ -1,94 +1,130 @@ - # Download -PySceneDetect is completely free software, and can be downloaded from the links below. See the [license and copyright information](copyright.md) page for details. If you have trouble running PySceneDetect, ensure that you have all the required dependencies listed in the [Dependencies](#dependencies) section below. +PySceneDetect is free, open-source software released under the BSD 3-Clause License (see [License & Copyright](copyright.md)). If you have trouble running PySceneDetect, verify that you have the packages listed under [Dependencies](#dependencies). + +## Windows Build (64-bit Only) + +
+
+ + + Windows 64-bit · v0.7.3 + + November 8, 2026 +
+ +
-PySceneDetect requires at least Python 3.10 or higher. +The `.msi` installer is recommended for most Windows users. Both Windows builds bundle `ffmpeg`. To use `split-video -m`, install MKVToolNix. After installing, see the [Command-Line Interface](cli.md) guide to get started. +## Install with pip, uv, or pipx -## Install via pip       +Installing from PyPI requires Python 3.10 or newer. -
-

Standard install (recommended):

-
pip install --upgrade scenedetect
-

Headless install (servers, no GUI libs):

-
pip install --upgrade scenedetect-headless
-
+Standard install with `pip` (CLI and Python API): -PySceneDetect is available via `pip` as two packages: +```bash +pip install --upgrade scenedetect +``` - - [`scenedetect`](https://pypi.org/project/scenedetect/): full install with the CLI, depends on `opencv-python` - - [`scenedetect-headless`](https://pypi.org/project/scenedetect-headless/): full install with the CLI, depends on `opencv-python-headless` (servers/containers without GUI libraries) +Headless install (for servers and containers without GUI libraries): -Both provide the same `scenedetect` Python module -- install only one of them. +```bash +pip install --upgrade scenedetect-headless +``` -## Windows Build (64-bit Only)   +Install with `uv` or `pipx`: -
-

Latest Release: v0.7.3

-

  Release Date:  November 8, 2026

-  Installer  (recommended)      -  Portable .zip      -  Getting Started -
+```bash +# uv (isolated CLI tool) +uv tool install scenedetect -## Docker Image   +# uv (add to a Python project) +uv add scenedetect -Official container images are published at [ghcr.io/breakthrough/pyscenedetect](https://github.com/breakthrough/PySceneDetect/pkgs/container/pyscenedetect). The image includes the full CLI, all optional backends (PyAV, MoviePy), and the external tools used for video splitting (`ffmpeg`, `mkvmerge`) -- no other setup is required: +# pipx (isolated CLI tool) +pipx install scenedetect +``` + +PySceneDetect is published on PyPI as two packages, both including the CLI and the `scenedetect` Python module: + +- [`scenedetect`](https://pypi.org/project/scenedetect/): depends on `opencv-python`. +- [`scenedetect-headless`](https://pypi.org/project/scenedetect-headless/): depends on `opencv-python-headless`. + +Install only one of them. + +## Docker Image + +Official container images are published on GitHub Container Registry at [ghcr.io/breakthrough/pyscenedetect](https://github.com/Breakthrough/PySceneDetect/pkgs/container/pyscenedetect). Each image includes the CLI, all optional video backends (PyAV and MoviePy), `ffmpeg`, and `mkvmerge`: ```bash docker pull ghcr.io/breakthrough/pyscenedetect docker run --rm ghcr.io/breakthrough/pyscenedetect version ``` -To process videos, mount the folder containing them into the container (the image runs as a non-root user, so output files are written with regular permissions): +To process videos, mount the folder that holds them into the container. The container runs as a non-root user, so output files keep normal permissions: ```bash docker run --rm -v "$(pwd):/files" ghcr.io/breakthrough/pyscenedetect \ -i /files/video.mp4 detect-adaptive split-video -o /files ``` -The `latest` tag (the default when no tag is given) points to the most recent recommended build, the `main` tag tracks the development branch, and version tags (e.g. `0.7.3`) point to specific releases. `podman` can be used in place of `docker` in the commands above. +The `latest` tag points to the most recent stable release, `main` tracks the development branch, and version tags (such as `0.7.3`) point to specific releases. You can also replace `docker` with `podman` in the commands above. -## Post Installation +## Post-Installation Check -After installation, you can call PySceneDetect from any terminal/command prompt by typing `scenedetect` (try running `scenedetect --help`, or `scenedetect version`). If you encounter any runtime errors while running PySceneDetect, ensure that you have all the required dependencies listed in the System Requirements section above (you should be able to `import numpy` and `import cv2`). If you encounter any issues or want to make a feature request, feel free to [report any bugs or share some feature requests/ideas](contributing.md) on the [issue tracker](https://github.com/Breakthrough/PySceneDetect/issues) and help make PySceneDetect even better. +After installing, open a terminal and run `scenedetect version` or `scenedetect --help`. If you see an import error, verify that `import numpy` and `import cv2` work in Python and review [Dependencies](#dependencies). +If you find a bug or want to suggest a feature, open an issue on [the issue tracker](https://github.com/Breakthrough/PySceneDetect/issues) or see [Contributing & Support](contributing.md). ## Dependencies -### Python Packages - -PySceneDetect requires [Python 3](https://www.python.org/) and the following packages, all of which the `scenedetect` and `scenedetect-headless` packages install automatically: - - - [OpenCV](http://opencv.org/): `pip install opencv-python` (any `opencv-python*` variant works) - - [Numpy](https://numpy.org/): `pip install numpy` - - [Click](https://click.palletsprojects.com): `pip install click` (command-line interface only) - - [tqdm](https://github.com/tqdm/tqdm): `pip install tqdm` (optional, enables progress bars) - - [platformdirs](https://github.com/tox-dev/platformdirs): `pip install platformdirs` (command-line interface only) +### Python packages -Optional packages: +The `scenedetect` and `scenedetect-headless` packages install these dependencies automatically: - - [PyAV](https://pyav.org/): `pip install av` +- [OpenCV](https://opencv.org/): `pip install opencv-python` (or `opencv-python-headless` with `scenedetect-headless`) +- [NumPy](https://numpy.org/): `pip install numpy` +- [Click](https://click.palletsprojects.com): `pip install click` (used by the CLI) +- [tqdm](https://github.com/tqdm/tqdm): `pip install tqdm` (displays progress bars) +- [platformdirs](https://github.com/tox-dev/platformdirs): `pip install platformdirs` (used by the CLI) -### Video Splitting Tools +Optional video backend packages: -For video splitting support, you need to have one of the following tools available (included in Windows builds): +- [PyAV](https://pyav.org/): `pip install av` (or `pip install "scenedetect[pyav]"`) +- [MoviePy](https://zulko.github.io/moviepy/): `pip install moviepy` (or `pip install "scenedetect[moviepy]"`) - - [ffmpeg](https://ffmpeg.org/download.html), required to split video files (`split-video` or `split-video -c/--copy`) - - [mkvmerge](https://mkvtoolnix.download/), part of mkvtoolnix, command-line tool, required to split video files in stream copy mode (`split-video -c/--copy` only) +### Video splitting tools -The `ffmpeg` and/or `mkvmerge` command must be available system wide (e.g. in a directory in `PATH`, so it can be used from any terminal/console by typing the command), or alternatively, placed in the same directory where PySceneDetect is installed. On Windows this is usually `C:\PythonXY\Scripts`, where `XY` is your Python version. For more information, [see the CLI documentation](cli.md). +To split videos into clips, install at least one of these tools (`ffmpeg` is bundled in the Windows builds; the Docker image has both): -### Building OpenCV from Source +- [FFmpeg](https://ffmpeg.org/download.html): splits videos with re-encoding (`split-video`) or stream copy (`split-video -c` / `--copy`). +- [MKVToolNix](https://mkvtoolnix.download/downloads.html) (`mkvmerge`): splits videos in stream-copy mode (`split-video -m` / `--mkvmerge`). -If you have installed OpenCV using `pip`, you will need to uninstall it before installing a different version of OpenCV, or building and installing it from source. +See [Video Splitting Requirements](cli.md#video-splitting-requirements) for installation and `PATH` setup steps. -You can [click here](http://breakthrough.github.io/Installing-OpenCV/) for a quick guide (OpenCV + Numpy on Windows & Linux) on installing OpenCV/Numpy on [Windows (using pre-built binaries)](http://breakthrough.github.io/Installing-OpenCV/#installing-on-windows-pre-built-binaries) and [Linux (compiling from source)](http://breakthrough.github.io/Installing-OpenCV/#installing-on-linux-compiling-from-source). If the Python module that comes with OpenCV on Windows is incompatible with your system architecture or Python version, [see this page](http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv) to obtain a pre-compiled (unofficial) module. +### Building OpenCV from source -To ensure you have all the requirements installed, open a `python` interpreter, and ensure you can run `import numpy` and `import cv2` without any errors. +If you installed OpenCV with `pip`, uninstall it before installing a different OpenCV build or compiling from source. See the [Installing OpenCV guide](https://breakthrough.github.io/Installing-OpenCV/) for steps on Windows and Linux. +To verify your setup, open a Python prompt and run `import numpy` and `import cv2`. ## Code Signing Policy -This program uses free code signing provided by [SignPath.io](https://signpath.io?utm_source=foundation&utm_medium=website&utm_campaign=PySceneDetect), and a free code signing certificate by the [SignPath Foundation](https://signpath.org?utm_source=foundation&utm_medium=website&utm_campaign=PySceneDetect) +This program uses free code signing provided by [SignPath.io](https://signpath.io?utm_source=foundation&utm_medium=website&utm_campaign=PySceneDetect), and a free code signing certificate by the [SignPath Foundation](https://signpath.org?utm_source=foundation&utm_medium=website&utm_campaign=PySceneDetect). diff --git a/website/pages/faq.md b/website/pages/faq.md index 0756fa33..89f3e51b 100644 --- a/website/pages/faq.md +++ b/website/pages/faq.md @@ -1,56 +1,84 @@ +# Frequently Asked Questions +## Installation and Setup -##   Frequently Asked Questions +### How do I fix `ImportError: No module named cv2`? -#### How can I fix `ImportError: No module named cv2`? - -As of PySceneDetect 0.7, the OpenCV dependency is bundled with the install. The standard `scenedetect` package depends on `opencv-python`: +Since PySceneDetect 0.7, OpenCV is installed automatically. Install the standard package: ```bash pip install scenedetect ``` -For server environments without GUI libraries, install the headless variant instead, which depends on `opencv-python-headless`: +For servers or containers without GUI libraries, install the headless package instead: ```bash pip install scenedetect-headless ``` -Both packages ship the same `scenedetect` Python module -- install only one of them. +Both packages provide the same `scenedetect` Python module. Install only one of them. -For projects that need a different OpenCV variant (e.g. `opencv-contrib-python`), install it *pinned to the same version* as the `opencv-python` variant your scenedetect package pulled in, so the two resolve to identical `cv2` files: +If your project needs a different OpenCV package (such as `opencv-contrib-python`), install the exact same version that `scenedetect` installed so both packages share identical `cv2` files: ```bash pip install scenedetect pip install "opencv-contrib-python==$(pip show opencv-python | grep ^Version | cut -d' ' -f2)" ``` -Mixing OpenCV variants at *different* versions corrupts the shared `cv2` install. First-class support for choosing your own OpenCV variant is tracked in [#558](https://github.com/Breakthrough/PySceneDetect/issues/558). +Mixing different versions of OpenCV packages can break your `cv2` install. See [Issue #558](https://github.com/Breakthrough/PySceneDetect/issues/558) for background. + +### How do I enable video splitting? + +PySceneDetect uses [FFmpeg](https://ffmpeg.org/download.html) or `mkvmerge` from [MKVToolNix](https://mkvtoolnix.download/downloads.html) to split videos. Make sure the executable is on your system `PATH` or in the same folder as `scenedetect`. The Windows builds include `ffmpeg`. The Docker image includes both tools. See [Video Splitting Requirements](cli.md#video-splitting-requirements) for setup steps. + +## Detection and Splitting + +### How do I tune the detection threshold? + +Generate a per-frame stats file with `-s` / `--stats`: + +```bash +scenedetect -i video.mp4 -s video.stats.csv detect-adaptive +``` + +Open `video.stats.csv` in a spreadsheet tool and inspect the metric column for your detector (`adaptive_ratio (w=2)` for `detect-adaptive`, where the `w=` suffix matches `--frame-window`; `content_val` for `detect-content`; or `average_rgb` for `detect-threshold`). + +- For fast-cut detectors (`detect-adaptive`, `detect-content`, `detect-hash`, `detect-hist`), lower the threshold (`-t`) if PySceneDetect misses real cuts, or raise `-t` to reduce false cuts. +- For `detect-threshold`, do the opposite: raise `-t` to find more fades and lower `-t` to reduce false detections. + +See [Detector Options](cli.md#detector-options) for a walkthrough and [Benchmarks](benchmarks.md) for parameter sweep results across datasets. + +### Does PySceneDetect support variable frame rate (VFR) videos? + +Yes. Both the default OpenCV backend and the PyAV backend support VFR videos using presentation timestamps (PTS) instead of assuming a constant frame rate. + +For difficult VFR files, use the PyAV backend (`pip install av`, then pass `-b pyav`), which reads native PTS timestamps directly from the video container. The MoviePy backend does not support VFR video. See [Video Backends](/docs/latest/cli/backends.html) for details. -#### How can I enable video splitting support? +### Should I use stream copy or re-encoding when splitting video? -Video splitting is performed by `ffmpeg` ([https://ffmpeg.org/download.html](https://ffmpeg.org/download.html)) or `mkvmerge` ([https://mkvtoolnix.download/downloads.html](https://mkvtoolnix.download/downloads.html)) depending on which command line arguments are used. Ensure the tool is available and somewhere in your system's PATH folder. +- **Default re-encoding (`split-video`)**: uses `ffmpeg` to re-encode each clip. Cuts are frame-accurate, and you can adjust quality with `-hq` / `--high-quality`, `-crf`, or `-p` / `--preset`. +- **Stream copy (`split-video --copy` or `split-video --mkvmerge`)**: copies the compressed video and audio streams without re-encoding. This is much faster and preserves original quality, but splits can only happen on keyframes, so clip start and end times may shift slightly. -#### How can I fix the error `Cannot split video due to too many scenes`? +## Troubleshooting -This error occurs on Windows platforms specifically when the number of detected scenes is too large. This is because PySceneDetect internally invokes other commands, such as those used for the `split-video` command. +### How do I fix `Cannot split video due to too many scenes`? -You can get around this issue by simply invoking those tools manually, using a smaller sub-set of scenes (or splitting the scene list into multiple parts). You can obtain a comma-separated list of timecodes by using the `list-scenes` command. +On Windows, passing hundreds of scene timecodes to an external command can exceed the operating system's command-line length limit. -See [Issue #164](https://github.com/Breakthrough/PySceneDetect/issues/164) for details, or if you have any further questions. +To work around this limit, export the scene list with `list-scenes` and split the video in smaller batches using `ffmpeg` or `mkvmerge` directly. See [Issue #164](https://github.com/Breakthrough/PySceneDetect/issues/164) for details. -#### How can I fix the error `Failed to read any frames from video file`? +### How do I fix `Failed to read any frames from video file`? -Unfortunately, the underlying library used to perform video I/O was unable to open the file. Try using a different backend by installing PyAV (`pip install av`) and see if the problem persists. +The active video backend could not decode the file. Install PyAV (`pip install av`) and run PySceneDetect with `-b pyav` to test another backend. -This can also happen due to videos having multiple audio tracks (as per [#179](https://github.com/Breakthrough/PySceneDetect/issues/179)). If the PyAV backend does not succeed in processing the video, as a workaround you can remove the audio track using either `ffmpeg` or `mkvmerge`: +Videos with multiple audio tracks can also cause decode failures in OpenCV (see [Issue #179](https://github.com/Breakthrough/PySceneDetect/issues/179)). If PyAV does not help, make a copy of the video without its audio tracks. Then run detection on the copy: ```bash ffmpeg -i input.mp4 -c copy -an output.mp4 ``` -Or: +Or with `mkvmerge`: ```bash -mkvmerge -o output.mkv input.mp4 +mkvmerge -o output.mkv --no-audio input.mp4 ``` diff --git a/website/pages/features.md b/website/pages/features.md index e40b6cc0..dfcff519 100644 --- a/website/pages/features.md +++ b/website/pages/features.md @@ -1,74 +1,63 @@ +# Features ## Overview -
-

  Content-Aware Scene Detection

-    Detects breaks in-between content, not only when the video fades to black (although a threshold mode is available as well for those cases). -
+### Content-aware scene detection -
-

  Compatible With Many External Tools

-    The detected scene boundaries/cuts can be exported in a variety of formats, with the default type (comma-separated HH:MM:SS.nnn values) being ready to copy-and-paste directly into other tools (such as ffmpeg, mkvmerge, etc...) for splitting and/or re-encoding the video. -
+PySceneDetect finds cuts between scenes by comparing frame content, not only fades to black. A threshold detector is also included for detecting fades. -
-

  Statistical Video Analysis

-    Can output a spreadsheet-compatible file for analyzing trends in a particular video file, to determine the optimal threshold values to use with specific scene detection methods/algorithms. -
+### Standard export formats -
-

  Extendible and Embeddable

-    Written in Python, and designed with an easy-to-use and extendable API, PySceneDetect is ideal for embedding into other programs, or to implement custom methods/algorithms of scene detection for specific applications (e.g. analyzing security camera footage). -
+Export detected scene cuts in formats that work directly with video editors and command-line tools. The default comma-separated `HH:MM:SS.nnn` format can be pasted directly into `ffmpeg` or `mkvmerge`. +### Per-frame video analysis ------------------------------------------------------------------------- +Export frame-by-frame metrics to a CSV stats file so you can plot trends in a spreadsheet and pick the best threshold for your video. +### Modular Python API -## Features +PySceneDetect is written in Python with an extensible API. You can embed it in your own applications or write custom detectors for specialized video workflows. - - exports timecodes in standard format (HH:MM:SS.nnn), comma-separated for easy copy-and-paste into external tools and analysis with spreadsheet software - - statistics/analysis mode to export frame-by-frame video metrics via the `-s [FILE]`/`--stats [FILE]` argument (e.g. `--stats metrics.csv`) - - output-suppression (quiet) mode for better automation with external scripts/programs (`-q`/`--quiet`) - - save an image of the first and last frame of each detected scene via the `save-images` command - - split the input video automatically if `ffmpeg` or `mkvmerge` is available via the `split-video` command +------------------------------------------------------------------------ -### Output Formats +## Key Capabilities - - **Chapters**: `save-chapters` command (save as FFmetadata chapters, which can be added to a video with ffmpeg) - - **EDL**: `save-edl` command (save as edit decision list in CMX 3600 format, compatible with most editors) - - **HTML**: `save-html` command (save HTML table that can be viewed with browser) - - **OTIO**: `save-otio` command (save as [OpenTimelineIO](https://github.com/AcademySoftwareFoundation/OpenTimelineIO) file) - - **QP**: `save-qp` command (can be used with x264 `--qpfile`) +- Export timecodes in comma-separated `HH:MM:SS.nnn` format for external tools and spreadsheets. +- Save frame-by-frame video metrics to a CSV stats file with `-s FILE` / `--stats FILE` (for example, `--stats metrics.csv`). +- Hide terminal output with `-q` / `--quiet` when automating scripts. +- Save still frames from each scene with the `save-images` command. +- Split the input video into separate scene clips with `split-video` using `ffmpeg` or `mkvmerge`. -### Detection Methods +## Output Formats -PySceneDetect implements a variety of different detection algorithms which can be used independently or combined depending on the source material being analyzed. +- **CSV** (`list-scenes`): save a scene list table and comma-separated cut times (`HH:MM:SS.nnn`). +- **EDL** (`save-edl`): save a CMX 3600 edit decision list for most video editors. +- **Final Cut Pro XML** (`save-fcp`): save a Final Cut Pro X (FCPXML) or Final Cut Pro 7 (xmeml) timeline. +- **HTML** (`save-html`): save an HTML scene table to view in a web browser, with optional preview images. +- **Images** (`save-images`): save still frames from each scene as JPEG, PNG, or WebP files. +- **Keyframes** (`save-keyframes`): save cut frame numbers in keyframe format v1 (for example, for Aegisub). +- **OpenTimelineIO** (`save-otio`): save an [OpenTimelineIO](https://github.com/AcademySoftwareFoundation/OpenTimelineIO) timeline file. +- **QP** (`save-qp`): save cut frame numbers for use with x264 and x265 `--qpfile`. +- **Video Clips** (`split-video`): split the input video into one file per scene with `ffmpeg` or `mkvmerge`. - - **adaptive content scene detection** (`detect-adaptive`): uses rolling average of differences in HSL colorspace combined with thresholding to detect shot changes (fast cut) - - **content-aware scene detection** (`detect-content`): uses differences in HSL colorspace combined with filtering to detect shot changes (fast cut) - - **content-aware scene detection** (`detect-hash`): uses perceptual hashing to determine differences between frames to find shot changes (fast cut) - - **content-aware scene detection** (`detect-hist`): uses differences in histograms of Y channel of frames after conversion to YUV (fast cut) - - **threshold scene detection** (`detect-threshold`): uses average frame intensity (brightness) to detect slow transitions (fade in/out) +## Detectors - By default, detection methods are tuned to provide high performance during processing, while maintaining reasonable accuracy. Each detection method is configurable, and different parameters can be changed for specific use cases. See [the documentation](docs.md) for details, and [the benchmarks page](benchmarks.md) for how each detector scores on public shot-boundary-detection datasets. +PySceneDetect includes five detectors. You can run them alone or combine more than one for the same video: ------------------------------------------------------------------------- +- **Adaptive detector** (`detect-adaptive`, default): compares each frame's HSV content score against a rolling average of nearby frames to find fast cuts while reducing false cuts during camera motion. +- **Content detector** (`detect-content`): compares differences in the HSV color space (and optional edges) between adjacent frames to find fast cuts. +- **Perceptual hash detector** (`detect-hash`): computes a perceptual hash for each frame and compares adjacent hashes to find fast cuts. +- **Histogram detector** (`detect-hist`): compares Y-channel (brightness) histograms in the YUV color space between adjacent frames to find fast cuts. +- **Threshold detector** (`detect-threshold`): measures average RGB frame brightness to find fades to and from black. +Each detector uses default settings tuned for both speed and accuracy. You can adjust every option from the command line or a config file, and every parameter in Python. See the [Reference Manual](/docs/latest/) for details and the [Benchmarks](benchmarks.md) page for accuracy scores across public datasets. -## Version Roadmap - -Future version roadmaps are now [tracked as milestones (link)](https://github.com/Breakthrough/PySceneDetect/milestones). Specific issues/features that are queued up for the very next release will have [the `backlog` tag](https://github.com/Breakthrough/PySceneDetect/issues?q=is%3Aissue+is%3Aopen+label%3A%22status%3A+backlog%22), and issues/features being worked on will have [the `status: in progress` tag](https://github.com/Breakthrough/PySceneDetect/issues?q=is%3Aissue+is%3Aopen+label%3A%22status%3A+in+progress%22). Also note that bug reports as well as additional feature requests can be submitted via [the issue tracker](https://github.com/Breakthrough/PySceneDetect/issues); read [the Bug Reports and Contributing page](contributing.md) for details. +------------------------------------------------------------------------ +## Version Roadmap -### Planned Features +Planned releases are tracked in [GitHub milestones](https://github.com/Breakthrough/PySceneDetect/milestones), and active work uses [the `in progress` label](https://github.com/Breakthrough/PySceneDetect/issues?q=is%3Aissue+is%3Aopen+label%3A%22in+progress%22). Submit bug reports and feature requests on [the issue tracker](https://github.com/Breakthrough/PySceneDetect/issues); see [Contributing & Support](contributing.md) for guidelines. -The following features are under consideration for future releases. Any contributions towards completing these features are most welcome (pull requests may be accepted via Github). +### Planned features - - graphical interface (GUI) - - automatic threshold detection for the current scene detection methods (or just output message indicating "Predicted Threshold: X") - - suppression of short-length flashes/bursts of light [#35](https://github.com/Breakthrough/PySceneDetect/issues/35) - - histogram-based detection algorithm in HSV/HSL color space [#53](https://github.com/Breakthrough/PySceneDetect/issues/53) - - [perceptual hash](https://en.wikipedia.org/wiki/Perceptual_hashing) based scene detection ([prototype by @wjs018 in PR#290](https://github.com/Breakthrough/PySceneDetect/pull/290)) - - adaptive bias for fade in/out interpolation - - export scenes in chapter/XML format [#323](https://github.com/Breakthrough/PySceneDetect/issues/323) +Areas under consideration for future releases include a cross-platform GUI, automatic threshold selection, improved flash suppression ([#35](https://github.com/Breakthrough/PySceneDetect/issues/35)), better dissolve detection, and adaptive fade bias. See [Features That Need Help](contributing.md#features-that-need-help) if you would like to contribute. diff --git a/website/pages/gallery.md b/website/pages/gallery.md deleted file mode 100644 index a4d5644b..00000000 --- a/website/pages/gallery.md +++ /dev/null @@ -1,34 +0,0 @@ - -# Project Gallery - -The following open-source projects use PySceneDetect in their own code. They are listed for reference only: PySceneDetect does not endorse or maintain them, and each project is covered by its own license. Use them at your own risk. - -If you know of a project that should be listed here, feel free to [raise an issue](https://github.com/Breakthrough/PySceneDetect/issues/new/choose) with a link to where it uses PySceneDetect. Research papers that use PySceneDetect are listed on the [Research & Literature](literature.md) page. - -## Datasets and Model Training - - - [LTX-2](https://github.com/Lightricks/LTX-2) - the LTX-2 trainer's `split_scenes.py` script cuts training videos into scenes - - [Data-Juicer](https://github.com/datajuicer/data-juicer) - the `video_split_by_scene_mapper` operator splits videos at scene changes, with a choice of detector - - [OneTrainer](https://github.com/Nerogar/OneTrainer) - the video tool finds cuts with `AdaptiveDetector` when extracting clips - - [VideoX-Fun](https://github.com/aigc-apps/VideoX-Fun) - detects cuts in its video captioning pipeline - -## Video Generation - - - [ViMax](https://github.com/HKUDS/ViMax) - splits generated transition videos into shots with `split_video_ffmpeg` - - [InfiniteTalk](https://github.com/MeiGen-AI/InfiniteTalk) - detects shots in the input video, combining the content, adaptive, and threshold detectors - -## Agents, RAG, and Data Tools - - - [ECC](https://github.com/affaan-m/ECC) - measures the cut cadence of a reference video by sweeping `ContentDetector` thresholds - - [RAG-Anything](https://github.com/HKUDS/RAG-Anything) - segments videos into scenes before indexing them - - [CAMEL](https://github.com/camel-ai/camel) - the `VideoAnalysisToolkit` extracts keyframes at scene changes - - [Skill Seekers](https://github.com/yusufkaraaslan/Skill_Seekers) - the video scraper finds scene boundaries, then extracts keyframes - - [OmAgent](https://github.com/om-ai-lab/OmAgent) - splits videos into scenes for its video understanding agent - - [Pixeltable](https://github.com/pixeltable/pixeltable) - provides `scene_detect` video functions, with a cookbook notebook - - [MassGen](https://github.com/massgen/MassGen) - the video extraction tool takes frames from each scene - -## Applications and Tools - - - [Moondream](https://github.com/m87-labs/moondream) - the content moderation recipe detects scenes before running the model - - [REAL Video Enhancer](https://github.com/TNTwise/REAL-Video-Enhancer) - includes a copy of `ContentDetector` to catch scene changes while rendering - - [movie-narrator](https://github.com/zcbacxc/movie-narrator) - detects scenes as one step of its movie recap pipeline diff --git a/website/pages/img/params.png b/website/pages/img/params.png deleted file mode 100644 index 68449fcc..00000000 Binary files a/website/pages/img/params.png and /dev/null differ diff --git a/website/pages/img/pyscenedetect_logo.png b/website/pages/img/pyscenedetect_logo.png deleted file mode 100644 index 1b8163e1..00000000 Binary files a/website/pages/img/pyscenedetect_logo.png and /dev/null differ diff --git a/website/pages/index.md b/website/pages/index.md index ef826e54..9a426b6f 100644 --- a/website/pages/index.md +++ b/website/pages/index.md @@ -1,40 +1,11 @@ +## Common Use Cases +People use PySceneDetect for many video workflows: -PySceneDetect +- Splitting home videos or raw footage into separate scene clips. +- Finding and removing commercials from recorded TV broadcasts. +- Reviewing and splitting security camera recordings. +- Finding clean loops in videos for GIFs and cinemagraphs. +- Analyzing film and video datasets, such as measuring average shot length. -
-

  Latest Release: v0.7.3 (November 8, 2026)

-  Download        Changelog        Documentation        Getting Started -
- -**PySceneDetect** is a tool for **detecting shot changes in videos** ([example](cli.md)), and can **automatically split the video into separate clips**. PySceneDetect is free and open-source software, and has several [detection methods](features.md#detection-methods) to find fast-cuts and threshold-based fades. - -

Quickstart

- -Split video on each fast cut using [command line (more examples)](cli.md): - -```bash -scenedetect -i video.mp4 split-video -``` - -Split video on each fast cut using [Python API (docs)](docs.md): - -```python -from scenedetect import detect, AdaptiveDetector, split_video_ffmpeg - -scene_list = detect("my_video.mp4", AdaptiveDetector()) -split_video_ffmpeg("my_video.mp4", scene_list) -``` - - -

Examples and Use Cases

- -Here are some of the things people are using PySceneDetect for: - - - splitting home videos or other source footage into individual scenes - - automated detection and removal of commercials from PVR-saved video sources - - processing and splitting surveillance camera footage - - statistical analysis of videos to find suitable "loops" for looping GIFs/cinemagraphs - - academic analysis of film and video (e.g. finding mean shot length) - -Of course, this is just a small slice of what you can do with PySceneDetect, so why not try it out for yourself! The timecode format used by default (`HH:MM:SS.nnnn`) is compatible with most popular video tools, so in most cases the output scene list from PySceneDetect can be directly copied and pasted into another tool of your choice (e.g. `ffmpeg`, `avconv` or the `mkvtoolnix` suite). +[Download PySceneDetect](download.md) to try it on your own videos, or review the [Features](features.md) page for a full list of detectors and export formats. The default timecode format (`HH:MM:SS.nnn`) works directly with tools such as `ffmpeg` and `mkvmerge`. diff --git a/website/pages/js/helper.js b/website/pages/js/helper.js deleted file mode 100644 index 72e366b1..00000000 --- a/website/pages/js/helper.js +++ /dev/null @@ -1,28 +0,0 @@ -// Adds a copy-to-clipboard button to code blocks (the readthedocs theme has no -// built-in equivalent of mkdocs-material's `content.code.copy` feature). -document.addEventListener("DOMContentLoaded", function () { - var blocks = document.querySelectorAll(".rst-content pre"); - blocks.forEach(function (pre) { - var code = pre.querySelector("code"); - if (!code) { - return; - } - var button = document.createElement("button"); - button.className = "copy-btn"; - button.type = "button"; - button.title = "Copy to clipboard"; - button.setAttribute("aria-label", "Copy to clipboard"); - button.innerHTML = ''; - button.addEventListener("click", function () { - navigator.clipboard.writeText(code.innerText.trim()).then(function () { - button.innerHTML = ''; - button.classList.add("copied"); - setTimeout(function () { - button.innerHTML = ''; - button.classList.remove("copied"); - }, 600); - }); - }); - pre.appendChild(button); - }); -}); diff --git a/website/pages/literature.md b/website/pages/literature.md deleted file mode 100644 index 8bce6ca8..00000000 --- a/website/pages/literature.md +++ /dev/null @@ -1,29 +0,0 @@ - -# PySceneDetect in Literature - -PySceneDetect is a useful tool for statistical analysis of video. Below are links to various research articles/papers which have either used PySceneDetect as a part of their analysis, or propose more accurate detection algorithms using the current implementation as a comparison. - - - [Panda-70M: Captioning 70M Videos with Multiple Cross-Modality Teachers](https://arxiv.org/abs/2402.19479) by Tsai-Shien Chen, Aliaksandr Siarohin, Willi Menapace, Ekaterina Deyneka, Hsiang-wei Chao, Byung Eun Jeon, Yuwei Fang, Hsin-Ying Lee, Jian Ren, Ming-Hsuan Yang, Sergey Tulyakov (2024) - - - [Stable Remaster: Bridging the Gap Between Old Content and New Displays](https://arxiv.org/pdf/2306.06803.pdf) by Nathan Paull, Shuvam Keshari, Yian Wong (2023) - - - [LoL-V2T: Large-Scale Esports Video Description Dataset](https://ieeexplore.ieee.org/abstract/document/9522986) by Tsunehiko Tanaka, Edgar Simo-Serra (2021) - - - [Online Detection of Action Start via Soft Computing for Smart City](https://ieeexplore.ieee.org/document/9099408) by Tian Wang, Yang Chen, Hongqiang Lv, Jing Teng, Hichem Snoussi, Fei Tao (2020) - - - [Thesis Project: Smart Shades and Cane for The Blind](https://www.linkedin.com/pulse/blind-people-dont-have-good-muhammad-hashim-1f/) by Muhammad Hashim (2020) - - - [Movienet: a movie multilayer network model using visual and textual semantic cues](https://appliednetsci.springeropen.com/articles/10.1007/s41109-019-0226-0) by Youssef Mourchid, Benjamin Renoust, Olivier Roupin, Lê Văn, Hocine Cherifi & Mohammed El Hassouni (2019) - - - [NLP-Enriched Automatic Video Segmentation](https://ieeexplore.ieee.org/document/8525880/) by Mohannad AlMousa, Rachid Benlamri, Richard Khoury (2018) - - - [Online Detection of Action Start in Untrimmed, Streaming Videos](https://arxiv.org/pdf/1802.06822) by Zheng Shou, Junting Pan, Jonathan Chan, Kazuyuki Miyazawa, Hassan Mansour, Anthony Vetro, Xavi Gir-i-Nieto, Shih-Fu Chang (2018) - - - [Story Understanding in Video Advertisements](https://arxiv.org/pdf/1807.11122) by Keren Ye, Kyle Buettner, Adriana Kovashka (2018) - -This list is only provided for academic and research purposes, and is far from an exhaustive source of the uses of PySceneDetect in literature. If you think a particular submission is relevant and should be added to this list, feel free to [raise an issue](https://github.com/Breakthrough/PySceneDetect/issues/new/choose) with your suggestion. Publicly available material is preferred, although not a requirement. - - -# Scene Detection Methodology - -You can find the source code for each scene detector in [the scenedetect/detectors folder](https://github.com/Breakthrough/PySceneDetect/tree/main/scenedetect/detectors). Also see [Issue #62: Reference of paper for the methods used](https://github.com/Breakthrough/PySceneDetect/issues/62) on Github for a further discussion on detection methodologies. You are more than welcome to propose any new ideas on the [issue tracker](https://github.com/Breakthrough/PySceneDetect/issues), or share a proof of concept using the Python API by creating a pull request. diff --git a/website/pages/projects.md b/website/pages/projects.md new file mode 100644 index 00000000..7f1f639f --- /dev/null +++ b/website/pages/projects.md @@ -0,0 +1,67 @@ +# Projects & Research + +This page lists open-source projects, research papers, and similar tools related to PySceneDetect. To suggest an addition, [open an issue on GitHub](https://github.com/Breakthrough/PySceneDetect/issues/new/choose). + +## Projects Using PySceneDetect + +The open-source projects below use PySceneDetect in their own code. They are listed for reference only: PySceneDetect does not maintain or endorse them, and each project has its own license. + +### Datasets and model training + +- [LTX-2](https://github.com/Lightricks/LTX-2): cuts training videos into scenes with `split_scenes.py`. +- [Data-Juicer](https://github.com/datajuicer/data-juicer): splits videos at scene changes with its `video_split_by_scene_mapper` operator. +- [OneTrainer](https://github.com/Nerogar/OneTrainer): finds cuts with `AdaptiveDetector` when extracting training clips. +- [VideoX-Fun](https://github.com/aigc-apps/VideoX-Fun): detects cuts in its video captioning pipeline. + +### Video generation + +- [ViMax](https://github.com/HKUDS/ViMax): splits generated transition videos into shots with `split_video_ffmpeg`. +- [InfiniteTalk](https://github.com/MeiGen-AI/InfiniteTalk): detects shots in input videos by combining the content, adaptive, and threshold detectors. + +### Agents, RAG, and data tools + +- [ECC](https://github.com/affaan-m/ECC): measures the cut cadence of a reference video by sweeping `ContentDetector` thresholds. +- [RAG-Anything](https://github.com/HKUDS/RAG-Anything): splits videos into scenes before indexing them. +- [CAMEL](https://github.com/camel-ai/camel): extracts keyframes at scene changes in `VideoAnalysisToolkit`. +- [Skill Seekers](https://github.com/yusufkaraaslan/Skill_Seekers): finds scene boundaries in scraped videos before extracting keyframes. +- [OmAgent](https://github.com/om-ai-lab/OmAgent): splits videos into scenes for its video understanding agent. +- [Pixeltable](https://github.com/pixeltable/pixeltable): provides `scene_detect` video functions with an example notebook. +- [MassGen](https://github.com/massgen/MassGen): extracts frames from each scene in its video extraction tool. + +### Applications and tools + +- [Moondream](https://github.com/m87-labs/moondream): detects scenes before running its content moderation model. +- [REAL Video Enhancer](https://github.com/TNTwise/REAL-Video-Enhancer): includes `ContentDetector` to catch scene changes during rendering. +- [movie-narrator](https://github.com/zcbacxc/movie-narrator): detects scenes as part of its movie recap pipeline. + +## Research and Literature + +The papers below either use PySceneDetect for video analysis or compare new shot-boundary detection methods against it: + +- [Panda-70M: Captioning 70M Videos with Multiple Cross-Modality Teachers](https://arxiv.org/abs/2402.19479) by Tsai-Shien Chen, Aliaksandr Siarohin, Willi Menapace, Ekaterina Deyneka, Hsiang-wei Chao, Byung Eun Jeon, Yuwei Fang, Hsin-Ying Lee, Jian Ren, Ming-Hsuan Yang, and Sergey Tulyakov (2024). +- [Stable Remaster: Bridging the Gap Between Old Content and New Displays](https://arxiv.org/pdf/2306.06803.pdf) by Nathan Paull, Shuvam Keshari, and Yian Wong (2023). +- [LoL-V2T: Large-Scale Esports Video Description Dataset](https://ieeexplore.ieee.org/abstract/document/9522986) by Tsunehiko Tanaka and Edgar Simo-Serra (2021). +- [Online Detection of Action Start via Soft Computing for Smart City](https://ieeexplore.ieee.org/document/9099408) by Tian Wang, Yang Chen, Hongqiang Lv, Jing Teng, Hichem Snoussi, and Fei Tao (2020). +- [Thesis Project: Smart Shades and Cane for The Blind](https://www.linkedin.com/pulse/blind-people-dont-have-good-muhammad-hashim-1f/) by Muhammad Hashim (2020). +- [Movienet: a movie multilayer network model using visual and textual semantic cues](https://appliednetsci.springeropen.com/articles/10.1007/s41109-019-0226-0) by Youssef Mourchid, Benjamin Renoust, Olivier Roupin, Lê Văn, Hocine Cherifi, and Mohammed El Hassouni (2019). +- [NLP-Enriched Automatic Video Segmentation](https://ieeexplore.ieee.org/document/8525880/) by Mohannad AlMousa, Rachid Benlamri, and Richard Khoury (2018). +- [Online Detection of Action Start in Untrimmed, Streaming Videos](https://arxiv.org/pdf/1802.06822) by Zheng Shou, Junting Pan, Jonathan Chan, Kazuyuki Miyazawa, Hassan Mansour, Anthony Vetro, Xavi Gir-i-Nieto, and Shih-Fu Chang (2018). +- [Story Understanding in Video Advertisements](https://arxiv.org/pdf/1807.11122) by Keren Ye, Kyle Buettner, and Adriana Kovashka (2018). + +Publicly accessible links are preferred when suggesting new citations, though not required. + +### Scene detection methodology + +You can inspect the implementation of every built-in detector in [`scenedetect/detectors/`](https://github.com/Breakthrough/PySceneDetect/tree/main/scenedetect/detectors). For background discussion on references and methods, see [Issue #62](https://github.com/Breakthrough/PySceneDetect/issues/62). + +## Similar Programs + +These tools and models also detect scene cuts in video: + +- [Scenecut Extractor](https://github.com/slhck/scenecut-extractor): wraps the `ffmpeg` `select` filter. +- `ffmpeg` `blackframe` filter ([thanks @tonycpsu](https://github.com/Breakthrough/PySceneDetect/issues/7)): detects fades to black only. +- [Shotdetect](https://github.com/johmathe/Shotdetect): content-based detector for Linux and macOS. +- [MATLAB Scene Change Detection](https://www.mathworks.com/help/vision/examples/scene-change-detection.html): uses feature extraction and edge detection (requires MATLAB and Computer Vision Toolbox). +- [chaptertool](https://github.com/Mtillmann/chaptertool): CLI and web tool that converts PySceneDetect output to other formats. +- [TransNetV2](https://github.com/soCzech/TransNetV2): neural network for shot boundary detection (2020). +- [AutoShot](https://github.com/wentaozhu/AutoShot): neural network for shot boundary detection using neural architecture search (2023). diff --git a/website/pages/similar.md b/website/pages/similar.md deleted file mode 100644 index 94b017cb..00000000 --- a/website/pages/similar.md +++ /dev/null @@ -1,13 +0,0 @@ - -## Alternative and Related Programs - -The following is a list of programs or commands also performing scene cut analysis of some kind on video files. [Additions/contributions to this list are welcome](contributing.md). - - - [Scenecut Extractor](https://github.com/slhck/scenecut-extractor) - uses ffmpeg `select` filter - - ffmpeg `blackframe` filter ([thanks @tonycpsu](https://github.com/Breakthrough/PySceneDetect/issues/7)) - threshold mode only - - [Shotdetect](http://johmathe.name/shotdetect.html) - appears to be only for *NIX, content mode only - - [Matlab Scene Change Detection](http://www.mathworks.com/help/vision/examples/scene-change-detection.html) - requires Matlab and Simulink/Computer Vision Toolbox, uses feature extraction and edge detection - - [chaptertool](https://github.com/Mtillmann/chaptertool) - CLI/Web tool that converts PySceneDetect output to other formats - - [TransNetV2](https://github.com/soCzech/TransNetV2) - Shot Boundary Detection Neural Network (2020) - - [AutoShot](https://github.com/wentaozhu/AutoShot) - Shot Boundary Detection Neural Network, based on a neural architecture search (2023) - diff --git a/website/pages/style.css b/website/pages/style.css deleted file mode 100644 index 8c59567a..00000000 --- a/website/pages/style.css +++ /dev/null @@ -1,99 +0,0 @@ -.wy-side-nav-search { - display: block; - width: 300px; - padding: .809em; - margin-bottom: .809em; - z-index: 200; - background-color: #CCD7E2; - text-align: center; - color: #fcfcfc -} - -.wy-side-nav-search .wy-dropdown>a, -.wy-side-nav-search>a { - color:#3B3F47; - font-size:100%; - font-weight:700; - display:inline-block; - padding:4px 6px; - margin-bottom:.809em; - max-width:100% -} - - -#side-nav-logo { - margin-bottom: -1em; -} - -/* Benchmark results tables (benchmarks.md). F1 cells are shaded on a single-hue - sequential scale: darker = higher score. */ -.bm-table { - border-collapse: collapse; - margin-bottom: 24px; -} -.bm-table th, .bm-table td { - border: 1px solid #e1e0d9; - padding: 6px 12px; - text-align: center; -} -.bm-table td:first-child { - text-align: left; -} -.bm-t1 { background-color: #6da7ec; } /* F1 >= 80 */ -.bm-t2 { background-color: #9ec5f4; } /* F1 60-79 */ -.bm-t3 { background-color: #cde2fb; } /* F1 40-59 */ - -/* Copy-to-clipboard button injected into code blocks by js/helper.js. */ -.rst-content pre { - position: relative; -} -.rst-content pre .copy-btn { - position: absolute; - top: 4px; - right: 4px; - padding: 2px 8px; - border: 1px solid transparent; - border-radius: 3px; - background: transparent; - color: #9a9a9a; - cursor: pointer; - font-size: 14px; - line-height: 1.5; -} -.rst-content pre:hover .copy-btn, -.rst-content pre .copy-btn:focus { - border-color: #c4c4c4; - background: rgba(255, 255, 255, 0.8); - color: #404040; -} -.rst-content pre .copy-btn.copied, -.rst-content pre .copy-btn.copied:focus { - color: #27ae60; -} - -/* Prominent pip install commands inside the download page "important" divs: - full-width like regular code blocks, but white with larger bold text. */ -.rst-content .important h4:has(+ pre.command) { - margin-bottom: 6px; -} -.rst-content .important pre.command { - margin: 0 0 28px 0; - padding: 6px 42px 6px 12px; /* right padding leaves room for the copy button */ - background: #fff; - border: 1px solid #e1e4e5; -} -.rst-content .important pre.command code { - font-size: 120%; - font-weight: 700; - color: #404040; - background: transparent; - border: none; - padding: 0; -} -.rst-content .important pre.command:last-child { - margin-bottom: 4px; /* tighten space at the bottom of the box */ -} -.rst-content .important pre.command .copy-btn { - top: 50%; - transform: translateY(-50%); -} \ No newline at end of file diff --git a/website/pages/supporting.md b/website/pages/supporting.md deleted file mode 100644 index a1d99b66..00000000 --- a/website/pages/supporting.md +++ /dev/null @@ -1,32 +0,0 @@ - -#   Supporting Development - -This page is dedicated to the various people, tools, technologies, and companies which support the development of PySceneDetect. This page has been created to give credit to the things which allow PySceneDetect to exist, and is not meant to imply any kind of endorsement. - - -##   Tools, Technologies, and Companies - -The development of PySceneDetect is supported by the following tools, technologies, and companies: - - - [Github](https://github.com/) - Git and website hosting, code review, issue tracking, Linux/Windows/OSX builds - - [AppVeyor](https://www.appveyor.com/) - Windows builds (portable + MSI) - - [AdvancedInstaller](https://www.advancedinstaller.com/) - MSI installer - - [SignPath](https://signpath.io/) - Code signing for Windows builds - -Special thanks to these companies for their support. - - -##   Community Contributions - -PySceneDetect is an open source project which anyone can freely contribute to (see [this page for various ways you can contribute](contributing.md)). You can view [the contribution graph on Github](https://github.com/Breakthrough/PySceneDetect/graphs/contributors) or [visit PySceneDetect at libraries.io](https://libraries.io/github/Breakthrough/PySceneDetect/contributors) or view the to see a list detailing the contributions people have made to the PySceneDetect project. - -In addition to those who have made a direct contribution in the form of a pull request, a special thank you to *everyone* who has submitted an issue, bug report, feature request, and/or pull request (see the links above for complete lists), as well as for those who continue to help the ongoing development of PySceneDetect. - -Your contributions continue to improve PySceneDetect, highlight the assets and talents of the FOSS community, and help to make the project's goal of being the most accurate scene detection program/library become a reality. Lastly, thank you all for your help, support, feedback, and direction on the project. - - -##   Donations - -Monetary donations are not accepted for the project, but [there are ways you can contribute](contributing.md) to the project. Furthermore, if you have resources, tools, or technologies which may benefit the development of PySceneDetect, please feel free to contact me via the issue tracker or [my website](http://bcastell.com/contact/). - -Many thanks to everyone who continually supports the development of the project. diff --git a/website/requirements.txt b/website/requirements.txt new file mode 100644 index 00000000..0cdb0fc5 --- /dev/null +++ b/website/requirements.txt @@ -0,0 +1,4 @@ +# Dependencies for building the static website (website/build.py). +jinja2>=3.1.6 +markdown>=3.5 +pygments>=2.17 diff --git a/website/theme/404.html b/website/theme/404.html new file mode 100644 index 00000000..969915b6 --- /dev/null +++ b/website/theme/404.html @@ -0,0 +1,75 @@ +{% extends "base.html" %} + +{% block main %} +
+
+ +

Page Not Found

+

The requested page does not exist. Try searching above or return to the PySceneDetect homepage.

+
+
+ + +{% endblock %} diff --git a/website/theme/base.html b/website/theme/base.html new file mode 100644 index 00000000..63b5b370 --- /dev/null +++ b/website/theme/base.html @@ -0,0 +1,255 @@ + + + + + + + + {{ page.html_title }} + + {% if site.base_path %} + + {% endif %} + + {% if page.canonical_path and not site.base_path %} + + {% endif %} + + + + + + + {% if not site.base_path %} + + + {% endif %} + + + + + + + + +
+ + + + + +
+
+

Type a keyword to search guides, CLI options, detectors, and FAQs.

+
+
+
+ + {% block main %} +
+ + +
+
+ {{ page.content }} +
+ + + + {% if page.prev_page or page.next_page %} + + {% endif %} +
+ + {% if page.toc %} + + {% endif %} +
+ {% endblock %} + + + + diff --git a/website/theme/home.html b/website/theme/home.html new file mode 100644 index 00000000..cc22a4d3 --- /dev/null +++ b/website/theme/home.html @@ -0,0 +1,238 @@ +{% extends "base.html" %} + +{% block main %} +
+
+
+ + Latest release + {{ site.version }} + · {{ site.release_date_short }} + +

Fast, frame-accurate scene cut detection for video.

+

Detect fast cuts and fades from the command line or Python. Split videos with ffmpeg or mkvmerge, export timeline files for video editors, or save per-frame metrics.

+
+
+ + + +
+
+
+
+ + pip install --upgrade scenedetect + +
+
+ + +
+
+ +
+ +
+
+
+ {% for tab in hero_tabs %} + + {% endfor %} +
+ +
+ +
+ {% for tab in hero_tabs %} + + {% endfor %} +
+ +
+ Or run one command in your terminal: + scenedetect -i goldeneye.mp4 split-video +
+
+
+ +
+
+

Five Detectors

+

Choose from Adaptive, Content (HSV and edges), Perceptual Hash, Histogram, and Threshold detectors. All five are tested on BBC Planet Earth, AutoShot, and ClipShots.

+ +
+
+

Standard Export Formats

+

Export HH:MM:SS.nnn CSV scene lists, CMX 3600 EDL, Final Cut Pro XML, OpenTimelineIO (OTIO), x264 QP files, HTML reports, and still frames.

+ +
+
+

Modular Video Backends

+

Decode video with OpenCV by default, or switch to PyAV or MoviePy. Install via pip (standard or headless), the signed Windows installer, or Docker.

+ +
+
+ + +
+{% endblock %} diff --git a/website/theme/site.css b/website/theme/site.css new file mode 100644 index 00000000..bde7df5a --- /dev/null +++ b/website/theme/site.css @@ -0,0 +1,1935 @@ +@layer base, theme, layout, components, utilities; + +@media (prefers-reduced-motion: no-preference) { + @view-transition { + navigation: auto; + } +} + +@layer theme { + :root { + --bg: light-dark(oklch(99.2% 0.002 250), oklch(15.5% 0.012 255)); + --surface: light-dark(oklch(96.8% 0.005 250), oklch(19.5% 0.015 255)); + --surface-elevated: light-dark(oklch(100% 0 0), oklch(22% 0.016 255)); + --fg: light-dark(oklch(21% 0.02 255), oklch(94% 0.008 250)); + --muted: light-dark(oklch(44% 0.02 255), oklch(72% 0.015 250)); + --border: light-dark(oklch(87.5% 0.01 250), oklch(29.5% 0.018 255)); + --border-strong: light-dark(oklch(76% 0.015 250), oklch(40% 0.02 255)); + --brand: light-dark(oklch(44% 0.12 248), oklch(75% 0.12 240)); + --brand-hover: light-dark(oklch(38% 0.13 248), oklch(81% 0.11 240)); + --brand-fg: light-dark(oklch(99.5% 0 0), oklch(15.5% 0.02 255)); + --brand-subtle: light-dark(oklch(94.5% 0.025 248), oklch(24.5% 0.04 248)); + --code-bg: light-dark(oklch(96.2% 0.006 250), oklch(13.5% 0.012 255)); + + /* Calibrated syntax tokens (>= 6.6:1 contrast in both schemes) */ + --syn-kw: light-dark(oklch(44% 0.17 295), oklch(77% 0.13 295)); + --syn-fn: light-dark(oklch(43% 0.14 245), oklch(77% 0.11 235)); + --syn-str: light-dark(oklch(42% 0.13 155), oklch(77% 0.13 155)); + --syn-num: light-dark(oklch(44% 0.14 45), oklch(78% 0.13 65)); + --syn-cm: light-dark(oklch(45% 0.02 255), oklch(68% 0.015 250)); + --syn-var: light-dark(oklch(41% 0.12 200), oklch(78% 0.1 200)); + + /* Calibrated benchmark F1 heatmap tokens (>= 9.0:1 text contrast in both schemes) */ + --bm-t1: light-dark(oklch(85% 0.075 245), oklch(36% 0.095 245)); + --bm-t2: light-dark(oklch(90.5% 0.048 245), oklch(29.5% 0.065 245)); + --bm-t3: light-dark(oklch(95% 0.025 245), oklch(24% 0.038 245)); + + /* Status / Admonition accents */ + --note: light-dark(oklch(45% 0.13 248), oklch(74% 0.12 240)); + --warn: light-dark(oklch(48% 0.14 68), oklch(78% 0.13 75)); + --danger: light-dark(oklch(46% 0.17 25), oklch(75% 0.15 25)); + --ok: light-dark(oklch(44% 0.13 152), oklch(76% 0.13 152)); + + color-scheme: light dark; + &:has(> head > meta[name="color-scheme"][content="dark"]) { + color-scheme: dark; + } + &:has(> head > meta[name="color-scheme"][content="light"]) { + color-scheme: light; + } + + accent-color: var(--brand); + + --font-sans: "Noto Sans", "Segoe UI", system-ui, -apple-system, BlinkMacSystemFont, sans-serif; + --font-heading: var(--font-sans); + --font-brand: "Roboto Slab", "Georgia", serif; + --font-mono: "JetBrains Mono", "Cascadia Code", "Cascadia Mono", ui-monospace, "SFMono-Regular", Consolas, monospace; + } + + @media (forced-colors: active) { + :root { + --bg: Canvas; + --surface: Canvas; + --surface-elevated: Canvas; + --fg: CanvasText; + --muted: CanvasText; + --border: ButtonBorder; + --border-strong: ButtonBorder; + --brand: LinkText; + --brand-hover: LinkText; + --brand-fg: HighlightText; + --brand-subtle: Canvas; + --code-bg: Canvas; + } + } +} + +@layer base { + *, + *::before, + *::after { + box-sizing: border-box; + } + + body, + h1, + h2, + h3, + h4, + h5, + h6, + p, + ul, + ol, + dl, + dd, + pre, + figure, + blockquote { + margin: 0; + } + + html { + scroll-padding-block-start: 5rem; + } + + body { + min-block-size: 100dvh; + display: flex; + flex-direction: column; + background: var(--bg); + color: var(--fg); + font-family: var(--font-sans); + font-size-adjust: from-font; + font-size: 1rem; + line-height: 1.6; + text-align: start; + overflow-wrap: break-word; + } + + h1, + h2, + h3, + h4 { + font-family: var(--font-heading); + font-size-adjust: from-font; + } + + h1, + h2, + h3, + h4, + th { + line-height: 1.2; + letter-spacing: -0.018em; + text-wrap: balance; + } + + @supports not (font-size-adjust: from-font) { + body { + line-height: 1.64; + } + } + + p, + li, + dd, + blockquote { + text-wrap: pretty; + } + + code, + pre, + kbd { + font-family: var(--font-mono); + } + + a { + color: var(--brand); + text-underline-offset: 0.2em; + } + + a:hover { + color: var(--brand-hover); + } + + img, + svg { + display: block; + max-inline-size: 100%; + } + + img { + block-size: auto; + } + + button, + input { + font: inherit; + color: inherit; + } + + :where(a:any-link, button, input, [tabindex="0"]):focus-visible { + outline: 2px solid var(--brand); + outline-offset: 2px; + } + + main:focus { + outline: none; + } + + dialog:modal { + overscroll-behavior: contain; + } + + dialog::backdrop { + overflow: hidden; + overscroll-behavior: contain; + background: oklch(10% 0.015 255 / 0.55); + backdrop-filter: blur(3px); + } +} + +@layer layout { + .site-header { + position: sticky; + inset-block-start: 0; + z-index: 30; + background: color-mix(in oklab, var(--bg) 90%, transparent); + backdrop-filter: blur(10px); + border-block-end: 1px solid var(--border); + } + + .site-header.is-measuring, + .site-header.is-measuring :where(a, button, ul, li) { + transition: none !important; + } + + .header-inner { + max-inline-size: 78rem; + margin-inline: auto; + padding-block: 0.65rem; + padding-inline: 1.25rem; + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + } + + .header-inner > :where(a, nav, div) { + flex-shrink: 0; + white-space: nowrap; + } + + .brand-link { + display: inline-flex; + align-items: center; + gap: 0.6rem; + text-decoration: none; + color: var(--fg); + min-block-size: 2.25rem; + } + + .brand-link:hover { + color: var(--fg); + } + + .brand-link:hover .brand-mark { + color: var(--brand); + } + + .brand-mark { + flex: none; + inline-size: 2.15rem; + block-size: 2.15rem; + color: var(--fg); + transition: color 130ms ease-out; + } + + .brand-wordmark { + font-family: var(--font-brand); + font-size-adjust: from-font; + font-size: 1.12rem; + font-weight: 600; + letter-spacing: -0.015em; + line-height: 1.1; + } + + @supports not (font-size-adjust: from-font) { + .brand-wordmark { + font-size: 1.1rem; + } + } + + @media (width < 30rem) { + .header-inner { + padding-inline: 0.75rem; + gap: 0.45rem; + } + + .brand-mark { + inline-size: 1.95rem; + block-size: 1.95rem; + } + + .brand-wordmark { + font-size: 0.98rem; + } + } + + /* Non-color light/dark branching for theme toggle */ + .theme-option-light { + display: none; + } + + @media (prefers-color-scheme: dark) { + :root:not(:has(> head > meta[name="color-scheme"][content="light"])) { + .theme-option-dark { + display: none; + } + .theme-option-light { + display: block; + } + } + } + + :root:has(> head > meta[name="color-scheme"][content="dark"]) { + .theme-option-dark { + display: none; + } + .theme-option-light { + display: block; + } + } + + /* Narrow default: native popover menu */ + .site-nav { + margin-inline-start: auto; + } + + .menu-button { + anchor-name: --menu-button; + display: inline-flex; + align-items: center; + gap: 0.4rem; + min-block-size: 2.15rem; + padding-block: 0.35rem; + padding-inline: 0.7rem; + border: 1px solid var(--border); + border-radius: 0.45rem; + background: var(--surface); + color: var(--fg); + font-size: 0.875rem; + font-weight: 500; + cursor: pointer; + } + + .menu-button:hover { + background: var(--surface-elevated); + border-color: var(--border-strong); + } + + .site-menu { + list-style: none; + padding: 0.5rem; + position: fixed; + inset: auto; + inset-block-start: 3.6rem; + inset-block-start: anchor(--menu-button bottom); + inset-inline-end: 1rem; + inline-size: min(85dvw, 20rem); + max-inline-size: calc(100dvw - 2rem); + block-size: fit-content; + max-block-size: calc(100dvh - 4.75rem); + margin-block-start: 0.4rem; + overflow: auto; + overscroll-behavior: contain; + background: var(--surface-elevated); + border: 1px solid var(--border); + border-radius: 0.6rem; + box-shadow: 0 12px 32px oklch(0% 0 0 / 0.18); + } + + .site-menu:not(:is(:popover-open, .\:popover-open)) { + display: none; + } + + .site-menu[popover]:is(:popover-open, .\:popover-open) { + display: grid; + gap: 0.15rem; + } + + .site-menu a { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.35rem; + min-block-size: 2.1rem; + padding-block: 0.4rem; + padding-inline: 0.7rem; + border-radius: 0.4rem; + border: 1px solid transparent; + color: var(--muted); + text-decoration: none; + font-size: 0.875rem; + font-weight: 500; + } + + .site-menu a:hover { + color: var(--fg); + background: var(--surface); + } + + .site-menu a[aria-current="page"] { + color: var(--fg); + font-weight: 600; + background: var(--surface); + border-color: var(--border); + } + + /* Wide inline layout toggled by ResizeObserver when row fits */ + .site-header.is-wide { + .site-nav { + margin-inline-start: 0; + } + + .menu-button, + .mobile-only-nav { + display: none; + } + + .site-menu { + position: static; + display: flex; + align-items: center; + gap: 0.2rem; + inline-size: auto; + max-inline-size: none; + block-size: auto; + max-block-size: none; + overflow: visible; + margin: 0; + padding: 0; + border: 0; + border-radius: 0; + background: transparent; + box-shadow: none; + } + + .site-menu::backdrop { + display: none; + } + + .site-menu a { + display: inline-flex; + justify-content: flex-start; + padding-inline: 0.56rem; + } + } + + .header-actions { + display: flex; + align-items: center; + gap: 0.45rem; + } + + .container { + inline-size: 100%; + max-inline-size: 78rem; + margin-inline: auto; + padding-inline: 1.25rem; + } + + .home-main, + .not-found-main { + flex: 1 0 auto; + inline-size: 100%; + min-inline-size: 0; + } + + /* Inner 3-column documentation layout */ + .docs-shell { + flex: 1 0 auto; + inline-size: 100%; + max-inline-size: 78rem; + margin-inline: auto; + padding-block: 1.75rem 3rem; + padding-inline: 1.25rem; + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 2rem; + align-items: start; + } + + .docs-sidebar, + .docs-toc { + display: none; + } + + @media (width >= 50rem) { + .docs-shell { + grid-template-columns: 14rem minmax(0, 1fr); + gap: 2.25rem; + } + + .docs-sidebar { + display: block; + position: sticky; + inset-block-start: 4.75rem; + max-block-size: calc(100dvh - 5.5rem); + overflow-y: auto; + overscroll-behavior: contain; + padding-inline-end: 0.5rem; + } + } + + @media (width >= 68rem) { + .docs-shell:not(.docs-shell-no-toc) { + grid-template-columns: 14rem minmax(0, 1fr) 13rem; + gap: 2.5rem; + } + + .docs-toc { + display: block; + position: sticky; + inset-block-start: 4.75rem; + max-block-size: calc(100dvh - 5.5rem); + overflow-y: auto; + overscroll-behavior: contain; + } + } + + .docs-main { + min-inline-size: 0; + max-inline-size: 50rem; + inline-size: 100%; + } + + .site-footer { + margin-block-start: auto; + border-block-start: 1px solid var(--border); + background: var(--surface); + } + + .footer-inner { + max-inline-size: 78rem; + margin-inline: auto; + padding-block: 1.5rem; + padding-inline: 1.25rem; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 1rem; + font-size: 0.85rem; + color: var(--muted); + } + + .footer-links { + list-style: none; + padding: 0; + display: flex; + flex-wrap: wrap; + gap: 1rem; + } + + .footer-links a { + color: var(--muted); + text-decoration: none; + } + + .footer-links a:hover { + color: var(--fg); + text-decoration: underline; + } +} + +@layer components { + /* Header action controls */ + .search-trigger { + display: inline-flex; + align-items: center; + gap: 0.45rem; + min-block-size: 2.15rem; + padding-block: 0.3rem; + padding-inline: 0.65rem; + border: 1px solid var(--border); + border-radius: 0.45rem; + background: var(--surface); + color: var(--muted); + font-size: 0.85rem; + cursor: pointer; + } + + .search-trigger:hover { + color: var(--fg); + border-color: var(--border-strong); + background: var(--surface-elevated); + } + + .kbd { + font-size: 0.75rem; + line-height: 1.2; + padding-block: 0.1rem; + padding-inline: 0.35rem; + border: 1px solid var(--border); + border-radius: 0.25rem; + background: var(--bg); + color: var(--muted); + } + + .theme-toggle { + display: inline-flex; + align-items: center; + justify-content: center; + min-inline-size: 2.15rem; + min-block-size: 2.15rem; + padding: 0.4rem; + border: 1px solid var(--border); + border-radius: 0.45rem; + background: var(--surface); + color: var(--fg); + cursor: pointer; + } + + .theme-toggle:hover { + border-color: var(--border-strong); + background: var(--surface-elevated); + } + + .icon-link { + display: inline-flex; + align-items: center; + gap: 0.4rem; + min-block-size: 2.15rem; + padding-block: 0.35rem; + padding-inline: 0.65rem; + border: 1px solid var(--border); + border-radius: 0.45rem; + background: var(--surface); + color: var(--fg); + text-decoration: none; + font-size: 0.85rem; + font-weight: 500; + } + + .icon-link:hover { + color: var(--fg); + border-color: var(--border-strong); + background: var(--surface-elevated); + } + + @media (width < 34rem) { + .search-trigger .kbd { + display: none; + } + + .search-trigger-label, + .github-label { + position: absolute; + clip-path: inset(50%); + overflow: hidden; + inline-size: 1px; + block-size: 1px; + margin: -1px; + padding: 0; + border: 0; + white-space: nowrap; + } + + .search-trigger, + .icon-link { + justify-content: center; + gap: 0; + padding-inline: 0.5rem; + } + } + + @media (width < 28rem) { + .header-actions { + gap: 0.3rem; + } + + .menu-button { + justify-content: center; + gap: 0; + padding-inline: 0.5rem; + } + + .menu-button > span { + position: absolute; + clip-path: inset(50%); + overflow: hidden; + inline-size: 1px; + block-size: 1px; + margin: -1px; + padding: 0; + border: 0; + white-space: nowrap; + } + } + + @media (width < 23rem) { + .header-inner { + padding-inline: 0.6rem; + gap: 0.35rem; + } + + .brand-link { + gap: 0.4rem; + } + + .header-actions .icon-link { + display: none; + } + } + + @media (pointer: coarse) { + .menu-button, + .search-trigger, + .theme-toggle, + .icon-link { + min-block-size: 2.75rem; + min-inline-size: 2.75rem; + } + } + + /* Search modal dialog */ + .search-dialog { + inline-size: min(38rem, calc(100dvw - 1.5rem)); + max-block-size: min(32rem, calc(100dvh - 4rem)); + margin-block-start: min(10dvh, 4.5rem); + margin-inline: auto; + padding: 0; + border: 1px solid var(--border-strong); + border-radius: 0.7rem; + background: var(--surface-elevated); + color: var(--fg); + box-shadow: 0 20px 50px oklch(0% 0 0 / 0.28); + } + + .search-dialog[open] { + display: grid; + grid-template-rows: auto minmax(0, 1fr); + } + + .search-header { + display: flex; + align-items: center; + gap: 0.65rem; + padding-block: 0.75rem; + padding-inline: 1rem; + border-block-end: 1px solid var(--border); + } + + .search-input-icon { + color: var(--muted); + flex-shrink: 0; + } + + .search-input { + flex: 1 1 auto; + min-inline-size: 0; + border: 0; + background: transparent; + font-size: 0.98rem; + padding-block: 0.2rem; + } + + .search-input:focus-visible { + outline: none; + } + + .search-header:focus-within { + background: var(--surface); + } + + .search-close { + flex-shrink: 0; + min-block-size: 1.85rem; + padding-block: 0.2rem; + padding-inline: 0.55rem; + border: 1px solid var(--border); + border-radius: 0.35rem; + background: var(--surface); + color: var(--muted); + font-family: var(--font-mono); + font-size: 0.75rem; + cursor: pointer; + } + + .search-close:hover { + color: var(--fg); + border-color: var(--border-strong); + } + + .search-results { + overflow-y: auto; + overscroll-behavior: contain; + padding: 0.6rem; + display: grid; + gap: 0.25rem; + align-content: start; + } + + .search-empty { + padding: 1.5rem 1rem; + text-align: center; + color: var(--muted); + font-size: 0.9rem; + } + + .search-hit { + display: grid; + gap: 0.2rem; + padding: 0.65rem 0.8rem; + border-radius: 0.45rem; + border: 1px solid transparent; + text-decoration: none; + color: var(--fg); + } + + .search-hit:hover, + .search-hit.is-active { + background: var(--surface); + border-color: var(--border); + color: var(--fg); + } + + .search-hit-meta { + display: flex; + align-items: center; + gap: 0.4rem; + font-size: 0.8rem; + color: var(--brand); + font-weight: 600; + } + + .search-hit-snippet { + font-size: 0.85rem; + color: var(--muted); + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + line-clamp: 2; + overflow: clip; + } + + /* Home Style A Precision Technical Hero */ + .hero { + padding-block: 2.5rem 2.25rem; + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 2rem; + align-items: center; + border-block-end: 1px solid var(--border); + } + + @media (width >= 60rem) { + .hero { + padding-block: 3.25rem 2.75rem; + grid-template-columns: minmax(0, 1.08fr) minmax(0, 0.92fr); + gap: 2.5rem; + } + } + + .hero-copy { + min-inline-size: 0; + } + + .release-pill { + display: inline-flex; + flex-wrap: wrap; + align-items: center; + gap: 0.45rem; + padding-block: 0.28rem; + padding-inline: 0.8rem; + border: 1px solid var(--border); + border-radius: 99rem; + background: var(--surface); + font-size: 0.82rem; + color: var(--muted); + text-decoration: none; + margin-block-end: 1.1rem; + } + + .release-pill:hover { + border-color: var(--brand); + color: var(--fg); + } + + .release-pill strong { + color: var(--fg); + font-weight: 600; + } + + .hero h1 { + font-size: clamp(1.75rem, 1.3rem + 2vw, 2.75rem); + margin-block-end: 1rem; + } + + .hero-lead { + font-size: 1.05rem; + color: var(--muted); + max-inline-size: 54ch; + margin-block-end: 1.4rem; + } + + .install-box { + display: inline-grid; + grid-template-columns: minmax(0, 1fr); + min-inline-size: min(100%, 22rem); + max-inline-size: 100%; + border: 1px solid var(--border); + border-radius: 0.5rem; + background: var(--code-bg); + overflow: clip; + margin-block-end: 1.35rem; + } + + .install-tabs { + display: flex; + overflow-x: auto; + gap: 0.15rem; + padding-inline: 0.5rem; + background: var(--surface); + border-block-end: 1px solid var(--border); + } + + .install-tab { + position: relative; + flex: none; + min-inline-size: 2.25rem; + min-block-size: 2rem; + padding-block: 0.3rem; + padding-inline: 0.6rem; + border: 0; + background: transparent; + color: var(--muted); + font-family: var(--font-mono); + font-size: 0.78rem; + font-weight: 500; + cursor: pointer; + } + + .install-tab:hover { + color: var(--fg); + } + + .install-tab[aria-selected="true"] { + color: var(--fg); + + &::after { + content: ""; + position: absolute; + inset: auto 0 0; + border-block-end: 2px solid var(--brand); + } + } + + .install-panels { + display: grid; + } + + .install-panel { + grid-area: 1 / 1; + min-inline-size: 0; + } + + .install-strip { + display: flex; + align-items: center; + gap: 0.55rem; + max-inline-size: 100%; + padding-block: 0.5rem; + padding-inline: 0.8rem 0.6rem; + background: var(--code-bg); + font-family: var(--font-mono); + font-size: 0.86rem; + } + + .install-strip code { + flex: 1 1 auto; + min-inline-size: 0; + overflow-x: auto; + scrollbar-width: none; + white-space: nowrap; + } + + .install-strip .prompt { + color: var(--muted); + user-select: none; + } + + .copy-inline-btn { + display: inline-flex; + align-items: center; + justify-content: center; + min-inline-size: 1.75rem; + min-block-size: 1.75rem; + padding: 0.25rem; + border: 1px solid transparent; + border-radius: 0.35rem; + background: transparent; + color: var(--muted); + cursor: pointer; + flex-shrink: 0; + } + + .copy-inline-btn:hover { + color: var(--fg); + background: var(--surface-elevated); + border-color: var(--border); + } + + .copy-inline-btn.is-copied { + color: var(--ok); + } + + .cta-row { + display: flex; + flex-wrap: wrap; + gap: 0.7rem; + align-items: center; + } + + .btn-primary { + display: inline-flex; + align-items: center; + gap: 0.45rem; + min-block-size: 2.5rem; + padding-block: 0.55rem; + padding-inline: 1.15rem; + border-radius: 0.45rem; + background: var(--brand); + color: var(--brand-fg); + border: 1px solid transparent; + font-weight: 600; + font-size: 0.92rem; + text-decoration: none; + } + + .btn-primary:hover { + background: var(--brand-hover); + color: var(--brand-fg); + } + + .btn-secondary { + display: inline-flex; + align-items: center; + gap: 0.45rem; + min-block-size: 2.5rem; + padding-block: 0.55rem; + padding-inline: 1.05rem; + border-radius: 0.45rem; + background: var(--surface-elevated); + color: var(--fg); + border: 1px solid var(--border); + font-weight: 500; + font-size: 0.92rem; + text-decoration: none; + } + + .btn-secondary:hover { + color: var(--fg); + border-color: var(--border-strong); + background: var(--surface); + } + + /* Hero interactive code window */ + .code-window { + min-inline-size: 0; + background: var(--surface-elevated); + border: 1px solid var(--border); + border-radius: 0.65rem; + overflow: clip; + } + + .code-tabs { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; + padding-inline: 0.75rem 0.95rem; + background: var(--surface); + border-block-end: 1px solid var(--border); + font-size: 0.82rem; + } + + .tab-group { + display: flex; + overflow-x: auto; + gap: 0.15rem; + } + + .tab { + position: relative; + flex: none; + min-block-size: 2.35rem; + padding-block: 0.55rem; + padding-inline: 0.65rem; + border: 0; + background: transparent; + color: var(--muted); + font-weight: 500; + font-size: 0.82rem; + cursor: pointer; + } + + .tab:hover { + color: var(--fg); + } + + .tab[aria-selected="true"] { + color: var(--fg); + + &::after { + content: ""; + position: absolute; + inset: auto 0 0; + border-block-end: 2px solid var(--brand); + } + } + + .code-hint { + color: var(--muted); + font-family: var(--font-mono); + font-size: 0.75rem; + white-space: nowrap; + } + + @media (width < 30rem) { + .code-hint { + display: none; + } + } + + .code-panels { + display: grid; + } + + .code-panel { + grid-area: 1 / 1; + min-inline-size: 0; + } + + .code-window .codehilite { + margin: 0; + border: 0; + border-radius: 0; + } + + .code-body { + padding: 1.05rem 2.75rem 1.05rem 1.15rem; + background: var(--code-bg); + font-size: 0.85rem; + line-height: 1.65; + overflow-x: auto; + } + + .code-divider { + border-block-start: 1px solid var(--border); + padding: 0.8rem 1.15rem; + background: var(--surface-elevated); + font-size: 0.84rem; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.35rem 0.65rem; + } + + .code-divider-label { + color: var(--muted); + } + + .code-divider code { + font-size: 0.84rem; + background: var(--code-bg); + padding: 0.15rem 0.45rem; + border-radius: 0.3rem; + border: 1px solid var(--border); + } + + /* 3 Feature highlight cards */ + .grid-3 { + padding-block: 2rem; + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 1.15rem; + border-block-end: 1px solid var(--border); + } + + @media (width >= 52rem) { + .grid-3 { + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 1.25rem; + } + } + + .feature-card { + padding: 1.25rem 1.35rem; + border: 1px solid var(--border); + border-radius: 0.6rem; + background: var(--surface-elevated); + display: flex; + flex-direction: column; + gap: 0.45rem; + } + + .feature-card h2 { + font-size: 1.02rem; + } + + .feature-card p { + font-size: 0.9rem; + color: var(--muted); + flex: 1 0 auto; + } + + .feature-card code { + font-size: 0.84em; + background: var(--surface); + padding: 0.1em 0.32em; + border-radius: 0.25rem; + } + + .feature-meta { + margin-block-start: 0.5rem; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.1rem 0.45rem; + font-family: var(--font-mono); + font-size: 0.78rem; + font-weight: 500; + } + + .feature-meta a { + display: inline-flex; + align-items: center; + min-block-size: 1.5rem; + color: var(--brand); + text-decoration: none; + } + + .feature-meta a:hover { + text-decoration: underline; + } + + .feature-meta-sep { + color: var(--muted); + user-select: none; + } + + @media (pointer: coarse) { + .install-tab { + min-block-size: 2.5rem; + } + + .feature-meta a { + min-block-size: 2.25rem; + } + } + + /* Home lower prose & quick navigation grid */ + .home-content { + padding-block: 2.25rem 3rem; + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 2.5rem; + } + + .quick-nav-section { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 1rem; + } + + .quick-nav-section h2 { + font-size: clamp(1.25rem, 1.1rem + 0.6vw, 1.5rem); + } + + .quick-nav-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr)); + gap: 1rem; + } + + .quick-nav-card { + display: grid; + gap: 0.3rem; + padding: 1.05rem 1.2rem; + border: 1px solid var(--border); + border-radius: 0.55rem; + background: var(--surface-elevated); + text-decoration: none; + color: var(--fg); + } + + .quick-nav-card:hover { + border-color: var(--brand); + background: var(--surface); + color: var(--fg); + } + + .quick-nav-card strong { + font-size: 0.95rem; + color: var(--brand); + } + + .quick-nav-card span { + font-size: 0.86rem; + color: var(--muted); + } + + /* Sidebar & Right TOC */ + .side-group-title { + font-size: 0.75rem; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--muted); + margin-block: 1.15rem 0.4rem; + padding-inline: 0.6rem; + } + + .side-group-title:first-child { + margin-block-start: 0; + } + + .side-list { + list-style: none; + padding: 0; + display: grid; + gap: 0.12rem; + font-size: 0.88rem; + } + + .side-list a { + display: block; + padding-block: 0.35rem; + padding-inline: 0.65rem; + border-radius: 0.38rem; + border-inline-start: 2px solid transparent; + color: var(--muted); + text-decoration: none; + } + + .side-list a:hover { + color: var(--fg); + background: var(--surface); + } + + .side-list a[aria-current="page"] { + color: var(--brand); + font-weight: 600; + background: var(--surface); + border-inline-start-color: var(--brand); + } + + .toc-title { + font-size: 0.78rem; + font-weight: 600; + color: var(--fg); + margin-block-end: 0.55rem; + } + + .toc-list, + .toc-sublist { + list-style: none; + padding: 0; + display: grid; + gap: 0.32rem; + font-size: 0.82rem; + } + + .toc-list { + border-inline-start: 1px solid var(--border); + } + + .toc-sublist { + margin-block-start: 0.3rem; + padding-inline-start: 0.65rem; + } + + .toc-list a { + display: block; + padding-inline-start: 0.75rem; + color: var(--muted); + text-decoration: none; + line-height: 1.35; + border-inline-start: 2px solid transparent; + margin-inline-start: -1px; + } + + .toc-list a:hover, + .toc-list a.is-active { + color: var(--brand); + } + + .toc-list a.is-active { + font-weight: 600; + border-inline-start-color: var(--brand); + } + + /* Article Prose */ + .prose { + min-inline-size: 0; + } + + .prose > :where(p, ul, ol, dl, blockquote, .admonition, .important, .download-card) { + max-inline-size: 68ch; + } + + .prose h1 { + font-size: clamp(1.65rem, 1.35rem + 1.2vw, 2.2rem); + margin-block-end: 1rem; + } + + .prose h2 { + font-size: clamp(1.25rem, 1.1rem + 0.6vw, 1.52rem); + margin-block: 2rem 0.75rem; + padding-block-end: 0.4rem; + border-block-end: 1px solid var(--border); + } + + .prose h3 { + font-size: clamp(1.06rem, 1rem + 0.3vw, 1.22rem); + margin-block: 1.5rem 0.55rem; + } + + .prose h4 { + font-size: 1rem; + margin-block: 1.2rem 0.45rem; + } + + .prose p { + margin-block-end: 1rem; + } + + .prose :where(ul, ol) { + margin-block-end: 1rem; + padding-inline-start: 1.5rem; + } + + .prose li + li { + margin-block-start: 0.3rem; + } + + .prose blockquote { + margin-block: 1.1rem; + padding-block: 0.25rem; + padding-inline-start: 1rem; + border-inline-start: 3px solid var(--border-strong); + color: var(--muted); + } + + .prose hr { + border: 0; + border-block-start: 1px solid var(--border); + margin-block: 2rem; + } + + /* Inline code vs fenced code blocks */ + .prose :not(pre) > code { + font-size: 0.875em; + background: var(--surface); + border: 1px solid var(--border); + padding: 0.1em 0.35em; + border-radius: 0.28rem; + } + + .codehilite, + .prose > pre { + position: relative; + margin-block: 1rem 1.35rem; + border: 1px solid var(--border); + border-radius: 0.55rem; + background: var(--code-bg); + overflow: clip; + } + + .prose pre { + padding: 0.95rem 2.75rem 0.95rem 1.1rem; + overflow-x: auto; + font-size: 0.85rem; + line-height: 1.6; + background: var(--code-bg); + } + + .prose pre code { + background: transparent; + border: 0; + padding: 0; + font-size: inherit; + } + + .copy-code-btn { + position: absolute; + inset-block-start: 0.45rem; + inset-inline-end: 0.45rem; + display: inline-flex; + align-items: center; + justify-content: center; + min-inline-size: 1.85rem; + min-block-size: 1.85rem; + padding: 0.3rem; + border: 1px solid var(--border); + border-radius: 0.35rem; + background: var(--surface-elevated); + color: var(--muted); + cursor: pointer; + opacity: 0.85; + } + + .copy-code-btn:hover, + .copy-code-btn:focus-visible { + opacity: 1; + color: var(--fg); + border-color: var(--border-strong); + } + + .copy-code-btn.is-copied { + opacity: 1; + color: var(--ok); + border-color: var(--ok); + } + + /* Dual-scheme Pygments syntax highlighting */ + .codehilite { + .k, .kc, .kd, .kn, .kp, .kr, .kt, .ow { + color: var(--syn-kw); + font-weight: 500; + } + .nf, .fm, .nc, .nn, .nd, .nb, .bp { + color: var(--syn-fn); + } + .s, .sa, .sb, .sc, .dl, .sd, .s1, .s2, .se, .sh, .si, .sx, .sr, .ss { + color: var(--syn-str); + } + .m, .mb, .mf, .mh, .mi, .mo, .il { + color: var(--syn-num); + } + .c, .ch, .cm, .cp, .cpf, .c1, .cs { + color: var(--syn-cm); + font-style: italic; + } + .nv, .vc, .vg, .vi, .vm, .na, .nt { + color: var(--syn-var); + } + } + + /* Admonitions & Legacy .important callout boxes */ + .admonition, + .prose .important { + margin-block: 1.15rem 1.35rem; + padding: 0.95rem 1.15rem; + border: 1px solid var(--border); + border-inline-start: 3px solid var(--note); + border-radius: 0.5rem; + background: var(--surface); + } + + .admonition.warning { + border-inline-start-color: var(--warn); + } + + .admonition.danger, + .admonition.error { + border-inline-start-color: var(--danger); + } + + .admonition.tip, + .admonition.hint { + border-inline-start-color: var(--ok); + } + + .admonition-title { + font-weight: 600; + font-size: 0.92rem; + margin-block-end: 0.4rem; + color: var(--fg); + } + + .admonition > :last-child, + .prose .important > :last-child { + margin-block-end: 0; + } + + .prose .important pre.command { + position: relative; + margin-block: 0.45rem 0.9rem; + border: 1px solid var(--border); + border-radius: 0.45rem; + } + + .prose .btn { + display: inline-flex; + align-items: center; + gap: 0.35rem; + padding: 0.45rem 0.9rem; + border-radius: 0.4rem; + border: 1px solid var(--border-strong); + background: var(--surface-elevated); + color: var(--fg); + text-decoration: none; + font-size: 0.88rem; + font-weight: 500; + } + + .prose .btn:hover { + border-color: var(--brand); + color: var(--brand); + } + + /* DVR-Scan-style Windows build download card & buttons */ + .download-card { + margin-block: 1rem 1.25rem; + border: 1px solid var(--border); + border-radius: 0.6rem; + background: var(--surface-elevated); + overflow: clip; + } + + .download-card-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.4rem 1rem; + padding: 0.65rem 1.1rem; + background: var(--surface); + border-block-end: 1px solid var(--border); + font-size: 0.875rem; + } + + .download-card-title { + display: inline-flex; + align-items: center; + gap: 0.5rem; + color: var(--fg); + font-weight: 500; + } + + .download-os-icon { + flex: none; + color: var(--brand); + } + + .download-card-date { + color: var(--muted); + font-size: 0.82rem; + } + + .download-btn-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr)); + gap: 0.75rem; + padding: 1rem 1.1rem; + } + + .download-btn { + display: inline-flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 0.5rem; + min-block-size: 2.75rem; + padding-block: 0.6rem; + padding-inline: 1.05rem; + border-radius: 0.48rem; + font-family: var(--font-heading); + font-size: 0.92rem; + font-weight: 600; + line-height: 1.25; + text-decoration: none; + transition: background-color 130ms ease-out, border-color 130ms ease-out, box-shadow 130ms ease-out, scale 120ms ease-out; + } + + .download-btn svg { + flex: none; + } + + .prose .download-btn code { + font-family: var(--font-mono); + font-size: 0.85em; + font-weight: 600; + padding: 0.1em 0.35em; + border-radius: 0.28rem; + } + + .download-btn-primary { + background: var(--brand); + color: var(--brand-fg); + border: 1px solid transparent; + } + + .prose .download-btn-primary code { + background: color-mix(in oklab, var(--brand-fg) 16%, transparent); + border: 1px solid color-mix(in oklab, var(--brand-fg) 24%, transparent); + color: inherit; + } + + .download-btn-primary:hover { + background: var(--brand-hover); + color: var(--brand-fg); + box-shadow: 0 3px 10px oklch(0% 0 0 / 0.14); + } + + .download-btn-secondary { + background: var(--surface); + color: var(--fg); + border: 1px solid var(--border-strong); + } + + .prose .download-btn-secondary code { + background: var(--surface-elevated); + border: 1px solid var(--border); + color: var(--fg); + } + + .download-btn-secondary:hover { + background: var(--brand-subtle); + border-color: var(--brand); + color: var(--brand); + box-shadow: 0 3px 10px oklch(0% 0 0 / 0.1); + } + + .download-badge { + font-family: var(--font-sans); + font-size: 0.72rem; + font-weight: 600; + padding: 0.12rem 0.48rem; + border-radius: 99rem; + background: color-mix(in oklab, var(--brand-fg) 18%, transparent); + color: inherit; + } + + @media (prefers-reduced-motion: no-preference) { + :where(.release-pill, .btn-primary, .btn-secondary, .download-btn):active { + scale: 0.98; + } + } + + /* Charts & SVG media inside prose */ + .prose img { + margin-block: 0.85rem 1.25rem; + border-radius: 0.45rem; + } + + .prose td img { + margin-block: 0; + } + + .prose img[src$=".svg"] { + background: oklch(99% 0.002 250); + padding: 0.75rem; + border-radius: 0.5rem; + border: 1px solid var(--border); + } + + /* Responsive accessible tables & benchmark heatmaps */ + .table-wrapper { + overflow: auto; + max-inline-size: 100%; + container-type: inline-size; + margin-block: 1rem 1.5rem; + border: 1px solid var(--border); + border-radius: 0.5rem; + background: var(--surface-elevated); + } + + .table-wrapper table { + inline-size: 100%; + border-collapse: separate; + border-spacing: 0; + font-size: 0.875rem; + } + + .table-wrapper thead { + position: sticky; + inset-block-start: 0; + z-index: 1; + } + + .table-wrapper :where(th, td) { + padding: 0.55rem 0.85rem; + text-align: start; + } + + .table-wrapper thead th { + background: var(--surface); + font-weight: 600; + color: var(--fg); + border-block-end: 1px solid var(--border); + white-space: nowrap; + } + + .table-wrapper tbody tr:not(:last-child) :where(th, td) { + border-block-end: 1px solid var(--border); + } + + .bm-table :where(th, td):not(:first-child) { + text-align: end; + font-variant-numeric: tabular-nums; + } + + .bm-table-sweep :where(th, td):nth-child(n + 3) { + text-align: start; + font-variant-numeric: normal; + } + + .bm-t1 { + background: var(--bm-t1); + color: var(--fg); + font-weight: 600; + } + + .bm-t2 { + background: var(--bm-t2); + color: var(--fg); + font-weight: 600; + } + + .bm-t3 { + background: var(--bm-t3); + color: var(--fg); + } + + /* Inner-page edit link & prev/next pagination */ + .doc-meta-bar { + margin-block-start: 2.5rem; + padding-block-start: 1.25rem; + border-block-start: 1px solid var(--border); + display: flex; + justify-content: flex-end; + } + + .edit-link { + display: inline-flex; + align-items: center; + gap: 0.4rem; + font-size: 0.85rem; + color: var(--muted); + text-decoration: none; + } + + .edit-link:hover { + color: var(--brand); + } + + .pagination-nav { + margin-block-start: 1.25rem; + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1rem; + } + + @media (width < 32rem) { + .pagination-nav { + grid-template-columns: minmax(0, 1fr); + } + } + + .pagination-link { + display: grid; + gap: 0.2rem; + padding: 0.85rem 1rem; + border: 1px solid var(--border); + border-radius: 0.5rem; + background: var(--surface-elevated); + text-decoration: none; + } + + .pagination-link:hover { + border-color: var(--brand); + background: var(--surface); + } + + .pagination-next { + text-align: end; + } + + .pagination-hint { + font-size: 0.78rem; + color: var(--muted); + } + + .pagination-title { + font-size: 0.92rem; + font-weight: 600; + color: var(--brand); + } + + /* 404 Page */ + .not-found-main { + display: grid; + place-items: center; + padding-block: 4rem; + } + + .not-found-card { + max-inline-size: 34rem; + padding: 2.25rem 2rem; + border: 1px solid var(--border); + border-radius: 0.75rem; + background: var(--surface-elevated); + text-align: center; + display: grid; + gap: 0.75rem; + } + + .not-found-code { + font-family: var(--font-mono); + font-size: 2.25rem; + font-weight: 700; + color: var(--brand); + line-height: 1; + } + + .not-found-card h1 { + font-size: 1.6rem; + } + + .not-found-card p { + color: var(--muted); + } +} + +@layer utilities { + .visually-hidden:where(:not(:focus-within, :active)) { + position: absolute !important; + clip-path: inset(50%) !important; + overflow: hidden !important; + inline-size: 1px !important; + block-size: 1px !important; + margin: -1px !important; + padding: 0 !important; + border: 0 !important; + white-space: nowrap !important; + } + + .skip-link:is(:focus-within, :active) { + position: fixed; + inset-block-start: 0.6rem; + inset-inline-start: 0.6rem; + z-index: 100; + padding: 0.55rem 0.95rem; + border-radius: 0.45rem; + background: var(--brand); + color: var(--brand-fg); + font-weight: 600; + font-size: 0.9rem; + text-decoration: none; + } +} diff --git a/website/theme/site.js b/website/theme/site.js new file mode 100644 index 00000000..879b1446 --- /dev/null +++ b/website/theme/site.js @@ -0,0 +1,549 @@ +// Conditionally load Popover API polyfill only in older browsers lacking native support. +if (!Object.hasOwn(HTMLElement.prototype, "popover")) { + import("https://unpkg.com/@oddbird/popover-polyfill@0.6.1/dist/popover.min.js").catch(() => {}); +} + +const COPY_ICON_SVG = + ''; +const CHECK_ICON_SVG = + ''; + +/* -------------------------------------------------------------------------- * + * 1. Light-dismiss fallback for + * -------------------------------------------------------------------------- */ +function initDialogLightDismissFallback() { + if ("closedBy" in HTMLDialogElement.prototype) { + return; + } + for (const dialog of document.querySelectorAll('dialog[closedby="any"]')) { + dialog.addEventListener("click", (event) => { + if (event.target !== dialog) { + return; + } + const rect = dialog.getBoundingClientRect(); + const isDialogContent = + rect.top <= event.clientY && + event.clientY <= rect.top + rect.height && + rect.left <= event.clientX && + event.clientX <= rect.left + rect.width; + if (!isDialogContent) { + dialog.close(); + } + }); + } +} + +/* -------------------------------------------------------------------------- * + * 2. Responsive Navbar (intrinsic measurement, no hardcoded width breakpoint) + * -------------------------------------------------------------------------- */ +function initResponsiveNavbar() { + const header = document.querySelector(".site-header"); + const inner = header?.querySelector(".header-inner"); + const menu = document.getElementById("site-menu"); + if (!header || !inner || !menu) { + return; + } + + let lastHeaderWidth = 0; + + const isMenuOpen = () => { + try { + return menu.matches(":popover-open, .\\:popover-open"); + } catch { + return menu.classList.contains(":popover-open"); + } + }; + + const syncLayout = (forceMeasure = false) => { + const currentWidth = header.clientWidth; + const isCurrentlyWide = header.classList.contains("is-wide"); + if (!forceMeasure && !isCurrentlyWide && currentWidth <= lastHeaderWidth) { + lastHeaderWidth = currentWidth; + return; + } + lastHeaderWidth = currentWidth; + + const wasOpen = isMenuOpen(); + header.classList.add("is-measuring", "is-wide"); + const fits = inner.scrollWidth <= inner.clientWidth; + header.classList.toggle("is-wide", fits); + + if (fits) { + menu.removeAttribute("popover"); + } else { + menu.setAttribute("popover", "auto"); + if (wasOpen && typeof menu.showPopover === "function") { + try { + menu.showPopover(); + } catch { + // Ignore if polyfill is still initializing. + } + } + } + + requestAnimationFrame(() => { + header.classList.remove("is-measuring"); + }); + }; + + syncLayout(true); + + if (document.fonts && document.fonts.ready) { + document.fonts.ready.then(() => syncLayout(true)).catch(() => {}); + } + + if (typeof ResizeObserver !== "undefined") { + const headerObserver = new ResizeObserver(() => syncLayout(false)); + headerObserver.observe(header); + } +} + +/* -------------------------------------------------------------------------- * + * 3. Two-state persistent color-scheme toggle (syncs ) + * -------------------------------------------------------------------------- */ +function initThemeToggle() { + const meta = document.querySelector('meta[name="color-scheme"]'); + const toggleBtn = document.querySelector(".theme-toggle"); + if (!meta) { + return; + } + + const getStored = () => { + try { + const value = localStorage.getItem("color-scheme"); + return value === "light" || value === "dark" ? value : null; + } catch { + return null; + } + }; + + const applyMeta = (value) => { + meta.content = value === "light" || value === "dark" ? value : "light dark"; + }; + + if (toggleBtn) { + toggleBtn.addEventListener("click", () => { + const stored = getStored(); + const systemScheme = window.matchMedia("(prefers-color-scheme: dark)").matches + ? "dark" + : "light"; + const currentRendered = + meta.content === "light" || meta.content === "dark" + ? meta.content + : (stored ?? systemScheme); + const target = currentRendered === "dark" ? "light" : "dark"; + + if (target !== systemScheme) { + try { + localStorage.setItem("color-scheme", target); + } catch { + // Storage blocked; still apply to current page. + } + applyMeta(target); + } else { + try { + localStorage.removeItem("color-scheme"); + } catch { + // Ignore storage error. + } + applyMeta("light dark"); + } + }); + } + + window.addEventListener("storage", (event) => { + if (event.key === "color-scheme" || event.key === null) { + applyMeta(event.newValue); + } + }); +} + +/* -------------------------------------------------------------------------- * + * 4. Accessible Tabs (roving tabindex, selection-on-focus, find-in-page sync) + * -------------------------------------------------------------------------- */ +function initTabGroups() { + for (const tablist of document.querySelectorAll('[role="tablist"]')) { + const tabs = Array.from(tablist.querySelectorAll('[role="tab"]')); + if (!tabs.length) { + continue; + } + const hintTargetId = tablist.dataset.hintTarget; + const hintEl = hintTargetId ? document.getElementById(hintTargetId) : null; + const panels = tabs.map((tab) => + tab.id ? document.querySelector(`[role="tabpanel"][aria-labelledby="${CSS.escape(tab.id)}"]`) : null + ); + + const selectTab = (nextTab, moveFocus = false) => { + tabs.forEach((tab, idx) => { + const isSelected = tab === nextTab; + tab.setAttribute("aria-selected", isSelected ? "true" : "false"); + tab.tabIndex = isSelected ? 0 : -1; + const panel = panels[idx]; + if (panel) { + panel.hidden = isSelected ? false : "until-found"; + } + }); + if (hintEl && nextTab.dataset.hint) { + hintEl.textContent = nextTab.dataset.hint; + } + nextTab.scrollIntoView({ block: "nearest", inline: "nearest" }); + if (moveFocus) { + nextTab.focus(); + } + }; + + tabs.forEach((tab, idx) => { + tab.addEventListener("click", () => selectTab(tab, false)); + tab.addEventListener("keydown", (event) => { + let targetIdx = -1; + if (event.key === "ArrowRight") { + targetIdx = (idx + 1) % tabs.length; + } else if (event.key === "ArrowLeft") { + targetIdx = (idx - 1 + tabs.length) % tabs.length; + } else if (event.key === "Home") { + targetIdx = 0; + } else if (event.key === "End") { + targetIdx = tabs.length - 1; + } + if (targetIdx !== -1) { + event.preventDefault(); + selectTab(tabs[targetIdx], true); + } + }); + + const panel = panels[idx]; + if (panel) { + panel.addEventListener("beforematch", () => selectTab(tab, false)); + } + }); + } +} + +/* -------------------------------------------------------------------------- * + * 5. Copy-to-clipboard buttons (hero inline command + prose code blocks) + * -------------------------------------------------------------------------- */ +const copyTimers = new WeakMap(); + +function flashCopied(button, defaultLabel) { + const prevTimer = copyTimers.get(button); + if (prevTimer !== undefined) { + window.clearTimeout(prevTimer); + } + button.innerHTML = CHECK_ICON_SVG; + button.classList.add("is-copied"); + button.setAttribute("aria-label", "Copied to clipboard"); + const timerId = window.setTimeout(() => { + button.innerHTML = COPY_ICON_SVG; + button.classList.remove("is-copied"); + button.setAttribute("aria-label", defaultLabel); + copyTimers.delete(button); + }, 1400); + copyTimers.set(button, timerId); +} + +function initCopyButtons() { + for (const inlineBtn of document.querySelectorAll(".copy-inline-btn")) { + const text = inlineBtn.getAttribute("data-copy") || ""; + const defaultLabel = inlineBtn.getAttribute("aria-label") || "Copy command"; + inlineBtn.addEventListener("click", () => { + if (!text || !navigator.clipboard) { + return; + } + navigator.clipboard + .writeText(text) + .then(() => flashCopied(inlineBtn, defaultLabel)) + .catch(() => {}); + }); + } + + for (const container of document.querySelectorAll(".prose .codehilite, .code-window .codehilite")) { + const codeEl = container.querySelector("code") || container; + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "copy-code-btn"; + const defaultLabel = "Copy code to clipboard"; + btn.setAttribute("aria-label", defaultLabel); + btn.innerHTML = COPY_ICON_SVG; + btn.addEventListener("click", () => { + const raw = (codeEl.textContent || "").trim(); + if (!raw || !navigator.clipboard) { + return; + } + navigator.clipboard + .writeText(raw) + .then(() => flashCopied(btn, defaultLabel)) + .catch(() => {}); + }); + container.appendChild(btn); + } +} + +/* -------------------------------------------------------------------------- * + * 6. Right-hand TOC active section highlight + * -------------------------------------------------------------------------- */ +function initTocHighlight() { + const tocLinks = Array.from(document.querySelectorAll(".toc-list a[href^='#']")); + if (!tocLinks.length || typeof IntersectionObserver === "undefined") { + return; + } + + const linkById = new Map(); + const headings = []; + for (const link of tocLinks) { + const id = decodeURIComponent(link.getAttribute("href").slice(1)); + const target = document.getElementById(id); + if (target) { + linkById.set(id, link); + headings.push(target); + } + } + if (!headings.length) { + return; + } + + const setActive = (id) => { + for (const [key, link] of linkById.entries()) { + link.classList.toggle("is-active", key === id); + } + }; + + setActive(headings[0].id); + + const observer = new IntersectionObserver( + (entries) => { + for (const entry of entries) { + if (entry.isIntersecting) { + setActive(entry.target.id); + break; + } + } + }, + { rootMargin: "-72px 0px -70% 0px", threshold: 0 } + ); + + for (const heading of headings) { + observer.observe(heading); + } +} + +/* -------------------------------------------------------------------------- * + * 7. Client-side search modal (Ctrl+K / '/', lazy JSON index, arrow nav) + * -------------------------------------------------------------------------- */ +function initSearchDialog() { + const dialog = document.getElementById("search-dialog"); + const input = document.getElementById("search-input"); + const resultsEl = document.getElementById("search-results"); + const statusEl = document.getElementById("search-status"); + if (!(dialog instanceof HTMLDialogElement) || !(input instanceof HTMLInputElement) || !resultsEl) { + return; + } + + const announceStatus = (msg) => { + if (statusEl) { + statusEl.textContent = msg; + } + }; + + let indexPromise = null; + let searchData = []; + let activeHitIndex = -1; + + const ensureIndex = () => { + if (!indexPromise) { + indexPromise = fetch(new URL("../search_index.json", import.meta.url)) + .then((res) => (res.ok ? res.json() : [])) + .then((data) => { + searchData = Array.isArray(data) ? data : []; + return searchData; + }) + .catch(() => { + searchData = []; + return searchData; + }); + } + return indexPromise; + }; + + const renderMessage = (msg) => { + resultsEl.textContent = ""; + const p = document.createElement("p"); + p.className = "search-empty"; + p.textContent = msg; + resultsEl.appendChild(p); + activeHitIndex = -1; + }; + + const updateActiveHit = (nextIdx) => { + const hits = Array.from(resultsEl.querySelectorAll(".search-hit")); + if (!hits.length) { + activeHitIndex = -1; + return; + } + activeHitIndex = ((nextIdx % hits.length) + hits.length) % hits.length; + hits.forEach((el, idx) => { + const active = idx === activeHitIndex; + el.classList.toggle("is-active", active); + if (active) { + el.scrollIntoView({ block: "nearest" }); + } + }); + }; + + const runQuery = (rawQuery) => { + const q = rawQuery.trim().toLowerCase(); + if (!q) { + renderMessage( + "Type a keyword to search guides, CLI options, detectors, and FAQs." + ); + announceStatus(""); + return; + } + + const terms = q.split(/\s+/).filter(Boolean); + const scored = []; + + for (const item of searchData) { + const titleL = (item.title || "").toLowerCase(); + const sectionL = (item.section || "").toLowerCase(); + const textL = (item.text || "").toLowerCase(); + const combined = `${titleL} ${sectionL} ${textL}`; + + let matchesAll = true; + for (const term of terms) { + if (!combined.includes(term)) { + matchesAll = false; + break; + } + } + if (!matchesAll) { + continue; + } + + let score = 0; + if (titleL === q || sectionL === q) score += 80; + if (sectionL.startsWith(q)) score += 40; + if (titleL.includes(q)) score += 25; + if (sectionL.includes(q)) score += 20; + for (const term of terms) { + if (sectionL.includes(term)) score += 10; + if (titleL.includes(term)) score += 8; + if (textL.includes(term)) score += 3; + } + scored.push({ item, score }); + } + + scored.sort((a, b) => b.score - a.score); + const topHits = scored.slice(0, 12); + + if (!topHits.length) { + renderMessage(`No matching sections found for "${rawQuery.trim()}".`); + announceStatus("No matching sections found."); + return; + } + + resultsEl.textContent = ""; + topHits.forEach(({ item }, idx) => { + const link = document.createElement("a"); + link.className = idx === 0 ? "search-hit is-active" : "search-hit"; + link.href = item.url; + + const meta = document.createElement("span"); + meta.className = "search-hit-meta"; + meta.textContent = + item.section && item.section !== item.title + ? `${item.title} / ${item.section}` + : item.title; + + const snippet = document.createElement("span"); + snippet.className = "search-hit-snippet"; + snippet.textContent = item.text || ""; + + link.appendChild(meta); + if (item.text) { + link.appendChild(snippet); + } + link.addEventListener("click", () => { + dialog.close(); + }); + resultsEl.appendChild(link); + }); + activeHitIndex = 0; + announceStatus( + topHits.length === 1 ? "1 result found." : `${topHits.length} results found.` + ); + }; + + const openSearch = () => { + if (!dialog.open) { + dialog.showModal(); + } + if (input.value.trim()) { + ensureIndex().then(() => runQuery(input.value)); + } + input.focus(); + input.select(); + }; + + dialog.addEventListener("toggle", () => { + if (dialog.open) { + ensureIndex(); + } + }); + + const triggerBtn = document.querySelector(".search-trigger"); + if (triggerBtn) { + triggerBtn.addEventListener("click", openSearch); + } + + input.addEventListener("input", () => { + ensureIndex().then(() => runQuery(input.value)); + }); + + input.addEventListener("keydown", (event) => { + if (event.key === "ArrowDown") { + event.preventDefault(); + updateActiveHit(activeHitIndex + 1); + } else if (event.key === "ArrowUp") { + event.preventDefault(); + updateActiveHit(activeHitIndex - 1); + } else if (event.key === "Enter") { + event.preventDefault(); + const hits = resultsEl.querySelectorAll(".search-hit"); + if (activeHitIndex >= 0 && hits[activeHitIndex]) { + const href = hits[activeHitIndex].getAttribute("href"); + dialog.close(); + if (href) { + window.location.href = href; + } + } + } + }); + + document.addEventListener("keydown", (event) => { + if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") { + event.preventDefault(); + openSearch(); + return; + } + if (event.key === "/" && !dialog.open && !event.ctrlKey && !event.metaKey && !event.altKey) { + const active = document.activeElement; + const isEditable = + active instanceof HTMLInputElement || + active instanceof HTMLTextAreaElement || + active instanceof HTMLSelectElement || + (active instanceof HTMLElement && active.isContentEditable); + if (!isEditable) { + event.preventDefault(); + openSearch(); + } + } + }); +} + +initDialogLightDismissFallback(); +initResponsiveNavbar(); +initThemeToggle(); +initTabGroups(); +initCopyButtons(); +initTocHighlight(); +initSearchDialog();