From d99d65c7b52d39419c214ea16abf7559c3b5c7d9 Mon Sep 17 00:00:00 2001 From: Breakthrough Date: Mon, 16 Nov 2026 23:57:02 -0500 Subject: [PATCH 1/4] [site] New design --- .github/workflows/check-docs.yml | 4 +- .github/workflows/generate-docs.yml | 15 +- .github/workflows/generate-website.yml | 19 +- docs/_ext/doc_versions.py | 85 + docs/_ext/section_sidebar.py | 10 +- docs/_static/pyscenedetect.css | 1027 +++++++++- .../pyscenedetect_logo_small_darkmode.png | Bin 0 -> 15017 bytes docs/_templates/about.html | 7 + docs/_templates/layout.html | 247 +++ docs/_templates/navigation.html | 25 +- docs/_templates/searchbox.html | 7 + docs/cli_index.inc | 37 +- docs/conf.py | 28 +- docs/generate_cli_docs.py | 65 +- docs/index.rst | 39 +- pyproject.toml | 2 +- website/build.py | 907 +++++++++ website/mkdocs.yml | 47 - website/overrides/404.html | 42 - website/overrides/main.html | 22 - website/pages/api.md | 47 +- website/pages/benchmarks.md | 91 +- website/pages/changelog.md | 68 +- website/pages/cli.md | 130 +- website/pages/contributing.md | 33 +- website/pages/copyright.md | 34 +- website/pages/docs.md | 27 +- website/pages/download.md | 88 +- website/pages/faq.md | 24 +- website/pages/features.md | 84 +- website/pages/gallery.md | 37 +- website/pages/index.md | 32 +- website/pages/js/helper.js | 28 - website/pages/literature.md | 28 +- website/pages/similar.md | 18 +- website/pages/style.css | 99 - website/pages/supporting.md | 28 +- website/theme/404.html | 58 + website/theme/base.html | 234 +++ website/theme/home.html | 125 ++ website/theme/site.css | 1778 +++++++++++++++++ website/theme/site.js | 514 +++++ 42 files changed, 5488 insertions(+), 752 deletions(-) create mode 100644 docs/_ext/doc_versions.py create mode 100644 docs/_static/pyscenedetect_logo_small_darkmode.png create mode 100644 docs/_templates/about.html create mode 100644 docs/_templates/layout.html create mode 100644 docs/_templates/searchbox.html create mode 100644 website/build.py delete mode 100644 website/mkdocs.yml delete mode 100644 website/overrides/404.html delete mode 100644 website/overrides/main.html delete mode 100644 website/pages/js/helper.js delete mode 100644 website/pages/style.css create mode 100644 website/theme/404.html create mode 100644 website/theme/base.html create mode 100644 website/theme/home.html create mode 100644 website/theme/site.css create mode 100644 website/theme/site.js diff --git a/.github/workflows/check-docs.yml b/.github/workflows/check-docs.yml index b74db10c..c3462c62 100644 --- a/.github/workflows/check-docs.yml +++ b/.github/workflows/check-docs.yml @@ -61,7 +61,7 @@ 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: | - mkdocs build --strict -f website/mkdocs.yml + python website/build.py --strict diff --git a/.github/workflows/generate-docs.yml b/.github/workflows/generate-docs.yml index 0a42776a..61f16389 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 @@ -92,7 +97,9 @@ jobs: - name: Commit and Push 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] @${{ github.triggering_actor }}: Generate Documentation" \ + -m "Source: ${{ github.ref_name }} (${{ github.sha }})" \ + -m "Destination: ${{ env.scenedetect_docs_dest }}" + git push + fi diff --git a/.github/workflows/generate-website.yml b/.github/workflows/generate-website.yml index 406ef7ed..68a4b8fc 100644 --- a/.github/workflows/generate-website.yml +++ b/.github/workflows/generate-website.yml @@ -7,8 +7,14 @@ on: - main paths: - 'website/**' + - 'docs/LATEST_VERSION' + - 'docs/_ext/doc_versions.py' workflow_dispatch: +concurrency: + group: gh-pages + cancel-in-progress: false + jobs: update_site: runs-on: ubuntu-latest @@ -27,12 +33,11 @@ jobs: - name: Install Dependencies run: | - python -m pip install --upgrade pip build wheel virtualenv - pip install .[website] + python -m pip install "jinja2>=3.1.6" "markdown>=3.5" "pygments>=2.17" - name: Generate Website run: | - mkdocs build -f website/mkdocs.yml + python website/build.py --strict - name: Update Website run: | @@ -49,6 +54,8 @@ jobs: git rm website/build/* -r -f --ignore-unmatch 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] @${{ github.triggering_actor }}: Generate Website" \ + -m "Commit: ${{ github.sha }}" + git push + fi diff --git a/docs/_ext/doc_versions.py b/docs/_ext/doc_versions.py new file mode 100644 index 00000000..893a433f --- /dev/null +++ b/docs/_ext/doc_versions.py @@ -0,0 +1,85 @@ +# 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 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: list[dict[str, Any]] = [ + { + "slug": "latest", + "label": f"v{latest_ver} (latest)", + "group": "channel", + "same_layout": True, + }, + { + "slug": "head", + "label": "dev (head)", + "group": "channel", + "same_layout": True, + }, + ] + for slug in stable_slugs: + entries.append( + { + "slug": slug, + "label": f"v{slug}", + "group": "release", + "same_layout": True, + } + ) + if legacy_slugs: + latest_legacy = legacy_slugs[0] + entries.append( + { + "slug": latest_legacy, + "label": f"v{latest_legacy} (legacy)", + "group": "legacy", + "same_layout": False, + } + ) + return latest_ver, entries diff --git a/docs/_ext/section_sidebar.py b/docs/_ext/section_sidebar.py index 32aebba3..d525c415 100644 --- a/docs/_ext/section_sidebar.py +++ b/docs/_ext/section_sidebar.py @@ -201,11 +201,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. diff --git a/docs/_static/pyscenedetect.css b/docs/_static/pyscenedetect.css index cf1d0147..93b9dec6 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.surfaces div.surface p.rubric { - font-size: 1.2em; - margin: 0 0 0.3em 0; +div.body div.surfaces ul { + list-style: none; + margin: 0; + padding: 0; } -div.surfaces div.surface > ul { - margin-left: 1.2em; +div.body div.surfaces div.surface > ul > li + li { + margin-block-start: 0.35rem; } -div.surfaces div.surface li > ul { - margin: 0.1em 0 0.3em 1.4em; +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.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,916 @@ 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.3% 0.002 250), oklch(17% 0.012 255)); + --psd-surface: light-dark(oklch(97% 0.005 250), oklch(21% 0.015 255)); + --psd-surface-elevated: light-dark(oklch(100% 0 0), oklch(23.5% 0.016 255)); + --psd-fg: light-dark(oklch(21% 0.02 255), oklch(90% 0.008 250)); + --psd-muted: light-dark(oklch(45% 0.018 255), oklch(71% 0.015 250)); + --psd-border: light-dark(oklch(88.5% 0.01 250), oklch(30% 0.018 255)); + --psd-brand: light-dark(oklch(42% 0.115 245), oklch(75% 0.115 240)); + --psd-code-bg: light-dark(oklch(96.4% 0.005 250), oklch(14.2% 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-sun { + display: block; +} +.psd-theme-toggle .psd-icon-moon, +.psd-theme-toggle .psd-label-light { + display: none; +} +:root:has(> head > meta[name="color-scheme"][content="dark"]) .psd-theme-toggle .psd-icon-sun, +: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-moon { + 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-sun, + :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-moon { + 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 { + 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)); +} +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; +} +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.top, .related.bottom { + border-color: var(--psd-border); +} +div.footer { + width: 1080px; + color: var(--psd-muted); + border-top: 1px solid var(--psd-border); + padding-top: 1rem; + margin-top: 2.5rem; +} +div.footer a { + color: var(--psd-muted); +} +div.footer a:hover { + color: var(--psd-brand); +} + +/* 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; } - /* The sidebar is drawn as a dark block at the bottom of the page. */ - div.sphinxsidebar code, - div.sphinxsidebar code span.pre { - color: #DDD; + .psd-topbar-inner, + div.document, + div.footer { + max-inline-size: 100%; + width: auto; + padding-inline: 1rem; + box-sizing: border-box; + } + 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; + } + 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; } } diff --git a/docs/_static/pyscenedetect_logo_small_darkmode.png b/docs/_static/pyscenedetect_logo_small_darkmode.png new file mode 100644 index 0000000000000000000000000000000000000000..5b080af2df966a92452a58b730c98902683f956f GIT binary patch literal 15017 zcmbumWn5NY5H7l38l}5SN*Z3eOOZx8q&ozZmyqrb5owTaB&F-6l}4l+q+7c0=6}wY z^W~m%@A*LdcFbC9_N-Ym&odLDrXq*=jO-Zz0GRS`WYqxxG6McTi-rRJE|DH%0{@^p zztM960F)B&ryNq9x_<;-B!#`wg=sih!Q4$hS_1Cw?i{v`_Ach8&XycbAFb05Mackw z29TGP()7qUSp1Y>ptUG*JbFnFop}ERmP$XNlAu)LAI_XjQ}gWmv&f%xbj*R+x!KvH zr!M`N=WlV{KM_cMesv7d{QN2eE8D-==GAeIdaBzOm_pL*N9csD$S<+wWojtP)XgAttDN`{g&UkxLw?3>s}P&Pegjp+Al^8h84e6#{8A+IOGfFN1NU z8)*VGz}wDJ2u0w{)j%W_@Yyb8^bGKk;OBUPA>dVFdgo{0RgVAn7e{903TkCg-w$Ah z6t%nn2O^GlVC6q8IPGHr?0MJe5mb<>FyLt1BT=t{I#Mf4 zwssd@fm1WTn^+7GQYe7-<mgdl5y7K#TdMrwT&m{h$+#;Ag&-fyD z#H@-`^(P^c^f6X02-QP98C;_Qp5PvR0_i(#x_cC5T^YDOaNugMbYgmvG&bQ{W{gJL zMbFb17(tpY;^k4WeHIh6+Qn_@WfhULpZ?)Z36sAIF1b$M3 zy4_VmD0-gmg?f3J_z5$78t_2$|177K4Do#?`v|N{1E-7H@a#OiczBlBZXAwuIEzK` zl(e;5aRKfoy7}nKldJqcnq z)3P$Cn#rMaxX_8vMm3POJG115;3rIk?n90BP0sNbk#QN}^0Uyq4MzRblY{R${fvu> z;2T=QP4LtKj5dmVRk|)Rlq`T|+w}Yq;WMgpt1Gv!zgG9Fh@=p`mS@n^p+MZ_J174g z^_j(c9$$hu6i(MALr{X_!D)bth9mO=eDmaKnMgE;rsr)mq6(5>w*P{_kqChN+CCB8 z)qWGUdcg)@ENm?vexO38uoc6HaYqo%A7v(X^2S-nzb0y$1~l0a9}ee>vop52imgoG zSRTU&am7TH+{805f?ADi&+L0=(c6twGaiFCIOEDyO}7?>2C#%r*QLEtm@S1ZEm4Xv z#K+HaObA-C!2*3!ax5$Zwj5g*k4B%`w&BV)(mkyX-;_lR}d0~n^# z&O-c&o5w=c`J$G8g z5i<}I>#0gIGesUv1;cqwkw^?~*MV}h3z?k8#@cDuMlO;gxK67!U6LV*v8m4AbXb_a(MRHcyP23$^+`O*fb3|h%w)S05gKjuFq#&D9$uMuPs~%{kU1ZZiy#gh}Tmkwsy;hTi)7m~!!% zxw!>{f((g7YSBQrJ)BEaxr_@UrTWV86DT{Oa4$BY*#!|bS<2q#EcTxu5G7jfNB)`# zO%Hi_E3wZ@yB_6nGh19?GX@)HJslv@|2i1Blk35I3;?i80-fa4X*_dwfBe;hv~h)c zM2{+rWz>r(wt?v;_Wz`_IXik*`xU5`@W~3=I$ZIsnVzQwoFkQ+Z@PBh=P(hou~VTO zvm><*t+nFe`Y;e-c@ttyiMxT4)6<+fw=FX5NTN}tW~f~$Vkz?=cbWcJ0Hvqbaol8R zCg^27@+tzLpaZH;7#a-UraZn7VgT}i@)vzF;u>N#X0Ke9dl2%PthWp?yHHKzUBmo~ z2E@<5X$_`59%LK(u~>WK!HEIhKMS{W@9DA;qp`FK<>uxP?kC1j!O7R|5(!SsKIm{= zQ-wCTC$*3$c}vkzH22G|TBx23=by*$*M11=JUan(@j~}+ys{Mvwr1os&oRW`c(s0= zZ<}@n7ezRw=>;w(Ls9mV$I$x2?p*k>uM)^GN**x&H=!PMJwBdI+rs9q)zY(<+a80J`B)y1z{GP^B zj3f*}jl(F&fDy7sx(&F<*)pH~-JP7#>%RbxHzjE?#4WV_EC>@bDN~vAqVnw4TLRhni{Y%N$qKR=O!5QjLAIQE^$Hwz z_H>MToj=R?IzZ~y9hEuMI`s?MGNQuEhZM~jbn;6#wX-6lIvjKY%$i@$;h)Y|DJt8=O5 z2v_DMg8Q}N?iU3`1;*X|BW&KU-pk0&IhLK(2OTyr!3z@Ll;W~q3?FU`IW&3Q@9ej& z`o+Q!jrKx$LP%5OZEW^3brf6ssQjvCy$8>m<&_Uz?gISKu^bXg5~(oJA_D2~rkrmH zLA(ptVLaTv3$h~OL=m#}dW1t8AD=h4Oo)VU>;L)iIQ*dokQj=NMbU6C*R9U?dNv0} z8{FLnIaYtjZrXrQc>9dYB=Kc1-=+9eM_Y7<0Hd z#;WBHm@Bd_Y*w-Ue6D&L413 z!YiohPy4ibu6pvx7Gu643a%>~-qLJJ^ycM^s=5mVEs8Bv4*8Y7Q{Z;=IA}S@zkCyV0yLLF`d)`?V8yC9t#gMhe`zJ`ACH>DQ zh*j}u@;~-|2L@|@q%u**A-$Mb1kb*iWRJ7x1nSd5Do__@R;SF6!1m0Xk(1mCvAvBr z=?VPFSm;}%o(}1a_r0NftFWwy-E?z&6|*iaEiCaOUSl|sNUlwYDvq<;#>mO{p0l=6 zW&D>3SNsS@+D-Neo(G`zcY6}xq@dYKBtjpMR+u?=5dnmIFnrO*6a_vHkh7vA=AZ=vz>$Ok7lF<$cE|sFJ^m2o6N6z0{B7cv>ZXG@3 zVbCE|=cd2C?h1-fjfi6+e$ zLk(tl>Eh7i9NEDxhr0ErGd-wD-(=x6{1(`@+bXK*O@Q3VC3cTG?mhSYRqFTP|G~1( zM=s)I9du|TYp|?QUcYB1QUyUOMj}vyr5G??FQ!%vwR5+%x1YyaAp_oQM4zgO`F&6H z!i!&_)JFa>dn^GYX^Q?li%5)@oD^9eMnsg7D4}-QXit=1_tB16O=w!%L%Y(g>z==7 z7=#6ul%E*Wc={xEs~Fv$7hlYQruxUw5Q;jP-2k4G<{aBaLev00JR-YUy% zKY~`({N|>+`B=`^*gn^knQ23}O%7-d{LD+e?m|prCogyN<$-$8py_A}?Vr_UnQ6TS zqYj_pVz_*?;?u#aBeJwO-GCswT>jA`o$eh*6zv+!@%X!}w{LGybdgtAK&9S!rRm#~ zGJsO^8rIH;i+R7a2J2A2u>ww6DKq}sgCP?4D^beQ%=~%t@fA+C*aX{~N>uX?y+Lrl z3JlaTtZ~NYAvggQ-#>a3#hrO!qbf{}sBWMdW3R<&3blU9VKIE$wkHXmtq5@3#JGR& zt8ISX)Ft0ZK(u_HY_D(xqiOwbbfs*vUgDe0n5a&{rh(O1UHU8hvQt~8dmMOVu(A z9Ou;6OHNvx7^X^Rkm%?LIeb+<^{FDsRo;A71o6;Gtbbf0M)w^o^?G6VFkQyL0<6y; ze5WlNlJ{ji1=nBt!|8f1VOF|ptq$DuDP~ZU;-qgcF#Uw>Tl4hM3$|r|G}dpJcNJ3C zM#&>&m1VGZ_yhr^6+84}l?F9^^AlRn)d;e&wSxo>iLcSQzd;ORB7m|$Xt`+msW77e)=kK=l}1L#s4MCgwj9|mQ`ghmEAe5@U1cs zS1>0QvB6146^c3YnEQz0wK_K6a;Jk9rh`ELl&%&AU`+lWWTgMgApc)d+5gKIA7So5 zaPLlQwOw-ycNte;_RitcQKQ^5S7@>B}(569qfzWAD0FCZTXK+P1P@!d4?1Vm~E!1C~ZY$S#Pq69gfPj4V`h) z`9`OT;Ej)&1F+2b4BRIuBKbaQgfaIygaR=dS$>NI4h5*j3Y+VEKApZE6?wV&Rda*{ zsj3)D3+k^-BRV{!%K!D8Q@dREw_%uD@Nth4b_PB}#E19z2aSw)5f15V^+l1KsRA5~ zg`)`jvy@`EROZS$y?Fu4W@k|fXga$jf=s_IyH-|*ICqmezWn+kERd14I>SJN3ToXNwVm8h$eDloz^(giWa7Ppa?jW--?zf z@LUxoW2ausEZ zRb!`giHt-jA+(RXS<^Kzr=sZ*2Q}^}~ z#kVnJuNVqBY@WR(Upwu*VuXrenRt-RNr3J)&Vnb% z^_qvEt0e76P$x7f9e7u}_ejp4{b8KPoDv#aD;j^oi{>+lg^#l`zB-T+b=b<8$>&QR zh2pommO)CJ$!hd0u$z`_gzHbH?44k^0Dgj0IkC+@RCork?#wI>!T1#VQj{1w>=4EI za>noem-h+1*+b^Atq36cc0(5m=l0j9bPxP66aM?s)om?!vaEXI)3)3+-`;4aFg!NVcq8~95HjMoSDPXpW?IVBM|M8$WM?qua_+3I zXc3LNWFa|=01m&%Z&Qbo@wd%@)7IT`ob|7Dwhx0v4yfO2K)mF;Rsd)zYT52QtLlO+ zCcc>+vsdCccm5M2&sGaaMat^m@BIFLVsmV_!P@pLPo~ptj+pIbhQX2VCtF3U6&nD( z<>Qd|TQ-Wu-#hfhiK{Dxvh-)T2#((zs6&byWO=_vzY5af+g(i#a^|C8lb~H$v#4;M zBY>%fw++p}n+69g2aSR&R|x>2`7YU77Uwht%7g5gya=1^qPjnozs8ZnaG=um_Iu8v z6n98LBOyUT_((S@?(Ua&FSpZhyiy2j?bZj0EYyY8Yk`Ue7CAWj;^N||wc-s&O)4%5 zU~*$QjL9WtcvQEZZnSSaE7{J)iiA#ML%{pNn2u~N@TKlroR0t%L$hI^Qofa*@AcJgH-gjPb82M$gspkCkZR>wI$D~ng4Cs*v4*kn zU{`x;YxxUY^gAaOYc`}~{Pf&|jnK_FgsVA=`Tc!ajqa`-t#X(eF6Zx_HY@o{_Uufb z@87>`NZ<~Tvt$b3S(u^U;`~+$5?@=&^sTi%|H9B)vMmWN)B6Csu6B(^iW6yvl5ry2 z3ANxU_tZSgp|UgT*OOC-l~uDUB>Gh6)%?I)_rCPYG@0l`YnD znlO!DqF539o)6=FMun8?@kg{`yZKU1`DI zi*wJ0!MF8}l<)NI#*Tn>3qBjvk+#`V*gSljsVcW0P6Db6h zg?mIyCr&G? zuN-yiJ%Z^n5Rdf%)Z80PeF?Z9!YXdoXlvfnw$MH={1{>&_2B@QPRIFDB9i7eu5OL(4S z0BFIU0I?pS_2%WIu%^h|>s29ttWuA$S1U?IF}1!kOSpwpSeP+o;Tb*YG9=y)%Z0$7aLV5Ub-^0?)$8b4m0R(vAg4&GgCZ9=b_v$Z^ zlxuQudnqXW%gtqVYJJPy4q4ISP-TZSmh`l{CZql5v6$Jg$}+J^z8PxPLhES|Cs@%WUNZ zuz+Rkj=Qc=ZF4*_=Y^hs8YEY{SsB!rq@+p~?e*igPJI}$gh2@yQDby&wyh9wQ-SUx zsk&z%+OJQD3jcR~NO+LO7-8j%cmqRjgK|a0FJsAkmp=K0U_ZR|gkp9Z1W6J9z2uGP zt%RoBVZ)wp{FemAQ)3Qyq|s&eXlVcr$_ZadM)k-ZpFhSkM0nByywf+u&lQ&!VnT)M zBc2F#oUek!)cwd(GBXmkepg0<-Q_ce^!lh~X<2f!)_@1Gf9iLb=PYLpvntJCKNNr~ z9evQZ<}vW7v=SBJ|Gmy(g8-axmmhCwE?uSUx$Nb$8i;lYIc zPlVZRF6mv)=E@H1xTWk&$W%{I+Z2hB<8XPzy;Zj}L+B-4aQTl+`ujQ(;53^#IikmTt;U^NsgSWvW>DK(Z zShG&QFe%C-sHM-hit7YDWOqbXebeg)2>QL#{E*=fZMFdcaqgB;Zlm^YPhV1bqYoAE zytkOkG!aMa*gkw&aZxoQFaLvI0(<4rA(C%o;(_nKe0_`L>W8}+BFPnu$Dk2DD7**~ zD0O5oVzqgjSA=VGjia-trgAcVr!An^JXBOitd zl<^YYLcAhoEy2PA@1e+>ke9I!q+wweaCUR38xP3q4 z-*=tU>Gm%b6>od1iuBQXtPN=23Fe~RDTXzHs-@e9Nk-NyoTq)ts~eCRDgmg}fI#|l0;=i}E zqnF>fQv`@K$zPE}A5kKC6kfpL@ieW3Q=Ko>{*}dNav6kkYol)S*$wruCb+fVhEju__*z@?VRw*kUYWarqR3&=5w{~;~S zFWGLBA3;|zrV=T_KaJ@G?ek@Nbr_=SD?h2w{CMI+K;}RyV(`4SJ_#1^KMB_dEO{R$5@s z10m=3*|9qbfaAx0+i>(o#a(^)+Q+Fv>=p;>6-7pGfkR@wugmA%AcLdWex-uqxBRPz z5v7e441_9Q;VNuKcSN%z*L<<+En?7@_EN@D+>AV;J07mOyZ?88^5*BiioB&-JNMZy z?Csk45|(=5Roqlqhpst^Lqrwyxuf&EZ>=_?SlfuzQ*)AKQab`%Lo3ZnI^XHNfB!cW z)8<{{pQ^z!gK)XPSjKix4-o)WJ^PzGi2}3jN9CcN`9;Hbx%b{8_)8Y9%~RgqUiRD7 z5fapGjTx7%i@h)XeNi}+Wdq$cg;R!zmsFGlvgf|=04B|BRG9BHcGQH81+!AwYV&Z{ z=X7~JB9tWz(=lc0SQ1&i`^T#Ya@MHP01{YcP(9Y+05-*1zDAxwz^X?X55_}k!g&w~ zd99nYPs+F8GXwVF+eKE0Tk1mQhCEL1zOWJ4Q7!F*=GEh{iRU2<0AwsrwE$TX$>ENX za?(c?{L13(4pO1%SE9O$EY2IWP6gNIRnOCc&kH(Ngc9ph>_7mIDh_E`)qf+I9rx4M zy|2)oO?&+KmFa#|Wk8UExwk7ID?XymKPdliPZIiL!u1+CCDJgi^35LwDSQCrl}Aah z0+r=dX3xwX71G@bW%aK2ttU>G+>M*wInv_#+Z3C|UDosb!f1Cjtq7zMd=EgZx8_k*g2xj_{MkQ;u${iR%? zdKsj15D+u9o)@SD!Uo#lKvH8B{KY%p_NnZ z>en!@RXF2$QDrt`EC%&ed(XbW@$h@a9inR)_trPd?=_n$chvJtrK@>+?E{q|5#stI z%OxD_Ft(1?{wYHPMq1hy!yM7y=W8nvlB{<*HSu5c+A)Zh8Q9s`Wrpt92lb2B?CEg) zX6p0c$@n0f|6b8n(-8YPQ10eQ`Y2>&^jWVl#?YS2P zNgJ!`Mobu7a4@$tZ-r)NdLCrgQU^MN&qe)1E$~hmTRGW{=9w9rQLq?;xlb!2wqa3p zMk9_D3fE_;RauSatV}M{XlM4oa*4kGc>PZAL*n}0?f@~?Tbh<8RG-tTb+3!*Wq6jj*x~W4%Y?VJ+ zctXrgvrPMT7B{KPR#%$AC|?pq9I?y7MdU)*R# zy%UHE^73Iut6B)OD_823C%}&>FrBy2OD?@EhksCd?4bBsdh;IYz)y+VqW3kpD6{b7 z#pmG=O6A3)zHf^)>}>C5YHwfDr1prS>>sA2Y6j(9;#DsmJ&X8mfXdFa;L-DN+Szic zR7VhplmMW7AGo@+i@OB4XAK)6@HQ0{#jEkPI$ksmh=%X*+b88|j@#m8)|4_-&F-LM+;9i5hYd;! zmet}DQkPrvq#~<5-w*Xaw6V1%{Ww=-*T=YYC*WUM~8$1wcbhvUe;>dkNH4t-igvnqmQQUR>r7&W&!W)>6<;5u>+-Ws!TJa%9Nn`J? zvr}Bv!GBb7>G{#Zwz^Bqp#<|^B*`?hgWa@1;ujA^H7;7JYpNUES4DYe+RjX)$vtJz^HU{hCD!hF z(@iX}E?+!=&yN0gJAOltQvTIV8Jstp=IQ*Y&n2%oC!S zp6LjF@3zETAgMb-I64u_=F^Tppr#Jv>7LcsVoG4=o#u09`B;TXyJG!XIo(DxchZO$ z5xvFbbtuvMj}xy&$y&+a`R=u83bh}KFR=5^s!!f*FV-Et>_?ivOAa3BuEUxN6yLMh z%hCUCRFj_)j^s-fhcc?4{hAI#m^gU3Yf=X0i=1|`)cu*4jS~%!WF1URNmyg59~Ri< zOVetKId~MOI_)g`6PzG9q%sw7$bB7?U3k~lqcHs0P!8Z*F)Q5ZP2O+jS? zrsIrt+S;6Y>Pj2YS>2wTL!a!JG9f0HT{az~msGmO4*O~h3!85R4D}}QJRor7U++%z z5gs}B!wh}IwUZGzG52tJg-8-g=c_W+|5gebzlk=x7|tfB(Rhtdsm$*rf+Eqd^;q<% zGHV~Xk~I<+rY>7}-|wg5?O!D7Y}b`}fJ^-HvUCKJNzn_-WUOD1^>lDMP$Ydta#Z)Q zv}RmihfG<}_7wA}H)(!iFU|!~2ub$T;Lo6mE`a;%hu(z*Bz+4PLzocGK;l)4Z8GnOZEMDOno@?VF~zbuG8>zi~;rgr6d-DPprjQWJwF9~H%D~q@x)${T0 zCl=f1`W&ise9;3z-jCX^5&e`mVmjvO$;3?+osRw`4kopwfH?g`kgFi;_bf|d!h%WRW=K!Z>9&D|} zXTO&YNR@`PVR5huQK7e!Cd{jkD+oBWYt;XZxf*aDn;e>(wNk;3KF}WQUi^Ax7Fcl=ip8}zxW2Nbd5;;Ry5FO zleW-j(>-B?%o`eQfi-ZLcOs*Q=_L?x0JM z!6eMs7&^VeTl%a|&nS=@=Z=>lHFGRDNaX?DKT?3Ir+ho1^d|Kv0_CXWNAd|QZNfbR zkeu^XW|GXRd+F@g#n{Jtu&<14d5ZnP+nj1bkD_3Gs%{#JF&IK8iHyHxQcCj zI4-;7gT@7E?+1@%v98nDb}mLtvb139ZqhB?K8 ztM+Snk_Yd~iVECycq_lAZxV#*-6BdaYlNUU=GHB>u*1Y!?Q1`TThsWNs#%Xy&-CD9 ztM%M6NO=|Wm$+BS`zLHHL|Bd}Gj1eF{!s}{U2+ElF%8uX4MLfmzO;#~3tOA5q#;*i zs0G^B?xiB{4*3*z%0FncSc}#cG`N5IzL<{W2c~o#`_rRB7->G@e%I#O$ljQnai)(( z7u|n|h)+;9NDz1vQQzAYyk{pKY$|h)I2~e(-h@J-NrCg+KIlR)gmQ zg#iMSe|4skodQEqs*|jbRn@iRRm$vGhLUAWSwDY4y*DC#LQ3)g;nJ4I?n}X+FVR;D zBP2-X+1IS=t?@>5lb}>{3mOadbka3yXaz2PbtX5TT?t_#Ebo-Rtd*^pOO`LXA_|h};5U@1vrRy#&xj zjHvrJ{oE196_MnG(NMRAUo{nkYMTi=?@s<%)Oad1f#s$OV3mu?Mzkvkcmi#Sd_rv= zwTmII0y-MNPoI8l-u2B-!fLaO;>Q;1gdun=wt#BY@+$(XL%_=3x+i!ua?lVk>OGE(;*e#)Ixn!-0E#rEn}QC z8-HeL24bwq7v{bpdPchsFOy&8;xfcakLE*KfaKoh4663$Dt?o@FH~;%GD0R{_A!mZ zOW-?S<;Uj7RS$!j-f6qFqIch{09{r1a{vX-Y!gUVXh|cE10Q#;@!Bso^3$W#wT-F* zgKyTM->>0s9hH=WnRM5MaFQW&*zl7oW3=J4v$FZ_DAtNRMa$<6{@Y?$bEvO__9Z&+ zFy5R8Hrm3b@naz{W)}J`>p}y(amn7+?#$VoB$VwJfH(wcu!Rihrg@-1i|dn{#yfPS z9a~%!>)1Dj(c^wcJ|<1SQ2;9FyNqAoZE7U`<7PSyX~0j&6C>`o==8wr;pF*>-e;!1 zz*8UE^qW|xvXYm?9)u5!R#Q4yjXgr*cF<6$<5+|;_aZtU6T^c`o#3J)|AQ+y<#6jH zwOWZo%7-)i;~-QKMCc1BZ}HrF^qfhqKh`~1$WC^ zkYc8wDUumt^zXnOKP_)cMvDT1Q>w_KWzb{GLGdYrUp)cgL!NMKCb_`+!dU88OI`_{Gi;0TnL^1}B!!c|h1JXULo3^-*gP0`zzXtfLP}=mKMT9<#wAg*s;Z)qO(NB-lKm z12(5`60b^+jUDeOZn2Thplk9QlYT7Y>tTSZL=iEV(4gVMKzTn+IQYC!m6GZ?>V8(6 z4sKkixT>u2S(VOuyjAN|sU$t#EK07^w7QUtmiJwv4f-9HQjs|f-)VGqQTedJ`xlW$ z$vXPX+J_0hlSC9scKpaNnaeJz+~j9(kfXc|KMOJhxMX~q`GmS}-4R2#AUgZ1sZ7V* z8dQGnsIf08;xy!ZzCSjA81Ai3hgY6K-M~W`g~G`&wgI%xMEHc0Z1r|YS*N2Sk{Dz> z2y-dhu{NQ*ae<5G^(YNGM{Lv%E?GT{CqH40! zJMCaH&;#lCF99x+DUAWQ7NXed{b2Wu$o{jw?tn@J{4e7oovk%?nd5N8F+n$8xoSBy z#364}QHq-?!*MP40OFZxXL^4u)j2Cq>4e80EThw`FYPtj@cE*ZuK5&K&bqd>XhoVz zEe*8=JSH8VB6bjaL>)Np1#T!>hi*Er1aQUGs4&`js4$xz#}Fu@kbHpy5e)cZG52>G zsMv^p8$S`|($2*K$mSBpp{SU26*zO{{gIZyuV6{vd@v`*sTIdP2O%ZWI24K3`LW$L z|8DhDY3>5Qit|%pe%o=C#wM;0awZNRotYvQ-v?Ix-w_FqkfYcN>e)J=vSMIfrOH zoDlT;dab1`EyIL=w^p0oXn$X&a-{hmVi>b_Qp1C+2OAL?5yqM1Y$t)g22_~~_gZ)RpWyBv zJs#xvBcOp-S|%~!G)J7s;fRfyINn-kyJr0r5l)Lfd9%AqBa{f;=uthhk5e+% zT3Dy>}!UELb*$^(F;Yw$y^5W|m-FvAYB_L=8qwoZAq z1JW*N|K|gp0S(pCZND{1*GvJO7F-SQkrn_&`9b8L$ zUBlQ$VQHMOKTE`5co^C%Oid@;F?G*lUq@x5o5o&l5<;VdEmTaA{{%DN; z=DVF?E1|}Zo+rv}oPQC<#hnz0V^Q@h7-GY6_4+DAmu-9Fv+k>>QrmRP$A|nX61C?f zp5*DQs%y{u=x8}y4&KIwzgqqt991CM<0TmxQN>!o=Z^lLX6(Gi7D2-fKX@0 z6@Q+R4e=NnR=eQW68JZD(j9X|GwN~v?Nl~s*3mk)xoBuofkHq39wF~Jh~g=kf63Ya ztDl%m2=S$XVU2RsRBs;#b%{|(PfSrfpd{g>%!6U=3x;y+yIx&`f@|97J=mBGSLeEPf?k zV+QPa!GR8Cw5;!gHPa>wO5IPr5l@A2I^_>Q6o~elc-M|BJ{8z^4>yU7R4?Q(neg6g z;pEvq?&I?Jb$15Q)Z&ETn5mQva;!qhRwaQ`pmA>HtF9jf9xr%(Bwa(M&OBYZWt6DX z+n%k)mE`DW6(Y_I$9hK>kt?}= zq~mGx3VB+9(B>aXCIZUsDvMNfoy5>Ux$nB;@4S9nfGfDo5OVEDA12Q}HsFc{s$iAt z!7*cv%UgN&^ZE#xXsSNMU={O_gNvik0LK$WPCoW$mvhG|VR8&%+1VXD8~7LR@xak* yhiCt5mi%MpD7OC8Jjp2kf88$mzb}ludfc@)Q^^jwGXvX90r^)dvK7)Mf&UNe-ET$! literal 0 HcmV?d00001 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..d7c2f158 --- /dev/null +++ b/docs/_templates/layout.html @@ -0,0 +1,247 @@ +{%- extends "!layout.html" %} + +{%- block extrahead %} + + + + + + + + + + {{ super() }} +{%- endblock %} + +{%- block header %} +{%- set psd_page_rel = '' if pagename == root_doc else (pagename ~ '.html') %} +
+
+ +
+
+ +
+ +
+
+ + + + GitHub + +
+
+
+{%- endblock %} diff --git a/docs/_templates/navigation.html b/docs/_templates/navigation.html index 7da16877..ef2aae97 100644 --- a/docs/_templates/navigation.html +++ b/docs/_templates/navigation.html @@ -1,24 +1,13 @@ -{#- 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) }} 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/cli_index.inc b/docs/cli_index.inc index ebc2ca75..eef856f5 100644 --- a/docs/cli_index.inc +++ b/docs/cli_index.inc @@ -4,8 +4,41 @@ - :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-hist ` + - :ref:`detect-hash ` + + - **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..22090471 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -13,12 +13,20 @@ # 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" @@ -56,6 +64,10 @@ # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] +# 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" + # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # @@ -156,17 +168,22 @@ # -- Theme ------------------------------------------------- -# TODO: Consider switching to sphinx_material. - html_theme = "alabaster" html_theme_options = { - "sidebar_width": "235px", + "page_width": "1080px", + "sidebar_width": "255px", "description": f"Version: [{release}]", "show_relbar_bottom": True, "show_relbar_top": False, + "github_button": False, "github_user": "Breakthrough", "github_repo": "PySceneDetect", "github_type": "star", + "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' + ), "tip_bg": "#f0f6fa", "tip_border": "#c2dcf2", "hint_bg": "#f0faf0", @@ -179,6 +196,11 @@ "logo_name": False, } +html_context = { + "psd_latest_version": _psd_latest_version, + "psd_doc_versions": _psd_doc_versions, +} + # 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 diff --git a/docs/generate_cli_docs.py b/docs/generate_cli_docs.py index 6e1e99e1..674980da 100644 --- a/docs/generate_cli_docs.py +++ b/docs/generate_cli_docs.py @@ -845,6 +845,59 @@ def create_help() -> tuple[str, list[str]]: return "".join(lines), commands +CLI_INDEX_DETECTOR_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("Fast Cuts", ("detect-adaptive", "detect-content", "detect-hist", "detect-hash")), + ("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, ...]], ...], + indent: 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-")] @@ -855,13 +908,11 @@ def generate_cli_index(commands: list[str]) -> str: "- :doc:`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", ] ) diff --git a/docs/index.rst b/docs/index.rst index 307be028..981f3d68 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -65,12 +65,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.histogram_detector.HistogramDetector` + - :class:`~scenedetect.detectors.hash_detector.HashDetector` + + - **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` diff --git a/pyproject.toml b/pyproject.toml index 29246a1c..fc4e89f4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -67,7 +67,7 @@ dev = [ "pytest-rerunfailures", ] docs = ["Sphinx==7.0.1", "sphinx-copybutton==0.5.2"] -website = ["mkdocs==1.5.2", "jinja2>=3.1.6"] +website = ["jinja2>=3.1.6", "markdown>=3.5", "pygments>=2.17"] [project.urls] Homepage = "https://www.scenedetect.com" diff --git a/website/build.py b/website/build.py new file mode 100644 index 00000000..70dd1bc6 --- /dev/null +++ b/website/build.py @@ -0,0 +1,907 @@ +# +# 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 + +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/" +RELEASE_DATE = "November 8, 2026" +DEFAULT_DESCRIPTION = ( + "Fast, frame-accurate video scene cut detection and splitting tool in Python " + "with command-line interface and API." +) + +PAGES_DIR = WEBSITE_DIR / "pages" +IMG_SRC_DIR = PAGES_DIR / "img" +THEME_DIR = WEBSITE_DIR / "theme" +BUILD_DIR = WEBSITE_DIR / "build" + +# Each entry is (sidebar_title, top_nav_label, src_name, slug, is_top_primary). +NAV_GROUPS: list[tuple[str, list[tuple[str, str, str, str, bool]]]] = [ + ( + "PySceneDetect", + [ + ("Home", "Overview", "index.md", "", True), + ("Features", "Features", "features.md", "features", True), + ("Download", "Download", "download.md", "download", True), + ("Changelog", "Changelog", "changelog.md", "changelog", False), + ], + ), + ( + "Reference", + [ + ("Documentation", "Documentation", "docs.md", "docs", False), + ("Command-Line", "CLI", "cli.md", "cli", True), + ("Python API", "Python API", "api.md", "api", True), + ("Benchmarks", "Benchmarks", "benchmarks.md", "benchmarks", True), + ], + ), + ( + "Support", + [ + ("FAQ", "FAQ", "faq.md", "faq", True), + ("Bugs & Contributing", "Contributing", "contributing.md", "contributing", False), + ("Development & Support", "Support", "supporting.md", "supporting", False), + ], + ), + ( + "Resources", + [ + ("Project Gallery", "Project Gallery", "gallery.md", "gallery", False), + ("Similar Projects", "Similar Projects", "similar.md", "similar", False), + ("Research & Literature", "Literature", "literature.md", "literature", False), + ("License & Copyright", "License", "copyright.md", "copyright", False), + ], + ), +] + +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" + "# Detect shot boundaries and split with ffmpeg\n" + 'scenes = detect("goldeneye.mp4", AdaptiveDetector())\n' + 'split_video_ffmpeg("goldeneye.mp4", scenes)\n' + ), + ), + ( + "cli", + "Command Line", + "scenedetect", + "bash", + ( + "# Split footage on every detected shot cut\n" + "scenedetect -i goldeneye.mp4 split-video\n\n" + "# Export CSV cut list, thumbnails, and HTML sheet\n" + "scenedetect -i goldeneye.mp4 list-scenes save-images save-html\n" + ), + ), + ( + "docker", + "Docker", + "ghcr.io", + "bash", + ( + "# Full CLI + ffmpeg + mkvmerge + PyAV 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:") + +KNOWN_SLUGS: set[str] = {slug for _, items in NAV_GROUPS for _, _, _, slug, _ in items} + + +@dataclass(frozen=True) +class PageSpec: + """Static definition of a single page in the canonical site tree.""" + + group: str + title: str + nav_label: str + src_name: str + slug: str + is_primary: bool + + @property + def is_home(self) -> bool: + return self.slug == "" + + @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" + + +@dataclass +class TocItem: + """Right-hand 'On this page' anchor entry.""" + + id: str + title: str + children: list[TocItem] = field(default_factory=list) + + +def iter_page_specs() -> list[PageSpec]: + """Flatten NAV_GROUPS into the ordered page sequence.""" + return [ + PageSpec( + group=group_title, + title=title, + nav_label=nav_label, + src_name=src_name, + slug=slug, + is_primary=is_primary, + ) + for group_title, entries in NAV_GROUPS + for title, nav_label, src_name, slug, is_primary in entries + ] + + +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.""" + if not img_path.is_file(): + return None + 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 rewrite_internal_href(href: str) -> str: + """Normalize Markdown and relative internal links to root-absolute site paths.""" + raw = href.strip() + if not raw or raw.startswith(("#", "/docs/", *EXTERNAL_SCHEMES)): + return href + + path_part, sep, frag = raw.partition("#") + suffix = f"#{frag}" if sep else "" + clean_path = path_part.split("?", 1)[0] + + img_match = IMG_PATH_RE.match(clean_path) + if img_match: + return f"/img/{img_match.group(1)}{suffix}" + + if clean_path.endswith(".md"): + stem = posixpath.basename(clean_path)[:-3] + if stem == "index": + return f"/{suffix}" + if stem in KNOWN_SLUGS: + return f"/{stem}/{suffix}" + + slug_candidate = clean_path.strip("/") + if slug_candidate in KNOWN_SLUGS: + target = "/" if slug_candidate == "" else f"/{slug_candidate}/" + return f"{target}{suffix}" + + 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]]) -> 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) 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"/img/{local_img_name}" + + rebuilt: list[tuple[str, str | None]] = [] + has_width = False + has_height = False + has_loading = False + + for k, v in attrs: + kl = k.lower() + if kl == "src": + rebuilt.append(("src", src)) + elif kl == "width" and v: + has_width = True + rebuilt.append((k, v)) + elif kl == "height" and v: + has_height = True + rebuilt.append((k, v)) + elif kl == "loading" and v: + has_loading = True + rebuilt.append((k, v)) + else: + rebuilt.append((k, v)) + + if local_img_name and local_img_name in img_dims: + w, h = img_dims[local_img_name] + if not has_width: + rebuilt.append(("width", str(w))) + if not has_height: + rebuilt.append(("height", str(h))) + + if not has_loading 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) -> 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]] = [] + + 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 = spec.url_path if (level == 1 and idx == 0) or not hid else f"{spec.url_path}#{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": "/", + "text": ( + "Fast, frame-accurate shot and scene cut detection for video. " + "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 _nav_item(label: str, slug: str, current_slug: str | None) -> dict[str, Any]: + return { + "title": label, + "href": "/" if slug == "" else f"/{slug}/", + "is_current": current_slug == slug, + } + + +def build_nav_context(current_slug: str | None) -> dict[str, Any]: + """Build sidebar groups and responsive top-navbar link lists derived from NAV_GROUPS.""" + groups = [ + { + "title": group_title, + "pages": [ + _nav_item(item_title, slug, current_slug) for item_title, _, _, slug, _ in items + ], + } + for group_title, items in NAV_GROUPS + ] + top_primary = [ + _nav_item(nav_label, slug, current_slug) + for _, items in NAV_GROUPS + for _, nav_label, _, slug, is_primary in items + if is_primary + ] + top_mobile_extra = [ + _nav_item(nav_label, slug, current_slug) + for _, items in NAV_GROUPS + for _, nav_label, _, slug, is_primary in items + if not is_primary + ] + return { + "nav_groups": groups, + "top_nav_primary": top_primary, + "top_nav_mobile_extra": top_mobile_extra, + } + + +def build_site() -> None: + """Cleanly generate website/build/ from website/pages/ and website/theme/.""" + if BUILD_DIR.exists(): + shutil.rmtree(BUILD_DIR) + BUILD_DIR.mkdir(parents=True, exist_ok=True) + + assets_out = BUILD_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, BUILD_DIR / "img") + favicon_src = IMG_SRC_DIR / "favicon.ico" + if favicon_src.is_file(): + shutil.copy2(favicon_src, BUILD_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) + rel_dt = datetime.strptime(RELEASE_DATE, "%B %d, %Y") + + site_ctx = { + "url": SITE_URL, + "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"}, + }, + ) + + specs = iter_page_specs() + hero_tabs = render_hero_tabs() + search_index: list[dict[str, str]] = [] + + for idx, spec in enumerate(specs): + md.reset() + raw_md = (PAGES_DIR / spec.src_name).read_text(encoding="utf-8") + processed_html = postprocess_html(md.convert(raw_md), img_dims) + toc_items = extract_toc(processed_html) + search_index.extend(extract_search_entries(spec, processed_html)) + + prev_spec = specs[idx - 1] if idx > 0 else None + next_spec = specs[idx + 1] if idx + 1 < len(specs) else None + + page_ctx = { + "html_title": ( + "PySceneDetect - Video Scene Cut Detection & Analysis" + if spec.is_home + else f"{spec.title} | PySceneDetect" + ), + "description": DEFAULT_DESCRIPTION, + "url_path": spec.url_path, + "content": Markup(processed_html), + "toc": toc_items, + "prev_page": ( + {"title": prev_spec.title, "href": prev_spec.url_path} if prev_spec else None + ), + "next_page": ( + {"title": next_spec.title, "href": 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, + **build_nav_context(spec.slug), + ) + + out_file = BUILD_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, + "url_path": "/404.html", + }, + **build_nav_context(None), + ) + (BUILD_DIR / "404.html").write_text(rendered_404, encoding="utf-8") + + (BUILD_DIR / "search_index.json").write_text( + json.dumps(search_index, ensure_ascii=True, separators=(",", ":")), + encoding="utf-8", + ) + (BUILD_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 specs), + "", + ] + (BUILD_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 verify_build() -> list[str]: + """Strictly validate routes, internal links, #fragment anchors, and asset paths.""" + errors: list[str] = [] + specs = iter_page_specs() + + required_files = [BUILD_DIR / spec.out_rel_path for spec in specs] + [ + 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.relative_to(WEBSITE_DIR)}") + + 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 = "/" if parent_posix == "." else f"/{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 + + target_file = _map_site_path_to_file(site_path) + 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) + target_file = BUILD_DIR / 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) -> 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) -> None: + """Serve website/build/ locally on 127.0.0.1: with custom 404.html handling.""" + + class PreviewHandler(http.server.SimpleHTTPRequestHandler): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, directory=str(BUILD_DIR), **kwargs) + + 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) + print(f"Serving {BUILD_DIR} at http://127.0.0.1:{port}/ (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( + "--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 website/build/ locally on 127.0.0.1:PORT (default: 8000).", + ) + args = parser.parse_args(argv) + + build_site() + print(f"Built {len(iter_page_specs())} pages + 404 + search index into {BUILD_DIR}") + + if args.strict: + errors = verify_build() + 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) + + return 0 + + +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..b4ea8993 100644 --- a/website/pages/api.md +++ b/website/pages/api.md @@ -1,42 +1,40 @@ - # API Reference The Python API is documented using Sphinx and [can be found here](docs.md). -# Scene Detection Algorithms +## Scene Detection Algorithms 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. -## Content-Aware Detector +### Content-Aware Detector -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`). +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`). -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. +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. -`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. +`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. -See [the documentation for detect-content](https://www.scenedetect.com/docs/latest/cli.html#detect-content) for details. +See [the documentation for `detect-content`](/docs/latest/cli.html#detect-content) for details. -## Adaptive Content Detector +### Adaptive Content Detector 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. -## Threshold Detector +### Threshold Detector -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). +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). -## Histogram Detector +### Histogram Detector -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. +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. -## Perceptual Hash Detector +### Perceptual Hash Detector 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. +## Creating New Detection Algorithms -# Creating New Detection Algorithms - -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...). +All scene detection algorithms must inherit from [the base `SceneDetector` class](/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.). Creating a new scene detection method can be as simple as implementing the `process_frame` function, and optionally `post_process`: @@ -62,20 +60,17 @@ class CustomDetector(SceneDetector): 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. +`process_frame` is called on every frame in the input video, and `post_process` is 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`). +For example, a detector may output at most 1 cut 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](/docs/latest/api/detector.html#scenedetect.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. +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 returned as a list of `FrameTimecode` values 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. - -`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`: the `FrameTimecode` of the current frame being processed +- `frame_img`: frame decoded from the video file or stream (accessible 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. +`post_process(...)` is called **after** the final frame has been processed, to allow for any stored scene cuts to be emitted *if required* (e.g. in the case of the `ThresholdDetector`). +You may also want to look into the implementation of current detectors to understand how frame metrics are saved/loaded to/from a [`StatsManager`](/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`](/docs/latest/api/scene_manager.html) for details. diff --git a/website/pages/benchmarks.md b/website/pages/benchmarks.md index 9b8f9198..09896072 100644 --- a/website/pages/benchmarks.md +++ b/website/pages/benchmarks.md @@ -1,4 +1,3 @@ - # Benchmarks PySceneDetect's detectors are benchmarked for accuracy against public @@ -11,13 +10,13 @@ The benchmark harness, datasets, and full raw results live in Three datasets are used, chosen to cover very different content: - - **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-form web/user-generated clips (hard cuts only) +- **ClipShots** - 500 short web clips with hard cuts *and* typed gradual transitions ## 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. @@ -28,45 +27,61 @@ These results were measured with the v0.7 defaults. In v0.7.2 the `HistogramDete ### 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 @@ -77,22 +92,26 @@ hard-cut scores are expected. Included for completeness. Beyond the default values, a sweep over each detector's key parameters shows how accuracy per dataset changes: -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. -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 diff --git a/website/pages/changelog.md b/website/pages/changelog.md index 958e5040..642cc133 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) @@ -103,20 +103,22 @@ 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 ``` + - [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 +191,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/head/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 +248,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 @@ -301,7 +303,7 @@ This release brings crop support, performance improvements to save-images, lots 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 +353,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 +367,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 +385,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 +403,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 +419,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 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 +447,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 +471,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 +482,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 +513,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 +653,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 +723,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 +854,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..6843283e 100644 --- a/website/pages/cli.md +++ b/website/pages/cli.md @@ -1,7 +1,6 @@ - # PySceneDetect CLI -See [the documentation](../docs/latest/) for a complete reference to the `scenedetect` command with more examples. +See [the documentation](/docs/latest/) for a complete reference to the `scenedetect` command with more examples. ## Quickstart @@ -31,7 +30,7 @@ As a concrete example to become familiar with PySceneDetect, let's use the follo 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`). -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. +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. Let's first save a scene list in CSV format and generate some images of each scene to check the output: @@ -39,26 +38,24 @@ Let's first save a scene list in CSV format and generate some images of each sce 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 | | - +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 | 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 @@ -70,50 +67,45 @@ 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`). -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). - +You can also specify `-hq` / `--high-quality` to produce 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). ## Detection Methods 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. -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). - -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. +Each mode has slightly different parameters, and is described in detail below. Most detector parameters can also be [set with 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. ### Content-Aware Detection 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. -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). - +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). ### Threshold Detection -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. +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 `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. ```bash -scenedetect -i my_video.mp4 -s my_video.stats.mp4 detect-threshold +scenedetect -i my_video.mp4 -s my_video.stats.csv detect-threshold ``` ```bash -scenedetect -i my_video.mp4 -s my_video.stats.mp4 detect-threshold -t 20 +scenedetect -i my_video.mp4 -s my_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). - +The optimal threshold can be determined by generating a statsfile (`-s`), opening it with a spreadsheet editor (e.g. Excel), and examining the `average_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). ### Adaptive Detection 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`. - ## 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. +Detectors take a variety of parameters, which can be [configured via command-line](/docs/latest/cli.html#detectors) or by [using a config file](/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: @@ -129,35 +121,33 @@ The peaks in values correspond to the scene breaks in the input video. In some c ## 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. +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. +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. +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. -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. +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. 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`). -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). - -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. +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). -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. +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. -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. +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. +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 Setting Start / Stop Times -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`). +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`). -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 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): ```bash scenedetect -i my_video.mp4 time --start 00:05:00 --end 00:06:30 @@ -177,24 +167,21 @@ scenedetect -i my_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` - - * Mac: - * `~/Library/Preferences/PySceneDetect/scenedetect.cfg` +- Windows: + - `C:/Users/%USERNAME%/AppData/Local/PySceneDetect/scenedetect.cfg` +- Linux: + - `~/.config/PySceneDetect/scenedetect.cfg` + - `$XDG_CONFIG_HOME/scenedetect.cfg` +- Mac: + - `~/Library/Preferences/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 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. -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. +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. The syntax of a configuration file is: @@ -230,36 +217,29 @@ 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. - -##   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. - +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. ### 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. - +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 Enabling `split-video` Support below for details. ### 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. - +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. - - 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. - - 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. - +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. +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. +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. diff --git a/website/pages/contributing.md b/website/pages/contributing.md index 7e3f55d9..f9fa1439 100644 --- a/website/pages/contributing.md +++ b/website/pages/contributing.md @@ -1,39 +1,40 @@ +# Bug Reports and Contributing -##   Bug Reports +## Bug Reports -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). +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). -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. +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 to Development +## Contributing to Development -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. +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. The following checklist covers the basics of pre-submission requirements: - - 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) +- 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) 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). -##   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. +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. ### 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. +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. ### 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. +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. -Ideally, this would be something like `-threshold=auto` as a default. +Ideally, this would be something like `--threshold=auto` as a default. ### Dissolve Detection -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. +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. ### Advanced Strategies @@ -41,8 +42,8 @@ Research into detection methods and performance are ongoing. All contributions i ### 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 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. ### 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 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. diff --git a/website/pages/copyright.md b/website/pages/copyright.md index d522083c..22758fb3 100644 --- a/website/pages/copyright.md +++ b/website/pages/copyright.md @@ -1,3 +1,4 @@ +# License and Copyright Information ## PySceneDetect License Agreement @@ -38,43 +39,41 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ``` - ## 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 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. ----------------------------------------------------------------------- - ### click - - Copyright (C) 2017, Armin Ronacher. - - URL: http://click.pocoo.org/license/ +- Copyright (C) 2017, Armin Ronacher. +- URL: [http://click.pocoo.org/license/](http://click.pocoo.org/license/) ### NumPy - - Copyright (C) 2005-2016, NumPy Developers. - - URL: http://www.numpy.org/license.html +- Copyright (C) 2005-2016, NumPy Developers. +- URL: [https://www.numpy.org/license.html](https://www.numpy.org/license.html) ### OpenCV - - Copyright (C) 2017, Itseez. - - URL: http://opencv.org/license.html +- Copyright (C) 2017, Itseez. +- URL: [https://opencv.org/license.html](https://opencv.org/license.html) ### 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 +- URL: [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 +- URL: [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. +- URL: [https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE](https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE) ----------------------------------------------------------------------- @@ -86,5 +85,4 @@ 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 ]. - +`thirdparty/LICENSE-FFMPEG` file or visit [https://ffmpeg.org](https://ffmpeg.org). diff --git a/website/pages/docs.md b/website/pages/docs.md index 407efe94..0fad8db6 100644 --- a/website/pages/docs.md +++ b/website/pages/docs.md @@ -1,24 +1,23 @@ - # Documentation ## 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..d8296397 100644 --- a/website/pages/download.md +++ b/website/pages/download.md @@ -1,38 +1,62 @@ - # 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 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 requires at least Python 3.10 or higher. +## Install via pip -## Install via pip       +Standard install (recommended): -
-

Standard install (recommended):

-
pip install --upgrade scenedetect
-

Headless install (servers, no GUI libs):

-
pip install --upgrade scenedetect-headless
-
+```bash +pip install --upgrade scenedetect +``` + +Headless install (servers, no GUI libs): + +```bash +pip install --upgrade scenedetect-headless +``` PySceneDetect is available via `pip` as two packages: - - [`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) +- [`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) Both provide the same `scenedetect` Python module -- install only one of them. -## Windows Build (64-bit Only)   - -
-

Latest Release: v0.7.3

-

  Release Date:  November 8, 2026

-  Installer  (recommended)      -  Portable .zip      -  Getting Started +## Windows Build (64-bit Only) + +
+
+ + + Windows 64-bit · v0.7.3 + + November 8, 2026 +
+
-## Docker Image   +The installer is recommended for most users. Windows builds include `ffmpeg` and `mkvmerge` out of the box -- see [Getting Started](cli.md) after installing. + +## Docker Image 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: @@ -52,8 +76,7 @@ The `latest` tag (the default when no tag is given) points to the most recent re ## Post Installation -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 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 [Dependencies](#dependencies) section below (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. ## Dependencies @@ -61,34 +84,33 @@ After installation, you can call PySceneDetect from any terminal/command prompt 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) +- [OpenCV](https://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) Optional packages: - - [PyAV](https://pyav.org/): `pip install av` +- [PyAV](https://pyav.org/): `pip install av` ### Video Splitting Tools For video splitting support, you need to have one of the following tools available (included in Windows builds): - - [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) +- [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) -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). +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). ### Building OpenCV from Source 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. -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. +You can [click here](https://breakthrough.github.io/Installing-OpenCV/) for a quick guide (OpenCV + Numpy on Windows & Linux) on installing OpenCV/Numpy on [Windows (using pre-built binaries)](https://breakthrough.github.io/Installing-OpenCV/#installing-on-windows-pre-built-binaries) and [Linux (compiling from source)](https://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. 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. - ## 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) diff --git a/website/pages/faq.md b/website/pages/faq.md index 0756fa33..052629fc 100644 --- a/website/pages/faq.md +++ b/website/pages/faq.md @@ -1,8 +1,8 @@ +# Frequently Asked Questions +## Installation and Setup -##   Frequently Asked Questions - -#### How can 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`: @@ -18,7 +18,7 @@ pip install scenedetect-headless Both packages ship 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: +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: ```bash pip install scenedetect @@ -27,23 +27,25 @@ pip install "opencv-contrib-python==$(pip show opencv-python | grep ^Version | c 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). -#### How can I enable video splitting support? +### How can I enable video splitting support? + +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. -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. +## Troubleshooting -#### How can I fix the error `Cannot split video due to too many scenes`? +### How can I fix the error `Cannot split video due to too many scenes`? -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. +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. -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. +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. See [Issue #164](https://github.com/Breakthrough/PySceneDetect/issues/164) for details, or if you have any further questions. -#### How can I fix the error `Failed to read any frames from video file`? +### How can I fix the error `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. -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`: +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`: ```bash ffmpeg -i input.mp4 -c copy -an output.mp4 diff --git a/website/pages/features.md b/website/pages/features.md index e40b6cc0..115edfaf 100644 --- a/website/pages/features.md +++ b/website/pages/features.md @@ -1,74 +1,66 @@ +# 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). -
+!!! note "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. -
+ Detects breaks in-between *content*, not only when the video fades to black (although a threshold mode is available as well for those cases). -
-

  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. -
+!!! important "Compatible With Many External Tools" -
-

  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). -
+ 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. +!!! note "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. + +!!! important "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). +------------------------------------------------------------------------ -## Features +## Key Capabilities - - 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 +- 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 +## Output Formats - - **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`) +- **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`) -### Detection Methods +## Detection Methods PySceneDetect implements a variety of different detection algorithms which can be used independently or combined depending on the source material being analyzed. - - **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) +- **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) - 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. +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. ------------------------------------------------------------------------ - ## 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. - +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. ### Planned Features 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). - - 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) +- 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 diff --git a/website/pages/gallery.md b/website/pages/gallery.md index a4d5644b..83900edd 100644 --- a/website/pages/gallery.md +++ b/website/pages/gallery.md @@ -1,34 +1,33 @@ - # 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. +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. +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 +- [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 +- [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 +- [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 +- [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/index.md b/website/pages/index.md index ef826e54..51288613 100644 --- a/website/pages/index.md +++ b/website/pages/index.md @@ -1,23 +1,16 @@ +## Overview +**PySceneDetect** is a tool for **detecting shot changes in videos** ([CLI guide](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. -PySceneDetect +## Quickstart -
-

  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): +Split video on each fast cut using the [CLI guide](cli.md): ```bash scenedetect -i video.mp4 split-video ``` -Split video on each fast cut using [Python API (docs)](docs.md): +Split video on each fast cut using the [Python API (docs)](docs.md): ```python from scenedetect import detect, AdaptiveDetector, split_video_ffmpeg @@ -26,15 +19,14 @@ scene_list = detect("my_video.mp4", AdaptiveDetector()) split_video_ffmpeg("my_video.mp4", scene_list) ``` - -

Examples and Use Cases

+## 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) +- 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). +Of course, this is just a small slice of what you can do with PySceneDetect -- [Download PySceneDetect](download.md) to 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). 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 index 8bce6ca8..455dfa1d 100644 --- a/website/pages/literature.md +++ b/website/pages/literature.md @@ -1,29 +1,27 @@ - # 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) +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. - - [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) +- [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) - - [LoL-V2T: Large-Scale Esports Video Description Dataset](https://ieeexplore.ieee.org/abstract/document/9522986) by Tsunehiko Tanaka, Edgar Simo-Serra (2021) +- [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) - - [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) +- [LoL-V2T: Large-Scale Esports Video Description Dataset](https://ieeexplore.ieee.org/abstract/document/9522986) by Tsunehiko Tanaka, Edgar Simo-Serra (2021) - - [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) +- [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) - - [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) +- [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) - - [NLP-Enriched Automatic Video Segmentation](https://ieeexplore.ieee.org/document/8525880/) by Mohannad AlMousa, Rachid Benlamri, Richard Khoury (2018) +- [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) - - [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) +- [NLP-Enriched Automatic Video Segmentation](https://ieeexplore.ieee.org/document/8525880/) by Mohannad AlMousa, Rachid Benlamri, Richard Khoury (2018) - - [Story Understanding in Video Advertisements](https://arxiv.org/pdf/1807.11122) by Keren Ye, Kyle Buettner, Adriana Kovashka (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) -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. +- [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 +## 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. +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/similar.md b/website/pages/similar.md index 94b017cb..b21f12de 100644 --- a/website/pages/similar.md +++ b/website/pages/similar.md @@ -1,13 +1,11 @@ - -## Alternative and Related Programs +# 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) - +- [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](https://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 index a1d99b66..98b44a05 100644 --- a/website/pages/supporting.md +++ b/website/pages/supporting.md @@ -1,32 +1,28 @@ +# Supporting Development -#   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. -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 +## 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 +- [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 -##   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. +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) 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. - +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 +## 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/). +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](https://bcastell.com/contact/). Many thanks to everyone who continually supports the development of the project. diff --git a/website/theme/404.html b/website/theme/404.html new file mode 100644 index 00000000..bb75859b --- /dev/null +++ b/website/theme/404.html @@ -0,0 +1,58 @@ +{% extends "base.html" %} + +{% block main %} +
+
+ +

Page Not Found

+

The requested page could not be found. 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..c3d669a1 --- /dev/null +++ b/website/theme/base.html @@ -0,0 +1,234 @@ + + + + + + + + {{ page.html_title }} + + + {% if page.url_path != "/404.html" %} + + {% endif %} + + + + + + + + + + + + + + + + + +
+ + + + +
+
+

Type a keyword to search across all 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..914a58aa --- /dev/null +++ b/website/theme/home.html @@ -0,0 +1,125 @@ +{% extends "base.html" %} + +{% block main %} +
+
+
+ + Latest release + {{ site.version }} + · {{ site.release_date_short }} + +

Fast, frame-accurate shot & scene cut detection for video.

+

Detect hard cuts, dissolves, and fades from the command line or Python. Automatically split footage with ffmpeg or mkvmerge, export EDL/OTIO timelines, or inspect frame-by-frame metrics.

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

Five Benchmarked Detectors

+

Adaptive, Content (HSV + edges), Perceptual Hash, Y-Channel Histogram, and Threshold detectors — evaluated against BBC Planet Earth, AutoShot, and ClipShots.

+ 91.6 F1 on BBC broadcast → +
+
+

NLE & Pipeline Ready

+

Export standard HH:MM:SS.nnn CSV cut lists, CMX 3600 EDL, OpenTimelineIO (OTIO), x264 QP files, HTML contact sheets, and boundary thumbnails.

+ save-edl · save-otio · save-images → +
+
+

Pluggable Video Backends

+

Decode via OpenCV out of the box, PyAV, or MoviePy. Ships as scenedetect, headless server wheels, signed Windows MSI, and official GHCR containers.

+ Python 3.10+ · Win64 · Docker → +
+
+ + +
+{% endblock %} diff --git a/website/theme/site.css b/website/theme/site.css new file mode 100644 index 00000000..abde9071 --- /dev/null +++ b/website/theme/site.css @@ -0,0 +1,1778 @@ +@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-label, + .search-trigger .kbd, + .github-label { + display: none; + } + } + + @media (pointer: coarse) { + .menu-button, + .search-trigger, + .theme-toggle, + .icon-link { + min-block-size: 2.4rem; + min-inline-size: 2.4rem; + } + } + + /* 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-strip { + display: inline-flex; + align-items: center; + gap: 0.75rem; + max-inline-size: 100%; + padding-block: 0.5rem; + padding-inline: 0.85rem; + background: var(--code-bg); + border: 1px solid var(--border); + border-radius: 0.5rem; + font-family: var(--font-mono); + font-size: 0.875rem; + margin-block-end: 1.35rem; + overflow-x: auto; + } + + .install-strip code { + 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-window .codehilite { + margin: 0; + border: 0; + border-radius: 0; + } + + .code-body { + padding: 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; + font-family: var(--font-mono); + font-size: 0.78rem; + font-weight: 500; + color: var(--brand); + text-decoration: none; + } + + .feature-meta:hover { + text-decoration: underline; + } + + /* 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-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..1bb25be0 --- /dev/null +++ b/website/theme/site.js @@ -0,0 +1,514 @@ +// 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 (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. Hero Quickstart Code Tabs (accessible roving tabindex, selection-on-focus) + * -------------------------------------------------------------------------- */ +function initHeroTabs() { + const tablist = document.querySelector('[role="tablist"]'); + if (!tablist) { + return; + } + const tabs = Array.from(tablist.querySelectorAll('[role="tab"]')); + const hintEl = document.getElementById("hero-code-hint"); + if (!tabs.length) { + return; + } + + const selectTab = (nextTab, moveFocus = false) => { + for (const tab of tabs) { + const isSelected = tab === nextTab; + tab.setAttribute("aria-selected", isSelected ? "true" : "false"); + tab.tabIndex = isSelected ? 0 : -1; + const panelId = tab.id.replace("hero-tab-", "hero-panel-"); + const panel = document.getElementById(panelId); + if (panel) { + panel.hidden = !isSelected; + } + } + if (hintEl && nextTab.dataset.hint) { + hintEl.textContent = nextTab.dataset.hint; + } + if (moveFocus) { + nextTab.focus(); + nextTab.scrollIntoView({ block: "nearest", inline: "nearest" }); + } + }; + + for (const tab of tabs) { + tab.addEventListener("click", () => selectTab(tab, false)); + tab.addEventListener("keydown", (event) => { + const idx = tabs.indexOf(tab); + 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); + } + }); + } +} + +/* -------------------------------------------------------------------------- * + * 5. Copy-to-clipboard buttons (hero inline command + prose code blocks) + * -------------------------------------------------------------------------- */ +function flashCopied(button, defaultLabel) { + button.innerHTML = CHECK_ICON_SVG; + button.classList.add("is-copied"); + button.setAttribute("aria-label", "Copied to clipboard"); + window.setTimeout(() => { + button.innerHTML = COPY_ICON_SVG; + button.classList.remove("is-copied"); + button.setAttribute("aria-label", defaultLabel); + }, 1400); +} + +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)); + }); + } + + for (const container of document.querySelectorAll(".prose .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)); + }); + 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"); + if (!(dialog instanceof HTMLDialogElement) || !(input instanceof HTMLInputElement) || !resultsEl) { + return; + } + + let indexPromise = null; + let searchData = []; + let activeHitIndex = -1; + + const ensureIndex = () => { + if (!indexPromise) { + indexPromise = fetch("/search_index.json") + .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 across all guides, CLI options, detectors, and FAQs." + ); + 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()}".`); + 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; + }; + + 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") { + const hits = resultsEl.querySelectorAll(".search-hit"); + if (activeHitIndex >= 0 && hits[activeHitIndex]) { + event.preventDefault(); + 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(); +initHeroTabs(); +initCopyButtons(); +initTocHighlight(); +initSearchDialog(); From 62f85ea8048c7273a3022bcd5add784b8e2da5c8 Mon Sep 17 00:00:00 2001 From: Breakthrough Date: Tue, 17 Nov 2026 22:05:07 -0500 Subject: [PATCH 2/4] [site] Add layout verifier, mobile fixes, and staging workflow --- .github/workflows/actions.lock | 1 + .github/workflows/check-docs.yml | 21 +- .github/workflows/generate-docs.yml | 7 +- .github/workflows/generate-website.yml | 99 ++- docs/_ext/doc_versions.py | 41 +- docs/_ext/section_sidebar.py | 22 +- docs/_static/pyscenedetect.css | 13 + docs/_templates/navigation.html | 9 +- docs/conf.py | 108 +-- docs/generate_cli_docs.py | 124 ++-- pyproject.toml | 1 - website/build.py | 419 ++++++----- website/check_layout.py | 978 +++++++++++++++++++++++++ website/requirements.txt | 4 + website/theme/404.html | 8 +- website/theme/base.html | 46 +- website/theme/home.html | 20 +- website/theme/site.css | 63 +- website/theme/site.js | 2 +- 19 files changed, 1490 insertions(+), 496 deletions(-) create mode 100644 website/check_layout.py create mode 100644 website/requirements.txt 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 c3462c62..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 @@ -65,3 +62,19 @@ jobs: shell: bash run: | python website/build.py --strict + + - name: Check Responsive Layout & Capture Screenshots + shell: bash + run: | + 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 61f16389..43396258 100644 --- a/.github/workflows/generate-docs.yml +++ b/.github/workflows/generate-docs.yml @@ -54,12 +54,11 @@ jobs: if: ${{ env.scenedetect_docs_dest == '' }} 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 @@ -76,7 +75,7 @@ jobs: - name: Generate Docs run: | - sphinx-build -b html docs build + sphinx-build -b html -d "${RUNNER_TEMP}/doctrees" docs build - name: Update gh-pages Branch run: | diff --git a/.github/workflows/generate-website.yml b/.github/workflows/generate-website.yml index 68a4b8fc..5c7ab8bc 100644 --- a/.github/workflows/generate-website.yml +++ b/.github/workflows/generate-website.yml @@ -1,15 +1,27 @@ - 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 @@ -25,37 +37,90 @@ 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_NAME}" == "main" ]]; then + target="production" + else + target="staging" + fi + else + target="${INPUT_TARGET}" + 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 "jinja2>=3.1.6" "markdown>=3.5" "pygments>=2.17" + python -m pip install -r website/requirements.txt - - name: Generate Website + - name: Generate Website (--strict) + if: env.deploy_target != 'clear-staging' + shell: bash run: | - python website/build.py --strict + python website/build.py \ + --strict \ + --base-path "${SITE_BASE_PATH}" \ + --out-dir "${RUNNER_TEMP}/site-build" + env: + 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 + + 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 if ! git diff --quiet || ! git diff --cached --quiet; then - git commit -a -m "[docs] @${{ github.triggering_actor }}: Generate Website" \ - -m "Commit: ${{ github.sha }}" + 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/docs/_ext/doc_versions.py b/docs/_ext/doc_versions.py index 893a433f..29045be0 100644 --- a/docs/_ext/doc_versions.py +++ b/docs/_ext/doc_versions.py @@ -12,6 +12,11 @@ _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]]]: @@ -49,37 +54,11 @@ def load_doc_versions( if not legacy_slugs: legacy_slugs = ["0.6.7"] - entries: list[dict[str, Any]] = [ - { - "slug": "latest", - "label": f"v{latest_ver} (latest)", - "group": "channel", - "same_layout": True, - }, - { - "slug": "head", - "label": "dev (head)", - "group": "channel", - "same_layout": True, - }, + entries = [ + _entry("latest", f"v{latest_ver} (latest)", "channel"), + _entry("head", "dev (head)", "channel"), ] - for slug in stable_slugs: - entries.append( - { - "slug": slug, - "label": f"v{slug}", - "group": "release", - "same_layout": True, - } - ) + entries += [_entry(slug, f"v{slug}", "release") for slug in stable_slugs] if legacy_slugs: - latest_legacy = legacy_slugs[0] - entries.append( - { - "slug": latest_legacy, - "label": f"v{latest_legacy} (legacy)", - "group": "legacy", - "same_layout": False, - } - ) + 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 d525c415..d205580f 100644 --- a/docs/_ext/section_sidebar.py +++ b/docs/_ext/section_sidebar.py @@ -16,14 +16,12 @@ 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 + "reftoc": (None, None, 2, 2), # no label: not part of the switch } 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 whose label is ``None`` is not part of the switch. 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 @@ -185,7 +183,6 @@ 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] @@ -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 93b9dec6..11585ab6 100644 --- a/docs/_static/pyscenedetect.css +++ b/docs/_static/pyscenedetect.css @@ -910,6 +910,10 @@ dl.py > dt.sig { 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; @@ -1007,6 +1011,15 @@ div.footer a:hover { } 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%; diff --git a/docs/_templates/navigation.html b/docs/_templates/navigation.html index ef2aae97..522d5513 100644 --- a/docs/_templates/navigation.html +++ b/docs/_templates/navigation.html @@ -12,11 +12,4 @@

{{ _('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/conf.py b/docs/conf.py index 22090471..7b1a78bb 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,16 +1,10 @@ # # 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 @@ -23,7 +17,7 @@ from scenedetect import __version__ as scenedetect_version _REPO_DIR = Path(__file__).resolve().parent.parent -_psd_latest_version, _psd_doc_versions = load_doc_versions( +_, _psd_doc_versions = load_doc_versions( _REPO_DIR, fallback_version=scenedetect_version.split(".dev")[0] ) @@ -33,16 +27,11 @@ 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", @@ -61,124 +50,38 @@ # 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"] # 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" -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# -# source_suffix = ['.rst', '.md'] 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 ------------------------------------------------- html_theme = "alabaster" html_theme_options = { "page_width": "1080px", "sidebar_width": "255px", - "description": f"Version: [{release}]", "show_relbar_bottom": True, - "show_relbar_top": False, - "github_button": False, - "github_user": "Breakthrough", - "github_repo": "PySceneDetect", - "github_type": "star", "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": ( @@ -192,23 +95,20 @@ "warn_border": "#f2caa2", "attention_bg": "#f5dcdc", "attention_border": "#ffaaaa", - "logo": "pyscenedetect_logo.png", - "logo_name": False, } html_context = { - "psd_latest_version": _psd_latest_version, "psd_doc_versions": _psd_doc_versions, } # 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. +# Examples page spans both halves, so it is its own one-page section. 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. + # No label: the sidebar shows only the headings of the current page. "reftoc": (None, None, 2, 2), } # The index page shows every labelled section; keep the API tree to page titles there (the diff --git a/docs/generate_cli_docs.py b/docs/generate_cli_docs.py index 674980da..00c89998 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 = { @@ -357,7 +353,6 @@ class Counterpart: CLI_ONLY = "*CLI only*" NO_API = "*no Python API equivalent*" -API_ONLY = "*Python API 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,7 +810,7 @@ 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, ...]], ...] = ( @@ -872,7 +840,6 @@ def create_help() -> tuple[str, list[str]]: def _format_cli_index_groups( available: list[str], groups: tuple[tuple[str, tuple[str, ...]], ...], - indent: str = " ", ) -> str: """Format a grouped, logically ordered nested RST bullet list of CLI command refs.""" available_set = set(available) @@ -892,16 +859,15 @@ def _format_cli_index_groups( lines: list[str] = [] for label, members in grouped: - lines.append(f"\n{indent}- **{label}**\n\n") + lines.append(f"\n{INDENT}- **{label}**\n\n") for cmd in members: - lines.append(f"{indent} - :ref:`{cmd} `\n") + 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", @@ -955,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: @@ -1044,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 " @@ -1053,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 @@ -1227,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(): @@ -1241,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/pyproject.toml b/pyproject.toml index fc4e89f4..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 = ["jinja2>=3.1.6", "markdown>=3.5", "pygments>=2.17"] [project.urls] Homepage = "https://www.scenedetect.com" diff --git a/website/build.py b/website/build.py index 70dd1bc6..8269f319 100644 --- a/website/build.py +++ b/website/build.py @@ -38,7 +38,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "docs" / "_ext")) -from doc_versions import load_doc_versions +from doc_versions import load_doc_versions # type: ignore[import-not-found] WEBSITE_DIR = Path(__file__).resolve().parent REPO_DIR = WEBSITE_DIR.parent @@ -57,45 +57,81 @@ THEME_DIR = WEBSITE_DIR / "theme" BUILD_DIR = WEBSITE_DIR / "build" -# Each entry is (sidebar_title, top_nav_label, src_name, slug, is_top_primary). -NAV_GROUPS: list[tuple[str, list[tuple[str, str, str, str, bool]]]] = [ + +@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 + + @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", [ - ("Home", "Overview", "index.md", "", True), - ("Features", "Features", "features.md", "features", True), - ("Download", "Download", "download.md", "download", True), - ("Changelog", "Changelog", "changelog.md", "changelog", False), + PageSpec("", "Home", "Overview", is_primary=True), + PageSpec("features", "Features", is_primary=True), + PageSpec("download", "Download", is_primary=True), + PageSpec("changelog", "Changelog"), ], ), ( "Reference", [ - ("Documentation", "Documentation", "docs.md", "docs", False), - ("Command-Line", "CLI", "cli.md", "cli", True), - ("Python API", "Python API", "api.md", "api", True), - ("Benchmarks", "Benchmarks", "benchmarks.md", "benchmarks", True), + PageSpec("docs", "Documentation"), + PageSpec("cli", "Command-Line", "CLI", is_primary=True), + PageSpec("api", "Python API", is_primary=True), + PageSpec("benchmarks", "Benchmarks", is_primary=True), ], ), ( "Support", [ - ("FAQ", "FAQ", "faq.md", "faq", True), - ("Bugs & Contributing", "Contributing", "contributing.md", "contributing", False), - ("Development & Support", "Support", "supporting.md", "supporting", False), + PageSpec("faq", "FAQ", is_primary=True), + PageSpec("contributing", "Bugs & Contributing", "Contributing"), + PageSpec("supporting", "Development & Support", "Support"), ], ), ( "Resources", [ - ("Project Gallery", "Project Gallery", "gallery.md", "gallery", False), - ("Similar Projects", "Similar Projects", "similar.md", "similar", False), - ("Research & Literature", "Literature", "literature.md", "literature", False), - ("License & Copyright", "License", "copyright.md", "copyright", False), + PageSpec("gallery", "Project Gallery"), + PageSpec("similar", "Similar Projects"), + PageSpec("literature", "Research & Literature", "Literature"), + PageSpec("copyright", "License & Copyright", "License"), ], ), ] +PAGES: list[PageSpec] = [page for _, group in NAV_GROUPS for page in group] +KNOWN_SLUGS: set[str] = {page.slug for page in PAGES} + HERO_SNIPPETS: list[tuple[str, str, str, str, str]] = [ ( "python", @@ -144,32 +180,6 @@ ) EXTERNAL_SCHEMES = ("http://", "https://", "mailto:", "tel:", "data:", "javascript:") -KNOWN_SLUGS: set[str] = {slug for _, items in NAV_GROUPS for _, _, _, slug, _ in items} - - -@dataclass(frozen=True) -class PageSpec: - """Static definition of a single page in the canonical site tree.""" - - group: str - title: str - nav_label: str - src_name: str - slug: str - is_primary: bool - - @property - def is_home(self) -> bool: - return self.slug == "" - - @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" - @dataclass class TocItem: @@ -180,22 +190,6 @@ class TocItem: children: list[TocItem] = field(default_factory=list) -def iter_page_specs() -> list[PageSpec]: - """Flatten NAV_GROUPS into the ordered page sequence.""" - return [ - PageSpec( - group=group_title, - title=title, - nav_label=nav_label, - src_name=src_name, - slug=slug, - is_primary=is_primary, - ) - for group_title, entries in NAV_GROUPS - for title, nav_label, src_name, slug, is_primary in entries - ] - - def strip_tags(fragment: str) -> str: """Remove HTML tags and unescape entities into collapsed plain text.""" no_tags = re.sub(r"<[^>]+>", " ", fragment) @@ -205,8 +199,6 @@ def strip_tags(fragment: str) -> str: def get_image_dimensions(img_path: Path) -> tuple[int, int] | None: """Read intrinsic (width, height) in pixels for local PNG and SVG assets.""" - if not img_path.is_file(): - return None data = img_path.read_bytes() suffix = img_path.suffix.lower() @@ -242,30 +234,39 @@ def _parse_svg_length(svg_tag: str, attr_name: str) -> int | None: return max(1, round(val)) -def rewrite_internal_href(href: str) -> str: - """Normalize Markdown and relative internal links to root-absolute site paths.""" +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(("#", "/docs/", *EXTERNAL_SCHEMES)): + 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"/img/{img_match.group(1)}{suffix}" + 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"/{suffix}" + return f"{base_path}/{suffix}" if stem in KNOWN_SLUGS: - return f"/{stem}/{suffix}" + return f"{base_path}/{stem}/{suffix}" slug_candidate = clean_path.strip("/") if slug_candidate in KNOWN_SLUGS: - target = "/" if slug_candidate == "" else f"/{slug_candidate}/" + target = f"{base_path}/" if slug_candidate == "" else f"{base_path}/{slug_candidate}/" return f"{target}{suffix}" return href @@ -300,7 +301,11 @@ def _format_attrs(attrs: list[tuple[str, str | None]]) -> str: return (" " + " ".join(parts)) if parts else "" -def postprocess_html(rendered_html: str, img_dims: dict[str, tuple[int, int]]) -> str: +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: @@ -319,7 +324,10 @@ def _normalize_pre(match: re.Match[str]) -> str: def _rewrite_anchor(match: re.Match[str]) -> str: attrs = _parse_attrs(match.group(1)) new_attrs = [ - (k, rewrite_internal_href(v) if k.lower() == "href" and v is not None else v) + ( + 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"" @@ -337,37 +345,19 @@ def _rewrite_img(match: re.Match[str]) -> str: img_match = IMG_PATH_RE.match(clean_src) if img_match: local_img_name = img_match.group(1) - src = f"/img/{local_img_name}" - - rebuilt: list[tuple[str, str | None]] = [] - has_width = False - has_height = False - has_loading = False - - for k, v in attrs: - kl = k.lower() - if kl == "src": - rebuilt.append(("src", src)) - elif kl == "width" and v: - has_width = True - rebuilt.append((k, v)) - elif kl == "height" and v: - has_height = True - rebuilt.append((k, v)) - elif kl == "loading" and v: - has_loading = True - rebuilt.append((k, v)) - else: - rebuilt.append((k, v)) + 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 not has_width: + if "width" not in filled: rebuilt.append(("width", str(w))) - if not has_height: + if "height" not in filled: rebuilt.append(("height", str(h))) - if not has_loading and attr_map.get("fetchpriority") != "high": + if "loading" not in filled and attr_map.get("fetchpriority") != "high": rebuilt.append(("loading", "lazy")) return f"" @@ -443,11 +433,16 @@ def extract_toc(html_text: str) -> list[TocItem]: return items -def extract_search_entries(spec: PageSpec, html_text: str) -> list[dict[str, str]]: +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)) @@ -457,7 +452,7 @@ def extract_search_entries(spec: PageSpec, html_text: str) -> list[dict[str, str 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 = spec.url_path if (level == 1 and idx == 0) or not hid else f"{spec.url_path}#{hid}" + url = page_url if (level == 1 and idx == 0) or not hid else f"{page_url}#{hid}" entries.append( { "title": spec.title, @@ -473,7 +468,7 @@ def extract_search_entries(spec: PageSpec, html_text: str) -> list[dict[str, str { "title": "Home", "section": "Overview & Quickstart", - "url": "/", + "url": f"{base_path}/", "text": ( "Fast, frame-accurate shot and scene cut detection for video. " "pip install scenedetect AdaptiveDetector ContentDetector HashDetector " @@ -502,59 +497,20 @@ def render_hero_tabs() -> list[dict[str, str]]: return tabs -def _nav_item(label: str, slug: str, current_slug: str | None) -> dict[str, Any]: - return { - "title": label, - "href": "/" if slug == "" else f"/{slug}/", - "is_current": current_slug == slug, - } - - -def build_nav_context(current_slug: str | None) -> dict[str, Any]: - """Build sidebar groups and responsive top-navbar link lists derived from NAV_GROUPS.""" - groups = [ - { - "title": group_title, - "pages": [ - _nav_item(item_title, slug, current_slug) for item_title, _, _, slug, _ in items - ], - } - for group_title, items in NAV_GROUPS - ] - top_primary = [ - _nav_item(nav_label, slug, current_slug) - for _, items in NAV_GROUPS - for _, nav_label, _, slug, is_primary in items - if is_primary - ] - top_mobile_extra = [ - _nav_item(nav_label, slug, current_slug) - for _, items in NAV_GROUPS - for _, nav_label, _, slug, is_primary in items - if not is_primary - ] - return { - "nav_groups": groups, - "top_nav_primary": top_primary, - "top_nav_mobile_extra": top_mobile_extra, - } - - -def build_site() -> None: - """Cleanly generate website/build/ from website/pages/ and website/theme/.""" - if BUILD_DIR.exists(): - shutil.rmtree(BUILD_DIR) - BUILD_DIR.mkdir(parents=True, exist_ok=True) +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) + if out_dir.exists(): + shutil.rmtree(out_dir) + out_dir.mkdir(parents=True, exist_ok=True) - assets_out = BUILD_DIR / "assets" + 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, BUILD_DIR / "img") - favicon_src = IMG_SRC_DIR / "favicon.ico" - if favicon_src.is_file(): - shutil.copy2(favicon_src, BUILD_DIR / "favicon.ico") + 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(): @@ -568,6 +524,7 @@ def build_site() -> None: site_ctx = { "url": SITE_URL, + "base_path": base_path, "repo_url": REPO_URL, "pypi_url": PYPI_URL, "version": f"v{latest_ver}", @@ -599,19 +556,18 @@ def build_site() -> None: }, ) - specs = iter_page_specs() hero_tabs = render_hero_tabs() search_index: list[dict[str, str]] = [] - for idx, spec in enumerate(specs): + 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) + 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)) + search_index.extend(extract_search_entries(spec, processed_html, base_path)) - prev_spec = specs[idx - 1] if idx > 0 else None - next_spec = specs[idx + 1] if idx + 1 < len(specs) else None + 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": ( @@ -620,14 +576,19 @@ def build_site() -> None: else f"{spec.title} | PySceneDetect" ), "description": DEFAULT_DESCRIPTION, - "url_path": spec.url_path, + "slug": spec.slug, + "canonical_path": spec.url_path, "content": Markup(processed_html), "toc": toc_items, "prev_page": ( - {"title": prev_spec.title, "href": prev_spec.url_path} if prev_spec else None + {"title": prev_spec.title, "href": f"{base_path}{prev_spec.url_path}"} + if prev_spec + else None ), "next_page": ( - {"title": next_spec.title, "href": next_spec.url_path} if next_spec else None + {"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}", } @@ -637,10 +598,11 @@ def build_site() -> None: site=site_ctx, page=page_ctx, hero_tabs=hero_tabs, - **build_nav_context(spec.slug), + nav_groups=NAV_GROUPS, + pages=PAGES, ) - out_file = BUILD_DIR / spec.out_rel_path + 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") @@ -649,17 +611,19 @@ def build_site() -> None: page={ "html_title": "Page Not Found | PySceneDetect", "description": DEFAULT_DESCRIPTION, - "url_path": "/404.html", + "slug": None, + "canonical_path": None, }, - **build_nav_context(None), + nav_groups=NAV_GROUPS, + pages=PAGES, ) - (BUILD_DIR / "404.html").write_text(rendered_404, encoding="utf-8") + (out_dir / "404.html").write_text(rendered_404, encoding="utf-8") - (BUILD_DIR / "search_index.json").write_text( + (out_dir / "search_index.json").write_text( json.dumps(search_index, ensure_ascii=True, separators=(",", ":")), encoding="utf-8", ) - (BUILD_DIR / "versions.json").write_text( + (out_dir / "versions.json").write_text( json.dumps( {"latest": latest_ver, "versions": doc_versions}, ensure_ascii=True, @@ -671,10 +635,10 @@ def build_site() -> None: sitemap_lines = [ '', '', - *(f" {SITE_URL}{spec.url_path}" for spec in specs), + *(f" {SITE_URL}{spec.url_path}" for spec in PAGES), "", ] - (BUILD_DIR / "sitemap.xml").write_text("\n".join(sitemap_lines) + "\n", encoding="utf-8") + (out_dir / "sitemap.xml").write_text("\n".join(sitemap_lines) + "\n", encoding="utf-8") class _PageInspector(html.parser.HTMLParser): @@ -723,31 +687,42 @@ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None self.assets.append(("script", src)) -def verify_build() -> list[str]: +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] = [] - specs = iter_page_specs() - - required_files = [BUILD_DIR / spec.out_rel_path for spec in specs] + [ - 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", + required_files = [build_dir / spec.out_rel_path for spec in PAGES] + [ + 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.relative_to(WEBSITE_DIR)}") + errors.append(f"Missing expected output file: {req}") - html_files = sorted(BUILD_DIR.rglob("*.html")) + 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() + 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: @@ -756,10 +731,10 @@ def verify_build() -> list[str]: 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_file = html_file.relative_to(build_dir) rel_label = rel_file.as_posix() parent_posix = rel_file.parent.as_posix() - base_url_dir = "/" if parent_posix == "." else f"/{parent_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): @@ -777,7 +752,15 @@ def verify_build() -> list[str]: if SPHINX_ABS_RE.match(site_path): continue - target_file = _map_site_path_to_file(site_path) + 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}')" @@ -787,7 +770,7 @@ def verify_build() -> list[str]: 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() + 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})" @@ -798,7 +781,14 @@ def verify_build() -> list[str]: continue clean_src = src.split("#", 1)[0].split("?", 1)[0] site_path = _resolve_site_path(base_url_dir, clean_src) - target_file = BUILD_DIR / site_path.lstrip("/") + 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}')" @@ -822,23 +812,41 @@ def _resolve_site_path(base_url_dir: str, path_part: str) -> str: return joined -def _map_site_path_to_file(site_path: str) -> Path | None: - """Map a normalized site path (e.g. '/cli/') to an existing file path in BUILD_DIR.""" +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 + 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) -> None: - """Serve website/build/ locally on 127.0.0.1: with custom 404.html handling.""" +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) + 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, @@ -846,7 +854,7 @@ def send_error( message: str | None = None, explain: str | None = None, ) -> None: - not_found_path = BUILD_DIR / "404.html" + 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) @@ -858,7 +866,8 @@ def send_error( super().send_error(code, message, explain) server = http.server.ThreadingHTTPServer(("127.0.0.1", port), PreviewHandler) - print(f"Serving {BUILD_DIR} at http://127.0.0.1:{port}/ (Ctrl+C to stop)") + 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: @@ -870,6 +879,17 @@ def send_error( 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", @@ -881,15 +901,18 @@ def main(argv: list[str] | None = None) -> int: const=8000, type=int, metavar="PORT", - help="Build and serve website/build/ locally on 127.0.0.1:PORT (default: 8000).", + 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() - print(f"Built {len(iter_page_specs())} pages + 404 + search index into {BUILD_DIR}") + 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() + 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) @@ -898,7 +921,7 @@ def main(argv: list[str] | None = None) -> int: print("Strict verification passed (all routes, anchors, and assets verified).") if args.serve is not None: - serve_site(args.serve) + serve_site(args.serve, base_path=base_path, build_dir=out_dir) return 0 diff --git a/website/check_layout.py b/website/check_layout.py new file mode 100644 index 00000000..402156e6 --- /dev/null +++ b/website/check_layout.py @@ -0,0 +1,978 @@ +# +# 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")): + 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-gallery-light.png", "/gallery/", "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 /") + + 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/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 index bb75859b..73556fbe 100644 --- a/website/theme/404.html +++ b/website/theme/404.html @@ -5,13 +5,17 @@

Page Not Found

-

The requested page could not be found. Try searching above or return to the PySceneDetect homepage.

+

The requested page could not be found. Try searching above or return to the PySceneDetect homepage.

{{ page.html_title }} - - {% if page.url_path != "/404.html" %} - + {% if site.base_path %} + + {% endif %} + + {% if page.canonical_path %} + {% endif %} - - + + +{%- endif %} diff --git a/website/theme/base.html b/website/theme/base.html index da4ab1fc..63b5b370 100644 --- a/website/theme/base.html +++ b/website/theme/base.html @@ -11,7 +11,7 @@ {% endif %} - {% if page.canonical_path %} + {% if page.canonical_path and not site.base_path %} {% endif %} @@ -20,15 +20,25 @@ + {% if not site.base_path %} - + {% endif %} @@ -131,7 +141,7 @@
- +
-
+

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

diff --git a/website/theme/home.html b/website/theme/home.html index 66ce89f8..cc22a4d3 100644 --- a/website/theme/home.html +++ b/website/theme/home.html @@ -19,6 +19,7 @@

Fast, frame-accurate scene cut detection for video.

class="install-tab" id="install-tab-pip" aria-selected="true" + aria-controls="install-panel-pip" tabindex="0" >pip

class="install-tab" id="install-tab-uv" aria-selected="false" + aria-controls="install-panel-uv" tabindex="-1" >uv

class="install-tab" id="install-tab-pipx" aria-selected="false" + aria-controls="install-panel-pipx" tabindex="-1" >pipx @@ -137,6 +140,7 @@

Fast, frame-accurate scene cut detection for video.

class="tab" id="hero-tab-{{ tab.id }}" aria-selected="{{ 'true' if loop.first else 'false' }}" + aria-controls="hero-panel-{{ tab.id }}" tabindex="{{ '0' if loop.first else '-1' }}" data-hint="{{ tab.hint }}" >{{ tab.label }} @@ -169,7 +173,7 @@

Fast, frame-accurate scene cut detection for video.

-

Five Detection Methods

+

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.

diff --git a/website/theme/site.css b/website/theme/site.css index d2dbbaf8..bde7df5a 100644 --- a/website/theme/site.css +++ b/website/theme/site.css @@ -1130,7 +1130,7 @@ } .code-body { - padding: 1.05rem 1.15rem; + padding: 1.05rem 2.75rem 1.05rem 1.15rem; background: var(--code-bg); font-size: 0.85rem; line-height: 1.65; @@ -1784,6 +1784,11 @@ 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); diff --git a/website/theme/site.js b/website/theme/site.js index 63fac78f..879b1446 100644 --- a/website/theme/site.js +++ b/website/theme/site.js @@ -88,6 +88,10 @@ function initResponsiveNavbar() { 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); @@ -218,15 +222,23 @@ function initTabGroups() { /* -------------------------------------------------------------------------- * * 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"); - window.setTimeout(() => { + 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() { @@ -237,11 +249,14 @@ function initCopyButtons() { if (!text || !navigator.clipboard) { return; } - navigator.clipboard.writeText(text).then(() => flashCopied(inlineBtn, defaultLabel)); + navigator.clipboard + .writeText(text) + .then(() => flashCopied(inlineBtn, defaultLabel)) + .catch(() => {}); }); } - for (const container of document.querySelectorAll(".prose .codehilite")) { + 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"; @@ -254,7 +269,10 @@ function initCopyButtons() { if (!raw || !navigator.clipboard) { return; } - navigator.clipboard.writeText(raw).then(() => flashCopied(btn, defaultLabel)); + navigator.clipboard + .writeText(raw) + .then(() => flashCopied(btn, defaultLabel)) + .catch(() => {}); }); container.appendChild(btn); } @@ -315,10 +333,17 @@ 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; @@ -370,6 +395,7 @@ function initSearchDialog() { renderMessage( "Type a keyword to search guides, CLI options, detectors, and FAQs." ); + announceStatus(""); return; } @@ -411,6 +437,7 @@ function initSearchDialog() { if (!topHits.length) { renderMessage(`No matching sections found for "${rawQuery.trim()}".`); + announceStatus("No matching sections found."); return; } @@ -441,6 +468,9 @@ function initSearchDialog() { resultsEl.appendChild(link); }); activeHitIndex = 0; + announceStatus( + topHits.length === 1 ? "1 result found." : `${topHits.length} results found.` + ); }; const openSearch = () => { @@ -477,9 +507,9 @@ function initSearchDialog() { event.preventDefault(); updateActiveHit(activeHitIndex - 1); } else if (event.key === "Enter") { + event.preventDefault(); const hits = resultsEl.querySelectorAll(".search-hit"); if (activeHitIndex >= 0 && hits[activeHitIndex]) { - event.preventDefault(); const href = hits[activeHitIndex].getAttribute("href"); dialog.close(); if (href) {