diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..a6f82cd7 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,71 @@ +# +# PySceneDetect: Python-Based Video Scene Detector +# ------------------------------------------------------------------- +# [ Site: https://scenedetect.com ] +# [ Docs: https://scenedetect.com/docs/ ] +# [ Github: https://github.com/Breakthrough/PySceneDetect/ ] +# +# Copyright (C) 2014-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. +# + +# Version control +.git +.gitignore +.github + +# Python / Build artifacts +__pycache__/ +*.pyc +*.pyo +*.pyd +.Python +env/ +venv/ +.venv/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# Testing / Tooling +.pytest_cache/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.log +.mypy_cache/ +.hypothesis/ + +# IDE / Project files +.vscode/ +.idea/ +*.swp +*.swo +.DS_Store + +# Project specific exclusions (to keep the image lean) +test_clips/ +tests/ +docs/ +website/ +benchmark/ +scenedetect.cfg + diff --git a/.github/ISSUE_TEMPLATE/bug-or-issue-report.md b/.github/ISSUE_TEMPLATE/bug-or-issue-report.md deleted file mode 100644 index 8a19cabe..00000000 --- a/.github/ISSUE_TEMPLATE/bug-or-issue-report.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -name: Bug or Issue Report -about: Submit a bug report or issue to help us fix and improve PySceneDetect. - ---- - -**Bug/Issue Description:** -A clear and concise description of what the bug or issue is - in other words, what the *unexpected* behavior or output is. - -**Required Information:** -Provide the following information to assist with reporting the bug: -1. Provide a full copy of the command line options you are using, for example: - -`scenedetect -i some_video.mp4 -s some_video.stats.csv -o outdir detect-content --threshold 28 list-scenes save-images` - -2. Add `-v debug -l BUG_REPORT.txt` to the beginning of the command, then re-run PySceneDetect and **attach the generated `BUG_REPORT.txt` file**. - -**Expected Behavior:** -A clear and concise description of what you *expected* to happen. - -**Computing Environment:** - - OS: [e.g. Windows, Linux (Distro: Ubuntu, Mint, Fedora, etc...), OSX] - - Python Version: [e.g. 3.6 or 3.6.6] - - OpenCV Version: [e.g. 3.4.1] - -**Additional Information:** -Add any other information you feel might be relevant to the bug/issue report but was not covered in one of the previous categories. - -**Media [Videos/Images/Screenshots]:** -Provide any other information you can, including videos/media that can demonstrate the bug you are reporting (even YouTube links are fine). If applicable, add the output images from PySceneDetect, or any screenshots you feel are necessary to help explain your problem. - -Remove this section if there is no media associated with the issue/bug report. diff --git a/.github/ISSUE_TEMPLATE/feature-or-enhancement-request.md b/.github/ISSUE_TEMPLATE/feature-or-enhancement-request.md deleted file mode 100644 index 473a6710..00000000 --- a/.github/ISSUE_TEMPLATE/feature-or-enhancement-request.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: Feature or Enhancement Request -about: Submit an idea. or request for a feature to be added to PySceneDetect. - ---- - -**Description of Problem & Solution** -A clear and concise description of what the problem your feature/idea solves. Ex. PySceneDetect doesn't work well in cases X or Y but if it could detect Z [...], PySceneDetect is slow because of X but could be faster if it did Y [...], or I need PySceneDetect to do X because of some condition Y [...]. - -**Media Examples:** -Where possible, provide videos/images demonstrating the problem at hand or issue you would like to solve (even YouTube links are fine). - -**Proposed Implementation:** -A clear and concise description of what you want to happen, how you think the feature/enhancement should be implemented. Ex. what command line options/arguments should be added to PySceneDetect, and examples of how you expect them to function. - -**Alternative Solutions:** -A clear and concise list of descriptions for any alternative solutions or features you've considered. diff --git a/.github/ISSUE_TEMPLATE/scenedetect_app.md b/.github/ISSUE_TEMPLATE/scenedetect_app.md new file mode 100644 index 00000000..49658a85 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/scenedetect_app.md @@ -0,0 +1,27 @@ +--- +name: Application Bug +about: Help us fix and improve PySceneDetect by reporting bugs or other issues. + +--- + +**Description:** + +Describe what the bug or issue is (e.g. crashes when setting X) and how it can be reproduced. + +**Command:** + +Place a full copy of the command line options you are using here, for example: + +`scenedetect -i some_video.mp4 -s some_video.stats.csv -o outdir detect-content --threshold 28 list-scenes save-images` + +**Output:** + +Copy the output of running the application here. Where possible, generate a debug log by adding `-v debug -l BUG_REPORT.txt` to the beginning of your command, and **attach `BUG_REPORT.txt` to your issue**. + +**Environment:** + +The operating system and how you installed PySceneDetect may be relevant to the issue. Please run `scenedetect version` and copy the output here, or provide other details on how PySceneDetect was installed. + +**Media/Files:** + +Attach or link to any files relevant to the issue, including videos (or YouTube links), scene files, stats files, and log output. diff --git a/.github/ISSUE_TEMPLATE/scenedetect_package.md b/.github/ISSUE_TEMPLATE/scenedetect_package.md new file mode 100644 index 00000000..3215afc0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/scenedetect_package.md @@ -0,0 +1,28 @@ +--- +name: Python API +about: Programmers using the `scenedetect` package. + +--- + +**Description:** + +Describe the issue (unexpected result, exception thrown, etc...) and any relevant output. + +**Example:** + +Include code samples that demonstrate the issue: + +```python +from scenedetect import detect, ContentDetector, split_video_ffmpeg + +scene_list = detect("my_video.mp4", ContentDetector()) +split_video_ffmpeg("my_video.mp4", scene_list) +``` + +**Environment:** + +Run `scenedetect version` and include the output. This will describe the environment/OS/platform and versions of dependencies you have installed. + +**Media/Files:** + +Attach or link to any files relevant to the issue, including videos (or YouTube links), scene files, stats files, and log output. diff --git a/.github/ISSUE_TEMPLATE/scenedetect_request.md b/.github/ISSUE_TEMPLATE/scenedetect_request.md new file mode 100644 index 00000000..0de1ff8e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/scenedetect_request.md @@ -0,0 +1,25 @@ +--- +name: Feature or Enhancement +about: Submit an idea or feature request to make PySceneDetect better. + +--- + +**Problem/Use Case** + +Describe what problem you want to solve, or what use case you want to achieve. Ex. PySceneDetect doesn't work well in cases X or Y but if it could detect Z [...], PySceneDetect is slow because of X but could be faster if it did Y [...], or I need PySceneDetect to do X because of some condition Y [...]. + +**Solutions** + +Discuss any potential solutions here. + +**Proposed Implementation:** + +Description of what you want to happen, and how you think the feature/enhancement should be implemented. Ex. what command line options/arguments should be added to PySceneDetect, and examples of how you expect them to function. + +**Alternatives:** + +List any alternative solutions or related ideas you've considered. + +**Examples:** + +Attach or link to any relevant videos or images that are relevant. diff --git a/.github/actions/setup-ffmpeg/action.yml b/.github/actions/setup-ffmpeg/action.yml new file mode 100644 index 00000000..76cee703 --- /dev/null +++ b/.github/actions/setup-ffmpeg/action.yml @@ -0,0 +1,112 @@ +name: 'Setup FFmpeg' +description: 'Ensure ffmpeg is available on the runner, using OS package managers as a fallback.' +inputs: + github-token: + description: 'Unused; kept for backward compatibility with existing callers.' + required: false + default: '' + +runs: + using: 'composite' + steps: + - name: Set ffmpeg install config + shell: bash + run: | + VERSION=8.1 + echo "FFMPEG_VERSION=${VERSION}" >> "$GITHUB_ENV" + echo "FFMPEG_ASSET=ffmpeg-${VERSION}-essentials_build.zip" >> "$GITHUB_ENV" + + - name: Check for preinstalled ffmpeg + id: check + shell: bash + run: | + if command -v ffmpeg >/dev/null 2>&1; then + echo "ffmpeg already available at: $(command -v ffmpeg)" + ffmpeg -version | head -n 1 + echo "installed=true" >> "$GITHUB_OUTPUT" + else + echo "ffmpeg not found on PATH; will install via package manager." + echo "installed=false" >> "$GITHUB_OUTPUT" + fi + + - name: Install ffmpeg (Linux) + if: ${{ steps.check.outputs.installed == 'false' && runner.os == 'Linux' }} + shell: bash + run: | + attempts=4 + for attempt in $(seq 1 $attempts); do + echo "apt-get attempt $attempt" + if sudo apt-get update && sudo apt-get install -y ffmpeg; then + exit 0 + fi + if [ "$attempt" -lt "$attempts" ]; then + delay=$(( 15 * (1 << (attempt - 1)) + RANDOM % 6 )) + echo "install failed; sleeping ${delay}s before retry" + sleep "$delay" + fi + done + echo "Failed to install ffmpeg via apt-get after $attempts attempts" >&2 + exit 1 + + - name: Install ffmpeg (macOS) + if: ${{ steps.check.outputs.installed == 'false' && runner.os == 'macOS' }} + shell: bash + run: | + attempts=4 + for attempt in $(seq 1 $attempts); do + echo "brew attempt $attempt" + if brew install ffmpeg; then + exit 0 + fi + if [ "$attempt" -lt "$attempts" ]; then + delay=$(( 15 * (1 << (attempt - 1)) + RANDOM % 6 )) + echo "install failed; sleeping ${delay}s before retry" + sleep "$delay" + fi + done + echo "Failed to install ffmpeg via brew after $attempts attempts" >&2 + exit 1 + + - name: Cache ffmpeg (Windows) + if: ${{ steps.check.outputs.installed == 'false' && runner.os == 'Windows' }} + id: cache-ffmpeg-windows + uses: actions/cache@v4 + with: + path: C:\ffmpeg-bin + key: ffmpeg-windows-${{ env.FFMPEG_VERSION }}-v1 + + - name: Install ffmpeg (Windows) + if: ${{ steps.check.outputs.installed == 'false' && runner.os == 'Windows' && steps.cache-ffmpeg-windows.outputs.cache-hit != 'true' }} + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: | + $attempts = 4 + $downloaded = $false + for ($attempt = 1; $attempt -le $attempts; $attempt++) { + Write-Host "download attempt $attempt (GyanD/codexffmpeg $env:FFMPEG_VERSION)" + gh release download $env:FFMPEG_VERSION --repo GyanD/codexffmpeg --pattern $env:FFMPEG_ASSET --clobber + if ($LASTEXITCODE -eq 0) { $downloaded = $true; break } + if ($attempt -lt $attempts) { + $delay = [int]([math]::Pow(2, $attempt - 1) * 15) + (Get-Random -Minimum 0 -Maximum 6) + Write-Host "download failed; sleeping ${delay}s before retry" + Start-Sleep -Seconds $delay + } + } + if (-not $downloaded) { + Write-Error "Failed to download ffmpeg after $attempts attempts" + exit 1 + } + Expand-Archive -Path $env:FFMPEG_ASSET -DestinationPath ffmpeg-extract -Force + New-Item -ItemType Directory -Force -Path C:\ffmpeg-bin | Out-Null + Copy-Item -Path (Join-Path "ffmpeg-extract" "ffmpeg-$env:FFMPEG_VERSION-essentials_build\bin\*.exe") -Destination C:\ffmpeg-bin\ + Remove-Item -Recurse -Force ffmpeg-extract, $env:FFMPEG_ASSET + + - name: Add ffmpeg to PATH (Windows) + if: ${{ steps.check.outputs.installed == 'false' && runner.os == 'Windows' }} + shell: pwsh + run: Add-Content -Path $env:GITHUB_PATH -Value 'C:\ffmpeg-bin' + + - name: Verify ffmpeg + shell: bash + run: ffmpeg -version | head -n 1 diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml new file mode 100644 index 00000000..495d68c3 --- /dev/null +++ b/.github/workflows/build-windows.yml @@ -0,0 +1,134 @@ +# Build Portable Windows EXE (x64) Distribution for PySceneDetect + +name: Windows Distribution + +on: + schedule: + - cron: '0 0 * * *' + pull_request: + paths: + - packaging/** + - scripts/** + - scenedetect/** + - tests/** + - pyproject.toml + - .github/workflows/build-windows.yml + push: + paths: + - packaging/** + - scripts/** + - scenedetect/** + - tests/** + - pyproject.toml + - .github/workflows/build-windows.yml + branches: + - main + - 'releases/**' + tags: + - 'v*' + workflow_dispatch: + +jobs: + build: + runs-on: windows-latest + strategy: + matrix: + python-version: ["3.13"] + + env: + ffmpeg-version: "8.1" + + steps: + - uses: actions/checkout@v5 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python-version }} + cache: 'pip' + + - name: Install Dependencies + run: | + python -m pip install --upgrade pip build wheel virtualenv setuptools + pip install .[docs] + pip install --upgrade -r packaging/windows/requirements.txt --no-binary imageio-ffmpeg + + - name: Download Resources + run: | + git fetch --depth=1 https://github.com/Breakthrough/PySceneDetect.git refs/heads/resources:refs/remotes/origin/resources + git checkout refs/remotes/origin/resources -- tests/resources/ + + - name: Download FFMPEG ${{ env.ffmpeg-version }} + uses: dsaltares/fetch-gh-release-asset@1.1.2 + with: + repo: 'GyanD/codexffmpeg' + version: 'tags/${{ env.ffmpeg-version }}' + file: 'ffmpeg-${{ env.ffmpeg-version }}-full_build.7z' + + - name: Unit Test + shell: bash + run: | + 7z e ffmpeg-${{ env.ffmpeg-version }}-full_build.7z ffmpeg.exe -r + export PATH="$(pwd):$PATH" + # moviepy.config resolves ffmpeg via imageio_ffmpeg at import time; `--no-binary` + # strips the bundled binary, so point at the GyanD ffmpeg we just extracted + # for both pytest and the subsequent pyinstaller step. + echo "IMAGEIO_FFMPEG_EXE=$(realpath ffmpeg.exe)" >> "$GITHUB_ENV" + python -m pytest -vv + + - name: Build PySceneDetect + run: | + python scripts/pre_release.py + pyinstaller packaging/windows/scenedetect.spec + + - name: Build Documentation + run: | + sphinx-build -b singlehtml docs dist/scenedetect/docs + rm -r dist/scenedetect/docs/.doctrees + + - name: Assemble Portable Distribution + run: | + Move-Item -Path LICENSE -Destination dist/scenedetect/ + New-Item -Path dist/scenedetect/ -Name thirdparty -ItemType Directory + Copy-Item -Path packaging/windows/LICENSE-PYTHON -Destination dist/scenedetect/thirdparty/ + Copy-Item -Path scenedetect/_thirdparty/LICENSE* -Destination dist/scenedetect/thirdparty/ + 7z e -odist/ffmpeg ffmpeg-${{ env.ffmpeg-version }}-full_build.7z LICENSE -r + Move-Item -Path ffmpeg.exe -Destination dist/scenedetect/ffmpeg.exe + Move-Item -Path dist/ffmpeg/LICENSE -Destination dist/scenedetect/thirdparty/LICENSE-FFMPEG + + - name: Test Portable Distribution + run: | + ./dist/scenedetect/scenedetect -i tests/resources/goldeneye.mp4 detect-content time -e 2s + + - name: Upload Artifact + uses: actions/upload-artifact@v6 + with: + name: PySceneDetect-win64 + path: dist/scenedetect + include-hidden-files: true + + test: + runs-on: windows-latest + needs: build + steps: + - uses: actions/checkout@v5 + with: + ref: resources + + - uses: actions/download-artifact@v7 + with: + name: PySceneDetect-win64 + path: build + + - name: Test + run: | + echo Testing binary + ./build/scenedetect version + echo Test OpenCV + ./build/scenedetect -i tests/resources/goldeneye.mp4 -b opencv detect-content time --end 10s + echo Test PyAV + ./build/scenedetect -i tests/resources/goldeneye.mp4 -b pyav detect-content time --end 10s + echo Test moviepy + ./build/scenedetect -i tests/resources/goldeneye.mp4 -b moviepy detect-content time --end 10s + echo Test split-video + ffmpeg + ./build/scenedetect -i tests/resources/goldeneye.mp4 detect-content time --end 10s split-video diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..d6f0f6ef --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,161 @@ +# Test PySceneDetect on Linux/OSX/Windows and generate Python distribution (sdist/wheel). +name: Python Distribution + +on: + schedule: + - cron: '0 0 * * *' + pull_request: + paths: + - packaging/** + - scripts/** + - scenedetect/** + - tests/** + - pyproject.toml + - .github/workflows/build.yml + - .github/actions/setup-ffmpeg/** + push: + paths: + - packaging/** + - scripts/** + - scenedetect/** + - tests/** + - pyproject.toml + - .github/workflows/build.yml + - .github/actions/setup-ffmpeg/** + branches: + - main + - 'releases/**' + tags: + - 'v*' + workflow_dispatch: + +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macos-14, macos-latest, ubuntu-22.04, ubuntu-latest, windows-latest] + python-version: ["3.10", "3.11", "3.12", "3.13"] + env: + # Version is extracted below and used to find correct package install path. + scenedetect_version: "" + + steps: + - uses: actions/checkout@v5 + + - name: Setup FFmpeg + uses: ./.github/actions/setup-ffmpeg + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python-version }} + cache: 'pip' + + - name: Install Dependencies + run: | + python -m pip install --upgrade pip build wheel virtualenv setuptools + pip install -e .[dev] --only-binary av,opencv-python + + - name: Checkout test resources + run: | + git fetch --depth=1 https://github.com/Breakthrough/PySceneDetect.git refs/heads/resources:refs/remotes/origin/resources + git checkout refs/remotes/origin/resources -- tests/resources/ + + # Instrumented while chasing a windows-latest flake where python exits 1 after a + # fully green pytest run with no output. `-X dev` makes shutdown-time warnings and + # finalizer errors loud; echoing the exit code separates python's own return value + # from anything the shell wrapper does to a crash code. + - name: Unit Tests + shell: bash + run: | + set +e + python -X dev -m pytest -vv + code=$? + echo "pytest exit code: $code" + exit $code + + - name: Smoke Test (Module) + run: | + python -m scenedetect version + python -m scenedetect -i tests/resources/testvideo.mp4 -b opencv time --end 2s + python -m scenedetect -i tests/resources/testvideo.mp4 -b pyav time --end 2s + python -m pip uninstall -y scenedetect-core + + - name: Build Package + shell: bash + run: | + # Builds the scenedetect/scenedetect-headless packages. + python packaging/build_all.py + echo "scenedetect_version=`python -c \"import scenedetect; print(scenedetect.__version__.replace('-', '.'))\"`" >> "$GITHUB_ENV" + + - name: Smoke Test Package (Source Dist) + shell: bash + run: | + python -m venv .smoke-sdist + VENV_BIN=.smoke-sdist/bin + [ -d .smoke-sdist/Scripts ] && VENV_BIN=.smoke-sdist/Scripts + source "$VENV_BIN/activate" + pip install "dist/scenedetect-${{ env.scenedetect_version }}.tar.gz[pyav]" --only-binary av + python -c "import importlib.metadata as m; ds = sorted(d.metadata['Name'] for d in m.distributions() if d.metadata['Name'] in ('opencv-python', 'opencv-python-headless')); assert ds == ['opencv-python'], f'Expected only opencv-python, got: {ds}'" + scenedetect version + scenedetect -i tests/resources/testvideo.mp4 -b opencv time --end 2s + scenedetect -i tests/resources/testvideo.mp4 -b pyav time --end 2s + + - name: Smoke Test Package (Wheel) + shell: bash + run: | + python -m venv .smoke-wheel + VENV_BIN=.smoke-wheel/bin + [ -d .smoke-wheel/Scripts ] && VENV_BIN=.smoke-wheel/Scripts + source "$VENV_BIN/activate" + pip install "dist/scenedetect-${{ env.scenedetect_version }}-py3-none-any.whl[pyav]" --only-binary av + scenedetect version + scenedetect -i tests/resources/testvideo.mp4 -b opencv time --end 2s + scenedetect -i tests/resources/testvideo.mp4 -b pyav time --end 2s + + - name: Smoke Test Package (Headless Wheel) + shell: bash + run: | + python -m venv .smoke-headless + VENV_BIN=.smoke-headless/bin + [ -d .smoke-headless/Scripts ] && VENV_BIN=.smoke-headless/Scripts + source "$VENV_BIN/activate" + pip install "dist/scenedetect_headless-${{ env.scenedetect_version }}-py3-none-any.whl[pyav]" --only-binary av + # Confirm the install pulled `opencv-python-headless`, not the GUI variant. + # If both are present, cv2 imports may silently come from either. + python -c "import importlib.metadata as m; ds = sorted(d.metadata['Name'] for d in m.distributions() if d.metadata['Name'] in ('opencv-python', 'opencv-python-headless')); assert ds == ['opencv-python-headless'], f'Expected only opencv-python-headless, got: {ds}'" + scenedetect version + scenedetect -i tests/resources/testvideo.mp4 -b opencv time --end 2s + scenedetect -i tests/resources/testvideo.mp4 -b pyav time --end 2s + + - name: Smoke Test Package (Upgrade From 0.7) + shell: bash + run: | + # Both packages ship the code (no metapackage layering) precisely so that + # in-place upgrades from older installs keep working - a code-carrying dist + # flipped to a code-free metapackage would break here, since uninstalling the old + # version deletes module files a dependency just wrote. This is also why the + # short-lived scenedetect-core (published in 0.7.1 only) was yanked rather than + # layered on. Keep this as a regression guard for that failure mode + # (https://scenedetect.com/issues/558). + python -m venv .smoke-upgrade + VENV_BIN=.smoke-upgrade/bin + [ -d .smoke-upgrade/Scripts ] && VENV_BIN=.smoke-upgrade/Scripts + source "$VENV_BIN/activate" + pip install "scenedetect==0.7" + pip install --upgrade --find-links dist/ "scenedetect==${{ env.scenedetect_version }}" + python -c "import scenedetect; print(scenedetect.__version__)" + scenedetect version + + - name: Upload Package + if: ${{ matrix.python-version == '3.13' && matrix.os == 'ubuntu-latest' }} + uses: actions/upload-artifact@v6 + with: + name: scenedetect-dist + path: | + dist/*.tar.gz + dist/*.whl diff --git a/.github/workflows/check-code-format.yml b/.github/workflows/check-code-format.yml deleted file mode 100644 index 75512e4e..00000000 --- a/.github/workflows/check-code-format.yml +++ /dev/null @@ -1,31 +0,0 @@ - -name: Check Code Format - -on: [pull_request, push] - -jobs: - build: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - name: Set up Python 3.10 - uses: actions/setup-python@v3 - with: - python-version: '3.10' - - - name: Update pip - run: python -m pip install --upgrade pip - - name: Install yapf - run: python -m pip install --upgrade yapf toml - - - name: Install Binary Dependencies - run: python -m pip install av==9.2 opencv-python-headless --only-binary ":all:" - - name: Install Remaining Dependencies - run: python -m pip install -r requirements_headless.txt - - - name: Check Code Format (scenedetect) - run: python -m yapf --diff --recursive scenedetect/ - - name: Check Code Format (tests) - run: python -m yapf --diff --recursive tests/ diff --git a/.github/workflows/check-docs.yml b/.github/workflows/check-docs.yml new file mode 100644 index 00000000..199c5ef3 --- /dev/null +++ b/.github/workflows/check-docs.yml @@ -0,0 +1,60 @@ +name: Check Documentation + +on: + schedule: + - cron: '0 0 * * *' + pull_request: + paths: + - docs/** + - scenedetect/** + - website/** + push: + paths: + - docs/** + - scenedetect/** + - website/** + branches: + - main + - 'releases/**' + tags: + - 'v*' + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v5 + + - name: Set up Python 3.12 + uses: actions/setup-python@v6 + with: + python-version: '3.12' + cache: 'pip' + + - name: Install Dependencies + run: | + python -m pip install --upgrade pip build wheel virtualenv + pip install .[docs,website] + pip install -r packaging/windows/requirements.txt + + + - name: Check CLI Documentation + shell: bash + run: | + if [[ `git status --porcelain=1 | wc -l` -ne 0 ]]; then + echo "CLI documentation is of date: docs/cli.rst does not match output after running docs/generate_cli_docs.py!" + echo "Re-run `python docs/generate_cli_docs.py` to update and commit the result." + exit 1 + fi + + - name: Build Sphinx Reference (warnings as errors) + shell: bash + run: | + sphinx-build -W --keep-going -b html docs docs/_build/html + + - name: Build MkDocs Website (--strict) + shell: bash + run: | + mkdocs build --strict -f website/mkdocs.yml diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 7ab8b604..9dd65e17 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -1,10 +1,21 @@ +# CodeQL for PySceneDetect name: "CodeQL" on: push: - branches: [ "master" ] + branches: + - main + - releases/** + paths: + - scenedetect/** + - tests/** pull_request: - branches: [ "master" ] + branches: + - main + - releases/* + paths: + - scenedetect/** + - tests/** schedule: - cron: "20 7 * * 4" @@ -24,18 +35,18 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v5 - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} queries: +security-and-quality - name: Autobuild - uses: github/codeql-action/autobuild@v2 + uses: github/codeql-action/autobuild@v3 - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 with: category: "/language:${{ matrix.language }}" diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml new file mode 100644 index 00000000..046e9c88 --- /dev/null +++ b/.github/workflows/dependency-review.yml @@ -0,0 +1,20 @@ +# Dependency Review Action +# +# This Action will scan dependency manifest files that change as part of a Pull Request, surfacing known-vulnerable versions of the packages declared or updated in the PR. Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable packages will be blocked from merging. +# +# Source repository: https://github.com/actions/dependency-review-action +# Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement +name: 'Dependency Review' +on: [pull_request] + +permissions: + contents: read + +jobs: + dependency-review: + runs-on: ubuntu-latest + steps: + - name: 'Checkout Repository' + uses: actions/checkout@v5 + - name: 'Dependency Review' + uses: actions/dependency-review-action@v4 diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml new file mode 100644 index 00000000..0ce991b7 --- /dev/null +++ b/.github/workflows/docker-publish.yml @@ -0,0 +1,72 @@ +# Build and publish PySceneDetect Docker image to GitHub Container Registry (GHCR). +name: Publish Docker Image + +# Publishing a release build is driven by release.yml, which dispatches this workflow after +# artifact verification passes. +on: + workflow_dispatch: + inputs: + tag_latest: + description: 'Also tag this build as `latest`' + type: boolean + default: false + push: + branches: [ "main" ] + +env: + REGISTRY: ghcr.io + # Image names must be lowercase; github.repository is Breakthrough/PySceneDetect. + IMAGE_NAME: breakthrough/pyscenedetect + +jobs: + build-and-push: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + attestations: write + id-token: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Docker buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to the Container registry + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=semver,pattern={{major}} + type=sha + type=raw,value=latest,enable=${{ github.event_name == 'workflow_dispatch' && inputs.tag_latest }} + + - name: Build and push Docker image + id: push + uses: docker/build-push-action@v5 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + + - name: Generate artifact attestation + uses: actions/attest-build-provenance@v1 + with: + subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + subject-digest: ${{ steps.push.outputs.digest }} + push-to-registry: true + diff --git a/.github/workflows/generate-docs.yml b/.github/workflows/generate-docs.yml new file mode 100644 index 00000000..12ccd7a2 --- /dev/null +++ b/.github/workflows/generate-docs.yml @@ -0,0 +1,93 @@ +# Generate PySceneDetect documentation and updates the gh-pages branch. +name: Generate Documentation + +on: + push: + branches: + - main # docs/head + - 'releases/**' # docs/** + paths: + - 'docs/**' + workflow_dispatch: + +jobs: + update_docs: + runs-on: ubuntu-latest + permissions: + contents: write # pushes generated docs to the gh-pages branch + env: + scenedetect_docs_dest: '' + + steps: + - uses: actions/checkout@v5 + + - name: Get Latest Version + run: | + git fetch origin main --depth=1 + echo "scenedetect_docs_latest=$(git show origin/main:docs/LATEST_VERSION | tr -d '[:space:]')" >> "$GITHUB_ENV" + + - name: Set up Python 3.12 + uses: actions/setup-python@v6 + with: + python-version: '3.12' + cache: 'pip' + + - name: Set Destination (Releases) + if: ${{ contains(github.ref_name, 'releases') }} + run: | + echo "scenedetect_docs_dest=$(echo ${{ github.ref_name }} | cut -b 10-)" >> "$GITHUB_ENV" + + - name: Set Destination (Head) + if: ${{ contains(github.ref_name, 'main') }} + run: | + echo "scenedetect_docs_dest=head" >> "$GITHUB_ENV" + + - name: Check Destination + if: ${{ env.scenedetect_docs_dest == '' }} + run: | + echo "Failing build: destination must be set!" + + - name: Setup Environment + run: | + python -m pip install --upgrade pip build wheel virtualenv + pip install .[docs] + pip install -r packaging/windows/requirements.txt + git config --global user.name github-actions + git config --global user.email github-actions@github.com + + - name: Check CLI Documentation + shell: bash + run: | + if [[ `git status --porcelain=1 | wc -l` -ne 0 ]]; then + echo "CLI documentation is of date: docs/cli.rst does not match output after running docs/generate_cli_docs.py!" + echo "Re-run `python docs/generate_cli_docs.py` to update and commit the result." + exit 1 + fi + + - name: Generate Docs + run: | + sphinx-build -b html docs build + + - name: Update gh-pages Branch + run: | + git fetch origin gh-pages + git checkout gh-pages + git rm "docs/${{ env.scenedetect_docs_dest }}" -r -f --ignore-unmatch + git add build/ + git mv build "docs/${{ env.scenedetect_docs_dest }}" + + - name: Update Latest + if: ${{ env.scenedetect_docs_dest == env.scenedetect_docs_latest }} + run: | + git rm "docs/latest" -r -f --ignore-unmatch + mkdir -p latest + cp -r -f "docs/${{ env.scenedetect_docs_dest }}" docs/latest + git add docs/latest + echo "scenedetect_docs_dest='${{ env.scenedetect_docs_dest }} (latest)'" >> "$GITHUB_ENV" + + - 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 diff --git a/.github/workflows/generate-website.yml b/.github/workflows/generate-website.yml new file mode 100644 index 00000000..6e924106 --- /dev/null +++ b/.github/workflows/generate-website.yml @@ -0,0 +1,53 @@ + +name: Generate Website + +on: + push: + branches: + - main + paths: + - 'website/**' + workflow_dispatch: + +jobs: + update_site: + runs-on: ubuntu-latest + permissions: + contents: write # pushes generated site to the gh-pages branch + + steps: + - uses: actions/checkout@v5 + + - name: Set up Python 3.12 + uses: actions/setup-python@v6 + with: + python-version: '3.12' + cache: 'pip' + + - name: Install Dependencies + run: | + python -m pip install --upgrade pip build wheel virtualenv + pip install .[website] + + - name: Generate Website + run: | + mkdocs build -f website/mkdocs.yml + + - name: Update Website + run: | + git fetch origin gh-pages + git checkout gh-pages + git rm * -r -f --ignore-unmatch + git checkout HEAD -- .nojekyll + git checkout HEAD -- CNAME + git checkout HEAD -- docs/ + git rm docs/index.html --ignore-unmatch + git add website/build/ + git mv website/build/* . -f -k + git mv website/build/docs/index.html docs/index.html -k + git rm website/build/* -r -f --ignore-unmatch + git 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 diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml new file mode 100644 index 00000000..de468367 --- /dev/null +++ b/.github/workflows/publish-pypi.yml @@ -0,0 +1,118 @@ +name: Publish PyPI Package + +on: + workflow_dispatch: + inputs: + tag: + description: 'Tag To Publish' + required: true + environment: + description: 'PyPI Environment' + required: true + type: choice + options: + - testpypi + - pypi + default: 'testpypi' + +jobs: + # Production publishes require all three release workflows to be green for the tag. + # TestPyPI publishes are exploratory and skip this job; the Resolve step in `publish` + # still gates on a successful Python Distribution run so artifacts are guaranteed to exist. + verify: + name: Verify Build + if: github.event.inputs.environment == 'pypi' + runs-on: ubuntu-latest + permissions: + actions: read + steps: + - name: Check required workflows succeeded for ${{ github.event.inputs.tag }} + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + TAG: ${{ github.event.inputs.tag }} + run: | + set -euo pipefail + required=("Python Distribution" "Windows Distribution" "Release Test Suite") + failed=0 + for workflow in "${required[@]}"; do + conclusion=$(gh run list \ + --workflow "$workflow" \ + --branch "$TAG" \ + --event push \ + --limit 1 \ + --json conclusion \ + -q '.[0].conclusion // ""') + if [[ "$conclusion" != "success" ]]; then + echo "::error::Workflow '$workflow' did not succeed for tag $TAG (got: '${conclusion:-no run found}')" + failed=1 + else + echo "[OK] $workflow" + fi + done + [[ "$failed" -eq 0 ]] + + publish: + name: Publish ${{ github.event.inputs.tag }} to ${{ github.event.inputs.environment }} + runs-on: ubuntu-latest + needs: verify + # Run when verify succeeded (pypi) or was skipped (testpypi). + if: | + always() && + (needs.verify.result == 'success' || needs.verify.result == 'skipped') + + environment: + name: ${{ github.event.inputs.environment }} + url: ${{ github.event.inputs.environment == 'testpypi' && 'https://test.pypi.org/p/scenedetect' || 'https://pypi.org/p/scenedetect' }} + + permissions: + id-token: write # mandatory for trusted publishing + actions: read # for cross-workflow artifact download + + steps: + - name: Resolve Python Distribution run for ${{ github.event.inputs.tag }} + id: resolve + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + TAG: ${{ github.event.inputs.tag }} + run: | + set -euo pipefail + run_id=$(gh run list \ + --workflow "Python Distribution" \ + --branch "$TAG" \ + --event push \ + --status success \ + --limit 1 \ + --json databaseId \ + -q '.[0].databaseId // ""') + if [[ -z "$run_id" ]]; then + echo "::error::No successful 'Python Distribution' run found for tag $TAG. Push the tag and wait for build.yml to finish before publishing." + exit 1 + fi + echo "run-id=$run_id" >> "$GITHUB_OUTPUT" + echo "Using Python Distribution run $run_id" + + - name: Download distribution artifact + uses: actions/download-artifact@v7 + with: + name: scenedetect-dist + path: pkg/ + github-token: ${{ secrets.GITHUB_TOKEN }} + repository: ${{ github.repository }} + run-id: ${{ steps.resolve.outputs.run-id }} + + - name: List artifact contents + # Expect 4 files: sdist + wheel for each of scenedetect and + # scenedetect-headless. Both projects publish from this one step; + # each needs a trusted publisher configured on PyPI/TestPyPI for this workflow. + run: ls -la pkg/ + + - name: Publish Package + uses: pypa/gh-action-pypi-publish@release/v1 + with: + repository-url: ${{ github.event.inputs.environment == 'testpypi' && 'https://test.pypi.org/legacy/' || 'https://upload.pypi.org/legacy/' }} + packages-dir: pkg/ + print-hash: true + # Tolerate retries: skip existing packages if for example only some variants were uploaded. + skip-existing: true diff --git a/.github/workflows/release-test.yml b/.github/workflows/release-test.yml new file mode 100644 index 00000000..4c6de70d --- /dev/null +++ b/.github/workflows/release-test.yml @@ -0,0 +1,117 @@ +name: Release Test Suite + +on: + workflow_dispatch: + push: + tags: + - 'v*' + +jobs: + static: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: '3.10' + cache: 'pip' + - name: Install dependencies + run: | + # setuptools is upgraded because the toolcache copy periodically lags + # security fixes (e.g. PYSEC-2026-3447) and would fail the audit below. + python -m pip install --upgrade pip setuptools + pip install build twine pip-audit + - name: Version consistency check + run: | + # Parse __version__ directly so we don't have to install scenedetect + # (importing it triggers a cv2-availability guard). + VERSION=$(python -c "import ast,pathlib; print(next(n.value.value for n in ast.parse(pathlib.Path('scenedetect/__init__.py').read_text()).body if isinstance(n, ast.Assign) and any(getattr(t,'id',None)=='__version__' for t in n.targets)))") + echo "scenedetect.__version__ = $VERSION" + if [[ "${{ github.ref }}" == refs/tags/* ]]; then + TAG_VERSION=${GITHUB_REF#refs/tags/v} + TAG_VERSION=${TAG_VERSION%-release} + if [[ "$VERSION" != "$TAG_VERSION" ]]; then + echo "Version mismatch: scenedetect=$VERSION, tag=$TAG_VERSION" + exit 1 + fi + # Pre-release tags (e.g. 0.7-dev0) ship before the changelog is finalized, + # so only enforce the heading on stable releases. + if [[ "$TAG_VERSION" == *-dev* ]]; then + echo "Pre-release ($TAG_VERSION); skipping changelog heading check." + # Major/minor releases use a '## PySceneDetect X.Y' heading; patch + # releases nest under it as '### PySceneDetect X.Y.Z (date)'. + elif ! grep -Eq "^#{2,3} (PySceneDetect )?$TAG_VERSION( |$)" website/pages/changelog.md; then + echo "Changelog is missing a heading for $TAG_VERSION (e.g. '### PySceneDetect $TAG_VERSION (...)')" + exit 1 + fi + fi + - name: Build and Check + run: | + # Builds the scenedetect/scenedetect-headless packages. + python packaging/build_all.py + # Glob by extension: dist/ also holds tracked website assets (dist/logo/), + # which `twine check dist/*` would reject as an unknown distribution. + twine check dist/*.whl dist/*.tar.gz + - name: pip-audit + # CVE-2026-3219 in pip 26.0.1 has no fix version available upstream + # and pip ships pre-installed on the runner (not controlled by this + # project). Re-evaluate when pip publishes a fix. + run: pip-audit --ignore-vuln CVE-2026-3219 + + release-tests: + needs: static + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + python-version: ['3.10', '3.13'] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v5 + - name: Checkout resources branch + run: | + git fetch --depth=1 origin refs/heads/resources:refs/remotes/origin/resources + git checkout refs/remotes/origin/resources -- tests/resources/ + git reset + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python-version }} + cache: 'pip' + - name: Install ffmpeg + uses: ./.github/actions/setup-ffmpeg + - name: Install dependencies + run: | + python -m pip install --upgrade pip + # The dev extra supplies the CLI deps (click/opencv/tqdm) plus av and moviepy; + # a bare `pip install .` is now scenedetect-core with numpy only. + pip install .[dev] + pip install opentimelineio pillow psutil pytest + - name: Run release tests + run: pytest -m release -vv --ignore=tests/release/test_long_video_stress.py + + long-stress: + needs: static + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - name: Checkout resources branch + run: | + git fetch --depth=1 origin refs/heads/resources:refs/remotes/origin/resources + git checkout refs/remotes/origin/resources -- tests/resources/ + git reset + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: '3.10' + cache: 'pip' + - name: Install ffmpeg + uses: ./.github/actions/setup-ffmpeg + - name: Install dependencies + run: | + python -m pip install --upgrade pip + # The dev extra supplies the CLI deps (click/opencv/tqdm) plus av. + pip install .[dev] + pip install psutil pytest + - name: Run long stress test + run: pytest -m release -k long_video -vv diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..80f5a530 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,217 @@ +# Release orchestrator: verifies the artifacts attached to a DRAFT GitHub +# release actually work, then publishes stage by stage, verifying each stage +# before starting the next: +# +# MSI install/upgrade test against the draft's assets (test-installer.yml) +# -> TestPyPI publish -> pip smoke install from TestPyPI +# -> publish the GitHub release (draft -> public, marked latest) +# -> PyPI publish -> pip smoke install from PyPI +# -> Docker publish -> docker pull + smoke run from GHCR +# +# This workflow is dispatched manually once the GitHub release has been DRAFTED +# with its artifacts attached (signed MSI/zip, wheels, SHA256SUMS); nothing goes +# public until artifact verification passes. Each stage is driven through the +# existing workflows via `gh workflow run` (rather than workflow_call) so they +# keep working standalone and the PyPI trusted-publisher configuration (which is +# bound to publish-pypi.yml as the top-level workflow) is unaffected. + +name: Release Orchestrator + +on: + workflow_dispatch: + inputs: + tag: + description: 'Release tag to verify and publish (e.g. v0.7.1)' + required: true + verify-only: + description: 'Stop after verification (no PyPI/Docker publish)' + type: boolean + default: false + +permissions: + contents: write # read the draft release's assets and publish it (draft -> public) + actions: write # `gh workflow run` on the workflows this one orchestrates + +# The run-id lookup after each dispatch assumes this is the only orchestrator +# running; never allow two concurrent releases. +concurrency: + group: release-orchestrator + +jobs: + orchestrate: + name: ${{ inputs.verify-only && 'Verify' || 'Verify + Publish' }} ${{ inputs.tag }} + runs-on: ubuntu-latest + timeout-minutes: 120 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + TAG: ${{ inputs.tag }} + steps: + - name: Validate release + run: | + set -euo pipefail + state=$(gh release view "$TAG" --json isDraft,isPrerelease \ + -q 'if .isDraft then "draft" elif .isPrerelease then "prerelease" else "published" end') + if [[ "$state" == "draft" ]]; then + echo "Release $TAG is a draft; it will be published after artifact verification passes." + else + echo "Release $TAG is already $state; the GitHub release publish step will be a no-op (re-run mode)." + fi + # Display version used by the pip smoke test; mirrors the tag + # normalization in release-test.yml (both vX.Y[.Z] and the legacy + # vX.Y[.Z]-release tag styles are accepted). + VERSION="${TAG#v}" + VERSION="${VERSION%-release}" + echo "VERSION=$VERSION" >> "$GITHUB_ENV" + + - name: Write dispatch helper + # `gh workflow run` returns no run id, so the helper polls for the + # newest workflow_dispatch run created at/after dispatch time (the + # concurrency group above guarantees it is ours), then watches it to + # completion, propagating failure. + run: | + cat > "$RUNNER_TEMP/dispatch.sh" <<'EOF' + dispatch_and_watch() { + local workflow="$1" ref="$2" + shift 2 + local start_epoch + start_epoch=$(date -u +%s) + echo "::group::Dispatch $workflow (ref $ref) $*" + gh workflow run "$workflow" --ref "$ref" "$@" + local run_id="" + for _ in $(seq 1 24); do + sleep 5 + run_id=$(gh run list --workflow "$workflow" --event workflow_dispatch --limit 5 \ + --json databaseId,createdAt \ + -q "[.[] | select((.createdAt | fromdateiso8601) >= $((start_epoch - 5)))] | first | .databaseId // \"\"") + [[ -n "$run_id" ]] && break + done + if [[ -z "$run_id" ]]; then + echo "::error::Dispatched $workflow but its run never appeared." + return 1 + fi + echo "Watching run $run_id: https://github.com/$GH_REPO/actions/runs/$run_id" + echo "::endgroup::" + gh run watch "$run_id" --exit-status --interval 30 + } + EOF + + - name: Write pip smoke-install helper + # Same smoke test for TestPyPI and production PyPI: fresh venv, install + # the exact release version, and check `scenedetect version` reports it. + # Both indexes can lag a fresh upload, so installs are retried briefly. + run: | + cat > "$RUNNER_TEMP/smoke.sh" <<'EOF' + pip_smoke_install() { + local venv="$1" + shift + python3 -m venv "$venv" + local ok=0 + for attempt in 1 2 3 4 5; do + if "$venv/bin/pip" install --quiet "$@" "scenedetect==$VERSION"; then + ok=1 + break + fi + echo "pip install attempt $attempt failed; retrying in 30s..." + sleep 30 + done + [[ "$ok" -eq 1 ]] + local out + out=$("$venv/bin/scenedetect" version) + echo "$out" + grep -F "$VERSION" <<<"$out" + } + EOF + + - name: 'Stage 1 - Verify: Windows installer (install + upgrade on clean runner)' + run: | + set -euo pipefail + source "$RUNNER_TEMP/dispatch.sh" + dispatch_and_watch test-installer.yml "$GITHUB_REF_NAME" -f "tag=$TAG" + + - name: 'Stage 2 - Publish: TestPyPI' + run: | + set -euo pipefail + source "$RUNNER_TEMP/dispatch.sh" + # Dispatched on the release tag: the pypi environment's deployment + # branch policy only permits release refs (v* tags / releases/* + # branches), and the tag is the immutable ref being released anyway. + dispatch_and_watch publish-pypi.yml "$TAG" -f "tag=$TAG" -f "environment=testpypi" + + - name: 'Stage 2 - Verify: pip install from TestPyPI' + run: | + set -euo pipefail + source "$RUNNER_TEMP/smoke.sh" + # Dependencies are not mirrored on TestPyPI, so resolve them from the + # production index. + pip_smoke_install smoke-testpypi \ + --index-url https://test.pypi.org/simple/ \ + --extra-index-url https://pypi.org/simple/ + + - name: 'Stage 3 - Publish: GitHub release (draft -> public)' + if: ${{ !inputs.verify-only }} + run: | + set -euo pipefail + is_draft=$(gh release view "$TAG" --json isDraft -q .isDraft) + if [[ "$is_draft" == "true" ]]; then + gh release edit "$TAG" --draft=false --latest + echo "Published release $TAG (marked as latest)." + else + echo "Release $TAG is already published; skipping." + fi + + - name: 'Stage 4 - Publish: PyPI (production)' + if: ${{ !inputs.verify-only }} + run: | + set -euo pipefail + source "$RUNNER_TEMP/dispatch.sh" + # publish-pypi.yml additionally gates production publishes on the + # build + release-test workflows being green for the tag. Dispatched + # on the tag ref to satisfy the pypi environment's deployment policy. + dispatch_and_watch publish-pypi.yml "$TAG" -f "tag=$TAG" -f "environment=pypi" + + - name: 'Stage 4 - Verify: pip install from PyPI' + if: ${{ !inputs.verify-only }} + run: | + set -euo pipefail + source "$RUNNER_TEMP/smoke.sh" + pip_smoke_install smoke-pypi + + - name: 'Stage 5 - Publish: Docker image (version tags + latest)' + if: ${{ !inputs.verify-only }} + run: | + set -euo pipefail + source "$RUNNER_TEMP/dispatch.sh" + # Dispatched on the release tag itself so docker/metadata-action + # derives the semver image tags from it (requires the tag to contain + # docker-publish.yml, i.e. v0.7.1 or newer). + dispatch_and_watch docker-publish.yml "$TAG" -f "tag_latest=true" + + - name: 'Stage 5 - Verify: docker pull + smoke run from GHCR' + if: ${{ !inputs.verify-only }} + run: | + set -euo pipefail + image="ghcr.io/breakthrough/pyscenedetect" + docker pull "$image:$VERSION" + docker pull "$image:latest" + # `latest` must point at the build we just published. + v=$(docker image inspect "$image:$VERSION" --format '{{.Id}}') + l=$(docker image inspect "$image:latest" --format '{{.Id}}') + if [[ "$v" != "$l" ]]; then + echo "::error::latest ($l) does not match $VERSION ($v)" + exit 1 + fi + out=$(docker run --rm "$image:$VERSION" version) + echo "$out" + grep -F "$VERSION" <<<"$out" + + - name: Summary + run: | + if [[ "${{ inputs.verify-only }}" == "true" ]]; then + echo "Verification of $TAG passed (release left as draft). Re-run without verify-only to publish." + else + echo "Release $TAG verified and published:" + echo " https://pypi.org/project/scenedetect/$VERSION/" + echo " https://pypi.org/project/scenedetect-headless/$VERSION/" + echo " https://github.com/$GH_REPO/pkgs/container/pyscenedetect" + fi diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml new file mode 100644 index 00000000..f2d432f3 --- /dev/null +++ b/.github/workflows/static-analysis.yml @@ -0,0 +1,47 @@ +# Check PySceneDetect code lint warnings and formatting. +name: Static Analysis + +on: + pull_request: + paths: + - scenedetect/** + - tests/** + - pyproject.toml + - .github/workflows/static-analysis.yml + push: + paths: + - scenedetect/** + - tests/** + - pyproject.toml + - .github/workflows/static-analysis.yml + +jobs: + check_format: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v5 + - name: Set up Python 3.12 + uses: actions/setup-python@v6 + with: + python-version: '3.12' + cache: 'pip' + + - name: Install Dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -e .[dev] --only-binary av,opencv-python + + - name: Static Analysis (ruff) + run: | + python -m pip install --upgrade ruff + python -m ruff check + python -m ruff format --check + + - name: Type Check (pyright) + env: + PYRIGHT_PYTHON_FORCE_VERSION: latest + run: | + python -m pip install pyright + python -m pyright + diff --git a/.github/workflows/test-installer.yml b/.github/workflows/test-installer.yml new file mode 100644 index 00000000..45f77a5e --- /dev/null +++ b/.github/workflows/test-installer.yml @@ -0,0 +1,657 @@ +# Post-release verification of the signed Windows MSI installer. +# +# Downloads the MSI attached to a published release, then on a clean +# windows-latest runner: verifies checksum + Authenticode signature, performs a +# silent install, checks the Apps & Features registration / PATH / smoke-runs +# the CLI, and uninstalls cleanly. A second job installs the previous release's +# MSI first and upgrades over it to catch duplicate-entry and leftover-file +# regressions. + +name: Windows Installer Test + +# Dispatched by release.yml (the release orchestrator) as part of post-release +# artifact verification; can also be run manually against any published release. +on: + workflow_dispatch: + inputs: + tag: + description: 'Release tag to test (e.g. v0.7-release or v0.7.1)' + required: true + previous-tag: + description: 'Release tag to upgrade from (default: auto-detect previous release)' + required: false + +# NOTE: This workflow never writes to the repository; `contents: write` is required +# only because draft-release assets are invisible to read-only tokens, and the +# release orchestrator runs this verification while the release is still a draft. +permissions: + contents: write + +jobs: + resolve: + name: Resolve Release Tags + runs-on: ubuntu-latest + outputs: + tag: ${{ steps.resolve.outputs.tag }} + version: ${{ steps.resolve.outputs.version }} + msi-version: ${{ steps.resolve.outputs.msi-version }} + prev-tag: ${{ steps.resolve.outputs.prev-tag }} + prev-msi-version: ${{ steps.resolve.outputs.prev-msi-version }} + steps: + - name: Resolve current and previous release + id: resolve + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + INPUT_TAG: ${{ inputs.tag }} + INPUT_PREV_TAG: ${{ inputs.previous-tag }} + run: | + set -euo pipefail + TAG="$INPUT_TAG" + if [[ -z "$TAG" ]]; then + echo "::error::No tag to test: the 'tag' input is required." + exit 1 + fi + # Both tag styles are in use (v0.7-release and v0.7.1); mirror the + # normalization release-test.yml applies to pushed tags. + VERSION="${TAG#v}" + VERSION="${VERSION%-release}" + # Pad to the numeric X.Y.Z the installer stamps into the MSI + # ProductVersion / DisplayVersion; mirrors msi_version() in + # scripts/_release_common.py ("0.7" -> "0.7.0"). + IFS=. read -r a b c _ <<<"$VERSION" + MSI_VERSION="${a}.${b:-0}.${c:-0}" + + if [[ -n "$INPUT_PREV_TAG" ]]; then + PREV_TAG="$INPUT_PREV_TAG" + else + # Newest-first list of published stable releases; the previous + # release is the entry right after the current tag. + mapfile -t tags < <(gh release list --exclude-drafts --exclude-pre-releases \ + --limit 30 --json tagName -q '.[].tagName') + PREV_TAG="" + found=0 + for i in "${!tags[@]}"; do + if [[ "${tags[$i]}" == "$TAG" ]]; then + found=1 + PREV_TAG="${tags[$((i + 1))]:-}" + break + fi + done + if [[ "$found" -eq 0 ]]; then + # Manual dispatch before the release is published: the current + # tag is not listed yet, so upgrade from the newest listed tag + # that differs from it. + for t in "${tags[@]}"; do + if [[ "$t" != "$TAG" ]]; then + PREV_TAG="$t" + break + fi + done + fi + fi + if [[ -z "$PREV_TAG" ]]; then + echo "::error::Could not determine a previous release to upgrade from; pass the 'previous-tag' input." + exit 1 + fi + PREV_VERSION="${PREV_TAG#v}" + PREV_VERSION="${PREV_VERSION%-release}" + IFS=. read -r a b c _ <<<"$PREV_VERSION" + PREV_MSI_VERSION="${a}.${b:-0}.${c:-0}" + + { + echo "tag=$TAG" + echo "version=$VERSION" + echo "msi-version=$MSI_VERSION" + echo "prev-tag=$PREV_TAG" + echo "prev-msi-version=$PREV_MSI_VERSION" + } >> "$GITHUB_OUTPUT" + echo "Testing $TAG (display $VERSION, MSI $MSI_VERSION); upgrading from $PREV_TAG (MSI $PREV_MSI_VERSION)" + + fresh-install: + name: Fresh Install + runs-on: windows-latest + needs: resolve + env: + TAG: ${{ needs.resolve.outputs.tag }} + VERSION: ${{ needs.resolve.outputs.version }} + MSI_VERSION: ${{ needs.resolve.outputs.msi-version }} + steps: + # Test videos live on the resources branch; this is the same layout + # build-windows.yml smoke-tests the portable distribution against. + - uses: actions/checkout@v5 + with: + ref: resources + + - name: Write helper functions + # Each `run:` step is a fresh pwsh process, so shared functions go into + # a file (in RUNNER_TEMP, which checkout cannot clean away) that later + # steps dot-source. + run: | + $helpers = @' + # All hives an uninstall entry could land in. The MSI installs + # per-machine (the .aip sets ALLUSERS=2 and the runner is elevated), + # so 64-bit HKLM is the expected home; the others are scanned so a + # misplaced entry fails the assertions loudly instead of hiding. + $UninstallRoots = @( + 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall' + 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall' + 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall' + ) + + function Get-PySceneDetectEntries { + # Every uninstall entry (any hive, visible or hidden) for + # PySceneDetect. A healthy install has exactly two: the MSI + # ProductCode key (hidden from Apps & Features by + # ARPSYSTEMCOMPONENT=1, set in PySceneDetect.aip) and the visible + # custom key "PySceneDetect " that carries + # DisplayVersion / InstallLocation. + foreach ($root in $UninstallRoots) { + if (-not (Test-Path $root)) { continue } + foreach ($key in Get-ChildItem $root) { + $props = Get-ItemProperty $key.PSPath -ErrorAction SilentlyContinue + if ($props.DisplayName -like 'PySceneDetect*') { + [pscustomobject]@{ + KeyPath = $key.PSPath + KeyName = $key.PSChildName + DisplayName = $props.DisplayName + DisplayVersion = $props.DisplayVersion + InstallLocation = $props.InstallLocation + SystemComponent = $props.SystemComponent + } + } + } + } + } + + function Get-VisiblePySceneDetectEntries { + # The set Apps & Features actually shows: SystemComponent != 1. + Get-PySceneDetectEntries | Where-Object { $_.SystemComponent -ne 1 } + } + + function Get-UninstallKeyByName { + # The visible key's name embeds the MSI version ("PySceneDetect + # 0.7.0"), so a lookup by name across hives is a precise + # per-version existence check. + param([Parameter(Mandatory)][string]$KeyName) + foreach ($root in $UninstallRoots) { + $path = Join-Path $root $KeyName + if (Test-Path $path) { $path } + } + } + + function Invoke-Msiexec { + # msiexec detaches from the console immediately, so a bare + # `msiexec ...` would return before the Windows Installer service + # finishes (and without the real exit code); Start-Process + # -Wait -PassThru blocks and surfaces it. + param( + [Parameter(Mandatory)][string[]]$MsiArgs, + [Parameter(Mandatory)][string]$LogPath + ) + $log = Join-Path (Get-Location) $LogPath + for ($attempt = 1; $attempt -le 3; $attempt++) { + $p = Start-Process msiexec.exe -ArgumentList ($MsiArgs + @('/L*v', $log)) -Wait -PassThru + switch ($p.ExitCode) { + 0 { Write-Host "msiexec $($MsiArgs -join ' ') succeeded (exit 0)"; return } + 3010 { Write-Host 'msiexec exit 3010 (success, reboot required) - treated as success'; return } + 1618 { + # ERROR_INSTALL_ALREADY_RUNNING: runner provisioning + # sometimes still holds the machine-wide MSI mutex. + Write-Host "msiexec exit 1618 (another install in progress), attempt $attempt of 3" + if ($attempt -lt 3) { Start-Sleep -Seconds 30 } + } + default { throw "msiexec $($MsiArgs -join ' ') failed with exit code $($p.ExitCode); see $LogPath" } + } + } + throw 'msiexec still blocked by another installation (exit 1618) after 3 attempts' + } + + function Get-PathRegistryValues { + # The installer edits PATH in the registry only; neither this + # process nor its children see the change, so assertions must + # read the raw values. Machine PATH is where a per-machine + # install writes (the .aip Environment row uses the '*' system + # prefix); HKCU is read too for completeness. + $values = @() + $machine = Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name Path -ErrorAction SilentlyContinue + if ($machine) { $values += $machine.Path } + $user = Get-ItemProperty 'HKCU:\Environment' -Name Path -ErrorAction SilentlyContinue + if ($user) { $values += $user.Path } + $values + } + + function Test-DirOnRegistryPath { + param([Parameter(Mandatory)][string]$Directory) + $needle = $Directory.TrimEnd('\') + foreach ($value in Get-PathRegistryValues) { + # -contains is case-insensitive, matching how Windows treats paths. + if (@($value -split ';' | ForEach-Object { $_.TrimEnd('\') }) -contains $needle) { + return $true + } + } + return $false + } + + function Assert-CleanRemoval { + param([string]$InstallDir) + $entries = @(Get-PySceneDetectEntries) + if ($entries.Count -ne 0) { + $entries | Format-List | Out-String | Write-Host + throw "Expected zero uninstall entries after uninstall, found $($entries.Count)" + } + # Also match stale keys by name in case a leftover key lost its + # DisplayName value. + foreach ($root in $UninstallRoots) { + if (-not (Test-Path $root)) { continue } + $stale = @(Get-ChildItem $root | Where-Object { $_.PSChildName -like 'PySceneDetect*' }) + if ($stale.Count -ne 0) { + throw "Stale uninstall keys remain under ${root}: $($stale.PSChildName -join ', ')" + } + } + if ($InstallDir) { + if (Test-Path (Join-Path $InstallDir 'scenedetect.exe')) { + throw "scenedetect.exe still present in $InstallDir after uninstall" + } + if (Test-DirOnRegistryPath -Directory $InstallDir) { + throw "$InstallDir still present in a PATH registry value after uninstall" + } + } + Write-Host 'Verified clean removal.' + } + '@ + $dest = Join-Path $env:RUNNER_TEMP 'installer-helpers.ps1' + Set-Content -LiteralPath $dest -Value $helpers + Write-Host "Wrote $dest" + + - name: Download release assets + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + run: | + gh release download $env:TAG --pattern 'PySceneDetect-*-win64.msi' --pattern 'SHA256SUMS' --dir dist + if ($LASTEXITCODE -ne 0) { throw "gh release download failed for $env:TAG" } + $expected = "PySceneDetect-$env:VERSION-win64.msi" + $msis = @(Get-ChildItem dist -Filter '*.msi') + if ($msis.Count -ne 1 -or $msis[0].Name -ne $expected) { + throw "Expected exactly one MSI named $expected, got: $($msis.Name -join ', ')" + } + if (-not (Test-Path dist\SHA256SUMS)) { throw 'SHA256SUMS missing from release assets' } + + - name: Verify checksum and Authenticode signature + run: | + $msi = "dist\PySceneDetect-$env:VERSION-win64.msi" + $name = Split-Path $msi -Leaf + # SHA256SUMS lines are ` ` (two spaces; the sha256sum -c + # format written by scripts/finalize_windows_dist.py). + $sums = @{} + foreach ($line in Get-Content dist\SHA256SUMS) { + $hash, $entry = $line -split ' ', 2 + $sums[$entry.Trim()] = $hash.Trim() + } + if (-not $sums.ContainsKey($name)) { throw "SHA256SUMS has no entry for $name" } + $actual = (Get-FileHash $msi -Algorithm SHA256).Hash.ToLowerInvariant() + if ($actual -ne $sums[$name].ToLowerInvariant()) { + throw "SHA256 mismatch for ${name}: expected $($sums[$name]), got $actual" + } + Write-Host "Checksum OK: $actual" + $sig = Get-AuthenticodeSignature $msi + if ($sig.Status -ne 'Valid') { + throw "Authenticode signature status is '$($sig.Status)' (expected 'Valid')" + } + Write-Host "Signature OK: $($sig.SignerCertificate.Subject)" + + - name: Install MSI + run: | + . (Join-Path $env:RUNNER_TEMP 'installer-helpers.ps1') + $msi = (Resolve-Path "dist\PySceneDetect-$env:VERSION-win64.msi").Path + Invoke-Msiexec -MsiArgs @('/i', $msi, '/qn', '/norestart') -LogPath install.log + + - name: Verify installation + run: | + . (Join-Path $env:RUNNER_TEMP 'installer-helpers.ps1') + # Locate the install via the registry - never hard-code the path: the + # .aip uses ALLUSERS=2 with a MixedAllUsersInstallLocation custom + # action, so APPDIR is resolved at install time. + $visible = @(Get-VisiblePySceneDetectEntries) + if ($visible.Count -ne 1) { + Get-PySceneDetectEntries | Format-List | Out-String | Write-Host + throw "Expected exactly 1 visible uninstall entry, found $($visible.Count)" + } + $entry = $visible[0] + if ($entry.DisplayVersion -ne $env:MSI_VERSION) { + throw "DisplayVersion is '$($entry.DisplayVersion)', expected '$env:MSI_VERSION'" + } + if (-not $entry.InstallLocation) { throw 'InstallLocation is empty' } + $exe = Join-Path $entry.InstallLocation 'scenedetect.exe' + if (-not (Test-Path $exe)) { throw "scenedetect.exe not found in $($entry.InstallLocation)" } + # Persist the discovered install dir for the later steps. + Add-Content $env:GITHUB_ENV "INSTALL_DIR=$($entry.InstallLocation)" + # Invoke by absolute path: the installer's PATH change is + # registry-only and not visible to this already-running process. + $out = & $exe version 2>&1 | Out-String + Write-Host $out + if ($LASTEXITCODE -ne 0) { throw "scenedetect version exited with $LASTEXITCODE" } + if (-not $out.Contains($env:VERSION)) { throw "version output does not mention $env:VERSION" } + if (-not (Test-DirOnRegistryPath -Directory $entry.InstallLocation)) { + throw "$($entry.InstallLocation) was not added to any PATH registry value" + } + Write-Host 'Install verified.' + + - name: Functional smoke test + run: | + # Same clip and command build-windows.yml uses to smoke-test the + # portable distribution. + $exe = Join-Path $env:INSTALL_DIR 'scenedetect.exe' + & $exe -i tests/resources/goldeneye.mp4 detect-content time --end 10s + if ($LASTEXITCODE -ne 0) { throw "smoke test exited with $LASTEXITCODE" } + + - name: Uninstall MSI + run: | + . (Join-Path $env:RUNNER_TEMP 'installer-helpers.ps1') + # Uninstall via the same local MSI file (not the ProductCode) so a + # broken product registration surfaces as a failure here. + $msi = (Resolve-Path "dist\PySceneDetect-$env:VERSION-win64.msi").Path + Invoke-Msiexec -MsiArgs @('/x', $msi, '/qn', '/norestart') -LogPath uninstall.log + + - name: Verify clean removal + run: | + . (Join-Path $env:RUNNER_TEMP 'installer-helpers.ps1') + Assert-CleanRemoval -InstallDir $env:INSTALL_DIR + + - name: Upload msiexec logs + if: failure() + uses: actions/upload-artifact@v6 + with: + name: fresh-install-logs + path: '*.log' + if-no-files-found: ignore + + upgrade: + name: Upgrade From Previous Release + runs-on: windows-latest + needs: resolve + env: + TAG: ${{ needs.resolve.outputs.tag }} + VERSION: ${{ needs.resolve.outputs.version }} + MSI_VERSION: ${{ needs.resolve.outputs.msi-version }} + PREV_TAG: ${{ needs.resolve.outputs.prev-tag }} + PREV_MSI_VERSION: ${{ needs.resolve.outputs.prev-msi-version }} + steps: + - name: Write helper functions + # Identical to the fresh-install helpers; jobs cannot share script + # blocks, so the definitions are duplicated per job. + run: | + $helpers = @' + # All hives an uninstall entry could land in. The MSI installs + # per-machine (the .aip sets ALLUSERS=2 and the runner is elevated), + # so 64-bit HKLM is the expected home; the others are scanned so a + # misplaced entry fails the assertions loudly instead of hiding. + $UninstallRoots = @( + 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall' + 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall' + 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall' + ) + + function Get-PySceneDetectEntries { + # Every uninstall entry (any hive, visible or hidden) for + # PySceneDetect. A healthy install has exactly two: the MSI + # ProductCode key (hidden from Apps & Features by + # ARPSYSTEMCOMPONENT=1, set in PySceneDetect.aip) and the visible + # custom key "PySceneDetect " that carries + # DisplayVersion / InstallLocation. + foreach ($root in $UninstallRoots) { + if (-not (Test-Path $root)) { continue } + foreach ($key in Get-ChildItem $root) { + $props = Get-ItemProperty $key.PSPath -ErrorAction SilentlyContinue + if ($props.DisplayName -like 'PySceneDetect*') { + [pscustomobject]@{ + KeyPath = $key.PSPath + KeyName = $key.PSChildName + DisplayName = $props.DisplayName + DisplayVersion = $props.DisplayVersion + InstallLocation = $props.InstallLocation + SystemComponent = $props.SystemComponent + } + } + } + } + } + + function Get-VisiblePySceneDetectEntries { + # The set Apps & Features actually shows: SystemComponent != 1. + Get-PySceneDetectEntries | Where-Object { $_.SystemComponent -ne 1 } + } + + function Get-UninstallKeyByName { + # The visible key's name embeds the MSI version ("PySceneDetect + # 0.7.0"), so a lookup by name across hives is a precise + # per-version existence check. + param([Parameter(Mandatory)][string]$KeyName) + foreach ($root in $UninstallRoots) { + $path = Join-Path $root $KeyName + if (Test-Path $path) { $path } + } + } + + function Invoke-Msiexec { + # msiexec detaches from the console immediately, so a bare + # `msiexec ...` would return before the Windows Installer service + # finishes (and without the real exit code); Start-Process + # -Wait -PassThru blocks and surfaces it. + param( + [Parameter(Mandatory)][string[]]$MsiArgs, + [Parameter(Mandatory)][string]$LogPath + ) + $log = Join-Path (Get-Location) $LogPath + for ($attempt = 1; $attempt -le 3; $attempt++) { + $p = Start-Process msiexec.exe -ArgumentList ($MsiArgs + @('/L*v', $log)) -Wait -PassThru + switch ($p.ExitCode) { + 0 { Write-Host "msiexec $($MsiArgs -join ' ') succeeded (exit 0)"; return } + 3010 { Write-Host 'msiexec exit 3010 (success, reboot required) - treated as success'; return } + 1618 { + # ERROR_INSTALL_ALREADY_RUNNING: runner provisioning + # sometimes still holds the machine-wide MSI mutex. + Write-Host "msiexec exit 1618 (another install in progress), attempt $attempt of 3" + if ($attempt -lt 3) { Start-Sleep -Seconds 30 } + } + default { throw "msiexec $($MsiArgs -join ' ') failed with exit code $($p.ExitCode); see $LogPath" } + } + } + throw 'msiexec still blocked by another installation (exit 1618) after 3 attempts' + } + + function Get-PathRegistryValues { + # The installer edits PATH in the registry only; neither this + # process nor its children see the change, so assertions must + # read the raw values. Machine PATH is where a per-machine + # install writes (the .aip Environment row uses the '*' system + # prefix); HKCU is read too for completeness. + $values = @() + $machine = Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name Path -ErrorAction SilentlyContinue + if ($machine) { $values += $machine.Path } + $user = Get-ItemProperty 'HKCU:\Environment' -Name Path -ErrorAction SilentlyContinue + if ($user) { $values += $user.Path } + $values + } + + function Test-DirOnRegistryPath { + param([Parameter(Mandatory)][string]$Directory) + $needle = $Directory.TrimEnd('\') + foreach ($value in Get-PathRegistryValues) { + # -contains is case-insensitive, matching how Windows treats paths. + if (@($value -split ';' | ForEach-Object { $_.TrimEnd('\') }) -contains $needle) { + return $true + } + } + return $false + } + + function Assert-CleanRemoval { + param([string]$InstallDir) + $entries = @(Get-PySceneDetectEntries) + if ($entries.Count -ne 0) { + $entries | Format-List | Out-String | Write-Host + throw "Expected zero uninstall entries after uninstall, found $($entries.Count)" + } + # Also match stale keys by name in case a leftover key lost its + # DisplayName value. + foreach ($root in $UninstallRoots) { + if (-not (Test-Path $root)) { continue } + $stale = @(Get-ChildItem $root | Where-Object { $_.PSChildName -like 'PySceneDetect*' }) + if ($stale.Count -ne 0) { + throw "Stale uninstall keys remain under ${root}: $($stale.PSChildName -join ', ')" + } + } + if ($InstallDir) { + if (Test-Path (Join-Path $InstallDir 'scenedetect.exe')) { + throw "scenedetect.exe still present in $InstallDir after uninstall" + } + if (Test-DirOnRegistryPath -Directory $InstallDir) { + throw "$InstallDir still present in a PATH registry value after uninstall" + } + } + Write-Host 'Verified clean removal.' + } + '@ + $dest = Join-Path $env:RUNNER_TEMP 'installer-helpers.ps1' + Set-Content -LiteralPath $dest -Value $helpers + Write-Host "Wrote $dest" + + - name: Download previous release MSI + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + run: | + gh release download $env:PREV_TAG --pattern '*-win64.msi' --dir prev + if ($LASTEXITCODE -ne 0) { throw "gh release download failed for $env:PREV_TAG" } + $msis = @(Get-ChildItem prev -Filter '*.msi') + if ($msis.Count -ne 1) { + throw "Expected exactly one MSI from $env:PREV_TAG, got: $($msis.Name -join ', ')" + } + # Older releases may not ship SHA256SUMS, so the previous MSI is + # deliberately not checksummed; only the new MSI under test is. + Add-Content $env:GITHUB_ENV "PREV_MSI=$($msis[0].FullName)" + + - name: Install previous release + run: | + . (Join-Path $env:RUNNER_TEMP 'installer-helpers.ps1') + Invoke-Msiexec -MsiArgs @('/i', $env:PREV_MSI, '/qn', '/norestart') -LogPath install-prev.log + # Sanity check the baseline before upgrading over it. + $visible = @(Get-VisiblePySceneDetectEntries) + if ($visible.Count -ne 1) { + Get-PySceneDetectEntries | Format-List | Out-String | Write-Host + throw "Expected exactly 1 visible uninstall entry after baseline install, found $($visible.Count)" + } + if ($visible[0].DisplayVersion -ne $env:PREV_MSI_VERSION) { + throw "Baseline DisplayVersion is '$($visible[0].DisplayVersion)', expected '$env:PREV_MSI_VERSION'" + } + $exe = Join-Path $visible[0].InstallLocation 'scenedetect.exe' + if (-not (Test-Path $exe)) { throw "scenedetect.exe not found in $($visible[0].InstallLocation)" } + & $exe version + if ($LASTEXITCODE -ne 0) { throw "baseline scenedetect version exited with $LASTEXITCODE" } + Add-Content $env:GITHUB_ENV "OLD_INSTALL_DIR=$($visible[0].InstallLocation)" + + - name: Download new release assets + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + run: | + gh release download $env:TAG --pattern 'PySceneDetect-*-win64.msi' --pattern 'SHA256SUMS' --dir dist + if ($LASTEXITCODE -ne 0) { throw "gh release download failed for $env:TAG" } + $expected = "PySceneDetect-$env:VERSION-win64.msi" + $msis = @(Get-ChildItem dist -Filter '*.msi') + if ($msis.Count -ne 1 -or $msis[0].Name -ne $expected) { + throw "Expected exactly one MSI named $expected, got: $($msis.Name -join ', ')" + } + if (-not (Test-Path dist\SHA256SUMS)) { throw 'SHA256SUMS missing from release assets' } + + - name: Verify checksum and Authenticode signature + run: | + $msi = "dist\PySceneDetect-$env:VERSION-win64.msi" + $name = Split-Path $msi -Leaf + # SHA256SUMS lines are ` ` (two spaces; the sha256sum -c + # format written by scripts/finalize_windows_dist.py). + $sums = @{} + foreach ($line in Get-Content dist\SHA256SUMS) { + $hash, $entry = $line -split ' ', 2 + $sums[$entry.Trim()] = $hash.Trim() + } + if (-not $sums.ContainsKey($name)) { throw "SHA256SUMS has no entry for $name" } + $actual = (Get-FileHash $msi -Algorithm SHA256).Hash.ToLowerInvariant() + if ($actual -ne $sums[$name].ToLowerInvariant()) { + throw "SHA256 mismatch for ${name}: expected $($sums[$name]), got $actual" + } + Write-Host "Checksum OK: $actual" + $sig = Get-AuthenticodeSignature $msi + if ($sig.Status -ne 'Valid') { + throw "Authenticode signature status is '$($sig.Status)' (expected 'Valid')" + } + Write-Host "Signature OK: $($sig.SignerCertificate.Subject)" + + - name: Install new release over previous + run: | + . (Join-Path $env:RUNNER_TEMP 'installer-helpers.ps1') + $msi = (Resolve-Path "dist\PySceneDetect-$env:VERSION-win64.msi").Path + Invoke-Msiexec -MsiArgs @('/i', $msi, '/qn', '/norestart') -LogPath install-upgrade.log + + - name: Verify upgrade + run: | + . (Join-Path $env:RUNNER_TEMP 'installer-helpers.ps1') + $visible = @(Get-VisiblePySceneDetectEntries) + if ($visible.Count -ne 1) { + Get-PySceneDetectEntries | Format-List | Out-String | Write-Host + throw "Expected exactly 1 visible uninstall entry after upgrade, found $($visible.Count)" + } + $entry = $visible[0] + if ($entry.DisplayVersion -ne $env:MSI_VERSION) { + throw "DisplayVersion is '$($entry.DisplayVersion)', expected '$env:MSI_VERSION'" + } + # The visible key name embeds the version ("PySceneDetect + # "), so the old key vanishing from every hive is a + # precise duplicate-Apps-&-Features-entry check. + $stale = @(Get-UninstallKeyByName -KeyName "PySceneDetect $env:PREV_MSI_VERSION") + if ($stale.Count -ne 0) { + throw "Previous version's uninstall key still present: $($stale -join ', ')" + } + # Belt and braces: no entry anywhere (visible or hidden) may still + # report the old version. + $old = @(Get-PySceneDetectEntries | Where-Object { $_.DisplayVersion -eq $env:PREV_MSI_VERSION }) + if ($old.Count -ne 0) { + $old | Format-List | Out-String | Write-Host + throw "Found $($old.Count) uninstall entries still at $env:PREV_MSI_VERSION" + } + if (-not $entry.InstallLocation) { throw 'InstallLocation is empty after upgrade' } + $exe = Join-Path $entry.InstallLocation 'scenedetect.exe' + if (-not (Test-Path $exe)) { throw "scenedetect.exe not found in $($entry.InstallLocation)" } + $out = & $exe version 2>&1 | Out-String + Write-Host $out + if ($LASTEXITCODE -ne 0) { throw "scenedetect version exited with $LASTEXITCODE" } + if (-not $out.Contains($env:VERSION)) { throw "version output does not mention $env:VERSION" } + # If the upgrade relocated the install, the old copy must be gone. + if ($env:OLD_INSTALL_DIR.TrimEnd('\') -ne $entry.InstallLocation.TrimEnd('\')) { + if (Test-Path (Join-Path $env:OLD_INSTALL_DIR 'scenedetect.exe')) { + throw "Old install at $env:OLD_INSTALL_DIR still present after relocating upgrade" + } + } + Add-Content $env:GITHUB_ENV "INSTALL_DIR=$($entry.InstallLocation)" + Write-Host 'Upgrade verified.' + + - name: Uninstall new MSI + run: | + . (Join-Path $env:RUNNER_TEMP 'installer-helpers.ps1') + $msi = (Resolve-Path "dist\PySceneDetect-$env:VERSION-win64.msi").Path + Invoke-Msiexec -MsiArgs @('/x', $msi, '/qn', '/norestart') -LogPath uninstall.log + + - name: Verify clean removal + run: | + . (Join-Path $env:RUNNER_TEMP 'installer-helpers.ps1') + Assert-CleanRemoval -InstallDir $env:INSTALL_DIR + + - name: Upload msiexec logs + if: failure() + uses: actions/upload-artifact@v6 + with: + name: upgrade-logs + path: '*.log' + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index 1f087746..b2f656fa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ -manual/_build/ +docs/_build/ +docs/STYLE.md +website/build/ +scripts/local/ tests/resources/* *.mp4 *.jpg @@ -6,11 +9,19 @@ tests/resources/* *.patch *.exe *.mkv -*.rtf -*.txt *.m4v *.csv +*.txt + +benchmark/BBC/ +benchmark/AutoShot/ +benchmark/ClipShots/ +benchmark/results/ +packaging/windows/.version_info +packaging/windows/installer/PySceneDetect.back*.aip +packaging/windows/installer/PySceneDetect-*.msi +packaging/windows/installer/PySceneDetect-cache/ # From https://raw.githubusercontent.com/github/gitignore/main/Python.gitignore @@ -84,3 +95,4 @@ dmypy.json .pyre/ .pytype/ cython_debug/ +test_clips/ diff --git a/.style.yapf b/.style.yapf deleted file mode 100644 index 9f089c5b..00000000 --- a/.style.yapf +++ /dev/null @@ -1,6 +0,0 @@ -[style] -based_on_style = yapf -spaces_before_comment = 15, 20 -indent_width = 4 -split_before_logical_operator = true -column_limit = 100 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 3a4b5698..00000000 --- a/.travis.yml +++ /dev/null @@ -1,81 +0,0 @@ -language: python -cache: pip - -matrix: - include: - - os: linux - dist: xenial - language: python - python: "3.9" - - - os: linux - dist: bionic - language: python - python: "3.7" - - os: linux - dist: bionic - language: python - python: "3.10" - - - os: linux - dist: focal - language: python - python: "3.8" - - os: linux - dist: focal - language: python - python: "3.9" - - os: linux - dist: focal - language: python - python: "3.10" - -install: - # TODO: `setuptools` is pinned for the Python 3.7 builder and can be unpinned when removed. - - "python -m pip install --upgrade pip build wheel virtualenv setuptools==62.3.4" - # Make sure we get latest binary packages of the video input libraries. - # TODO(#292): Add a Python 3.11 builder once newer versions of the `av` package are supported. - # TODO: `opencv-python-headless` is pinned for the xenial build. Unpin `opencv-python-headless` - # when https://github.com/opencv/opencv/issues/23090 is resolved. - - "python -m pip install av==9.2 opencv-python-headless==4.6.0.66 --only-binary :all:" - # Install other required packages and download required test resources. - - "python -m pip install -r requirements_headless.txt" - - "git fetch --depth=1 https://github.com/Breakthrough/PySceneDetect.git refs/heads/resources:refs/remotes/origin/resources" - - "git checkout refs/remotes/origin/resources -- tests/resources/" - - "python -m build" - -script: - - python -m pytest tests/ - # TODO: Install ffmpeg/mkvtoolnix to run split-video tests. - - # - # Test CLI using source code - # - - "PACKAGE_VERSION=`python -c \"import scenedetect; print(scenedetect.__version__[1:].replace('-', '.'))\"`" - # Test with OpenCV backend - - python -m scenedetect version - - python -m scenedetect -i tests/resources/testvideo.mp4 -b opencv detect-content time -e 2s - # Test with optional backends - - python -m scenedetect -i tests/resources/testvideo.mp4 -b pyav detect-content time -e 2s - # Cleanup - - python -m pip uninstall -y scenedetect - - # Test CLI using source distribution - - python -m pip install dist/scenedetect-$PACKAGE_VERSION.tar.gz - # Test with OpenCV backend - - scenedetect version - - scenedetect -i tests/resources/testvideo.mp4 -b opencv detect-content time -e 2s - # Test with optional backends - - scenedetect -i tests/resources/testvideo.mp4 -b pyav detect-content time -e 2s - # Cleanup - - python -m pip uninstall -y scenedetect - - # Test CLI using binary wheel - - python -m pip install dist/scenedetect-$PACKAGE_VERSION-py3-none-any.whl - # Test with OpenCV backend - - scenedetect version - - scenedetect -i tests/resources/testvideo.mp4 -b opencv detect-content time -e 2s - # Test with optional backends - - scenedetect -i tests/resources/testvideo.mp4 -b pyav detect-content time -e 2s - # Cleanup - - python -m pip uninstall -y scenedetect diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 00000000..748d4dbf --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,12 @@ +cff-version: 1.2.0 +title: PySceneDetect +message: www.scenedetect.com +type: software +authors: + - given-names: Brandon + family-names: Castellano + affiliation: www.bcastell.com +repository-code: 'https://github.com/Breakthrough/PySceneDetect' +url: 'https://www.scenedetect.com' +abstract: Video Cut Detection and Analysis Tool +license: BSD-3-Clause diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..039790f3 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,46 @@ +# +# PySceneDetect: Python-Based Video Scene Detector +# ------------------------------------------------------------------- +# [ Site: https://scenedetect.com ] +# [ Docs: https://scenedetect.com/docs/ ] +# [ Github: https://github.com/Breakthrough/PySceneDetect/ ] +# +# Copyright (C) 2014-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. +# + +FROM python:3.11.11-slim + +# Create a non-root user for security hardening +RUN useradd -m scenedetect + +# Set working directory and copy files with correct ownership +WORKDIR /app +COPY --chown=scenedetect:scenedetect . . + +# Install necessary system dependencies as root first +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + ffmpeg \ + mkvtoolnix && \ + rm -rf /var/lib/apt/lists/* + +# Install the scenedetect-headless variant: full program (CLI + opencv-python-headless) +# with the optional media backends. The repo root pyproject builds scenedetect-core +# (library only, no CLI), so swap in the headless variant pyproject first. +# pyav is highly recommended for faster/more robust video decodes +# moviepy provides an alternative video splitting backend +RUN --mount=type=cache,target=/root/.cache/pip \ + cp packaging/variants/pyproject-scenedetect-headless.toml pyproject.toml && \ + pip install ".[pyav,moviepy]" && \ + # TODO(https://github.com/Zulko/moviepy/issues/2553): moviepy caps pillow<12.0, but 11.x has + # CVEs only fixed in 12.3.0+. Tests pass against 12.3.0; drop this once moviepy lifts the cap. + pip install "pillow==12.3.0" + +# Switch to the non-root user +USER scenedetect + +# The default behavior is to run the CLI +ENTRYPOINT ["scenedetect"] + diff --git a/LICENSE b/LICENSE index 4fbc04ae..c03985e6 100644 --- a/LICENSE +++ b/LICENSE @@ -1,102 +1,28 @@ -By downloading, copying, installing, or using this software, you agree -to the terms of this license, and those contained in the "Ancillary -Software Licenses" section below. If you do not agree to any of these -terms or licenses, do not download, install, copy, or use the software -or any other material included in in distribution. +BSD 3-Clause License ------------------------------------------------------------------------ - - PySceneDetect License (BSD 3-Clause) - < http://www.bcastell.com/projects/PySceneDetect > - -Copyright (C) 2014-2022, Brandon Castellano. -All rights reserved. +Copyright (C) 2014, Brandon Castellano Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - 3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ------------------------------------------------------------------------ - - Ancillary Software Licenses - -This software uses the following third-party open source libraries and -are released under the terms detailed below. By downloading, copying, -installing or using this software/tutorial, you agree to these terms. - ------------------------------------------------------------------------ - -> NumPy [Copyright (C) 2005-2016, Numpy Developers]: - This software uses Numpy; see the scenedetect/thirdparty/LICENSE-NUMPY - file or visit [ http://www.numpy.org/license.html ] for details. - -> OpenCV [Copyright (C) 2017, Itseez]: - This software uses OpenCV; see the scenedetect/thirdparty/LICENSE-OPENCV - file or visit [ http://opencv.org/license.html ] for details. - -> click [Copyright (C) 2017, Armin Ronacher]: - This software uses OpenCV; see the scenedetect/thirdparty/LICENSE-CLICK - file or visit [ http://click.pocoo.org/license/ ] for details. - -> tqdm [Copyright (C) 2013-2018, Casper da Costa-Luis, - Google Inc., and Noam Yorav-Raphael]: - This software uses tqdm; see the scenedetect/thirdparty/LICENSE-TQDM - file or visit the following URL for details: - [ https://github.com/tqdm/tqdm/blob/master/LICENCE ] - -> pytest [Copyright (C) 2004-2017, Holger Krekel and others]: - This software uses pytest; see the scenedetect/thirdparty/LICENSE-PYTEST - file or visit [ https://docs.pytest.org/en/latest/license.html ]. - -> simpletable [Copyright (C) 2014-2019, Matheus Vieira Portela and others]: - This software uses simpletable; see the file - scenedetect/thirdparty/simpletable.py or visit the following URL: - [ https://github.com/matheusportela/simpletable/blob/master/LICENSE ] - ------------------------------------------------------------------------ - -This software may also invoke FFmpeg or mkvmerge, if available. If required, -these programs can be obtained from following URLs: - - FFmpeg: [ https://ffmpeg.org/download.html ] - mkvmerge: [ https://mkvtoolnix.download/downloads.html ] - -Once installed, ensure the program is in your PATH variable (i.e. you can -run the `ffmpeg` or `mkvmerge` command from any location). - -Certain distributions of PySceneDetect may include the above software; -see the included LICENSE-FFMPEG and LICENSE-MKVMERGE files, or visit -[ https://ffmpeg.org ] and [ https://mkvtoolnix.download ] respectively. - -FFmpeg is a trademark of Fabrice Bellard. -mkvmerge is Copyright (C) 2005-2016, Matroska. - -Additionally, certain Windows distributions may include a compiled -Python distribution. For license information regarding the distributed -version of Python, see the LICENSE-PYTHON file, or visit: - - [ https://docs.python.org/3/license.html ] diff --git a/MANIFEST.in b/MANIFEST.in index d3e42a4a..cf223d6b 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,11 +1,12 @@ recursive-exclude .github * -recursive-exclude dist * -recursive-exclude manual * -exclude manual/requirements.txt +recursive-exclude packaging * +recursive-exclude scripts * +recursive-exclude docs * +recursive-exclude website * exclude * include README.md include LICENSE include pyproject.toml -include setup.cfg include scenedetect.cfg -include dist/package-info.rst +include packaging/package-info.rst +recursive-include docs * diff --git a/README.md b/README.md index ebfdb4c6..f3508a94 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,25 @@ -![PySceneDetect](https://raw.githubusercontent.com/Breakthrough/PySceneDetect/master/docs/img/pyscenedetect_logo_small.png) -========================================================== -Video Scene Cut Detection and Analysis Tool ----------------------------------------------------------- + + + PySceneDetect + + +# Video Cut Detection and Analysis Tool -[![Build Status](https://img.shields.io/travis/com/Breakthrough/PySceneDetect/master)](https://travis-ci.com/github/Breakthrough/PySceneDetect) [![PyPI Status](https://img.shields.io/pypi/status/scenedetect.svg)](https://pypi.python.org/pypi/scenedetect/) [![LGTM Analysis](https://img.shields.io/lgtm/grade/python/github/Breakthrough/PySceneDetect.svg)](https://lgtm.com/projects/g/Breakthrough/PySceneDetect) [![PyPI Version](https://img.shields.io/pypi/v/scenedetect?color=blue)](https://pypi.python.org/pypi/scenedetect/) [![PyPI License](https://img.shields.io/pypi/l/scenedetect.svg)](http://pyscenedetect.readthedocs.org/en/latest/copyright/) +[![Build Status](https://img.shields.io/github/actions/workflow/status/Breakthrough/PySceneDetect/build.yml)](https://github.com/Breakthrough/PySceneDetect/actions) +[![PyPI Status](https://img.shields.io/pypi/status/scenedetect.svg)](https://pypi.python.org/pypi/scenedetect/) +[![PyPI Version](https://img.shields.io/pypi/v/scenedetect?color=blue)](https://pypi.python.org/pypi/scenedetect/) +[![PyPI License](https://img.shields.io/pypi/l/scenedetect.svg)](https://scenedetect.com/copyright/) ---------------------------------------------------------- -### Latest Release: v0.6.1 (November 28, 2022) +### Latest Release: v0.7.1 (July 21, 2026) -**Website**: [scenedetect.com](http://www.scenedetect.com) +**Website**: [scenedetect.com](https://www.scenedetect.com) -**Getting Started**: [Usage Example](https://scenedetect.com/en/latest/examples/usage-example/) +**Quickstart Example**: [scenedetect.com/cli/](https://www.scenedetect.com/cli/) -**Documentation**: [manual.scenedetect.com](http://manual.scenedetect.com) +**Documentation**: [scenedetect.com/docs/](https://www.scenedetect.com/docs/) **Discord**: https://discord.gg/H83HbJngk7 @@ -22,27 +27,33 @@ Video Scene Cut Detection and Analysis Tool **Quick Install**: - pip install scenedetect[opencv] --upgrade + pip install scenedetect --upgrade -Requires ffmpeg/mkvmerge for video splitting support. Windows builds (MSI installer/portable ZIP) can be found on [the download page](http://scenedetect.com/en/latest/download/). +Requires ffmpeg/mkvmerge for video splitting support. Windows builds (MSI installer/portable ZIP) can be found on [the download page](https://scenedetect.com/download/). A Docker image with all dependencies included is available as [`ghcr.io/breakthrough/pyscenedetect`](https://github.com/Breakthrough/PySceneDetect/pkgs/container/pyscenedetect). ---------------------------------------------------------- **Quick Start (Command Line)**: -Split the input video wherever a new scene is detected: +Split input video on each fast cut using `ffmpeg`: + + scenedetect -i video.mp4 split-video + +Save some frames from each cut: + + scenedetect -i video.mp4 save-images - scenedetect -i video.mp4 detect-adaptive split-video +Skip the first 10 seconds of the input video: -Skip the first 10 seconds of the input video, and output a list of scenes to the terminal: + scenedetect -i video.mp4 time -s 10s - scenedetect -i video.mp4 time -s 10s detect-adaptive list-scenes +More examples can be found throughout [the documentation](https://www.scenedetect.com/docs/latest/cli.html). -Help: +**Quick Start (Docker)**: - scenedetect help +The same commands work without installing anything using [the official Docker image](https://github.com/Breakthrough/PySceneDetect/pkgs/container/pyscenedetect), which includes all dependencies (`ffmpeg`/`mkvmerge` included). Mount the folder containing your videos and use it for input/output paths: -You can find more examples [on the website](https://scenedetect.com/en/latest/examples/usage-example/) or [in the manual](https://scenedetect.com/projects/Manual/en/latest/cli/global_options.html). + docker run --rm -v "$(pwd):/files" ghcr.io/breakthrough/pyscenedetect -i /files/video.mp4 split-video -o /files **Quick Start (Python API)**: @@ -50,7 +61,8 @@ To get started, there is a high level function in the library that performs cont ```python from scenedetect import detect, ContentDetector -scene_list = detect('my_video.mp4', ContentDetector()) + +scene_list = detect("my_video.mp4", ContentDetector()) ``` `scene_list` will now be a list containing the start/end times of all scenes found in the video. There also exists a two-pass version `AdaptiveDetector` which handles fast camera movement better, and `ThresholdDetector` for handling fade out/fade in events. @@ -59,77 +71,76 @@ Try calling `print(scene_list)`, or iterating over each scene: ```python from scenedetect import detect, ContentDetector -scene_list = detect('my_video.mp4', ContentDetector()) + +scene_list = detect("my_video.mp4", ContentDetector()) for i, scene in enumerate(scene_list): - print(' Scene %2d: Start %s / Frame %d, End %s / Frame %d' % ( - i+1, - scene[0].get_timecode(), scene[0].get_frames(), - scene[1].get_timecode(), scene[1].get_frames(),)) + print( + " Scene %2d: Start %s / Frame %d, End %s / Frame %d" + % ( + i + 1, + scene[0].get_timecode(), + scene[0].frame_num, + scene[1].get_timecode(), + scene[1].frame_num, + ) + ) ``` We can also split the video into each scene if `ffmpeg` is installed (`mkvmerge` is also supported): ```python from scenedetect import detect, ContentDetector, split_video_ffmpeg -scene_list = detect('my_video.mp4', ContentDetector()) -split_video_ffmpeg('my_video.mp4', scene_list) + +scene_list = detect("my_video.mp4", ContentDetector()) +split_video_ffmpeg("my_video.mp4", scene_list) ``` -For more advanced usage, the API is highly configurable, and can easily integrate with any pipeline. This includes using different detection algorithms, splitting the input video, and much more. The following example shows how to implement a function similar to the above, but using [the `scenedetect` API](https://scenedetect.com/projects/Manual/en/latest/api.html): +For more advanced usage, the API is highly configurable, and can easily integrate with any pipeline. This includes using different detection algorithms, splitting the input video, and much more. The following example shows how to implement a function similar to the above, but using [the `scenedetect` API](https://www.scenedetect.com/docs/latest/api.html): ```python from scenedetect import open_video, SceneManager, split_video_ffmpeg from scenedetect.detectors import ContentDetector from scenedetect.video_splitter import split_video_ffmpeg + def split_video_into_scenes(video_path, threshold=27.0): # Open our video, create a scene manager, and add a detector. video = open_video(video_path) scene_manager = SceneManager() - scene_manager.add_detector( - ContentDetector(threshold=threshold)) + scene_manager.add_detector(ContentDetector(threshold=threshold)) scene_manager.detect_scenes(video, show_progress=True) scene_list = scene_manager.get_scene_list() split_video_ffmpeg(video_path, scene_list, show_progress=True) ``` -See [the manual](https://scenedetect.com/projects/Manual/en/latest/api.html) for the -full PySceneDetect API documentation. +See [the documentation](https://www.scenedetect.com/docs/latest/api.html) for more examples. ----------------------------------------------------------- +**Benchmark**: -PySceneDetect is a command-line tool and Python library, which uses OpenCV to analyze a video to find each shot change (or "cut"/"scene"). If `ffmpeg` or `mkvmerge` is installed, the video can also be split into scenes automatically. A frame-by-frame analysis can also be generated for a video, to help with determining optimal threshold values or detecting patterns/other analysis methods for a particular video. See [the Usage documentation](https://scenedetect.com/en/latest/examples/usage/) for details. +We evaluate the performance of different detectors in terms of accuracy and processing speed. See [www.scenedetect.com/benchmarks](https://www.scenedetect.com/benchmarks/) for results, or the [benchmark report](benchmark/README.md) for details on the datasets and methodology. -There are two main detection methods PySceneDetect uses: `detect-threshold` (comparing each frame to a set black level, useful for detecting cuts and fades to/from black), and `detect-adaptive` (compares each frame sequentially looking for changes in content, useful for detecting fast cuts between video scenes, although slower to process). Each mode has slightly different parameters, and is described in detail below. +## Reference -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` / `--statsfile` flag) in order to determine the correct paramters - specifically, the proper threshold value. + - [Documentation](https://www.scenedetect.com/docs/) (covers application and Python API) + - [CLI Example](https://www.scenedetect.com/cli/) + - [Config File](https://www.scenedetect.com/docs/latest/cli/config_file.html) -For help or other issues, you can join [the official PySceneDetect Discord Server](https://discord.gg/H83HbJngk7), submit an issue/bug report [here on Github](https://github.com/Breakthrough/PySceneDetect/issues), or contact me via [my website](http://www.bcastell.com/about/). +## Help & Contributing +Please submit any bugs/issues or feature requests to [the Issue Tracker](https://github.com/Breakthrough/PySceneDetect/issues). Before submission, ensure you search through existing issues (both open and closed) to avoid creating duplicate entries. +Pull requests are welcome and encouraged. PySceneDetect is released under the BSD 3-Clause license, and submitted code should be compliant. -## Usage - - - [Basic Usage](https://scenedetect.com/en/latest/examples/usage/) - - [PySceneDetect Manual](https://manual.scenedetect.com/), covers `scenedetect` command and Python API - - [Example: Detecting and Splitting Scenes in Movie Clip](https://scenedetect.com/en/latest/examples/usage-example/) - - -## Features & Roadmap - -You can [view the latest features and version roadmap on Readthedocs](http://pyscenedetect.readthedocs.org/en/latest/features/). -See [`docs/changelog.md`](https://github.com/Breakthrough/PySceneDetect/blob/master/docs/changelog.md) for a list of changes in each version, or visit [the Releases page](https://github.com/Breakthrough/PySceneDetect/releases) to download a specific version. Feel free to submit any bugs/issues or feature requests to [the Issue Tracker](https://github.com/Breakthrough/PySceneDetect/issues). - -Additional features being planned or in development can be found [here (tagged as `feature`) in the issue tracker](https://github.com/Breakthrough/PySceneDetect/issues?q=is%3Aissue+is%3Aopen+label%3Afeature). You can also find additional information about PySceneDetect at [http://www.bcastell.com/projects/PySceneDetect/](http://www.bcastell.com/projects/PySceneDetect/). - +For help or other issues, you can join [the official PySceneDetect Discord Server](https://discord.gg/H83HbJngk7), submit an issue/bug report [here on Github](https://github.com/Breakthrough/PySceneDetect/issues), or contact me via [my website](https://bcastell.com/about/). ## Code Signing This program uses free code signing provided by [SignPath.io](https://signpath.io?utm_source=foundation&utm_medium=github&utm_campaign=PySceneDetect), and a free code signing certificate by the [SignPath Foundation](https://signpath.org?utm_source=foundation&utm_medium=github&utm_campaign=PySceneDetect) - ## License -Licensed under BSD 3-Clause (see the `LICENSE` file for details). +BSD-3-Clause; see [`LICENSE`](LICENSE) and [`THIRD-PARTY.md`](THIRD-PARTY.md) for details. + +---------------------------------------------------------- -Copyright (C) 2014-2022 Brandon Castellano. +Copyright (C) 2014 Brandon Castellano. All rights reserved. diff --git a/RELEASE-PLAN.md b/RELEASE-PLAN.md new file mode 100644 index 00000000..bcd86ce7 --- /dev/null +++ b/RELEASE-PLAN.md @@ -0,0 +1,73 @@ +# PySceneDetect Release Checklist + +Use one copy per release, copy into a pull request and check each box as steps are completed. +Optional: version referenced below as `X.Y[.Z]` - replace with the real version throughout. + +## 1. Version Identifiers, Branch Prep + +- [ ] Create release branch `releases/X.Y[.Z]` off `main` (each release, including patches, gets its own branch - e.g. `releases/0.6.7`, `releases/0.7.1`); fast-forward it to `main` as release work lands. +- [ ] Bump `__version__` in `scenedetect/__init__.py` +- [ ] Bump `docs/LATEST_VERSION` for any stable release: it must match the `releases/X.Y[.Z]` branch suffix for `generate-docs.yml` to update `docs/latest` +- [ ] Regular release: No `-dev` suffix or other, pre-release: has suffix `-dev0`, `-dev1`, ... + +## 2. Documentation, Website, Changelog + +- [ ] Docstrings / API docs reflect any signature changes (`cd docs/ && make html` builds clean). +- [ ] `docs/api/migration_guide.rst` updated if any public API changed. +- [ ] Docstring examples all run correctly, nothing references removed or deprecated symbols. +- [ ] Changelog has release notes for major/minor release, all features, breaking changes, bug fixes, and known issues are documented. +- [ ] `website/pages/download.md` updated with the new version / installer link / release date. +- [ ] `website/pages/changelog.md`: move the release changes from the **Development** section at the bottom to the top. +- [ ] `website/pages/index.md`: Latest release version and date updated. + +## 3. Tests + +- [ ] Static analysis passing (ruff + pyright). +- [ ] Unit tests green locally and in CI: `pytest -vv` (should collect `-m 'not release'` by default). +- [ ] Release test suite green: manually trigger or make a release candidate tag, all 4 jobs (`static`, `release-tests`, `install-matrix`, `long-stress`) green across the OS and Python version matrix. +- [ ] `pip-audit` clean (or exceptions documented in the changelog). + +## 4. Prepare Windows Distribution + +- [ ] Update `packaging/windows/requirements.txt` and bump bundled ffmpeg version in `appveyor.yml` +- [ ] Run AppVeyor build on release branch, ensure resulting portable distribution and MSI installer are correct + +> **GUI required for structural changes.** `scripts/update_installer.py` covers routine version bumps and `--sync-files` covers dependency-driven file-list changes, but anything that touches the *project structure* of the .aip still needs the AdvancedInstaller GUI. Examples: +> +> - Moving the .aip or its source tree (the build's `SourcePath` references are stored relative to the .aip and aren't rewritten by `/NewSync`. +> - Adding/removing build configurations, features, or prerequisites. +> - Install directory layout (`APPDIR` location), or per-component attributes. +> - Editing dialog layouts, branding bitmaps, install sequences, custom actions, file associations, or shortcuts. + +## 5. Tag & Draft Release + +- [ ] Final commit on `releases/X.Y[.Z]`: "Release vX.Y[.Z]". +- [ ] Tag `vX.Y[.Z]` on that commit and push (the legacy `vX.Y[.Z]-release` form is also accepted by all workflows). Wait for all tests/builds to pass. +- [ ] Approve code signing request on SignPath, download `scenedetect-signed.zip` +- [ ] Finalize Windows artifacts locally (CI can't do this - signing happens after the AppVeyor build, so the post-signing steps must run locally): + - Create `dist/signed/` and drop `scenedetect-signed.zip` (from SignPath) into it. No other inputs needed - the portable .zip is rebuilt from the signed .msi via `msiexec /a`, eliminating the AppVeyor download. + - Run `python scripts/finalize_windows_dist.py`. This extracts the signed `.msi` from the bundle, runs `msiexec /a` to recover the installed file tree, repacks it as the portable `.zip` with 7-Zip, writes `PySceneDetect-X.Y.Z-win64.manifest.json` + `SHA256SUMS`, and then runs `scripts/validate_release.py` to verify filenames, hashes, Authenticode signatures, MSI/zip parity, and frozen `.exe` smoke tests. +- [ ] Draft release on Github using the tagged commit: include full changelog & release notes, signed portable .ZIP, signed .MSI installer, Python .whl/.tar.gz packages, and checksum manifests (`PySceneDetect-X.Y.Z-win64.manifest.json` + `SHA256SUMS`) +- [ ] Verify all artifacts uploaded to Github release are valid and named correctly +- [ ] Smoke-test all release artifacts + +## 6. Publish & Release Checks + +- [ ] Dispatch `release.yml` (Release Orchestrator) with the release tag while the Github release is still a **draft**. It runs the verify-then-publish ladder (MSI install/upgrade test -> TestPyPI -> publish Github release -> PyPI -> Docker), verifying each stage before the next; `verify-only` stops before anything goes public. See the header of `release.yml` for details. +- [ ] Verify both projects: https://pypi.org/project/scenedetect/ and https://pypi.org/project/scenedetect-headless/. +- [ ] Deploy website: `generate-website.yml` +- [ ] Deploy docs: `generate-docs.yml` +- [ ] Merge release branch back into `main`, verify `docs/LATEST_VERSION` is correct +- [ ] [Manually dispatch `generate-docs.yml`](https://github.com/Breakthrough/PySceneDetect/actions/workflows/generate-docs.yml) against `releases/X.Y` to update www.scenedetect.com/docs/latest +- [ ] Smoke-test PyPI release: in a fresh venv, `pip install scenedetect==X.Y.Z`; CLI launches and `scenedetect --version` looks correct. +- [ ] Verify download links on website are correct, PyPI project page is up to date and correct. +- [ ] Clear / archive release-scoped tracking files (`tracking.md`, any release-specific TODOs). +- [ ] Announce: project site, relevant issues / discussions closed and linked to the release. + +--- + +## Notes + +- **Branching model**: work spans multiple commits on `releases/X.Y[.Z]`; the final one gets the `vX.Y[.Z]` tag which gates the release-test workflow. A passing release-test is a hard prerequisite for publishing. +- **Version consistency** is enforced in two places (`__init__.py`, `PySceneDetect.aip`). The `static` job of `release-test.yml` checks `__init__.py` against the tag and verifies the changelog has a matching `## PySceneDetect X.Y` heading; the installer parity is checked by `scripts/pre_release.py --release`. +- **Changelog convention**: the in-development section lives at the *bottom* of `website/pages/changelog.md` under the "Development" heading - don't move it to the top. diff --git a/THIRD-PARTY.md b/THIRD-PARTY.md new file mode 100644 index 00000000..959c2e4f --- /dev/null +++ b/THIRD-PARTY.md @@ -0,0 +1,75 @@ +# Ancillary Software Licenses + +This file includes license information for various open-source projects +that are imported, derived into, or distributed with PySceneDetect. +See [LICENSE](LICENSE) for the main PySceneDetect license. + +Depending on the features being used, PySceneDetect uses the following +third-party software which are released under the terms detailed below. +By downloading, copying, installing or using this software, you agree +to these terms. + +In no particular order: + +----------------------------------------------------------------------- + +> click [Copyright (C) 2017, Armin Ronacher]: + This software uses OpenCV; see thirdparty/LICENSE-CLICK or visit: + [ http://click.pocoo.org/license/ ] + +> NumPy [Copyright (C) 2005-2016, Numpy Developers]: + This software uses Numpy; see thirdparty/LICENSE-NUMPY or visit: + [ http://www.numpy.org/license.html ] + +> OpenCV [Copyright (C) 2017, Itseez]: + This software uses OpenCV; see thirdparty/LICENSE-OPENCV or visit: + [ http://opencv.org/license.html ] + +> PyAV [Copyright (C) 2017, Mike Boers and others]: + This software uses PyAV; see thirdparty/LICENSE-PYAV or visit: + [ https://github.com/PyAV-Org/PyAV/blob/main/LICENSE.txt ] + +> pytest [Copyright (C) 2004-2017, Holger Krekel and others]: + This software uses pytest; see thirdparty/LICENSE-PYTEST or visit: + [ https://docs.pytest.org/en/latest/license.html ] + +> simpletable [Copyright (C) 2014-2019, Matheus Vieira Portela and others]: + This software uses simpletable; see thirdparty/LICENSE-SIMPLETABLE or visit: + [ https://github.com/matheusportela/simpletable/blob/master/LICENSE ] + +> tqdm [Copyright (C) 2013-2018, Casper da Costa-Luis, + Google Inc., and Noam Yorav-Raphael]: + This software uses tqdm; see thirdparty/LICENSE-TQDM or visit: + [ https://github.com/tqdm/tqdm/blob/master/LICENCE ] + +> MoviePy [ Copyright (C) 2015 Zulko ] + This software uses tqdm; see thirdparty/LICENSE-TQDM or visit: + [ https://github.com/Zulko/moviepy/blob/master/LICENCE.txt ] + +----------------------------------------------------------------------- + +This software may also invoke FFmpeg or mkvmerge, if available. If required, +these programs can be obtained from following URLs: + + FFmpeg: [ https://ffmpeg.org/download.html ] + mkvmerge: [ https://mkvtoolnix.download/downloads.html ] + +Once installed, ensure the program is in your PATH variable (i.e. you can +run the `ffmpeg` or `mkvmerge` command from any location). + +Certain distributions of PySceneDetect may include ffmpeg. See +thirdparty/LICENSE-FFMPEG file or visit [ https://ffmpeg.org ] + +FFmpeg is a trademark of Fabrice Bellard +mkvmerge is Copyright (C) 2005-2016, Matroska + +Windows distributions may include a compiled Python distribution. For license +information regarding the distributed version of Python, see the +thirdparty/LICENSE-PYTHON file, or visit [ https://docs.python.org/3/license.html ] + +----------------------------------------------------------------------- + +If any information above is incorrect, please let us know. +Visit [ https://www.scenedetect.com ] for contact information. + + diff --git a/appveyor.yml b/appveyor.yml index 6e3b4dd3..0ffafc7c 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,81 +1,156 @@ +# Build signed releases for PySceneDetect Windows x64 -skip_commits: - files: - - docs/* - - 'manual/*' - - '**/*.rst' - - '**/*.md' - - -# We have to disable the `build` command explicitly otherwise the default is -# MSBuild which assumes this is a Visual Studio project. Python source/binary -# wheels a Windows .exe are generated below in `install`. build: false +cache: + # FFmpeg self-invalidates via %ffmpeg_version% in the filename; AdvInst MSI and + # Inkscape rarely need refresh and have `if not exist` install guards, so we + # don't tie them to appveyor.yml (any edit there would force a cold-cache + # reinstall of all three and blow past the 10-minute build limit). + - 'ffmpeg-%ffmpeg_version%-full_build.7z' + - 'packaging\windows\installer\advinst.msi' + - '%LOCALAPPDATA%\uv\cache -> pyproject.toml' + - 'C:\Program Files\Inkscape' + +# Branches applies to tags as well. We only build on tagged releases of the form +# vX.Y[.Z] (the legacy -release suffix is also accepted, matching the GitHub workflows). +branches: + only: + - main + - /releases\/.+/ + - /v.+/ + +skip_tags: false +skip_non_tags: true environment: matrix: - - PYTHON: "C:\\Python37-x64" - - PYTHON: "C:\\Python38-x64" - - PYTHON: "C:\\Python39-x64" - - PYTHON: "C:\\Python310-x64" - + - PYTHON: "C:\\Python313-x64" + # Encrypted AdvancedInstaller License + ai_license_secret: + secure: QRCPoNYF1nqgXDn7pHgBzg== + ai_license_salt: + secure: +Gy+SRk8JUsaM+5pMEKITiJxdLilrxHpkKlrZzR3C9DPwdgYLGxt5sJn6uXuAJg7e6JsKHcT7tRks/HcSKkHPw== + ffmpeg_version: "8.1.2" + +# SignPath Config for Code Signing +deploy: +- provider: Webhook + url: https://app.signpath.io/API/v1/f2efa44c-5b5c-45f2-b44f-8f9dde708313/Integrations/AppVeyor?ProjectSlug=PySceneDetect&SigningPolicySlug=release-signing + authorization: + secure: FBgWCaxCCKOqc2spYf5NGWSNUGLbT5WeuC5U0k4Of1Ids9n51YWxhGlMyzLbdNBFe64RUcOSzk/N3emlQzbsJg== + on: + APPVEYOR_REPO_TAG: true # keep casing this way for Linux builds where variables are case-sensitive install: - # Setup Python environment and update basic packages. + - echo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + - echo * * SETTING UP PYTHON ENVIRONMENT * * + - echo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - 'SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%' - python --version - - python -m pip install --upgrade pip build wheel virtualenv setuptools - - # Make sure we get latest binary packages of the video input libraries. - - python -m pip install av==9.2 opencv-python-headless --only-binary ":all:" + - python -m pip install uv + - uv pip install --system .[docs] + - uv pip install --system -r packaging/windows/requirements.txt --no-binary imageio-ffmpeg + # TODO(https://github.com/Zulko/moviepy/issues/2553): moviepy caps pillow<12.0, but 11.x has + # CVEs only fixed in 12.3.0+. Installed as a separate step since a pin in requirements.txt + # would fail strict resolution against moviepy's constraint. Tests pass against 12.3.0; + # drop this once moviepy lifts the cap. + - uv pip install --system pillow==12.3.0 + - if not exist ffmpeg-%ffmpeg_version%-full_build.7z appveyor DownloadFile https://github.com/GyanD/codexffmpeg/releases/download/%ffmpeg_version%/ffmpeg-%ffmpeg_version%-full_build.7z + - 7z e ffmpeg-%ffmpeg_version%-full_build.7z -odist/ffmpeg ffmpeg.exe LICENSE -r + # moviepy.config reads FFMPEG_BINARY (which routes through imageio_ffmpeg) at import time. + # `--no-binary imageio-ffmpeg` strips the bundled ffmpeg, so point it at the GyanD copy + # we just extracted; otherwise pre_release.py and pyinstaller analysis crash on + # `import scenedetect`. The runtime hook (pyi_rth_scenedetect.py) does the same at exe runtime. + - 'SET IMAGEIO_FFMPEG_EXE=%APPVEYOR_BUILD_FOLDER%\\dist\\ffmpeg\\ffmpeg.exe' + # Inkscape is required by scripts/pre_release.py --release (regenerates installer JPGs + # from the master SVG). Not preinstalled on the AppVeyor VS2019 image; cached + # in `C:\Program Files\Inkscape` (see cache: section) so we only re-install when + # the cache is busted (appveyor.yml changes). + - if not exist "C:\Program Files\Inkscape\bin\inkscape.exe" choco install inkscape -y --no-progress + - 'SET PATH=%PATH%;C:\Program Files\Inkscape\bin' + + - echo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + - echo * * BUILDING WINDOWS EXE * * + - echo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + # Build Windows .EXE and create portable .ZIP. The staging script copies + # ffmpeg.exe + LICENSE from --ffmpeg-dir, third-party licenses, the project + # LICENSE/README, and sphinx docs into dist/scenedetect/, then emits the + # portable .zip - keeps CI and local builds in sync (see scripts/stage_windows_dist.py). + - python scripts/pre_release.py --release + - pyinstaller packaging/windows/scenedetect.spec + - python scripts/stage_windows_dist.py --ffmpeg-dir dist/ffmpeg + + - echo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + - echo * * BUILDING MSI INSTALLER * * + - echo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + # Download, install, and register AdvancedInstaller + - cd packaging/windows/installer + - ps: iex ((New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/appveyor/secure-file/master/install.ps1')) + - appveyor-tools\secure-file -decrypt license65.dat.enc -secret %ai_license_secret% -salt %ai_license_salt% + - if not exist advinst.msi appveyor DownloadFile https://www.advancedinstaller.com/downloads/advinst.msi + - msiexec /i advinst.msi /qn + # Resolve the installed Advanced Installer bin path dynamically - the upstream + # MSI is unversioned so the directory name (Advanced Installer X.Y.Z) drifts. + - ps: $aiBin = (Get-ChildItem 'C:\Program Files (x86)\Caphyon\Advanced Installer*\bin\x86' | Sort-Object FullName -Descending | Select-Object -First 1).FullName; Add-Content $env:APPVEYOR_BUILD_FOLDER\ai_path.txt $aiBin + - set /p AI_BIN=<%APPVEYOR_BUILD_FOLDER%\ai_path.txt + - 'SET PATH=%PATH%;%AI_BIN%' + # License path must be absolute + - AdvancedInstaller.com /RegisterOffline "%cd%\license65.dat" + - cd ../../.. + # Re-sync APPDIR from CI's dist/scenedetect (handles drift between local and + # CI pyinstaller output - new transitive deps, Python patch updates, etc.). + # Does not touch version/GUID fields - those are committed to the .aip on the + # release tag and must stay stable across rebuilds for upgrade-chain integrity. + # On non-tag builds, also pass --dev so the MSI is named PySceneDetect-{ver}-dev-win64.msi + # (keeps dev artifacts distinguishable from signed releases). + - if "%APPVEYOR_REPO_TAG%"=="true" (python scripts/update_installer.py --sync-only) else (python scripts/update_installer.py --sync-only --dev) + # Snapshot the post-sync .aip and the actual payload tree as build artifacts. + # The committed .aip is a baseline; CI adapts it to its own pyinstaller output + # and we never write back to git, so these snapshots are the authoritative + # record of what each MSI was built from (for audit / release forensics). + - copy packaging\windows\installer\PySceneDetect.aip dist\PySceneDetect.aip + # Create MSI installer + - AdvancedInstaller.com /build packaging/windows/installer/PySceneDetect.aip + + - echo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + - echo * * PACKAGING BUILD ARTIFACTS * * + - echo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + # Zip all resources together for code signing + - move packaging\windows\installer\PySceneDetect-*.msi dist\ + - cd dist + - cp scenedetect\scenedetect.exe . + - 7z a scenedetect-signed.zip scenedetect.exe PySceneDetect-*.msi + - cd .. - # Install other PySceneDetect dependencies and checkout resources required for tests. - - python -m pip install -r requirements_headless.txt - - python -m pip install moviepy +test_script: + - echo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + - echo * * TESTING BUILD * * + - echo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + # Checkout required test resources - git fetch --depth=1 https://github.com/Breakthrough/PySceneDetect.git refs/heads/resources:refs/remotes/origin/resources - git checkout refs/remotes/origin/resources -- tests/resources/ - - git checkout refs/remotes/origin/resources -- dist/ - - # Build Python package - - python -m build - - -test_script: - # Checkout Windows dependencies and extract them. - - git checkout refs/remotes/origin/resources -- dist/ - - git checkout refs/remotes/origin/build-windows -- dist/ - - 7z e dist/windows_thirdparty.7z - - # Run Unit Tests - - python -m pytest tests/ - - # Remove optional dependencies before performing CLI tests - - python -m pip uninstall -y av - - # - # Test CLI using source code - # - # Test with OpenCV backend - - python -m scenedetect version - - python -m scenedetect -i tests/resources/testvideo.mp4 -b opencv detect-content time -e 2s - # Test with optional PyAV backend - - python -m pip install av==9.2 - - python -m scenedetect -i tests/resources/testvideo.mp4 -b pyav detect-content time -e 2s - # Cleanup - - python -m pip uninstall -y scenedetect av - - # TODO: Test Python Distributions install and function correctly. There's coverage for - # this on the Linux builds (.travis.yml), but should also do that here too. - # Wildcard expansion doesn't seem to work with pip here, e.g. the following fails: - #- python -m pip install dist\*.whl + - move dist\scenedetect\ffmpeg.exe ffmpeg.exe + # Run unit tests + # TODO: We are at the new build time limit for this plan apparently, 10 mins. Figure out a + # strategy to deal with that (see if we can use Github as a builder?). + # - pytest + # Test Windows build + - move ffmpeg.exe dist\scenedetect\ffmpeg.exe + - cd dist/scenedetect + - scenedetect.exe version + - scenedetect.exe -i ../../tests/resources/testvideo.mp4 -b opencv detect-content time -e 2s + - scenedetect.exe -i ../../tests/resources/testvideo.mp4 -b pyav detect-content time -e 2s artifacts: - # TODO: Need to incorporate the build number into the package version. Use a custom setup.py - # that modifies the version number in the package before building using an environment variable. - - - path: dist/*.tar.gz - name: PySceneDetect-sdist - - - path: dist/*.whl - name: PySceneDetect-bdist_wheel + # Portable ZIP (named PySceneDetect-X.Y.Z-win64.zip by stage_windows_dist.py) + - path: dist/PySceneDetect-*-win64.zip + name: PySceneDetect-win64 + # MSI Installer + .EXE Bundle for Signing + - path: dist/scenedetect-signed.zip + name: PySceneDetect-win64_installer + # Build provenance: post-sync .aip and the portable payload manifest. + - path: dist/PySceneDetect.aip + name: PySceneDetect-build-manifest-aip + - path: dist/PySceneDetect-*.manifest.txt + name: PySceneDetect-build-manifest-payload diff --git a/benchmark/AutoShot/.gitkeep b/benchmark/AutoShot/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/benchmark/BBC/.gitkeep b/benchmark/BBC/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/benchmark/README.md b/benchmark/README.md new file mode 100644 index 00000000..180b0d77 --- /dev/null +++ b/benchmark/README.md @@ -0,0 +1,194 @@ +# Benchmarking PySceneDetect + +This page contains the results of benchmarking PySceneDetect's detection accuracy againts public +shot-boundary-detection datasets. Scoring follows the [TRECVID-SBD][trecvid] convention +(greedy 1-to-1 nearest-neighbor matching, with a configurable frame tolerance for hard cuts; +point-in-interval matching for fade transitions; mean absolute frame offset on matched events) +so numbers are comparable to published SBD results. + +[trecvid]: https://www-nlpir.nist.gov/projects/tv2007/pastdata/shot_boundary.07.html + +Supported datasets: + +- [BBC Planet Earth](https://zenodo.org/records/14865504): + 11 long-form broadcast clips; hard cuts only +- [AutoShot](https://drive.google.com/file/d/17diRkLlNUUjHDooXdqFUTXYje2-x4Yt6/view?usp=sharing): + Short-form web clips; hard cuts only +- [ClipShots](https://github.com/Tangshitao/ClipShots): + Short-form web clips; hard cuts and typed gradual transitions (fades/dissolves) + +## Usage + +```bash +# Single detector x single dataset: +python -m benchmark --detector detect-content --dataset BBC +``` + +Pass `--help` for `--dataset-root`, `--backend`, `--tolerance`, and `--out` options. + +### Parameter sweeps + +`python -m benchmark.sweep` runs a grid over detector parameters and reports the +top cells by F1 plus the Pareto front across tolerances. One decode is shared by up to +`--workers` parallel detectors via an internal fan-out wrapper, so the cost scales with +`ceil(cells / workers)` decodes per video rather than `cells` decodes. + +```bash +python -m benchmark.sweep \ + --detector detect-content --dataset BBC \ + --params "threshold=15:35:1;min_scene_len=0.0:1.0:0.1" \ + --tolerance 0,1 --workers 16 \ + --out sweep-content-bbc.json +``` + +`--params`: assignments joined by `;`. Each is either `key=v1,v2,v3` (enumerated values) or +`key=start:stop:step` (numeric range, inclusive when `stop` lands on a step). Omitted keys +use the detector's default. + +Time-valued kwargs (`min_scene_len`, etc.) accept `TimecodeLike` - integers are +frames, floats are seconds, and strings like `"0.1s"` / `"00:00:00.500"` also work. +Prefer floats so the same sweep is comparable across datasets with different +framerates. Use `--quick N` to limit to the first N samples for iteration; published +numbers should always come from the full corpus. + +## Dataset Download + +### BBC + +```bash +# annotations +wget -O BBC/fixed.zip https://zenodo.org/records/14873790/files/fixed.zip +unzip BBC/fixed.zip -d BBC +rm -rf BBC/fixed.zip + +# videos +wget -O BBC/videos.zip https://zenodo.org/records/14873790/files/videos.zip +unzip BBC/videos.zip -d BBC +rm -rf BBC/videos.zip +``` + +### AutoShot + +Download `AutoShot_test.tar.gz` from +[Google Drive](https://drive.google.com/file/d/17diRkLlNUUjHDooXdqFUTXYje2-x4Yt6/view?usp=sharing). + +```bash +tar -zxvf AutoShot_test.tar.gz +rm AutoShot_test.tar.gz +``` + +### ClipShots + +ClipShots is gated behind a dataset request form; direct `wget`-style download links are not +published. See [the download instructions](https://github.com/Tangshitao/ClipShots#downloads) to +obtain the annotations and videos. The expected on-disk layout is: + +``` +ClipShots/ + annotations/{train,test,only_gradual}.json + video_lists/{train,test,only_gradual}.txt + videos/*.mp4 +``` + +The loader defaults to the test split (500 videos). The full corpus is ~46 GB. + +Set `--dataset-root /path/to/datasets` to override. The default dataset location assumes they are +all placed in the benchmark folder (e.g. `benchmark/BBC`, `benchmark/AutoShot`, `benchmark/ClipShots`). + +## Results (defaults) + +Generated by `scripts/benchmark_defaults.sh` at `tolerance=0` (frame-exact matching). +Elapsed is mean wall-clock seconds per video. + +#### BBC + +| Detector | Recall | Precision | F1 | Mean s/video | +|:-----------------:|:------:|:---------:|:-----:|:------------:| +| AdaptiveDetector | 87.12 | 96.55 | 91.59 | 36.12 | +| ContentDetector | 84.70 | 88.77 | 86.69 | 37.02 | +| HashDetector | 92.30 | 75.56 | 83.10 | 25.51 | +| HistogramDetector | 89.84 | 72.03 | 79.96 | 22.29 | +| ThresholdDetector | 0.06 | 0.70 | 0.11 | 16.05 | + +#### AutoShot + +| Detector | Recall | Precision | F1 | Mean s/video | +|:-----------------:|:------:|:---------:|:-----:|:------------:| +| AdaptiveDetector | 70.59 | 77.46 | 73.86 | 3.52 | +| ContentDetector | 63.49 | 76.19 | 69.26 | 4.80 | +| HashDetector | 56.48 | 76.11 | 64.84 | 4.14 | +| HistogramDetector | 63.27 | 53.23 | 57.82 | 3.76 | +| ThresholdDetector | 0.75 | 38.64 | 1.47 | 3.28 | + +#### ClipShots (hard cuts) + +| Detector | Recall | Precision | F1 | Mean s/video | +|:-----------------:|:------:|:---------:|:-----:|:------------:| +| AdaptiveDetector | 85.97 | 41.25 | 55.75 | 1.81 | +| ContentDetector | 81.93 | 42.36 | 55.84 | 2.52 | +| HashDetector | 81.34 | 30.14 | 43.98 | 1.04 | +| HistogramDetector | 72.20 | 11.47 | 19.80 | 0.71 | +| ThresholdDetector | 0.08 | 0.58 | 0.14 | 0.64 | + +#### ClipShots (fades) + +| Detector | Recall | Precision | F1 | +|:-----------------:|:------:|:---------:|:-----:| +| AdaptiveDetector | 13.65 | 98.12 | 23.96 | +| ContentDetector | 26.03 | 98.04 | 41.14 | +| HashDetector | 18.77 | 94.53 | 31.33 | +| HistogramDetector | 69.67 | 81.99 | 75.33 | +| ThresholdDetector | 5.69 | 99.24 | 10.77 | + +## Parameter sweep results + +The tables above use each detector's v0.7 defaults. A grid sweep over the key parameters +scored by hard-cut F1 at 1-frame tolerance, averaged across BBC / AutoShot / ClipShots gives the +best single parameter set for this corpus mix: + +| Detector | Best mean F1 | Best params | v0.7 default | +|:-----------------:|:------------:|:-----------------------------------------------------------|:---------------------------------------| +| ContentDetector | 73.4 | threshold=31, min_scene_len=0.6s | threshold=27 | +| AdaptiveDetector | 76.3 | adaptive_threshold=3.5, window_width=3, min_scene_len=0.6s | adaptive_threshold=3.0, window_width=2 | +| HashDetector | 69.8 | threshold=0.35, size=8 | threshold=0.395, size=16 | +| HistogramDetector | 66.3 | threshold=0.20, bins=128 | threshold=0.05, bins=256 | +| ThresholdDetector | -- | detects fades, not hard cuts (validation only) | threshold=12 | + +Full per-dataset breakdowns are in [`SWEEP_REPORT.md`](SWEEP_REPORT.md), and can be generated +with `python -m benchmark.report_sweep`. The full grids (all detectors and datasets) are driven +by `scripts/benchmark_sweep.sh`. + +## Citations + +### BBC + +``` +@InProceedings{bbc_dataset, + author = {Lorenzo Baraldi and Costantino Grana and Rita Cucchiara}, + title = {A Deep Siamese Network for Scene Detection in Broadcast Videos}, + booktitle = {Proceedings of the 23rd ACM International Conference on Multimedia}, + year = {2015}, +} +``` + +### AutoShot + +``` +@InProceedings{autoshot_dataset, + author = {Wentao Zhu and Yufang Huang and Xiufeng Xie and Wenxian Liu and Jincan Deng and Debing Zhang and Zhangyang Wang and Ji Liu}, + title = {AutoShot: A Short Video Dataset and State-of-the-Art Shot Boundary Detection}, + booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) Workshops}, + year = {2023}, +} +``` + +### ClipShots + +``` +@InProceedings{clipshots_dataset, + author = {Shitao Tang and Litong Feng and Zhanghui Kuang and Yimin Chen and Wei Zhang}, + title = {Fast Video Shot Transition Localization with Deep Structured Models}, + booktitle = {Asian Conference on Computer Vision (ACCV)}, + year = {2018}, +} +``` diff --git a/benchmark/SWEEP_REPORT.md b/benchmark/SWEEP_REPORT.md new file mode 100644 index 00000000..f368072a --- /dev/null +++ b/benchmark/SWEEP_REPORT.md @@ -0,0 +1,107 @@ +# Detector parameter sweep report + +Generated by `benchmark/report_sweep.py` from `benchmark/sweep.py` grid results (hash/hist were swept with `min_scene_len` fixed at its default). F1/precision/recall are percentages on hard cuts; tol = frame tolerance. + +## detect-content + +**Best cell per dataset (by F1@1):** + +| Dataset | F1@1 | Prec@1 | Rec@1 | F1@0 | Params | +| --------- | ----- | ------ | ----- | ----- | ------------------------------- | +| BBC | 88.34 | 90.00 | 86.75 | 87.35 | min_scene_len=0.8, threshold=25 | +| AutoShot | 73.44 | 79.54 | 68.21 | 70.54 | min_scene_len=0.4, threshold=29 | +| ClipShots | 66.74 | 58.93 | 76.95 | 66.44 | min_scene_len=0.8, threshold=35 | + +**Best params averaged across all datasets (mean F1@1):** + +| Mean F1@1 | BBC | AutoShot | ClipShots | Params | +| --------- | ----- | -------- | --------- | ------------------------------- | +| 73.39 | 85.95 | 71.51 | 62.73 | min_scene_len=0.6, threshold=31 | +| 73.37 | 84.27 | 70.95 | 64.89 | min_scene_len=0.6, threshold=33 | +| 73.32 | 83.99 | 72.43 | 63.54 | min_scene_len=0.4, threshold=33 | +| 73.15 | 87.28 | 72.05 | 60.13 | min_scene_len=0.6, threshold=29 | +| 73.09 | 85.18 | 72.97 | 61.10 | min_scene_len=0.4, threshold=31 | + +## detect-adaptive + +**Best cell per dataset (by F1@1):** + +| Dataset | F1@1 | Prec@1 | Rec@1 | F1@0 | Params | +| --------- | ----- | ------ | ----- | ----- | --------------------------------------------------------- | +| BBC | 94.57 | 94.89 | 94.26 | 93.50 | adaptive_threshold=2, min_scene_len=0.6, window_width=2 | +| AutoShot | 77.19 | 80.48 | 74.16 | 75.45 | adaptive_threshold=3.5, min_scene_len=0.4, window_width=3 | +| ClipShots | 65.53 | 60.19 | 71.89 | 65.47 | adaptive_threshold=5.5, min_scene_len=0.6, window_width=3 | + +**Best params averaged across all datasets (mean F1@1):** + +| Mean F1@1 | BBC | AutoShot | ClipShots | Params | +| --------- | ----- | -------- | --------- | --------------------------------------------------------- | +| 76.34 | 90.41 | 76.27 | 62.32 | adaptive_threshold=3.5, min_scene_len=0.6, window_width=3 | +| 76.21 | 87.87 | 76.17 | 64.58 | adaptive_threshold=4, min_scene_len=0.6, window_width=3 | +| 76.18 | 90.43 | 77.19 | 60.93 | adaptive_threshold=3.5, min_scene_len=0.4, window_width=3 | +| 76.16 | 87.91 | 77.07 | 63.51 | adaptive_threshold=4, min_scene_len=0.4, window_width=3 | +| 75.45 | 85.28 | 75.71 | 65.37 | adaptive_threshold=4.5, min_scene_len=0.6, window_width=3 | + +## detect-hash + +**Best cell per dataset (by F1@1):** + +| Dataset | F1@1 | Prec@1 | Rec@1 | F1@0 | Params | +| --------- | ----- | ------ | ----- | ----- | ------------------------ | +| BBC | 86.91 | 81.59 | 92.96 | 85.81 | size=16, threshold=0.425 | +| AutoShot | 70.17 | 76.06 | 65.12 | 66.89 | size=8, threshold=0.325 | +| ClipShots | 56.38 | 44.46 | 77.03 | 55.66 | size=8, threshold=0.4 | + +**Best params averaged across all datasets (mean F1@1):** + +| Mean F1@1 | BBC | AutoShot | ClipShots | Params | +| --------- | ----- | -------- | --------- | ----------------------- | +| 69.83 | 86.38 | 68.98 | 54.12 | size=8, threshold=0.35 | +| 69.63 | 86.65 | 65.86 | 56.38 | size=8, threshold=0.4 | +| 69.63 | 86.65 | 65.86 | 56.37 | size=8, threshold=0.375 | +| 68.18 | 84.28 | 70.17 | 50.10 | size=8, threshold=0.325 | +| 67.00 | 83.71 | 61.66 | 55.65 | size=8, threshold=0.425 | + +## detect-hist + +> Note: thresholds >= 0.21 come from a grid-extension run (`detect-hist-ext-.json`) after the initial grid's best cell landed on its 0.20 upper edge. + +**Best cell per dataset (by F1@1):** + +| Dataset | F1@1 | Prec@1 | Rec@1 | F1@0 | Params | +| --------- | ----- | ------ | ----- | ----- | ------------------------ | +| BBC | 86.58 | 87.32 | 85.86 | 85.42 | bins=128, threshold=0.11 | +| AutoShot | 68.99 | 75.29 | 63.67 | 65.70 | bins=128, threshold=0.2 | +| ClipShots | 53.25 | 46.26 | 62.74 | 52.90 | bins=128, threshold=0.35 | + +**Best params averaged across all datasets (mean F1@1):** + +| Mean F1@1 | BBC | AutoShot | ClipShots | Params | +| --------- | ----- | -------- | --------- | ------------------------ | +| 66.27 | 82.10 | 68.99 | 47.72 | bins=128, threshold=0.2 | +| 66.23 | 81.47 | 68.87 | 48.36 | bins=128, threshold=0.21 | +| 66.20 | 82.74 | 68.81 | 47.06 | bins=128, threshold=0.19 | +| 66.19 | 80.69 | 68.92 | 48.97 | bins=128, threshold=0.22 | +| 66.17 | 79.53 | 68.88 | 50.10 | bins=128, threshold=0.24 | + +## detect-threshold + +> Note: `detect-threshold` detects **fades** (fade to/from black), not hard cuts. These datasets' ground truth is hard cuts, so the hard-cut F1 below is expectedly near zero. It is included to validate the sweep pipeline end-to-end, not as a meaningful hard-cut accuracy result. + +**Best cell per dataset (by F1@1):** + +| Dataset | F1@1 | Prec@1 | Rec@1 | F1@0 | Params | +| --------- | ---- | ------ | ----- | ---- | ------------------------------- | +| BBC | 0.79 | 2.89 | 0.45 | 0.32 | min_scene_len=0.2, threshold=19 | +| AutoShot | 3.98 | 51.09 | 2.07 | 3.14 | min_scene_len=0.4, threshold=20 | +| ClipShots | 1.75 | 6.21 | 1.02 | 0.18 | min_scene_len=0, threshold=10 | + +**Best params averaged across all datasets (mean F1@1):** + +| Mean F1@1 | BBC | AutoShot | ClipShots | Params | +| --------- | ---- | -------- | --------- | ------------------------------- | +| 2.07 | 0.77 | 3.90 | 1.55 | min_scene_len=0, threshold=19 | +| 2.06 | 0.73 | 3.98 | 1.48 | min_scene_len=0, threshold=20 | +| 2.02 | 0.79 | 3.90 | 1.37 | min_scene_len=0.2, threshold=19 | +| 2.00 | 0.71 | 3.98 | 1.30 | min_scene_len=0.2, threshold=20 | +| 1.96 | 0.69 | 3.90 | 1.28 | min_scene_len=0.4, threshold=19 | diff --git a/benchmark/__main__.py b/benchmark/__main__.py new file mode 100644 index 00000000..2f4f9a3f --- /dev/null +++ b/benchmark/__main__.py @@ -0,0 +1,180 @@ +# +# 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. +# +"""Command-line entrypoint for the PySceneDetect benchmark harness. + +Runs one detector against a single dataset using default parameters, and calculates TRECVID-SBD +metrics using the given frame tolerance (usually 0 or 1). Hard-cut precision/recall/F1, mean +absolute frame offset on matches, and per-video elapsed wall-clock are calculated. If a dataset +advertises typed fade ground truth, a second table reports fade precision/recall/F1. +""" + +from __future__ import annotations + +import argparse +import time +from pathlib import Path + +from tqdm import tqdm + +from benchmark._common import ( + DEFAULT_BACKEND, + DETECTORS, + FADE_HEADER, + HARD_HEADER, + fade_row, + hard_row, + parse_tolerances, + render_table, + write_json, +) +from benchmark.dataset import DATASETS, Dataset, resolve_dataset +from benchmark.evaluator import BenchmarkResult, Prediction, evaluate +from scenedetect import AVAILABLE_BACKENDS, detect + + +def _run_predictions( + dataset: Dataset, + detector_name: str, + backend: str, +) -> dict[Path, Prediction]: + """Detect cuts for every video in ``dataset`` and return predictions keyed by path.""" + detector_cls = DETECTORS[detector_name] + predictions: dict[Path, Prediction] = {} + for sample in tqdm(dataset, desc=detector_name): + start = time.time() + pred_scene_list = detect(str(sample.video_file), detector_cls(), backend=backend) + elapsed = time.time() - start + predictions[sample.video_file] = Prediction( + predicted_cuts=[scene[1].frame_num for scene in pred_scene_list], + ground_truth=sample.ground_truth, + elapsed=elapsed, + ) + return predictions + + +def _print_results( + detector: str, + dataset_name: str, + dataset: Dataset, + results: list[BenchmarkResult], +) -> None: + print(f"\n## {detector} on {dataset_name} (hard cuts)\n") + print(render_table(HARD_HEADER, [hard_row(r) for r in results])) + if "fade" in dataset.event_types: + print(f"\n## {detector} on {dataset_name} (fades)\n") + print(render_table(FADE_HEADER, [fade_row(r) for r in results])) + + +# --------------------------------------------------------------------- # +# Entry point +# --------------------------------------------------------------------- # + + +def create_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description="Benchmarking PySceneDetect performance.") + parser.add_argument( + "--dataset", + type=str, + required=True, + choices=list(DATASETS.keys()), + help=f"Dataset name. One of: {', '.join(DATASETS.keys())}.", + ) + parser.add_argument( + "--detector", + type=str, + required=True, + choices=list(DETECTORS.keys()), + help=f"Detector name. One of: {', '.join(DETECTORS.keys())}.", + ) + parser.add_argument( + "--dataset-root", + type=str, + default=None, + help=( + "Base directory containing per-dataset subfolders. Defaults to 'benchmark' " + "(the in-repo location). Use this to read videos from an external location, " + "e.g. --dataset-root D:/path/to/benchmark." + ), + ) + parser.add_argument( + "--backend", + type=str, + default=DEFAULT_BACKEND, + choices=sorted(AVAILABLE_BACKENDS.keys()), + help=( + f"Video decoding backend (default: {DEFAULT_BACKEND}). Override to compare " + "detector output across backends, e.g. opencv vs pyav." + ), + ) + parser.add_argument( + "--tolerance", + type=str, + default="0,1", + help=( + "Comma-separated list of frame tolerances for hard-cut matching (default: 0,1). " + "+/-0 is the literature-strict number; +/-1 masks single-frame encoder artifacts." + ), + ) + parser.add_argument( + "--out", + type=str, + default=None, + help="Path to write a machine-readable JSON results file (includes per-video stats).", + ) + parser.add_argument( + "--quick", + type=int, + nargs="?", + const=10, + default=None, + metavar="N", + help=( + "Score only the first N samples from the dataset (default N=10) for fast " + "iteration. Use this to smoke-test config changes; published numbers should " + "always come from the full corpus." + ), + ) + return parser + + +def main() -> None: + args = create_parser().parse_args() + tolerances = parse_tolerances(args.tolerance) + dataset = resolve_dataset(args.dataset, args.dataset_root) + if len(dataset) == 0: + raise SystemExit( + f"Dataset {args.dataset!r} at {args.dataset_root or 'benchmark'} is empty - " + "check that videos and annotations are present." + ) + if args.quick is not None: + dataset._samples = dataset._samples[: args.quick] + print(f"--quick: limited to first {len(dataset)} samples") + print(f"Evaluating {args.detector} on {args.dataset} (backend={args.backend})") + + payloads = _run_predictions(dataset, args.detector, args.backend) + results = [evaluate(payloads, tolerance=t) for t in tolerances] + + _print_results(args.detector, args.dataset, dataset, results) + if args.out: + write_json( + args.out, + { + "detector": args.detector, + "dataset": args.dataset, + "backend": args.backend, + "results": [r.to_dict() for r in results], + }, + ) + + +if __name__ == "__main__": + main() diff --git a/benchmark/_common.py b/benchmark/_common.py new file mode 100644 index 00000000..c175dcc0 --- /dev/null +++ b/benchmark/_common.py @@ -0,0 +1,104 @@ +# +# 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. +# +"""Shared formatting and detector-registry helpers for ``python -m benchmark`` and +``python -m benchmark.sweep``. + +Kept intentionally small: the two entry points have different prediction loops (one +default-kwargs pass vs a fan-out parameter sweep) but render results into the same +tables. +""" + +from __future__ import annotations + +import json +import math +from typing import Any + +from benchmark.evaluator import BenchmarkResult +from scenedetect import ( + AdaptiveDetector, + ContentDetector, + HashDetector, + HistogramDetector, + ThresholdDetector, +) + +DEFAULT_BACKEND = "opencv" + +DETECTORS: dict[str, type] = { + "detect-adaptive": AdaptiveDetector, + "detect-content": ContentDetector, + "detect-hash": HashDetector, + "detect-hist": HistogramDetector, + "detect-threshold": ThresholdDetector, +} + + +def parse_tolerances(spec: str) -> tuple[int, ...]: + """Parse ``"0,1,5"`` into ``(0, 1, 5)``. Blank entries (e.g. trailing comma) are dropped.""" + return tuple(int(x.strip()) for x in spec.split(",") if x.strip()) + + +def fmt_pct(value: float, count: int) -> str: + """Percentage, or ``n/a`` when the underlying class has zero events.""" + return "n/a" if count == 0 else f"{value * 100:.2f}" + + +def fmt_offset(value: float) -> str: + return "n/a" if math.isnan(value) else f"{value:.3f}" + + +def render_table(header: list[str], rows: list[list[str]]) -> str: + """Build a pipe-delimited GitHub-flavored Markdown table as a single string.""" + widths = [max(len(header[i]), *(len(r[i]) for r in rows)) for i in range(len(header))] + sep = "| " + " | ".join("-" * w for w in widths) + " |" + header_line = "| " + " | ".join(h.ljust(w) for h, w in zip(header, widths, strict=True)) + " |" + body = [ + "| " + " | ".join(c.ljust(w) for c, w in zip(r, widths, strict=True)) + " |" for r in rows + ] + return "\n".join([header_line, sep, *body]) + + +HARD_HEADER = ["Tolerance", "Precision", "Recall", "F1", "Offset", "Elapsed"] +FADE_HEADER = ["Tolerance", "Precision", "Recall", "F1"] + + +def hard_row(result: BenchmarkResult) -> list[str]: + hard = result.hard_cuts + hard_predictions = hard.matched + hard.false_positives + hard_events = hard.matched + hard.missed + return [ + str(result.tolerance), + fmt_pct(hard.precision, hard_predictions), + fmt_pct(hard.recall, hard_events), + fmt_pct(hard.f1, hard_events), + fmt_offset(result.mean_abs_offset_hard_cuts), + f"{result.elapsed_mean:.2f}", + ] + + +def fade_row(result: BenchmarkResult) -> list[str]: + fades = result.fades + fade_predictions = fades.matched + fades.false_positives + fade_events = fades.matched + fades.missed + return [ + str(result.tolerance), + fmt_pct(fades.precision, fade_predictions), + fmt_pct(fades.recall, fade_events), + fmt_pct(fades.f1, fade_events), + ] + + +def write_json(out_path: str, payload: dict[str, Any]) -> None: + with open(out_path, "w") as f: + json.dump(payload, f, indent=2, default=str) + print(f"\nWrote results to {out_path}") diff --git a/benchmark/analyze_sweep.py b/benchmark/analyze_sweep.py new file mode 100644 index 00000000..01db94f3 --- /dev/null +++ b/benchmark/analyze_sweep.py @@ -0,0 +1,272 @@ +# +# 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. +# +"""Derive default-parameter recommendations from sweep results. + +Applies a fixed decision procedure to the grid JSONs under ``benchmark/results/sweep/`` +rather than just taking the argmax of mean F1@1: + +1. Baseline the shipped default (nearest grid cell). +2. Candidate set: cells within ``EPSILON`` of the best mean F1@1 (the plateau, not the peak). +3. Neighborhood robustness: reject cells with a steep drop to any one-grid-step neighbor + along a fine-grained numeric axis (categorical axes like ``size``/``bins`` are not + "steps" and are excluded). +4. Weighting sensitivity: a candidate must beat the default under the equal-dataset mean + and under every leave-one-dataset-out mean -- i.e. the *improvement* survives removing + any single dataset. (Being within EPSILON of each scheme's argmax is hopeless when + per-dataset optima diverge, and is not the question a defaults change asks.) The pooled + micro-average is reported for context but is not a gate: pooling events lets the + largest corpus (ClipShots, ~10x the cuts) dominate, making it a dataset-weighting + choice rather than a robustness check. +5. Precision floor: per dataset, candidate precision@1 must not fall more than + ``PRECISION_SLACK`` below the default's. +6. Materiality: recommend a change only for >= ``MIN_GAIN`` mean F1@1 over the default, + gains >= 1.0 on at least two datasets, and no dataset regressing by > 1.0. +7. min_scene_len isolation: for detectors that swept it, also rank with it fixed at the + default-equivalent slice so the threshold recommendation stands on its own. + +Prints a markdown report to stdout. Requires the sweep JSONs locally (not committed); +see ``scripts/benchmark_sweep.sh``. +""" + +from __future__ import annotations + +from benchmark.report_sweep import DATASETS, _load_cells, _params_str, _table + +EPSILON = 1.0 # candidate set: within this many F1 points of the best mean +MAX_NEIGHBOR_DROP = 2.0 # reject cells this much better than their worst neighbor +FINE_AXIS_MIN_VALUES = 4 # axes with fewer distinct values are categorical, not grid steps +PRECISION_SLACK = 5.0 # per-dataset precision@1 may not drop more than this vs default +MIN_GAIN = 2.0 # mean F1@1 gain required to recommend changing a default + +# Shipped defaults mapped onto the swept grid (nearest cell). min_scene_len defaults to +# 15 *frames*; the sweeps used seconds, so 0.6 matches only at 25 fps (BBC) and is ~0.5 +# at 30 fps web video -- flagged in the report. hash's 0.395 maps to the 0.4 grid point. +DEFAULTS: dict[str, dict] = { + "detect-content": {"min_scene_len": 0.6, "threshold": 27}, + "detect-adaptive": {"adaptive_threshold": 3.0, "min_scene_len": 0.6, "window_width": 2}, + "detect-hash": {"size": 16, "threshold": 0.4}, + "detect-hist": {"bins": 256, "threshold": 0.05}, +} +MSL_SWEPT = {"detect-content", "detect-adaptive"} + + +def _f1(matched: int, fp: int, missed: int) -> float: + p = matched / (matched + fp) if matched + fp else 0.0 + r = matched / (matched + missed) if matched + missed else 0.0 + return 200.0 * p * r / (p + r) if p + r else 0.0 + + +class Cell: + """One parameter combination with per-dataset hard-cut results at tolerance 1.""" + + def __init__(self, params: dict, per_ds: dict[str, dict]): + self.params = params + self.key = _params_str(params) + self.per_ds = per_ds # dataset -> hard_cuts dict (matched/fp/missed/precision/recall/f1) + self.mean_f1 = sum(d["f1"] for d in per_ds.values()) / len(per_ds) + self.micro_f1 = _f1( + sum(d["matched"] for d in per_ds.values()), + sum(d["false_positives"] for d in per_ds.values()), + sum(d["missed"] for d in per_ds.values()), + ) + + def lodo(self, skip: str) -> float: + rest = [d["f1"] for ds, d in self.per_ds.items() if ds != skip] + return sum(rest) / len(rest) + + +def _load(det: str) -> list[Cell]: + per_key: dict[str, dict[str, dict]] = {} + params_by_key: dict[str, dict] = {} + for ds in DATASETS: + cells = _load_cells(det, ds) + if cells is None: + return [] + for c in cells: + key = _params_str(c["params"]) + per_key.setdefault(key, {})[ds] = c["results"]["1"]["aggregate"]["hard_cuts"] + params_by_key[key] = c["params"] + return [Cell(params_by_key[k], v) for k, v in per_key.items() if len(v) == len(DATASETS)] + + +def _neighbors(cell: Cell, cells: list[Cell]) -> list[Cell]: + """Cells one grid step away along exactly one fine-grained numeric axis. + + Axes with fewer than ``FINE_AXIS_MIN_VALUES`` distinct values (e.g. ``size=8,16``, + ``bins=128,256``, ``window_width=2,3``) are categorical choices, not grid steps, so + a large score difference across them is not a knife-edge. + """ + axes = {k: sorted({c.params[k] for c in cells}) for k in cell.params} + out = [] + for other in cells: + diff = [k for k in cell.params if other.params[k] != cell.params[k]] + if len(diff) != 1: + continue + (k,) = diff + vals = axes[k] + if len(vals) < FINE_AXIS_MIN_VALUES: + continue + if abs(vals.index(other.params[k]) - vals.index(cell.params[k])) == 1: + out.append(other) + return out + + +def analyze(det: str) -> list[str]: + cells = _load(det) + out = [f"## {det}\n"] + if not cells: + return [*out, "(sweep JSONs missing)\n"] + + # Match by the canonical params string: grid generation leaves float artifacts + # (e.g. 0.4000000000000001) that a plain dict comparison would miss. + default_key = _params_str(DEFAULTS[det]) + default = next((c for c in cells if c.key == default_key), None) + best = max(cells, key=lambda c: c.mean_f1) + + def row(c: Cell, label: str) -> list[str]: + return [ + label, + f"{c.mean_f1:.2f}", + *(f"{c.per_ds[ds]['f1']:.2f}" for ds in DATASETS), + c.key, + ] + + rows = [row(best, "best")] + if default is not None: + rows.insert(0, row(default, "default")) + out.append(_table(["Cell", "Mean F1@1", *DATASETS, "Params"], rows)) + out.append("") + if default is None: + out.append(f"> Default cell {DEFAULTS[det]} not present in the grid; criteria that") + out.append("> compare against the default are skipped below.\n") + + # Gated weighting schemes: equal-dataset mean + leave-one-dataset-out means. A + # candidate is weighting-stable if it beats the default under every scheme, i.e. the + # improvement does not hinge on any single dataset. Micro-average is reported per + # candidate but deliberately not gated (see module docstring). Without a default cell + # to compare against, fall back to within-EPSILON-of-best per scheme. + schemes = [lambda c: c.mean_f1] + schemes += [lambda c, ds=ds: c.lodo(ds) for ds in DATASETS] + scheme_floor = ( + [s(default) for s in schemes] + if default is not None + else [max(s(c) for c in cells) - EPSILON for s in schemes] + ) + + candidates = sorted( + (c for c in cells if c.mean_f1 >= best.mean_f1 - EPSILON), + key=lambda c: c.mean_f1, + reverse=True, + ) + cand_rows = [] + passing = [] + for c in candidates: + nbrs = _neighbors(c, cells) + worst_drop = max((c.mean_f1 - n.mean_f1 for n in nbrs), default=0.0) + robust = worst_drop <= MAX_NEIGHBOR_DROP + stable = all(s(c) >= floor for s, floor in zip(schemes, scheme_floor, strict=True)) + if default is not None: + prec_ok = all( + c.per_ds[ds]["precision"] >= default.per_ds[ds]["precision"] - PRECISION_SLACK + for ds in DATASETS + ) + deltas = [c.per_ds[ds]["f1"] - default.per_ds[ds]["f1"] for ds in DATASETS] + material = ( + c.mean_f1 - default.mean_f1 >= MIN_GAIN + and sum(d >= 1.0 for d in deltas) >= 2 + and all(d >= -1.0 for d in deltas) + ) + else: + prec_ok = material = True + ok = robust and stable and prec_ok and material + if ok: + passing.append(c) + mark = lambda b: "yes" if b else "NO" # noqa: E731 + cand_rows.append( + [ + f"{c.mean_f1:.2f}", + f"{c.micro_f1:.2f}", + f"{worst_drop:.2f}", + mark(robust), + mark(stable), + mark(prec_ok), + mark(material), + "PASS" if ok else "-", + c.key, + ] + ) + out.append(f"**Candidates (mean F1@1 within {EPSILON:g} of best):**\n") + out.append( + _table( + [ + "Mean", + "Micro", + "NbrDrop", + "Robust", + "WeightStable", + "PrecFloor", + "Material", + "Verdict", + "Params", + ], + cand_rows, + ) + ) + out.append("") + + if det in MSL_SWEPT: + msl = DEFAULTS[det]["min_scene_len"] + fixed = [c for c in cells if c.params.get("min_scene_len") == msl] + top = sorted(fixed, key=lambda c: c.mean_f1, reverse=True)[:3] + out.append(f"**With min_scene_len fixed at the default-equivalent {msl:g}s:**\n") + out.append( + _table( + ["Mean F1@1", *DATASETS, "Params"], + [ + [f"{c.mean_f1:.2f}", *(f"{c.per_ds[ds]['f1']:.2f}" for ds in DATASETS), c.key] + for c in top + ], + ) + ) + out.append("") + + if passing: + pick = passing[0] + gain = f" (+{pick.mean_f1 - default.mean_f1:.2f} mean F1@1 vs default)" if default else "" + out.append(f"**Recommendation: CHANGE to `{pick.key}`{gain}.**\n") + else: + out.append( + "**Recommendation: KEEP current default** (no candidate passes all criteria; " + "see verdict column for which gate fails).\n" + ) + return out + + +def main() -> None: + print("# Detector default recommendations from sweep data\n") + print( + "Generated by `benchmark/analyze_sweep.py`. Criteria: candidate plateau within " + f"{EPSILON:g} F1 of best; worst one-step neighbor drop <= {MAX_NEIGHBOR_DROP:g} along " + "fine-grained axes; beats the default under equal-mean and each leave-one-dataset-out " + "weighting (pooled micro-average reported, not gated); " + f"per-dataset precision floor (default - " + f"{PRECISION_SLACK:g}); materiality (>= {MIN_GAIN:g} mean F1@1 gain, >= 1.0 on two " + "datasets, no dataset worse by > 1.0). min_scene_len defaults to 15 frames (= 0.6s " + "only at 25 fps); the default cell uses the nearest swept slice.\n" + ) + for det in DEFAULTS: + for line in analyze(det): + print(line) + + +if __name__ == "__main__": + main() diff --git a/benchmark/dataset.py b/benchmark/dataset.py new file mode 100644 index 00000000..e0a73a91 --- /dev/null +++ b/benchmark/dataset.py @@ -0,0 +1,240 @@ +# +# 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. +# +"""Benchmark dataset definitions and registry. + +Each :class:`Dataset` is a corpus of :class:`Sample` records (video file + typed ground truth) +loaded eagerly at construction. Ground-truth files for the supported corpora are at most a few +hundred kilobytes total, so eager loading avoids re-reading the same files for every sweep cell. + +Add a new dataset by: + +1. Subclassing :class:`Dataset` and populating ``self._samples`` in ``__init__``. +2. Registering it in :data:`DATASETS` under the name used by ``--dataset``. +""" + +from __future__ import annotations + +import glob +import json +import logging +import os +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path + +from benchmark.evaluator import EventInterval, Frames, GroundTruth + +logger = logging.getLogger("pyscenedetect") + + +@dataclass(frozen=True) +class Sample: + """One scored video: a path on disk plus its typed ground truth.""" + + video_file: Path + ground_truth: GroundTruth + + +class Dataset: + """Iterable corpus of :class:`Sample` records. + + Subclasses populate ``self._samples`` in their constructor; this base provides the iteration + and length protocol. ``event_types`` advertises which TRECVID-SBD event categories the + dataset's ground truth contains, so consumers can skip columns/tables for categories that + have no events (e.g. fade transitions on BBC/AutoShot). + """ + + event_types: frozenset[str] = frozenset({"hard_cut"}) + _samples: list[Sample] + + def __iter__(self) -> Iterator[Sample]: + return iter(self._samples) + + def __len__(self) -> int: + return len(self._samples) + + +def _read_tab_separated_cuts(scene_file: str) -> list[Frames]: + """Parse a BBC/AutoShot-style annotation file. + + Each line is tab-separated; the second column is the 0-based frame index of a + hard cut. Returns 1-based frame indices, matching the convention used by + :class:`scenedetect.FrameTimecode`. + """ + with open(scene_file) as f: + return [int(line.strip().split("\t")[1]) + 1 for line in f] + + +class BBCDataset(Dataset): + """The BBC Planet Earth dataset. + + Baraldi et al., "A Deep Siamese Network for Scene Detection in Broadcast Videos", + ACM Multimedia 2015. https://arxiv.org/abs/1510.08893 + + 11 long-form videos (``BBC/videos/bbc_.mp4``) with hard-cut annotations in + ``BBC/fixed/-scenes.txt``. + """ + + def __init__(self, dataset_dir: str): + video_files = sorted(glob.glob(os.path.join(dataset_dir, "videos", "*.mp4"))) + scene_files = sorted(glob.glob(os.path.join(dataset_dir, "fixed", "*.txt"))) + if len(video_files) != len(scene_files): + raise ValueError( + f"BBC dataset at {dataset_dir!r}: {len(video_files)} videos but " + f"{len(scene_files)} annotation files." + ) + self._samples: list[Sample] = [] + for video_file, scene_file in zip(video_files, scene_files, strict=True): + video_id = os.path.basename(video_file).replace("bbc_", "").split(".")[0] + scene_id = os.path.basename(scene_file).split("-")[0] + if video_id != scene_id: + raise ValueError(f"BBC id mismatch: {video_file} vs {scene_file}") + self._samples.append( + Sample( + video_file=Path(video_file), + ground_truth=GroundTruth(hard_cuts=_read_tab_separated_cuts(scene_file)), + ) + ) + + +class AutoShotDataset(Dataset): + """The AutoShot dataset (test splits). + + Zhu et al., "AutoShot: A Short Video Dataset and State-of-the-Art Shot Boundary + Detection", CVPRW 2023. The original test set has 200 videos; 36 are no longer + publicly available, so the corpus iterates over whatever is present on disk. + + Videos at ``AutoShot/videos/.mp4``, hard-cut annotations at + ``AutoShot/annotations/.txt``. + """ + + def __init__(self, dataset_dir: str): + # 36 of the original 200 videos are no longer publicly available, so intersect + # by id rather than zipping the directory listings strictly. + videos_by_id = { + os.path.basename(p).split(".")[0]: p + for p in glob.glob(os.path.join(dataset_dir, "videos", "*.mp4")) + } + scenes_by_id = { + os.path.basename(p).split(".")[0]: p + for p in glob.glob(os.path.join(dataset_dir, "annotations", "*.txt")) + } + self._samples: list[Sample] = [ + Sample( + video_file=Path(videos_by_id[vid]), + ground_truth=GroundTruth(hard_cuts=_read_tab_separated_cuts(scenes_by_id[vid])), + ) + for vid in sorted(videos_by_id.keys() & scenes_by_id.keys()) + ] + + +class ClipShotsDataset(Dataset): + """The ClipShots dataset (test split by default). + + Tang et al., "Fast Video Shot Transition Localization with Deep Structured Models", + ACCV 2018. https://github.com/Tangshitao/ClipShots + + The only in-tree dataset with typed gradual-transition (fade/dissolve) ground truth in + addition to hard cuts. Layout under ``ClipShots/``:: + + annotations/{train,test,only_gradual}.json + video_lists/{train,test,only_gradual}.txt (optional split filter) + videos/*.mp4 + + Each annotation entry is ``{"transitions": [[start, end], ...], "frame_num": float}``. + Hard cuts are single-frame spans (``end == start + 1``); wider spans are gradual + transitions. Unlike the BBC/AutoShot annotations, ClipShots frame indices already match + PySceneDetect's boundary-frame convention (the prediction's ``frame_num`` lines up with + ``transition[1]`` directly), so no offset is applied here. + + Loading rules: + + - Videos listed in ``video_lists/.txt`` but absent from the annotations JSON are + silently ignored (the filter runs against the JSON, not the other way). + - Annotations whose ``.mp4`` is not on disk are skipped (so partial corpora work). + - Malformed transitions (fewer than 2 entries, negative span, zero-width span) are + skipped with a warning rather than crashing the load. + + Only the ``ClipShotsDataset(dir, split=...)`` constructor honors a non-default split; + the registry entry in :data:`DATASETS` always loads the ``test`` split. + """ + + event_types = frozenset({"hard_cut", "fade"}) + + def __init__(self, dataset_dir: str, split: str = "test"): + ann_path = os.path.join(dataset_dir, "annotations", f"{split}.json") + videos_dir = os.path.join(dataset_dir, "videos") + with open(ann_path) as f: + annotations: dict = json.load(f) + split_list_path = os.path.join(dataset_dir, "video_lists", f"{split}.txt") + if os.path.exists(split_list_path): + with open(split_list_path) as allow_f: + allowed = {line.strip() for line in allow_f if line.strip()} + annotations = {k: v for k, v in annotations.items() if k in allowed} + total = len(annotations) + skipped_missing = 0 + self._samples: list[Sample] = [] + for video_name in sorted(annotations): + video_path = os.path.join(videos_dir, video_name) + if not os.path.exists(video_path): + skipped_missing += 1 + continue + hard_cuts: list[Frames] = [] + fades: list[EventInterval] = [] + # `... or []` (not `.get(k, [])`) so an explicit JSON `null` is treated as empty. + for transition in annotations[video_name].get("transitions") or []: + if len(transition) < 2: + logger.warning("ClipShots %s: malformed transition %r", video_name, transition) + continue + start, end = int(transition[0]), int(transition[1]) + span = end - start + if span == 1: + hard_cuts.append(end) + elif span > 1: + fades.append(EventInterval(start=start, end=end)) + else: + logger.warning( + "ClipShots %s: skipping degenerate transition %r", video_name, transition + ) + self._samples.append( + Sample( + video_file=Path(video_path), + ground_truth=GroundTruth(hard_cuts=hard_cuts, fades=fades), + ) + ) + logger.info( + "ClipShots %s: loaded %d/%d samples (%d videos missing on disk)", + split, + len(self._samples), + total, + skipped_missing, + ) + + +# Mapping of --dataset names to constructors. Typed as a plain callable so +# subclass-specific positional signatures (each takes ``dataset_dir: str``) +# aren't widened away by the base ``Dataset`` class's empty ``__init__``. +DATASETS: dict[str, type] = { + "BBC": BBCDataset, + "AutoShot": AutoShotDataset, + "ClipShots": ClipShotsDataset, +} + + +def resolve_dataset(name: str, root: str | None) -> Dataset: + """Instantiate the named dataset. + + ``root`` overrides the default repo-relative path; pass ``None`` (or the empty string) + to use ``benchmark//``. + """ + base = root if root else "benchmark" + return DATASETS[name](os.path.join(base, name)) diff --git a/benchmark/evaluator.py b/benchmark/evaluator.py new file mode 100644 index 00000000..07a666b6 --- /dev/null +++ b/benchmark/evaluator.py @@ -0,0 +1,346 @@ +# +# 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. +# +"""Scoring for shot-boundary-detection benchmarks. + +Implements the TRECVID-SBD evaluation convention. Each predicted boundary is one integer frame +number. Hard cuts are matched against ground-truth frames, with a configurable frame-tolerance. +Matches are scored via greedy 1-to-1 nearest-neighbor assignment. Fades and other gradual +transitions are matched by point-in-interval membership, where the prediction inside an interval +is considered a match. Other predictions in the same interval are considered false positives. + +References: +- Smeaton, Over & Doherty (2010), "Video shot boundary detection: Seven years of TRECVid activity", + *Computer Vision and Image Understanding*. + https://ora.ox.ac.uk/objects/uuid:868aebdf-298a-4567-b47f-c8f9e3a6ac7a +- Hassanien et al. (2017), "Large-scale, Fast and Accurate Shot Boundary Detection through + Spatio-temporal Convolutional Neural Networks", arXiv:1705.03281. + https://arxiv.org/abs/1705.03281 +""" + +from __future__ import annotations + +import math +from collections.abc import Iterable +from dataclasses import dataclass, field +from pathlib import Path +from statistics import mean +from typing import TypeAlias + +# 1-based frame number, matching the convention used by the BBC/AutoShot text annotations and by +# PySceneDetect's :class:`FrameTimecode`. Used for cut positions and for tolerance windows. +# +# Ironically, all the work we did in v0.7 to support VFR is meaningless for most existing benchmarks +# since they are all CFR. In the future we should consider extending the API to support temporal +# units of time or PTS, and also see if other datasets might take this into account. +Frames: TypeAlias = int + + +@dataclass(frozen=True) +class EventInterval: + """Inclusive ``[start, end]`` frame range for a gradual transition (dissolve/fade).""" + + start: Frames + end: Frames + + def contains(self, frame: Frames) -> bool: + return self.start <= frame <= self.end + + +@dataclass +class GroundTruth: + """Ground truth for one video, consisting of hard cut frames and fade intervals.""" + + hard_cuts: list[Frames] + fades: list[EventInterval] = field(default_factory=list) + category: str | None = None + + +@dataclass +class Prediction: + """One detector run on one video, ready for scoring against typed ground truth.""" + + predicted_cuts: list[Frames] + """Flat list of predicted hard cut frame numbers, 1-based.""" + ground_truth: GroundTruth + """Ground truth for the video being scored.""" + elapsed: float + """How long it took to run the prediction, in seconds. Used for performance not accuracy.""" + + +@dataclass +class EventMetrics: + """Per-event-type scoring counts used to calculate precision, recall, and F1 score. + + Each instance should be used to score *one* event type (either hard cuts *or* fade transitions) + against ground truth. + """ + + # Detector fired on a real event in the ground truth. + matched: int = 0 + # Detector fired but there was no real event at that frame. + false_positives: int = 0 + # Real event in the ground truth that the detector failed to fire on. + missed: int = 0 + + @property + def precision(self) -> float: + denom = self.matched + self.false_positives + return self.matched / denom if denom else 0.0 + + @property + def recall(self) -> float: + denom = self.matched + self.missed + return self.matched / denom if denom else 0.0 + + @property + def f1(self) -> float: + p, r = self.precision, self.recall + return 2 * p * r / (p + r) if (p + r) else 0.0 + + def __add__(self, other: EventMetrics) -> EventMetrics: + return EventMetrics( + matched=self.matched + other.matched, + false_positives=self.false_positives + other.false_positives, + missed=self.missed + other.missed, + ) + + def to_dict(self) -> dict: + return { + "matched": self.matched, + "false_positives": self.false_positives, + "missed": self.missed, + "precision": round(self.precision * 100, 4), + "recall": round(self.recall * 100, 4), + "f1": round(self.f1 * 100, 4), + } + + +@dataclass +class VideoMetrics: + """Per-video result at one tolerance. The video's path lives in the enclosing + :class:`BenchmarkResult.per_video` dict key, not on this object.""" + + elapsed: float + category: str | None + hard_cuts: EventMetrics + fades: EventMetrics + # (sum of |prediction - ground_truth|, match count) over hard-cut matches. + # Stored as raw sums so aggregation across videos is `sum / total_matched`, + # not a mean-of-means. + hard_offset: tuple[float, int] + + @property + def mean_abs_offset(self) -> float: + s, n = self.hard_offset + return s / n if n else math.nan + + def to_dict(self) -> dict: + return { + "elapsed": self.elapsed, + "category": self.category, + "hard_cuts": self.hard_cuts.to_dict(), + "fades": self.fades.to_dict(), + "mean_abs_offset_hard_cuts": self.mean_abs_offset, + } + + +@dataclass +class BenchmarkResult: + """Aggregate result of running one detector configuration on a dataset at one tolerance. + + ``per_video`` is keyed by source video path so per-video lookups are explicit; aggregate + properties sum counts across all videos (same convention used by TRECVID). + """ + + per_video: dict[Path, VideoMetrics] + tolerance: Frames + + @property + def hard_cuts(self) -> EventMetrics: + total = EventMetrics() + for v in self.per_video.values(): + total = total + v.hard_cuts + return total + + @property + def fades(self) -> EventMetrics: + total = EventMetrics() + for v in self.per_video.values(): + total = total + v.fades + return total + + @property + def mean_abs_offset_hard_cuts(self) -> float: + num = sum(v.hard_offset[0] for v in self.per_video.values()) + den = sum(v.hard_offset[1] for v in self.per_video.values()) + return num / den if den else math.nan + + @property + def elapsed_total(self) -> float: + return sum(v.elapsed for v in self.per_video.values()) + + @property + def elapsed_mean(self) -> float: + return mean(v.elapsed for v in self.per_video.values()) if self.per_video else 0.0 + + def by_category(self) -> dict[str, BenchmarkResult]: + buckets: dict[str, dict[Path, VideoMetrics]] = {} + for path, v in self.per_video.items(): + buckets.setdefault(v.category or "unknown", {})[path] = v + return { + g: BenchmarkResult(per_video=vids, tolerance=self.tolerance) + for g, vids in buckets.items() + } + + def to_dict(self, root: Path | None = None) -> dict: + def _fmt_path(p: Path) -> str: + if root is not None: + try: + return p.relative_to(root).as_posix() + except ValueError: + pass + return p.as_posix() + + return { + "tolerance": self.tolerance, + "aggregate": { + "hard_cuts": self.hard_cuts.to_dict(), + "mean_abs_offset_hard_cuts": self.mean_abs_offset_hard_cuts, + "fades": self.fades.to_dict(), + "elapsed_total": self.elapsed_total, + "elapsed_mean": self.elapsed_mean, + "video_count": len(self.per_video), + }, + "per_video": {_fmt_path(path): v.to_dict() for path, v in self.per_video.items()}, + } + + +def _score_hard_cuts( + predicted_cuts: Iterable[Frames], + ground_truth_cuts: Iterable[Frames], + tolerance: Frames, +) -> tuple[EventMetrics, list[Frames]]: + """Greedy 1-to-1 nearest-neighbor matching within ``tolerance`` frames. + + Builds the set of all (prediction, ground-truth) candidate pairs whose absolute frame distance + is within tolerance, sorts by distance, and walks the sorted list claiming the first unused + pair each time. Ties on distance are broken by stable iteration order, which is deterministic + but otherwise unspecified - fine since we report aggregate metrics, not per-event assignments. + + Returns the event metrics and the per-match absolute offsets (for later averaging). + """ + predicted_cuts = list(predicted_cuts) + ground_truth_cuts = list(ground_truth_cuts) + candidates: list[tuple[int, int, int]] = [] + for i, p in enumerate(predicted_cuts): + for j, g in enumerate(ground_truth_cuts): + d = abs(p - g) + if d <= tolerance: + candidates.append((d, i, j)) + candidates.sort() + prediction_used = [False] * len(predicted_cuts) + ground_truth_used = [False] * len(ground_truth_cuts) + offsets: list[int] = [] + for d, i, j in candidates: + if not prediction_used[i] and not ground_truth_used[j]: + prediction_used[i] = True + ground_truth_used[j] = True + offsets.append(d) + matched = len(offsets) + return ( + EventMetrics( + matched=matched, + false_positives=len(predicted_cuts) - matched, + missed=len(ground_truth_cuts) - matched, + ), + offsets, + ) + + +def _score_fade_transitions( + predicted_cuts: Iterable[Frames], + intervals: Iterable[EventInterval], +) -> tuple[EventMetrics, set[int]]: + """Point-in-interval matching for gradual fade transitions. + + Each prediction that falls inside any ground-truth interval is consumed by that interval + (first-match wins). The first prediction to land in an interval is the match; any further + predictions in the same interval are false positives. Predictions outside every interval are + not touched here - they go back to the hard-cut scorer. + + Returns the fade transition metrics and the set of *positional indices* (into + ``predicted_cuts``, not frame values) that were consumed by a fade interval, so the caller + can skip them when running hard matching. + """ + predicted_cuts = list(predicted_cuts) + intervals = list(intervals) + consumed: set[int] = set() + intervals_matched: set[EventInterval] = set() + matched = 0 + false_positives = 0 + for k, p in enumerate(predicted_cuts): + for interval in intervals: + if interval.contains(p): + consumed.add(k) + if interval in intervals_matched: + false_positives += 1 + else: + intervals_matched.add(interval) + matched += 1 + break + missed = len(intervals) - matched + return ( + EventMetrics(matched=matched, false_positives=false_positives, missed=missed), + consumed, + ) + + +def score_video( + predicted_cuts: Iterable[Frames], + ground_truth: GroundTruth, + tolerance: Frames, + elapsed: float, +) -> VideoMetrics: + """Score one video against typed ground truth at one tolerance. + + Fade transition matching runs first; predictions that land inside any fade interval are + consumed there and excluded from hard-cut matching. The remaining predictions are matched + against ground-truth hard cuts at ``tolerance`` frames. + """ + predicted_cuts = list(predicted_cuts) + + fade_metrics, consumed = _score_fade_transitions(predicted_cuts, ground_truth.fades) + remaining_cuts = [p for k, p in enumerate(predicted_cuts) if k not in consumed] + hard_metrics, offsets = _score_hard_cuts(remaining_cuts, ground_truth.hard_cuts, tolerance) + + return VideoMetrics( + elapsed=elapsed, + category=ground_truth.category, + hard_cuts=hard_metrics, + fades=fade_metrics, + hard_offset=(float(sum(offsets)), len(offsets)), + ) + + +def evaluate(predictions: dict[Path, Prediction], tolerance: Frames) -> BenchmarkResult: + """Score predictions at a single tolerance and return aggregate + per-video results.""" + assert predictions, "predictions must not be empty" + videos = { + path: score_video( + predicted_cuts=p.predicted_cuts, + ground_truth=p.ground_truth, + tolerance=tolerance, + elapsed=p.elapsed, + ) + for path, p in predictions.items() + } + return BenchmarkResult(per_video=videos, tolerance=tolerance) diff --git a/benchmark/report_sweep.py b/benchmark/report_sweep.py new file mode 100644 index 00000000..854049fa --- /dev/null +++ b/benchmark/report_sweep.py @@ -0,0 +1,149 @@ +# +# 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. +# +"""Consolidate per-(detector, dataset) sweep JSONs into a single markdown report. + +Reads ``benchmark/results/sweep/-.json`` for all five detectors and writes +``benchmark/SWEEP_REPORT.md``: the best cell by F1@1 per (detector, dataset), the top-5 +per cell, and the cell that is best *on average* across datasets per detector (a single +recommended default). + +All results come from the decode-based sweep (``benchmark/sweep.py``, driven by +``scripts/benchmark_sweep.sh``). Unlike content/adaptive, hash/hist were swept with the default +``min_scene_len`` fixed. If a ``-ext-.json`` grid-extension file exists +alongside the main JSON, its cells are merged in. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +DETECTORS = [ + "detect-content", + "detect-adaptive", + "detect-hash", + "detect-hist", + "detect-threshold", +] +DATASETS = ["BBC", "AutoShot", "ClipShots"] +SWEEP_DIR = Path("benchmark/results/sweep") +OUT = Path("benchmark/SWEEP_REPORT.md") + + +def _hard(cell: dict, tol: str) -> dict: + return cell["results"][tol]["aggregate"]["hard_cuts"] + + +def _params_str(p: dict) -> str: + # :g strips float artifacts from grid generation (e.g. 0.42500000000000016 -> 0.425). + def fmt(v): + return f"{v:g}" if isinstance(v, float) else str(v) + + return ", ".join(f"{k}={fmt(v)}" for k, v in sorted(p.items())) + + +def _table(header: list[str], rows: list[list[str]]) -> str: + widths = [max(len(header[i]), *(len(r[i]) for r in rows)) for i in range(len(header))] + + def line(cells): + return "| " + " | ".join(c.ljust(w) for c, w in zip(cells, widths, strict=True)) + " |" + + sep = "| " + " | ".join("-" * w for w in widths) + " |" + return "\n".join([line(header), sep, *(line(r) for r in rows)]) + + +def _load_cells(det: str, ds: str) -> list[dict] | None: + path = SWEEP_DIR / f"{det}-{ds}.json" + if not path.exists(): + return None + cells = json.loads(path.read_text())["cells"] + ext = SWEEP_DIR / f"{det}-ext-{ds}.json" + if ext.exists(): + cells = cells + json.loads(ext.read_text())["cells"] + return cells + + +def main() -> None: + out: list[str] = ["# Detector parameter sweep report", ""] + out.append( + "Generated by `benchmark/report_sweep.py` from `benchmark/sweep.py` grid results " + "(hash/hist were swept with `min_scene_len` fixed at its default). " + "F1/precision/recall are percentages on hard cuts; tol = frame tolerance.\n" + ) + + for det in DETECTORS: + out.append(f"## {det}\n") + if det == "detect-threshold": + out.append( + "> Note: `detect-threshold` detects **fades** (fade to/from black), not hard " + "cuts. These datasets' ground truth is hard cuts, so the hard-cut F1 below is " + "expectedly near zero. It is included to validate the sweep pipeline end-to-end, " + "not as a meaningful hard-cut accuracy result.\n" + ) + if det == "detect-hist": + out.append( + "> Note: thresholds >= 0.21 come from a grid-extension run " + "(`detect-hist-ext-.json`) after the initial grid's best cell landed " + "on its 0.20 upper edge.\n" + ) + # Best-per-dataset summary. + summary_rows = [] + # Track each cell's F1@1 across datasets for an averaged recommendation. + per_cell_f1: dict[str, list[float]] = {} + per_cell_params: dict[str, dict] = {} + for ds in DATASETS: + cells = _load_cells(det, ds) + if cells is None: + summary_rows.append([ds, "(missing)", "", "", "", ""]) + continue + best = max(cells, key=lambda c: _hard(c, "1")["f1"]) + h1, h0 = _hard(best, "1"), _hard(best, "0") + summary_rows.append( + [ + ds, + f"{h1['f1']:.2f}", + f"{h1['precision']:.2f}", + f"{h1['recall']:.2f}", + f"{h0['f1']:.2f}", + _params_str(best["params"]), + ] + ) + for c in cells: + key = _params_str(c["params"]) + per_cell_f1.setdefault(key, []).append(_hard(c, "1")["f1"]) + per_cell_params[key] = c["params"] + out.append("**Best cell per dataset (by F1@1):**\n") + out.append( + _table( + ["Dataset", "F1@1", "Prec@1", "Rec@1", "F1@0", "Params"], + summary_rows, + ) + ) + out.append("") + # Averaged recommendation: cells scored on all datasets, ranked by mean F1@1. + full = {k: v for k, v in per_cell_f1.items() if len(v) == len(DATASETS)} + if full: + ranked = sorted(full.items(), key=lambda kv: sum(kv[1]) / len(kv[1]), reverse=True) + rec_rows = [ + [f"{sum(v) / len(v):.2f}", *(f"{x:.2f}" for x in v), k] for k, v in ranked[:5] + ] + out.append("**Best params averaged across all datasets (mean F1@1):**\n") + out.append(_table(["Mean F1@1", *DATASETS, "Params"], rec_rows)) + out.append("") + + OUT.write_text("\n".join(out), encoding="utf-8") + print(f"Wrote {OUT}") + print("\n".join(out)) + + +if __name__ == "__main__": + main() diff --git a/benchmark/sweep.py b/benchmark/sweep.py new file mode 100644 index 00000000..dbd20d78 --- /dev/null +++ b/benchmark/sweep.py @@ -0,0 +1,452 @@ +# +# 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. +# +"""Parameter sweep harness for one detector on one dataset. + +Brute-force grid search over a Cartesian product of detector parameters. The cost of +the grid is amortized using :class:`FanOutVideoStream`. One video decode per chunk of +``--workers`` cells, so a 100-cell grid on a 500-video corpus costs roughly +``500 * ceil(100 / workers)`` decodes, not ``500 * 100``. + +Use ``--params "key=v1,v2,v3"`` for enumerated values and ``"key=a:b:s"`` for a numeric +``[a, b]`` range with step ``s`` (inclusive of ``b`` when the step lands there). +Multiple keys are separated by ``;`` and form a Cartesian product. + +Example:: + + python -m benchmark.sweep \\ + --detector detect-content --dataset BBC \\ + --params "threshold=15:35:1;min_scene_len=0.0:1.0:0.1" \\ + --tolerance 0,1 --workers 16 --out sweep.json + +``min_scene_len`` is a :data:`TimecodeLike`: integers are frames, floats are seconds, +strings like ``"0.1s"`` or ``"00:00:00.500"`` also work. Prefer floats so the same +sweep is meaningful across datasets with different framerates. + +Reports the top-10 cells by F1 at each tolerance plus the Pareto front across the two +tolerances. The full grid lives in the JSON output for offline plotting. +""" + +from __future__ import annotations + +import argparse +import itertools +import threading +import time +from pathlib import Path +from typing import Any + +from tqdm import tqdm + +from benchmark._common import ( + DEFAULT_BACKEND, + DETECTORS, + parse_tolerances, + render_table, + write_json, +) +from benchmark.dataset import DATASETS, Dataset, resolve_dataset +from benchmark.evaluator import BenchmarkResult, Prediction, evaluate +from scenedetect import AVAILABLE_BACKENDS, SceneManager, open_video +from scenedetect._fan_out import FanOutVideoStream + +# --------------------------------------------------------------------- # +# Spec language: "key=v1,v2,v3" or "key=a:b:s"; clauses joined by ";". +# --------------------------------------------------------------------- # + + +def _coerce(token: str) -> Any: + """Best-effort scalar coercion. Order: None, bool, int, float, str.""" + t = token.strip() + if t == "None": + return None + if t == "True": + return True + if t == "False": + return False + try: + return int(t) + except ValueError: + pass + try: + return float(t) + except ValueError: + pass + return t + + +def _expand_values(s: str) -> list[Any]: + if ":" in s: + parts = s.split(":") + if len(parts) != 3: + raise ValueError(f"Range spec must be 'start:stop:step', got {s!r}") + a, b, step = _coerce(parts[0]), _coerce(parts[1]), _coerce(parts[2]) + if not all(isinstance(x, (int, float)) for x in (a, b, step)): + raise ValueError(f"Range bounds must be numeric, got {s!r}") + if step == 0: + raise ValueError(f"Range step must be non-zero, got {s!r}") + out: list[Any] = [] + v = a + # Small epsilon to keep an inclusive upper bound robust against float drift. + epsilon = abs(step) * 1e-9 if isinstance(step, float) else 0 + # Direction-aware: support a > b with negative step too. + if step > 0: + while v <= b + epsilon: + out.append(v) + v = v + step + else: + while v >= b - epsilon: + out.append(v) + v = v + step + return out + return [_coerce(v) for v in s.split(",") if v.strip()] + + +def parse_params_spec(spec: str | None) -> dict[str, list[Any]]: + """Parse ``"k1=v1,v2;k2=a:b:s"`` into ``{"k1": [v1, v2], "k2": [...]}``.""" + if not spec: + return {} + out: dict[str, list[Any]] = {} + for clause in spec.split(";"): + clause = clause.strip() + if not clause: + continue + if "=" not in clause: + raise ValueError(f"Param clause missing '=': {clause!r}") + key, _, values = clause.partition("=") + out[key.strip()] = _expand_values(values.strip()) + return out + + +def cartesian_grid(spec: dict[str, list[Any]]) -> list[dict[str, Any]]: + """Expand ``{"k1": [a, b], "k2": [c]}`` into ``[{"k1": a, "k2": c}, {"k1": b, "k2": c}]``.""" + if not spec: + return [{}] + keys = list(spec.keys()) + return [dict(zip(keys, combo, strict=True)) for combo in itertools.product(*spec.values())] + + +# --------------------------------------------------------------------- # +# Per-video fan-out driver +# --------------------------------------------------------------------- # + + +def _run_chunk( + source_path: Path, + backend: str, + detector_cls: type, + chunk: list[dict[str, Any]], +) -> list[tuple[list[int], float]]: + """Drive one decode of ``source_path`` and fan out to ``len(chunk)`` parallel detectors. + + Returns one ``(cuts, elapsed)`` pair per chunk entry. ``elapsed`` is wall-clock per + worker thread and is bound by the slowest detector in the chunk, so it is only a + rough indicator of relative cost. + """ + source = open_video(source_path, backend=backend) + fan = FanOutVideoStream(source, n=len(chunk)) + fan.start() + results: list[tuple[list[int], float]] = [([], 0.0) for _ in chunk] + errors: list[BaseException | None] = [None] * len(chunk) + + def worker(i: int, params: dict[str, Any]) -> None: + try: + stream = fan.stream(i) + detector = detector_cls(**params) + sm = SceneManager() + sm.add_detector(detector) + t0 = time.time() + sm.detect_scenes(video=stream) + elapsed = time.time() - t0 + cuts = [scene[1].frame_num for scene in sm.get_scene_list()] + results[i] = (cuts, elapsed) + except BaseException as exc: + errors[i] = exc + fan.abort() + + threads = [threading.Thread(target=worker, args=(i, p)) for i, p in enumerate(chunk)] + try: + for t in threads: + t.start() + for t in threads: + t.join() + finally: + fan.close() + + first_err = next((e for e in errors if e is not None), None) + if first_err is not None: + raise first_err + return results + + +def _chunked(items: list, size: int) -> list[list]: + return [items[i : i + size] for i in range(0, len(items), size)] + + +def run_sweep( + dataset: Dataset, + detector_name: str, + backend: str, + grid: list[dict[str, Any]], + workers: int, +) -> list[dict[Path, Prediction]]: + """For each cell in ``grid``, return a ``{video_path: Prediction}`` mapping suitable + for :func:`benchmark.evaluator.evaluate`. Cells are evaluated in chunks of + ``workers`` parallel detectors per video decode.""" + detector_cls = DETECTORS[detector_name] + # predictions_by_cell[cell_index][video_path] = Prediction + predictions_by_cell: list[dict[Path, Prediction]] = [{} for _ in grid] + pbar = tqdm(dataset, desc=f"sweep[{detector_name}]") + for sample in pbar: + for chunk_indices in _chunked(list(range(len(grid))), workers): + chunk = [grid[i] for i in chunk_indices] + outputs = _run_chunk(sample.video_file, backend, detector_cls, chunk) + for cell_i, (cuts, elapsed) in zip(chunk_indices, outputs, strict=True): + predictions_by_cell[cell_i][sample.video_file] = Prediction( + predicted_cuts=cuts, + ground_truth=sample.ground_truth, + elapsed=elapsed, + ) + return predictions_by_cell + + +# --------------------------------------------------------------------- # +# Reporting +# --------------------------------------------------------------------- # + + +def _params_str(params: dict[str, Any]) -> str: + return ", ".join(f"{k}={v}" for k, v in sorted(params.items())) + + +def _f1_for(result: BenchmarkResult) -> float: + return result.hard_cuts.f1 + + +def _print_top_n( + label: str, + cells: list[tuple[dict[str, Any], BenchmarkResult]], + n: int = 10, +) -> None: + ranked = sorted(cells, key=lambda c: _f1_for(c[1]), reverse=True)[:n] + rows = [] + for params, result in ranked: + hard = result.hard_cuts + rows.append( + [ + f"{hard.f1 * 100:.2f}", + f"{hard.precision * 100:.2f}", + f"{hard.recall * 100:.2f}", + _params_str(params), + ] + ) + if not rows: + return + print(f"\n## {label} (top {min(n, len(ranked))})\n") + print(render_table(["F1", "Precision", "Recall", "Params"], rows)) + + +def _pareto_front( + cells_at_tols: dict[int, list[tuple[dict[str, Any], BenchmarkResult]]], +) -> list[tuple[dict[str, Any], dict[int, float]]]: + """Return cells that are not dominated by any other cell across the given tolerances. + + Domination: cell A dominates B if F1@tol(A) >= F1@tol(B) for every tol and strictly + greater on at least one. Identical (P, R) cells coexist on the frontier. + """ + tols = sorted(cells_at_tols.keys()) + if not tols: + return [] + n_cells = len(cells_at_tols[tols[0]]) + # Build a parallel array of (params, {tol: f1}) entries. + table: list[tuple[dict[str, Any], dict[int, float]]] = [] + for i in range(n_cells): + params = cells_at_tols[tols[0]][i][0] + f1s = {t: _f1_for(cells_at_tols[t][i][1]) for t in tols} + table.append((params, f1s)) + frontier: list[tuple[dict[str, Any], dict[int, float]]] = [] + for i, (pi, fi) in enumerate(table): + dominated = False + for j, (_, fj) in enumerate(table): + if i == j: + continue + if all(fj[t] >= fi[t] for t in tols) and any(fj[t] > fi[t] for t in tols): + dominated = True + break + if not dominated: + frontier.append((pi, fi)) + return frontier + + +def _print_pareto( + cells_at_tols: dict[int, list[tuple[dict[str, Any], BenchmarkResult]]], +) -> None: + frontier = _pareto_front(cells_at_tols) + if len(frontier) <= 1: + return + tols = sorted(cells_at_tols.keys()) + header = [*(f"F1@{t}" for t in tols), "Params"] + rows = [ + [*(f"{f1s[t] * 100:.2f}" for t in tols), _params_str(params)] + for params, f1s in sorted(frontier, key=lambda x: -x[1][tols[0]]) + ] + print(f"\n## Pareto frontier ({len(rows)} cells)\n") + print(render_table(header, rows)) + + +# --------------------------------------------------------------------- # +# Entry point +# --------------------------------------------------------------------- # + + +def create_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Sweep detector parameters on a benchmark dataset." + ) + parser.add_argument( + "--dataset", + type=str, + required=True, + choices=list(DATASETS.keys()), + help=f"Dataset name. One of: {', '.join(DATASETS.keys())}.", + ) + parser.add_argument( + "--detector", + type=str, + required=True, + choices=list(DETECTORS.keys()), + help=f"Detector name. One of: {', '.join(DETECTORS.keys())}.", + ) + parser.add_argument( + "--params", + type=str, + default="", + help=( + "Parameter spec. Clauses separated by ';'. Each clause is either " + "'key=v1,v2,...' (enumerated values) or 'key=start:stop:step' (numeric range, " + "inclusive of stop when it lands on a step). Omitted keys use the detector's " + "default. For time-valued kwargs like 'min_scene_len', use floats (seconds) " + "so the sweep is framerate-independent, e.g. " + "'threshold=15:35:1;min_scene_len=0.0:1.0:0.1'." + ), + ) + parser.add_argument( + "--dataset-root", + type=str, + default=None, + help="Base directory containing per-dataset subfolders. Defaults to 'benchmark'.", + ) + parser.add_argument( + "--backend", + type=str, + default=DEFAULT_BACKEND, + choices=sorted(AVAILABLE_BACKENDS.keys()), + help=f"Video decoding backend (default: {DEFAULT_BACKEND}).", + ) + parser.add_argument( + "--tolerance", + type=str, + default="0,1", + help="Comma-separated frame tolerances (default: 0,1).", + ) + parser.add_argument( + "--workers", + type=int, + default=8, + help=( + "Number of detector instances to drive in parallel from a single video decode " + "(default: 8). Cells beyond --workers are processed in subsequent chunks, each " + "re-decoding the source video. Memory grows with --workers * prefetch frames." + ), + ) + parser.add_argument( + "--quick", + type=int, + nargs="?", + const=10, + default=None, + metavar="N", + help="Score only the first N samples for fast iteration.", + ) + parser.add_argument( + "--out", + type=str, + default=None, + help="Path to write a machine-readable JSON sweep file (one entry per cell).", + ) + return parser + + +def main() -> None: + args = create_parser().parse_args() + tolerances = parse_tolerances(args.tolerance) + if not tolerances: + raise SystemExit("--tolerance must yield at least one value.") + if args.workers < 1: + raise SystemExit("--workers must be at least 1.") + + spec = parse_params_spec(args.params) + grid = cartesian_grid(spec) + if not grid: + raise SystemExit("Empty parameter grid.") + + dataset = resolve_dataset(args.dataset, args.dataset_root) + if len(dataset) == 0: + raise SystemExit( + f"Dataset {args.dataset!r} at {args.dataset_root or 'benchmark'} is empty - " + "check that videos and annotations are present." + ) + if args.quick is not None: + dataset._samples = dataset._samples[: args.quick] + print(f"--quick: limited to first {len(dataset)} samples") + + print( + f"Sweeping {args.detector} on {args.dataset}: " + f"{len(grid)} cells x {len(dataset)} videos " + f"(backend={args.backend}, workers={args.workers})" + ) + + predictions_by_cell = run_sweep(dataset, args.detector, args.backend, grid, args.workers) + + # Score every cell at every tolerance. + cells_at_tols: dict[int, list[tuple[dict[str, Any], BenchmarkResult]]] = { + t: [ + (params, evaluate(preds, tolerance=t)) + for params, preds in zip(grid, predictions_by_cell, strict=True) + ] + for t in tolerances + } + + for t in tolerances: + _print_top_n(f"Best by F1 @ tolerance={t}", cells_at_tols[t]) + if len(tolerances) >= 2: + _print_pareto(cells_at_tols) + + if args.out: + payload = { + "detector": args.detector, + "dataset": args.dataset, + "backend": args.backend, + "workers": args.workers, + "spec": args.params, + "cells": [ + { + "params": params, + "results": {str(t): cells_at_tols[t][i][1].to_dict() for t in tolerances}, + } + for i, params in enumerate(grid) + ], + } + write_json(args.out, payload) + + +if __name__ == "__main__": + main() diff --git a/dist/.version_info b/dist/.version_info deleted file mode 100644 index fbae74ad..00000000 --- a/dist/.version_info +++ /dev/null @@ -1,45 +0,0 @@ -# UTF-8 -# -# TODO: Generate this using Python. -# -# For more details about fixed file info 'ffi' see: -# http://msdn.microsoft.com/en-us/library/ms646997.aspx -VSVersionInfo( - ffi=FixedFileInfo( -# filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4) -# Set not needed items to zero 0. -filevers=(0, 6, 1, 0), -prodvers=(0, 6, 1, 0), -# Contains a bitmask that specifies the valid bits 'flags'r -mask=0x3f, -# Contains a bitmask that specifies the Boolean attributes of the file. -flags=0x0, -# The operating system for which this file was designed. -# 0x4 - NT and there is no need to change it. -OS=0x4, -# The general type of file. -# 0x1 - the file is an application. -fileType=0x1, -# The function of the file. -# 0x0 - the function is not defined for this fileType -subtype=0x0, -# Creation date and time stamp. -date=(0, 0) -), - kids=[ -StringFileInfo( - [ - StringTable( - u'040904B0', - [StringStruct(u'CompanyName', u'github.com/Breakthrough'), - StringStruct(u'FileDescription', u'www.scenedetect.com'), - StringStruct(u'FileVersion', u'v0.6.1'), - StringStruct(u'InternalName', u'PySceneDetect'), - StringStruct(u'LegalCopyright', u'Copyright © 2022 Brandon Castellano'), - StringStruct(u'OriginalFilename', u'scenedetect.exe'), - StringStruct(u'ProductName', u'PySceneDetect'), - StringStruct(u'ProductVersion', u'v0.6.1')]) - ]), -VarFileInfo([VarStruct(u'Translation', [1033, 1200])]) - ] -) diff --git a/dist/cleanup_dependencies.py b/dist/cleanup_dependencies.py deleted file mode 100644 index 69e38c18..00000000 --- a/dist/cleanup_dependencies.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -import glob -import os -import shutil - -BASE_PATH = 'dist/scenedetect' - -DIRECTORY_GLOBS = [ - 'altgraph-*.dist-info', - 'certifi', - 'importlib_metadata-*.dist-info', - 'matplotlib', - 'PIL', - 'PyQt5', - 'pip-*.dist-info', - 'psutil', - 'pyinstaller-*.dist-info', - 'setuptools-*.dist-info', - 'tcl8', - 'wheel-*.dist-info', - 'wx', -] - -FILE_GLOBS = [ - '_asyncio.pyd', - '_bz2.pyd', - '_decimal.pyd', - '_elementtree.pyd', - '_hashlib.pyd', - '_lzma.pyd', - '_multiprocessing.pyd', - '_tkinter.pyd', - 'd3dcompiler*.dll', - 'kiwisolver.*.pyd', - 'libEGL.dll', - 'libGLESv2.dll', - 'opengl32sw.dll', - 'Qt5*.dll', - 'wxbase*.dll', - 'wxmsw315u*.dll', -] - -for dir_glob in DIRECTORY_GLOBS: - for dir_path in glob.glob(os.path.join(BASE_PATH, dir_glob)): - shutil.rmtree(dir_path) - -for file_glob in FILE_GLOBS: - for file_path in glob.glob(os.path.join(BASE_PATH, file_glob)): - os.remove(file_path) diff --git a/dist/logo/pyscenedetect-logo-darkmode.svg b/dist/logo/pyscenedetect-logo-darkmode.svg new file mode 100644 index 00000000..333ee5a1 --- /dev/null +++ b/dist/logo/pyscenedetect-logo-darkmode.svg @@ -0,0 +1,247 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + PySceneDetect + + + diff --git a/dist/package-info.rst b/dist/package-info.rst deleted file mode 100644 index 88bc6fb2..00000000 --- a/dist/package-info.rst +++ /dev/null @@ -1,47 +0,0 @@ - -PySceneDetect -========================================================== - -Video Scene Cut Detection and Analysis Tool ----------------------------------------------------------- - -.. image:: https://img.shields.io/travis/com/Breakthrough/PySceneDetect - :target: https://travis-ci.com/github/Breakthrough/PySceneDetect - -.. image:: https://img.shields.io/github/release/Breakthrough/PySceneDetect.svg - :target: https://github.com/Breakthrough/PySceneDetect - -.. image:: https://img.shields.io/pypi/status/scenedetect.svg - :target: https://github.com/Breakthrough/PySceneDetect - -.. image:: https://img.shields.io/pypi/l/scenedetect.svg - :target: http://pyscenedetect.readthedocs.org/en/latest/copyright/ - -.. image:: https://img.shields.io/github/stars/Breakthrough/PySceneDetect.svg?style=social&label=View%20on%20Github - :target: https://github.com/Breakthrough/PySceneDetect - ----------------------------------------------------------- - -Website: http://scenedetect.com/ - -Documentation: http://manual.scenedetect.com/ - -Github Repo: https://github.com/Breakthrough/PySceneDetect/ - ----------------------------------------------------------- - -PySceneDetect is a command-line tool and Python library which analyzes a video, looking for scene changes or cuts. PySceneDetect integrates with external tools (e.g. `mkvmerge`, `ffmpeg`) to automatically split the video into individual clips when using the `split-video` command. A frame-by-frame analysis can also be generated for a video, called a stats file, to help with determining optimal threshold values or detecting patterns/other analysis methods for a particular video. - -There are two main detection methods PySceneDetect uses: `detect-threshold` (comparing each frame to a set black level, useful for detecting cuts and fades to/from black), and `detect-content` (compares each frame sequentially looking for changes in content, useful for detecting fast cuts between video scenes, although slower to process). Each mode has slightly different parameters, and is described in detail in the documentation. - -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-content` mode. Once you know what detection mode to use, you can try the parameters recommended below, or generate a statistics file (using the `-s` / `--stats` argument) in order to determine the correct paramters - specifically, the proper threshold value. - -For help or other issues, feel free to submit any bugs or feature requests to Github: https://github.com/Breakthrough/PySceneDetect/issues - ----------------------------------------------------------- - -Licensed under BSD 3-Clause (see the `LICENSE` file for details). - -Copyright (C) 2014-2022 Brandon Castellano. -All rights reserved. - diff --git a/dist/pyscenedetect.ico b/dist/pyscenedetect.ico deleted file mode 100644 index b52baa83..00000000 Binary files a/dist/pyscenedetect.ico and /dev/null differ diff --git a/dist/requirements_windows.txt b/dist/requirements_windows.txt deleted file mode 100644 index 39114d7b..00000000 --- a/dist/requirements_windows.txt +++ /dev/null @@ -1,13 +0,0 @@ -# -# PySceneDetect Requirements for Windows Build (Python 3.7+) -# -# These are pinned to the versions required for the Windows build to work -# using pyinstaller. If you are installing PySceneDetect directly as a Python -# distribution (e.g. via pip or setup.py), use requirements.txt instead. -appdirs -av==9.2.0 -click -numpy -opencv-python-headless==4.5.1.48 -pytest -tqdm diff --git a/dist/scenedetect.spec b/dist/scenedetect.spec deleted file mode 100644 index e5e07953..00000000 --- a/dist/scenedetect.spec +++ /dev/null @@ -1,42 +0,0 @@ -# -*- mode: python -*- - -block_cipher = None - - -a = Analysis(['../scenedetect/__main__.py'], - pathex=['.'], - binaries=None, - datas=[ - ('windows/*', '.'), - ('../*.md', '.'), - ('../LICENSE', '.'), - ('../docs/', 'docs/'), - ('../scenedetect.cfg', '.') - ], - hiddenimports=[], - hookspath=[], - runtime_hooks=[], - excludes=[], - win_no_prefer_redirects=False, - win_private_assemblies=False, - cipher=block_cipher) - -pyz = PYZ(a.pure, a.zipped_data, - cipher=block_cipher) -exe = EXE(pyz, - a.scripts, - exclude_binaries=True, - name='scenedetect', - debug=False, - strip=False, - upx=True, - console=True, - version='.version_info', - icon='pyscenedetect.ico') -coll = COLLECT(exe, - a.binaries, - a.zipfiles, - a.datas, - strip=False, - upx=True, - name='scenedetect') diff --git a/dist/windows/LICENSE-FFMPEG b/dist/windows/LICENSE-FFMPEG deleted file mode 100644 index 0a38f15c..00000000 --- a/dist/windows/LICENSE-FFMPEG +++ /dev/null @@ -1,692 +0,0 @@ - -Copyright (C) 2018 Kyle Schwarz - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . - - - - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/dist/windows/LICENSE-MKVMERGE b/dist/windows/LICENSE-MKVMERGE deleted file mode 100644 index d159169d..00000000 --- a/dist/windows/LICENSE-MKVMERGE +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/docs/LATEST_VERSION b/docs/LATEST_VERSION new file mode 100644 index 00000000..7deb86fe --- /dev/null +++ b/docs/LATEST_VERSION @@ -0,0 +1 @@ +0.7.1 \ No newline at end of file diff --git a/manual/Makefile b/docs/Makefile similarity index 100% rename from manual/Makefile rename to docs/Makefile diff --git a/docs/_static/favicon.ico b/docs/_static/favicon.ico new file mode 100644 index 00000000..bf8cbf10 Binary files /dev/null and b/docs/_static/favicon.ico differ diff --git a/manual/_static/pyscenedetect.css b/docs/_static/pyscenedetect.css similarity index 100% rename from manual/_static/pyscenedetect.css rename to docs/_static/pyscenedetect.css diff --git a/docs/_static/pyscenedetect_logo.png b/docs/_static/pyscenedetect_logo.png new file mode 100644 index 00000000..26cb1b24 Binary files /dev/null and b/docs/_static/pyscenedetect_logo.png differ diff --git a/docs/_static/pyscenedetect_logo_small.png b/docs/_static/pyscenedetect_logo_small.png new file mode 100644 index 00000000..a0180fb9 Binary files /dev/null and b/docs/_static/pyscenedetect_logo_small.png differ diff --git a/docs/_templates/navigation.html b/docs/_templates/navigation.html new file mode 100644 index 00000000..4493c591 --- /dev/null +++ b/docs/_templates/navigation.html @@ -0,0 +1,10 @@ +

{{ _('Navigation') }}

+{{ toctree(maxdepth=2, includehidden=theme_sidebar_includehidden, collapse=theme_sidebar_collapse) }} +{% if theme_extra_nav_links %} +
+
    + {% for text, uri in theme_extra_nav_links.items() %} +
  • {{ text }}
  • + {% endfor %} +
+{% endif %} \ No newline at end of file diff --git a/docs/api.rst b/docs/api.rst new file mode 100644 index 00000000..650975b4 --- /dev/null +++ b/docs/api.rst @@ -0,0 +1,106 @@ + +*********************************************************************** +``scenedetect`` 🎬 Package +*********************************************************************** + +The `scenedetect` API is easy to integrate with most application workflows, while also being highly extensible. See the `Getting Started`_ section below for some common use cases and integrations. The `scenedetect` package is organized into several sub-modules: + + * :ref:`scenedetect 🎬 `: high-level functions like :func:`scenedetect.detect() ` to quickly analyze a video with any :ref:`detection algorithm ` (:ref:`example `) and get a list of timecode pairs as a result + + * :ref:`scenedetect.detectors 🕵️ `: detection algorithms: + + * :class:`AdaptiveDetector `: finds fast cuts using rolling average of HSL changes + + * :class:`ContentDetector `: detects fast cuts using weighted average of HSV changes + + * :class:`ThresholdDetector `: finds fades in/out using average pixel intensity changes in RGB + + * :class:`HistogramDetector `: finds fast cuts using HSV histogram changes + + * :class:`HashDetector `: finds fast cuts using perceptual image hashing + + * :ref:`scenedetect.output ✂️ `: Output formats: + + * :func:`split_video_ffmpeg ` and :func:`split_video_mkvmerge ` split a video based on the detected scenes + + * :func:`save_images ` can save an arbitrary number of images from each scene + + * :func:`write_scene_list ` can be used to save scene/cut info as CSV, :func:`write_scene_list_html ` for HTML + + * :ref:`scenedetect.backends 🎥 `: PySceneDetect supports multiple libraries as an input backend: + + * OpenCV: :class:`VideoStreamCv2 ` + + * PyAV: :class:`VideoStreamAv ` + + * MoviePy: :class:`VideoStreamMoviePy ` + + * Multiple videos can be treated as a single continuous stream using :class:`VideoStreamConcat ` (e.g. ``open_video(["part1.mp4", "part2.mp4"])``) + + * :ref:`scenedetect.common ⏱️ `: common functionality such as :class:`FrameTimecode ` for timecode handling + + * :ref:`scenedetect.scene_manager 🎞️ `: the :class:`SceneManager ` coordinates performing scene detection on a video with one or more detectors + + * :ref:`scenedetect.detector 🌐 `: the interface (:class:`SceneDetector `) that detectors must implement to be compatible with PySceneDetect + + * :ref:`scenedetect.video_stream 📹 `: the interface (:class:`VideoStream `) that video backends must implement to be compatible with PySceneDetect + + * :ref:`scenedetect.stats_manager 🧮 `: the :class:`StatsManager ` allows you to store detection metrics for each frame and save them to CSV for further analysis + + * :ref:`scenedetect.platform 🐱‍💻 `: logging and utility functions + + +Most types/functions are also available directly from the `scenedetect` package to make imports simpler. + +.. warning:: + + The PySceneDetect API is still under development. It is recommended that you pin the `scenedetect` version in your requirements to below the next major release: + + .. code:: python + + scenedetect~=0.7 + + +.. _scenedetect-quickstart: + +======================================================================= +Getting Started +======================================================================= + +PySceneDetect makes it very easy to find scene transitions in a video with the :func:`scenedetect.detect` function: + +.. code:: python + + from scenedetect import detect, ContentDetector + path = "video.mp4" + scenes = detect(path, ContentDetector()) + for (scene_start, scene_end) in scenes: + print(f"{scene_start}-{scene_end}") + +``scenes`` now contains a list of :class:`FrameTimecode ` pairs representing the start/end of each scene. Note that you can set ``show_progress=True`` when calling :func:`detect ` to display a progress bar with estimated time remaining. + +Here, we use :mod:`ContentDetector ` to detect fast cuts. There are :ref:`many detector types ` which can be used to find fast cuts and fades in/out. PySceneDetect can also export scene data in various formats, and can :ref:`split the input video ` automatically if `ffmpeg` is available: + +.. code:: python + + from scenedetect import detect, ContentDetector, split_video_ffmpeg + scene_list = detect("my_video.mp4", ContentDetector()) + split_video_ffmpeg("my_video.mp4", scenes) + +Recipes for common use cases can be `found on Github `_ including limiting detection time and storing per-frame metrics. For advanced workflows, start with the :ref:`SceneManager usage examples `. + +.. _scenedetect-functions: + +======================================================================= +Functions +======================================================================= + +.. automodule:: scenedetect + :members: + + +======================================================================= +Logging +======================================================================= + +PySceneDetect outputs messages to a logger named ``pyscenedetect`` which does not have any default handlers. You can use :func:`scenedetect.init_logger ` with ``show_stdout=True`` or specify a log file (verbosity can also be specified) to attach some common handlers, or use ``logging.getLogger("pyscenedetect")`` and attach log handlers manually. diff --git a/docs/api/backends.rst b/docs/api/backends.rst new file mode 100644 index 00000000..8ba7d47c --- /dev/null +++ b/docs/api/backends.rst @@ -0,0 +1,21 @@ + +.. _scenedetect-backends: + +-------------- +Video Backends +-------------- + +.. automodule:: scenedetect.backends + :members: + +.. automodule:: scenedetect.backends.opencv + :members: + +.. automodule:: scenedetect.backends.pyav + :members: + +.. automodule:: scenedetect.backends.moviepy + :members: + +.. automodule:: scenedetect.backends.concat + :members: diff --git a/docs/api/common.rst b/docs/api/common.rst new file mode 100644 index 00000000..55cb8310 --- /dev/null +++ b/docs/api/common.rst @@ -0,0 +1,9 @@ + +.. _scenedetect-common: + +------ +Common +------ + +.. automodule:: scenedetect.common + :members: diff --git a/docs/api/detector.rst b/docs/api/detector.rst new file mode 100644 index 00000000..97b06d3b --- /dev/null +++ b/docs/api/detector.rst @@ -0,0 +1,9 @@ + +.. _scenedetect-detector: + +------------------ +Detector Interface +------------------ + +.. automodule:: scenedetect.detector + :members: diff --git a/docs/api/detectors.rst b/docs/api/detectors.rst new file mode 100644 index 00000000..5fbe7ff2 --- /dev/null +++ b/docs/api/detectors.rst @@ -0,0 +1,53 @@ + +.. _scenedetect-detectors: + +--------- +Detectors +--------- + +.. automodule:: scenedetect.detectors + +AdaptiveDetector +================ + +.. automodule:: scenedetect.detectors.adaptive_detector + :no-members: + +.. autoclass:: scenedetect.detectors.adaptive_detector.AdaptiveDetector + :members: + +ContentDetector +=============== + +.. automodule:: scenedetect.detectors.content_detector + :no-members: + +.. autoclass:: scenedetect.detectors.content_detector.ContentDetector + :members: + +HashDetector +============ + +.. automodule:: scenedetect.detectors.hash_detector + :no-members: + +.. autoclass:: scenedetect.detectors.hash_detector.HashDetector + :members: + +HistogramDetector +================= + +.. automodule:: scenedetect.detectors.histogram_detector + :no-members: + +.. autoclass:: scenedetect.detectors.histogram_detector.HistogramDetector + :members: + +ThresholdDetector +================= + +.. automodule:: scenedetect.detectors.threshold_detector + :no-members: + +.. autoclass:: scenedetect.detectors.threshold_detector.ThresholdDetector + :members: diff --git a/docs/api/migration_guide.rst b/docs/api/migration_guide.rst new file mode 100644 index 00000000..b481ebff --- /dev/null +++ b/docs/api/migration_guide.rst @@ -0,0 +1,290 @@ + +.. _scenedetect-migration-guide: + +*********************************************************************** +Migration Guide (v0.7) +*********************************************************************** + +PySceneDetect v0.7 is a major release that overhauls timestamp handling to support variable framerate (VFR) videos. While the high-level :func:`scenedetect.detect` workflow is largely unchanged, several internal APIs have been restructured. This guide covers the changes needed to update applications from v0.6 to v0.7. + +The minimum supported Python version is now **Python 3.10**. + + +======================================================================= +Quick Check +======================================================================= + +If your code only uses :func:`scenedetect.detect` with a built-in detector, it should work without changes: + +.. code:: python + + # This still works in v0.7 + from scenedetect import detect, ContentDetector + scenes = detect("video.mp4", ContentDetector()) + + +======================================================================= +Import Changes +======================================================================= + +Several submodules have been reorganized. If you import directly from `scenedetect` you do not need to make any changes. Update imports as follows: + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - v0.6 + - v0.7 + * - ``from scenedetect.frame_timecode import FrameTimecode`` + - ``from scenedetect.common import FrameTimecode`` + * - ``from scenedetect.scene_detector import SceneDetector`` + - ``from scenedetect.detector import SceneDetector`` + * - ``from scenedetect.video_splitter import split_video_ffmpeg`` + - ``from scenedetect.output import split_video_ffmpeg`` + * - ``from scenedetect.video_splitter import split_video_mkvmerge`` + - ``from scenedetect.output import split_video_mkvmerge`` + * - ``from scenedetect.scene_manager import save_images`` + - ``from scenedetect.output import save_images`` + * - ``from scenedetect.scene_manager import write_scene_list`` + - ``from scenedetect.output import write_scene_list`` + * - ``from scenedetect.scene_manager import write_scene_list_html`` + - ``from scenedetect.output import write_scene_list_html`` + * - ``from scenedetect.video_manager import VideoManager`` + - Removed. Use :func:`scenedetect.open_video` instead. + +.. note:: + + Most commonly used types and functions are also available directly from the top-level ``scenedetect`` package (e.g. ``from scenedetect import FrameTimecode``), which has not changed. + +.. note:: + + The ``frame_timecode``, ``scene_detector``, and ``video_splitter`` submodules emit a ``DeprecationWarning`` when imported directly. The ``save_images``, ``write_scene_list``, and ``write_scene_list_html`` re-exports from ``scenedetect.scene_manager`` continue to work silently in v0.7 but **will be removed in v0.8**. Import these symbols from ``scenedetect`` directly to avoid breakage. + + +======================================================================= +Custom Detector Changes +======================================================================= + +If you have written a custom :class:`SceneDetector ` subclass, there are several interface changes. + +``process_frame`` Signature +----------------------------------------------------------------------- + +The ``frame_num`` parameter (``int``) has been replaced with ``timecode`` (:class:`FrameTimecode `): + +.. code:: python + + # v0.6 + class MyDetector(SceneDetector): + def process_frame(self, frame_num: int, frame_img) -> List[int]: + ... + + # v0.7 + class MyDetector(SceneDetector): + def process_frame(self, timecode: FrameTimecode, frame_img) -> List[FrameTimecode]: + ... + +The same change applies to ``post_process()``. Using units of time instead of frame numbers is critical for temporal accuracy. If you need the frame number, use ``timecode.frame_num`` to the timecode to an integer. + +``SceneDetector`` is Now Abstract +----------------------------------------------------------------------- + +``SceneDetector`` is now a Python `abstract class `_. Subclasses **must** implement ``process_frame()``. + +Removed Methods and Properties +----------------------------------------------------------------------- + +The following have been removed from the ``SceneDetector`` interface: + +- ``is_processing_required()`` - detectors can now assume they always have frame data +- ``stats_manager_required`` property - no longer needed +- ``SparseSceneDetector`` interface - removed entirely + + +======================================================================= +``FrameTimecode`` Changes +======================================================================= + +Read-Only Properties +----------------------------------------------------------------------- + +:attr:`~scenedetect.common.FrameTimecode.frame_num` and :attr:`~scenedetect.common.FrameTimecode.frame_rate` are now read-only properties. To change them, construct a new ``FrameTimecode``: + +.. code:: python + + tc = FrameTimecode(0, 24.0) + # Can no longer reassign frame_num, must create a new FrameTimecode instead: + #tc.frame_num = 100 + tc = FrameTimecode(100, tc) + +New Properties +----------------------------------------------------------------------- + +Access :attr:`~scenedetect.common.FrameTimecode.frame_num`, :attr:`~scenedetect.common.FrameTimecode.frame_rate`, and :attr:`~scenedetect.common.FrameTimecode.seconds` as properties instead of getter methods. The new :attr:`~scenedetect.common.FrameTimecode.frame_rate` property returns an exact :class:`fractions.Fraction` and matches :attr:`~scenedetect.video_stream.VideoStream.frame_rate`: + +.. code:: python + + from fractions import Fraction + tc = FrameTimecode(100, 29.97) + tc.frame_num # 100 + tc.frame_rate # Fraction(30000, 1001) (exact) + tc.time_base # Fraction(1001, 30000) + tc.seconds # ~3.337 + +``time_base`` equals ``1 / frame_rate`` for CFR sources. For VFR (``Timecode``-backed) instances, ``time_base`` is authoritative and ``frame_rate`` is an approximation. + +``Fraction`` participates in numeric arithmetic and comparisons just like ``float``, and converts implicitly when mixed with floats (the result is a ``float``). When a ``float`` is explicitly required (e.g. format specifiers, ``json.dumps``, ``isinstance(x, float)`` checks) wrap the value with ``float(...)``: + +.. code:: python + + rate = tc.frame_rate # Fraction(30000, 1001) + rate * 2 # Fraction(60000, 1001) + rate > 24 # True + rate * 0.5 # 14.985... (float, mixed arithmetic) + f"{float(rate):.3f}" # '29.970' (explicit cast for format spec) + +The legacy ``framerate`` property (one word, returns ``float``) is retained as a deprecated alias and will emit a ``DeprecationWarning`` in a future release. Migrate to ``frame_rate``; cast with ``float(...)`` at the call site if you specifically need a ``float``. + +Renamed Method: ``equal_framerate()`` +----------------------------------------------------------------------- + +:meth:`~scenedetect.common.FrameTimecode.equal_framerate` has been renamed to :meth:`~scenedetect.common.FrameTimecode.equal_frame_rate` for consistency with the :attr:`~scenedetect.common.FrameTimecode.frame_rate` property. The legacy ``equal_framerate()`` method is retained as a deprecated alias and will emit a ``DeprecationWarning`` in a future release. The new form additionally accepts a ``Fraction`` or another ``FrameTimecode`` (in addition to ``float``). + +Removed Methods +----------------------------------------------------------------------- + +- ``previous_frame()`` - removed, use ``FrameTimecode(tc.frame_num - 1, tc)`` instead (passing a ``FrameTimecode`` as the ``fps`` argument reuses its rate) + + +======================================================================= +Framerate and Timestamp Changes +======================================================================= + +Rational Framerates +----------------------------------------------------------------------- + +:attr:`~scenedetect.video_stream.VideoStream.frame_rate` now returns a ``Fraction`` instead of ``float``. Common NTSC rates (23.976, 29.97, 59.94) are automatically detected from float values: + +.. code:: python + + from fractions import Fraction + video = open_video("video.mp4") + assert isinstance(video.frame_rate, Fraction) + # e.g. Fraction(24000, 1001) instead of 23.976023976... + +``frame_rate`` Keyword Argument +----------------------------------------------------------------------- + +The ``framerate`` keyword argument has been renamed to ``frame_rate`` on :func:`~scenedetect.open_video` and on every backend constructor (:class:`~scenedetect.backends.opencv.VideoStreamCv2`, :class:`~scenedetect.backends.opencv.VideoCaptureAdapter`, :class:`~scenedetect.backends.pyav.VideoStreamAv`, :class:`~scenedetect.backends.moviepy.VideoStreamMoviePy`). The new form accepts ``float | Fraction | None``. The legacy ``framerate`` keyword is retained as a deprecated alias and will emit a ``DeprecationWarning`` in a future release; if both are supplied, ``frame_rate`` takes precedence. + +.. code:: python + + # v0.6 - will still work but will be removed in a future version + video = open_video("video.mp4", framerate=30.0) + + # v0.7 + video = open_video("video.mp4", frame_rate=30.0) + +PTS-Backed Timestamps +----------------------------------------------------------------------- + +All backends now return presentation timestamp (PTS) backed values from :attr:`~scenedetect.video_stream.VideoStream.position`. This enables correct handling of VFR videos. + +``FrameTimecode`` has new :attr:`~scenedetect.common.FrameTimecode.time_base` and :attr:`~scenedetect.common.FrameTimecode.pts` properties for accessing the underlying timing information. For VFR videos, :attr:`~scenedetect.common.FrameTimecode.frame_num` is now an approximation based on PTS-derived time rather than a sequential count. + + +======================================================================= +``StatsManager`` Changes +======================================================================= + +The ``StatsManager`` methods :meth:`~scenedetect.stats_manager.StatsManager.get_metrics`, :meth:`~scenedetect.stats_manager.StatsManager.set_metrics`, and :meth:`~scenedetect.stats_manager.StatsManager.metrics_exist` now formally accept either a ``FrameTimecode`` or a plain ``int`` frame number for the timecode argument. Passing a ``FrameTimecode`` is preferred and matches the detector interface; the ``int`` form is retained for compatibility with the deprecated ``load_from_csv()`` path, which keys metrics by integer frame number. + +``StatsManager.load_from_csv()`` also accepts ``os.PathLike`` (e.g. ``pathlib.Path``) in addition to ``str`` / ``bytes`` / file handles. + + +======================================================================= +``SceneDetector`` Annotation Fixes +======================================================================= + +:meth:`~scenedetect.detector.SceneDetector.post_process` now declares its parameter as ``timecode: FrameTimecode`` (previously typed as ``int``). The method already received a ``FrameTimecode`` at runtime and concrete detectors (e.g. ``ThresholdDetector``, ``ContentDetector``) already used the ``FrameTimecode`` type - only the abstract-base-class annotation was inconsistent. No call-site changes are needed; this just brings the signature into agreement with the documented and actual behavior. + + +======================================================================= +``SceneManager.detect_scenes()`` Time Arguments +======================================================================= + +The ``duration`` and ``end_time`` arguments of :meth:`~scenedetect.scene_manager.SceneManager.detect_scenes` now formally accept ``int`` (frames), ``float`` (seconds), ``str`` (timecode string, e.g. ``"00:00:05.000"``), or ``FrameTimecode``. The internal code already validated these forms; the annotation was previously narrower than the documented behavior. + +.. code:: python + + # All of these were always supported at runtime; now they type-check too: + scene_manager.detect_scenes(video, end_time=15.0) # seconds + scene_manager.detect_scenes(video, end_time=1500) # frames + scene_manager.detect_scenes(video, end_time="00:01:00") # timecode + + +======================================================================= +``save_images()`` Path Handling +======================================================================= + +The ``output_dir`` argument of :func:`scenedetect.output.save_images` now accepts ``os.PathLike`` (e.g. ``pathlib.Path``) in addition to ``str``. No changes are required for existing string-based callers. + + +======================================================================= +Removed APIs +======================================================================= + +The following deprecated APIs have been fully removed in v0.7: + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Removed + - Replacement + * - ``scenedetect.video_manager`` module + - :func:`scenedetect.open_video` + * - ``base_timecode`` parameter (various functions) + - No longer needed, remove the argument + * - ``video_manager`` parameter (various functions) + - Use ``video`` parameter instead + * - ``SceneManager.get_event_list()`` + - Use :meth:`~scenedetect.scene_manager.SceneManager.get_cut_list` or :meth:`~scenedetect.scene_manager.SceneManager.get_scene_list` + * - ``AdaptiveDetector.get_content_val()`` + - Use ``StatsManager`` to query metrics + * - ``AdaptiveDetector(min_delta_hsv=...)`` + - Use ``min_content_val`` parameter instead + * - ``VideoStream.read(advance=...)`` + - Call ``read()`` without the ``advance`` parameter + * - ``SparseSceneDetector`` + - No direct replacement, use ``SceneDetector`` + +.. note:: + + Deprecated v0.6 compatibility shims that still exist now emit warnings using the ``warnings`` module. Address any ``DeprecationWarning`` messages to prepare for future releases. + + +======================================================================= +CLI Changes +======================================================================= + +Removed / Renamed +----------------------------------------------------------------------- + +- The ``-d``/``--min-delta-hsv`` option on ``detect-adaptive`` has been removed. Use ``-c``/``--min-content-val`` instead. +- The global ``--framerate`` flag has been renamed to ``-f``/``--frame-rate`` for consistency with the API. The legacy ``--framerate`` form is retained as a hidden alias and will be removed in v0.8; if both are supplied, ``--frame-rate`` takes precedence and a warning is logged. +- The ``export-html`` command has been renamed to :ref:`save-html `. The legacy ``export-html`` command is retained as a deprecated alias and emits a deprecation warning when used. + +New Commands and Options +----------------------------------------------------------------------- + +- New :ref:`save-fcp ` command exports scenes in Final Cut Pro XML format (FCP7/FCPX). +- New :ref:`save-qp ` command writes a QP file with scene boundary frame numbers, suitable for forcing keyframes at scene cuts in x264/x265. +- New :ref:`save-html ` command (replaces ``export-html``). +- New ``-s``/``--start-timecode`` option on :ref:`save-edl ` provides a custom start timecode for generated EDLs (SMPTE ``HH:MM:SS:FF`` or 8-digit ``HHMMSSFF``). + +Other Changes +----------------------------------------------------------------------- + +- VFR videos now work correctly with both the OpenCV and PyAV backends. +- All CLI options that previously accepted only frame numbers now also accept seconds (e.g. ``0.6s``) and timecodes (e.g. ``00:00:00.600``). diff --git a/docs/api/output.rst b/docs/api/output.rst new file mode 100644 index 00000000..6c3abb37 --- /dev/null +++ b/docs/api/output.rst @@ -0,0 +1,9 @@ + +.. _scenedetect-output: + +------ +Output +------ + +.. automodule:: scenedetect.output + :members: diff --git a/docs/api/platform.rst b/docs/api/platform.rst new file mode 100644 index 00000000..134fa2d1 --- /dev/null +++ b/docs/api/platform.rst @@ -0,0 +1,9 @@ + +.. _scenedetect-platform: + +------------------ +Platform & Logging +------------------ + +.. automodule:: scenedetect.platform + :members: diff --git a/docs/api/scene_manager.rst b/docs/api/scene_manager.rst new file mode 100644 index 00000000..2a0ee6a3 --- /dev/null +++ b/docs/api/scene_manager.rst @@ -0,0 +1,9 @@ + +.. _scenedetect-scene_manager: + +------------- +Scene Manager +------------- + +.. automodule:: scenedetect.scene_manager + :members: diff --git a/docs/api/stats_manager.rst b/docs/api/stats_manager.rst new file mode 100644 index 00000000..5f96dec0 --- /dev/null +++ b/docs/api/stats_manager.rst @@ -0,0 +1,9 @@ + +.. _scenedetect-stats_manager: + +------------- +Stats Manager +------------- + +.. automodule:: scenedetect.stats_manager + :members: diff --git a/docs/api/video_stream.rst b/docs/api/video_stream.rst new file mode 100644 index 00000000..a090d6d9 --- /dev/null +++ b/docs/api/video_stream.rst @@ -0,0 +1,9 @@ + +.. _scenedetect-video_stream: + +---------------- +Stream Interface +---------------- + +.. automodule:: scenedetect.video_stream + :members: diff --git a/docs/cli.rst b/docs/cli.rst new file mode 100644 index 00000000..b145a112 --- /dev/null +++ b/docs/cli.rst @@ -0,0 +1,909 @@ +.. NOTE: This file is auto-generated by docs/generate_cli_docs.py and should not be modified. + +************************************************************************ +``scenedetect`` 🎬 Command +************************************************************************ + + +.. _command-scenedetect: + +.. program:: scenedetect + +PySceneDetect is a scene cut/transition detection program. PySceneDetect takes an input video, runs detection on it, and uses the resulting scene information to generate output. The syntax for using PySceneDetect is: + + ``scenedetect -i video.mp4 [detector] [commands]`` + +For [detector] use :ref:`detect-adaptive ` or :ref:`detect-content ` to find fast cuts, and :ref:`detect-threshold ` for fades in/out. If [detector] is not specified, a default detector will be used. + + +************************************************************************ +Examples +************************************************************************ + + +Split video wherever a new scene is detected: + + ``scenedetect -i video.mp4 split-video`` + +Save scene list in CSV format with images at the start, middle, and end of each scene: + + ``scenedetect -i video.mp4 list-scenes save-images`` + +Skip the first 10 seconds of the input video: + + ``scenedetect -i video.mp4 time --start 10s detect-content`` + +Show summary of all options and commands: + + ``scenedetect --help`` + +Global options (e.g. :option:`-i/--input <-i>`, :option:`-c/--config <-c>`) must be specified before any commands and their options. The order of commands is not strict, but each command must only be specified once. + + +************************************************************************ +Options +************************************************************************ + + +.. option:: -i VIDEO, --input VIDEO + + [REQUIRED] Input video file. Image sequences and URLs are supported. + +.. option:: -o DIR, --output DIR + + Output directory for created files. If unset, working directory will be used. May be overridden by command options. + +.. option:: -c FILE, --config FILE + + Path to config file. See :ref:`config file reference ` for details. + +.. option:: -s CSV, --stats CSV + + Stats file (.csv) to write frame metrics. Existing files will be overwritten. Used for tuning detection parameters and data analysis. + +.. option:: -f FPS, --frame-rate FPS + + Override frame rate with value as frames/sec. + +.. option:: --framerate FPS + + Alias of :option:`-f/--frame-rate <-f>`. + +.. option:: -m TIMECODE, --min-scene-len TIMECODE + + Minimum length of any scene. TIMECODE can be specified as number of frames (-m 10), time in seconds (-m 2.5), or timecode (-m 00:02:53.633). + + Default: ``0.6s`` + +.. option:: --drop-short-scenes + + Drop scenes shorter than :option:`-m/--min-scene-len <-m>`, instead of combining with neighbors. + +.. option:: --merge-last-scene + + Merge last scene with previous if shorter than :option:`-m/--min-scene-len <-m>`. + +.. option:: -b BACKEND, --backend BACKEND + + Backend to use for video input. Backend options can be set using a config file (:option:`-c/--config <-c>`). [available: opencv, pyav, moviepy] + + Default: ``opencv`` + +.. option:: --crop X0 Y0 X1 Y1 + + Crop input video. Specified as two points representing top left and bottom right corner of crop region. 0 0 is top-left of the video frame. Bounds are inclusive (e.g. for a 100x100 video, the region covering the whole frame is 0 0 99 99). + +.. option:: -d N, --downscale N + + Integer factor to downscale video by before processing. If unset, value is selected based on resolution. Set -d 1 to disable downscaling. + +.. option:: -fs N, --frame-skip N + + Skip N frames during processing. Reduces processing speed at expense of accuracy. -fs 1 skips every other frame processing 50% of the video, -fs 2 processes 33% of the video frames, -fs 3 processes 25%, etc... + + Default: ``0`` + +.. option:: -v LEVEL, --verbosity LEVEL + + Amount of information to show. LEVEL must be one of: debug, info, warning, error, none. Overrides :option:`-q/--quiet <-q>`. + + Default: ``info`` + +.. option:: -l FILE, --logfile FILE + + Save debug log to FILE. Appends to existing file if present. + +.. option:: -q, --quiet + + Suppress output to terminal/stdout. Equivalent to setting :option:`--verbosity=none <--verbosity>`. + + +.. _command-help: + +``help``, ``version``, and ``about`` +======================================================================= + +.. program:: scenedetect help + +``scenedetect --help`` will print PySceneDetect options, commands, and examples. You can also specify: + + * ``scenedetect [command] --help`` to show options and examples *for* a command or detector + + * ``scenedetect help`` command to print full reference of all options, commands, and examples + +.. program:: scenedetect version + +``scenedetect version`` prints the version of PySceneDetect that is installed, as well as system dependencies. + +.. program:: scenedetect about + +``scenedetect about`` prints PySceneDetect copyright, licensing, and redistribution information. This includes a list of all third-party software components that PySceneDetect uses or interacts with, as well as a reference to the license and copyright information for each component. + +************************************************************************ +Detectors +************************************************************************ + + +.. _command-detect-adaptive: + +.. program:: scenedetect detect-adaptive + + +``detect-adaptive`` +======================================================================== + +Find fast cuts using diffs in HSL colorspace (rolling average). + +Two-pass algorithm that first calculates frame scores with :ref:`detect-content `, and then applies a rolling average when processing the result. This can help mitigate false detections in situations such as camera movement. + + +Examples +------------------------------------------------------------------------ + + + ``scenedetect -i video.mp4 detect-adaptive`` + + ``scenedetect -i video.mp4 detect-adaptive --threshold 3.2`` + + +Options +------------------------------------------------------------------------ + + +.. option:: -t VAL, --threshold VAL + + Threshold (float) that frame score must exceed to trigger a cut. Refers to "adaptive_ratio" in stats file. + + Default: ``3.0`` + +.. option:: -c VAL, --min-content-val VAL + + Minimum threshold (float) that "content_val" must exceed to trigger a cut. + + Default: ``15.0`` + +.. option:: -f VAL, --frame-window VAL + + Size of window to detect deviations from mean. Represents how many frames before/after the current one to use for mean. + + Default: ``2`` + +.. option:: -w, --weights + + Weights of 4 components ("delta_hue", "delta_sat", "delta_lum", "delta_edges") used to calculate "content_val". + + Default: ``1.000, 1.000, 1.000, 0.000`` + +.. option:: -l, --luma-only + + Only use luma (brightness) channel. Useful for greyscale videos. Equivalent to "--weights 0 0 1 0". + +.. option:: -k N, --kernel-size N + + Size of kernel for expanding detected edges. Must be odd number >= 3. If unset, size is estimated using video resolution. + + Default: ``auto`` + +.. option:: -m TIMECODE, --min-scene-len TIMECODE + + Minimum length of any scene. Overrides global option :option:`-m/--min-scene-len `. TIMECODE can be specified in frames (-m 100), in seconds with `s` suffix (-m 3.5s), or timecode (-m 00:01:52.778). + + +.. _command-detect-content: + +.. program:: scenedetect detect-content + + +``detect-content`` +======================================================================== + +Find fast cuts using differences in HSL (filtered). + +For each frame, a score from 0 to 255.0 is calculated which represents the difference in content between the current and previous frame (higher = more different). A cut is generated when a frame score exceeds :option:`-t/--threshold <-t>`. Frame scores are saved under the "content_val" column in a statsfile. + +Scores are calculated from several components which are also recorded in the statsfile: + + - *delta_hue*: Difference between pixel hue values of adjacent frames. + + - *delta_sat*: Difference between pixel saturation values of adjacent frames. + + - *delta_lum*: Difference between pixel luma (brightness) values of adjacent frames. + + - *delta_edges*: Difference between calculated edges of adjacent frames. Typically larger than other components, so threshold may need to be increased to compensate. + +Once calculated, these components are multiplied by the specified :option:`-w/--weights <-w>` to calculate the final frame score ("content_val"). Weights are set as a set of 4 numbers in the form (*delta_hue*, *delta_sat*, *delta_lum*, *delta_edges*). For example, "--weights 1.0 0.5 1.0 0.2 --threshold 32" is a good starting point for trying edge detection. The final sum is normalized by the weight of all components, so they need not equal 100%. Edge detection is disabled by default to improve performance. + + +Examples +------------------------------------------------------------------------ + + + ``scenedetect -i video.mp4 detect-content`` + + ``scenedetect -i video.mp4 detect-content --threshold 27.5`` + + +Options +------------------------------------------------------------------------ + + +.. option:: -t VAL, --threshold VAL + + The max difference (0.0 to 255.0) that adjacent frames score must exceed to trigger a cut. Lower values are more sensitive to shot changes. Refers to "content_val" in stats file. + + Default: ``27.0`` + +.. option:: -w HUE SAT LUM EDGE, --weights HUE SAT LUM EDGE + + Weights of 4 components used to calculate frame score from (delta_hue, delta_sat, delta_lum, delta_edges). + + Default: ``1.000, 1.000, 1.000, 0.000`` + +.. option:: -l, --luma-only + + Only use luma (brightness) channel. Useful for greyscale videos. Equivalent to setting -w 0 0 1 0. + +.. option:: -k N, --kernel-size N + + Size of kernel for expanding detected edges. Must be odd integer greater than or equal to 3. If unset, kernel size is estimated using video resolution. + + Default: ``auto`` + +.. option:: -m TIMECODE, --min-scene-len TIMECODE + + Minimum length of any scene. Overrides global option :option:`-m/--min-scene-len `. + +.. option:: -f MODE, --filter-mode MODE + + Mode used to enforce :option:`-m/--min-scene-len <-m>` option. Can be one of: merge, suppress. + + Default: ``Mode.MERGE`` + + +.. _command-detect-hash: + +.. program:: scenedetect detect-hash + + +``detect-hash`` +======================================================================== + +Find fast cuts using perceptual hashing. + +The perceptual hash is taken of adjacent frames, and used to calculate the hamming distance between them. The distance is then normalized by the squared size of the hash, and compared to the threshold. + +Saved as the ``hash_dist`` metric in a statsfile. + + +Examples +------------------------------------------------------------------------ + + + ``scenedetect -i video.mp4 detect-hash`` + + ``scenedetect -i video.mp4 detect-hash --size 32 --lowpass 3`` + + +Options +------------------------------------------------------------------------ + + +.. option:: -t VAL, --threshold VAL + + Max distance between hash values (0.0 to 1.0) of adjacent frames. Lower values are more sensitive to changes. + + Default: ``0.35`` + +.. option:: -s SIZE, --size SIZE + + Size of square of low frequency data to include from the discrete cosine transform. + + Default: ``8`` + +.. option:: -l FRAC, --lowpass FRAC + + How much high frequency information to filter from the DCT. 2 means keep lower 1/2 of the frequency data, 4 means only keep 1/4, etc... + + Default: ``2`` + +.. option:: -m TIMECODE, --min-scene-len TIMECODE + + Minimum length of any scene. Overrides global min-scene-len (-m) setting. TIMECODE can be specified as exact number of frames, a time in seconds followed by s, or a timecode in the format HH:MM:SS or HH:MM:SS.nnn. + + +.. _command-detect-hist: + +.. program:: scenedetect detect-hist + + +``detect-hist`` +======================================================================== + +Find fast cuts by differencing YUV histograms. + +Uses Y channel after converting each frame to YUV to create a histogram of each frame. Histograms between frames are compared to determine a score for how similar they are. + +Saved as the ``hist_diff`` metric in a statsfile. + + +Examples +------------------------------------------------------------------------ + + + ``scenedetect -i video.mp4 detect-hist`` + + ``scenedetect -i video.mp4 detect-hist --threshold 0.1 --bins 240`` + + +Options +------------------------------------------------------------------------ + + +.. option:: -t VAL, --threshold VAL + + Max difference (0.0 to 1.0) between histograms of adjacent frames. Lower values are more sensitive to changes. + + Default: ``0.2`` + +.. option:: -b NUM, --bins NUM + + The number of bins to use for the histogram calculation. + + Default: ``128`` + +.. option:: -m TIMECODE, --min-scene-len TIMECODE + + Minimum length of any scene. Overrides global min-scene-len (-m) setting. TIMECODE can be specified as exact number of frames, a time in seconds followed by s, or a timecode in the format HH:MM:SS or HH:MM:SS.nnn. + + +.. _command-detect-threshold: + +.. program:: scenedetect detect-threshold + + +``detect-threshold`` +======================================================================== + +Find fade in/out using averaging. + +Detects fade-in and fade-out events using average pixel values. Resulting cuts are placed between adjacent fade-out and fade-in events. + + +Examples +------------------------------------------------------------------------ + + + ``scenedetect -i video.mp4 detect-threshold`` + + ``scenedetect -i video.mp4 detect-threshold --threshold 15`` + + +Options +------------------------------------------------------------------------ + + +.. option:: -t VAL, --threshold VAL + + Threshold (integer) that frame score must exceed to start a new scene. Refers to "delta_rgb" in stats file. + + Default: ``12.0`` + +.. option:: -f PERCENT, --fade-bias PERCENT + + Percent (%) from -100 to 100 of timecode skew of cut placement. -100 indicates the start frame, +100 indicates the end frame, and 0 is the middle of both. + + Default: ``0`` + +.. option:: -l, --add-last-scene + + If set and video ends after a fade-out event, generate a final cut at the last fade-out position. + + Default: ``True`` + +.. option:: -m TIMECODE, --min-scene-len TIMECODE + + Minimum length of any scene. Overrides global option :option:`-m/--min-scene-len `. TIMECODE can be specified in frames (-m 100), in seconds with `s` suffix (-m 3.5s), or timecode (-m 00:01:52.778). + + +************************************************************************ +Commands +************************************************************************ + + +.. _command-list-scenes: + +.. program:: scenedetect list-scenes + + +``list-scenes`` +======================================================================== + +Create scene list CSV file (will be named $VIDEO_NAME-Scenes.csv by default). + + +Examples +------------------------------------------------------------------------ + + +Default: + + ``scenedetect -i video.mp4 list-scenes`` + +Without cut list (RFC 4180 compliant CSV): + + ``scenedetect -i video.mp4 list-scenes --skip-cuts`` + + +Options +------------------------------------------------------------------------ + + +.. option:: -o DIR, --output DIR + + Output directory to save videos to. Overrides global option :option:`-o/--output `. + +.. option:: -f NAME, --filename NAME + + Filename format to use for the scene list CSV file. You can use the $VIDEO_NAME macro in the file name. Note that you may have to wrap the name using single quotes or use escape characters (e.g. -f \$VIDEO_NAME-Scenes.csv). + + Default: ``$VIDEO_NAME-Scenes.csv`` + +.. option:: -n, --no-output-file + + Only print scene list. + +.. option:: -q, --quiet + + Suppress printing scene list. + +.. option:: -s, --skip-cuts + + Skip cutting list as first row in the CSV file. Set for RFC 4180 compliant output. + + +.. _command-load-scenes: + +.. program:: scenedetect load-scenes + + +``load-scenes`` +======================================================================== + +Load scenes from CSV instead of detecting. Can be used with CSV generated by :ref:`list-scenes `. Scenes are loaded using the specified column as cut locations (frame number or timecode). + + +Examples +------------------------------------------------------------------------ + + + ``scenedetect -i video.mp4 load-scenes -i scenes.csv`` + + ``scenedetect -i video.mp4 load-scenes -i scenes.csv --start-col-name "Start Timecode"`` + + +Options +------------------------------------------------------------------------ + + +.. option:: -i FILE, --input FILE + + Scene list to read cut information from. + +.. option:: -c STRING, --start-col-name STRING + + Name of column used to mark scene cuts. + + Default: ``"Start Frame"`` + + +.. _command-save-edl: + +.. program:: scenedetect save-edl + + +``save-edl`` +======================================================================== + +Save cuts in EDL format (CMX 3600). + + +Options +------------------------------------------------------------------------ + + +.. option:: -f NAME, --filename NAME + + Filename format to use. + + Default: ``$VIDEO_NAME.edl`` + +.. option:: -t NAME, --title NAME + + Title format to use. + + Default: ``$VIDEO_NAME`` + +.. option:: -r REEL, --reel REEL + + Reel name to use. + + Default: ``AX`` + +.. option:: -o DIR, --output DIR + + Output directory to save EDL file to. Overrides global option :option:`-o/--output `. + +.. option:: -s TIMECODE, --start-timecode TIMECODE + + Start timecode added to every event so the EDL aligns with the source media's on-screen timecode. Accepts SMPTE HH:MM:SS:FF or 8 digits (HHMMSSFF, e.g. 01000000). + + +.. _command-save-fcp: + +.. program:: scenedetect save-fcp + + +``save-fcp`` +======================================================================== + +Save cuts in Final Cut Pro XML format (FCP7 xmeml or FCPX). + + +Options +------------------------------------------------------------------------ + + +.. option:: -f NAME, --filename NAME + + Filename format to use. + + Default: ``$VIDEO_NAME.xml`` + +.. option:: --format TYPE + + Format to export. TYPE must be one of: fcpx, fcp7. + + Default: ``FcpFormat.FCPX`` + +.. option:: -o DIR, --output DIR + + Output directory to save XML file to. Overrides global option :option:`-o/--output `. + + +.. _command-save-html: + +.. program:: scenedetect save-html + + +``save-html`` +======================================================================== + +Save scene list to HTML file. + +To customize image generation, specify the :ref:`save-images ` command before :ref:`save-html `. This command always uses the result of the preceeding :ref:`save-images ` command, or runs it with the default config values unless ``--no-images`` is set. + + +Options +------------------------------------------------------------------------ + + +.. option:: -f NAME, --filename NAME + + Filename format to use for the scene list HTML file. You can use the $VIDEO_NAME macro in the file name. Note that you may have to wrap the format name using single quotes. + + Default: ``$VIDEO_NAME-Scenes.html`` + +.. option:: -n, --no-images + + Do not include images with the result. + +.. option:: -w pixels, --image-width pixels + + Width in pixels of the images in the resulting HTML table. + +.. option:: -h pixels, --image-height pixels + + Height in pixels of the images in the resulting HTML table. + +.. option:: -s, --show + + Automatically open resulting HTML when processing is complete. + + +.. _command-save-images: + +.. program:: scenedetect save-images + + +``save-images`` +======================================================================== + +Save images from each detected scene. + + +Examples +------------------------------------------------------------------------ + + + ``scenedetect -i video.mp4 save-images --num-images 5`` + + ``scenedetect -i video.mp4 save-images --width 1024`` + + ``scenedetect -i video.mp4 save-images --filename \$SCENE_NUMBER-img\$IMAGE_NUMBER`` + + +Options +------------------------------------------------------------------------ + + +.. option:: -o DIR, --output DIR + + Output directory for images. Overrides global option :option:`-o/--output `. + +.. option:: -f NAME, --filename NAME + + Filename format *without* extension to use when saving images. You can use the $VIDEO_NAME, $SCENE_NUMBER, $IMAGE_NUMBER, and $FRAME_NUMBER macros in the file name. You may have to use escape characters (e.g. -f \$SCENE_NUMBER-Image-\$IMAGE_NUMBER) or single quotes. + + Default: ``$VIDEO_NAME-Scene-$SCENE_NUMBER-$IMAGE_NUMBER`` + +.. option:: -n N, --num-images N + + Number of images to generate per scene. Will always include start/end frame, unless -n 1, in which case the image will be the frame at the mid-point of the scene. + + Default: ``3`` + +.. option:: -j, --jpeg + + Set output format to JPEG (default). + +.. option:: -w, --webp + + Set output format to WebP + +.. option:: -q Q, --quality Q + + JPEG/WebP encoding quality, from 0-100 (higher indicates better quality). For WebP, 100 indicates lossless. + + Default: ``JPEG: 95, WebP: 100`` + +.. option:: -p, --png + + Set output format to PNG. + +.. option:: -c C, --compression C + + PNG compression rate, from 0-9. Higher values produce smaller files but result in longer compression time. This setting does not affect image quality, only file size. + + Default: ``3`` + +.. option:: -m DURATION, --frame-margin DURATION + + Padding around the beginning/end of each scene used when selecting which frames to extract. DURATION can be specified in frames (-m 1), in seconds with `s` suffix (-m 0.1s), or timecode (-m 00:00:00.100). + + Default: ``1`` + +.. option:: -s S, --scale S + + Factor to scale images by. Ignored if :option:`-W/--width <-W>` or :option:`-H/--height <-H>` is set. + +.. option:: -H H, --height H + + Height (pixels) of images. + +.. option:: -W W, --width W + + Width (pixels) of images. + + +.. _command-save-otio: + +.. program:: scenedetect save-otio + + +``save-otio`` +======================================================================== + +Save cuts as an OTIO timeline. + +Uses the Timeline.1 schema. OTIO (OpenTimelineIO) timelines can be imported by many video editors. + + +Options +------------------------------------------------------------------------ + + +.. option:: -f NAME, --filename NAME + + Filename format to use. + + Default: ``$VIDEO_NAME.otio`` + +.. option:: -n NAME, --name NAME + + Name of timeline to use. + + Default: ``"$VIDEO_NAME (PySceneDetect)"`` + +.. option:: -o DIR, --output DIR + + Output directory to save OTIO file to. Overrides global option :option:`-o/--output `. + +.. option:: --audio + + Include audio track (default). + +.. option:: --no-audio + + Exclude audio track. + + +.. _command-save-qp: + +.. program:: scenedetect save-qp + + +``save-qp`` +======================================================================== + +Save cuts as keyframes (I-frames) for video encoding. + +The resulting QP file can be used with the ``--qpfile`` argument in x264/x265. + + +Options +------------------------------------------------------------------------ + + +.. option:: -f NAME, --filename NAME + + Filename format to use. + + Default: ``$VIDEO_NAME.qp`` + +.. option:: -o DIR, --output DIR + + Output directory to save QP file to. Overrides global option :option:`-o/--output `. + +.. option:: -d, --disable-shift + + Disable shifting frame numbers by start time. + + +.. _command-split-video: + +.. program:: scenedetect split-video + + +``split-video`` +======================================================================== + +Split input video using ffmpeg or mkvmerge. + + +Examples +------------------------------------------------------------------------ + + +Default: + + ``scenedetect -i video.mp4 split-video`` + +Codec-copy mode (not frame accurate): + + ``scenedetect -i video.mp4 split-video --copy`` + +Customized filenames: + + ``scenedetect -i video.mp4 split-video --filename \$VIDEO_NAME-Clip-\$SCENE_NUMBER`` + + +Options +------------------------------------------------------------------------ + + +.. option:: -o DIR, --output DIR + + Output directory to save videos to. Overrides global option :option:`-o/--output `. + +.. option:: -f NAME, --filename NAME + + File name format to use when saving videos, with or without extension. You can use $VIDEO_NAME and $SCENE_NUMBER macros in the filename. You may have to wrap the format in single quotes or use escape characters to avoid variable expansion (e.g. -f \$VIDEO_NAME-Scene-\$SCENE_NUMBER). + + Default: ``$VIDEO_NAME-Scene-$SCENE_NUMBER`` + +.. option:: -q, --quiet + + Hide output from external video splitting tool. + +.. option:: -c, --copy + + Copy instead of re-encode. Faster but less precise. + +.. option:: -hq, --high-quality + + Encode video with higher quality, overrides -f option if present. Equivalent to: :option:`--rate-factor=17 <--rate-factor>` :option:`--preset=slow <--preset>` + +.. option:: -crf RATE, --rate-factor RATE + + Video encoding quality (x264 constant rate factor), from 0-100, where lower is higher quality (larger output). 0 indicates lossless. + + Default: ``22`` + +.. option:: -p LEVEL, --preset LEVEL + + Video compression quality (x264 preset). Can be one of: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow. Faster modes take less time but output may be larger. + + Default: ``veryfast`` + +.. option:: -a ARGS, --args ARGS + + Override codec arguments passed to FFmpeg when splitting scenes. Use double quotes (") around arguments. Must specify at least audio/video codec. + + Default: ``"-map 0:v:0 -map 0:a? -map 0:s? -c:v libx264 -preset veryfast -crf 22 -c:a aac"`` + +.. option:: -m, --mkvmerge + + Split video using mkvmerge. Faster than re-encoding, but less precise. If set, options other than :option:`-f/--filename <-f>`, :option:`-q/--quiet <-q>` and :option:`-o/--output <-o>` will be ignored. Note that mkvmerge automatically appends the $SCENE_NUMBER suffix. + +.. option:: --expand + + Extend the first/last output clips to cover the full input video, even if `time -s/-e` limited the analysis window. Useful for keeping content outside the analyzed region attached to the adjacent split. + + +.. _command-time: + +.. program:: scenedetect time + + +``time`` +======================================================================== + +Set start/end/duration of input video. + +Values can be specified as seconds (SSSS.nn), frames (NNNN), or timecode (HH:MM:SS.nnn). For example, to process only the first minute of a video: + + ``scenedetect -i video.mp4 time --end 00:01:00`` + + ``scenedetect -i video.mp4 time --duration 60.0`` + +Note that --end and --duration are mutually exclusive (i.e. only one of the two can be set). Lastly, the following is an example using absolute frame numbers to process frames 0 through 1000: + + ``scenedetect -i video.mp4 time --start 0 --end 1000`` + + +Options +------------------------------------------------------------------------ + + +.. option:: -s TIMECODE, --start TIMECODE + + Time in video to start detection. TIMECODE can be specified as seconds (:option:`--start=100.0 <--start>`), frames (:option:`--start=100 <--start>`), or timecode (:option:`--start=00:01:40.000 <--start>`). + +.. option:: -d TIMECODE, --duration TIMECODE + + Maximum time in video to process. TIMECODE format is the same as other arguments. Mutually exclusive with :option:`-e/--end <-e>`. + +.. option:: -e TIMECODE, --end TIMECODE + + Time in video to end detecting scenes. TIMECODE format is the same as other arguments. Mutually exclusive with :option:`-d/--duration <-d>` + diff --git a/docs/cli/backends.rst b/docs/cli/backends.rst new file mode 100644 index 00000000..7c235915 --- /dev/null +++ b/docs/cli/backends.rst @@ -0,0 +1,50 @@ + +.. _cli-backends: + +*********************************************************************** +Backends +*********************************************************************** + +PySceneDetect supports multiple backends for video input. Some can be configured by using :ref:`a config file `. Installed backends can be verified by running ``scenedetect version --all``. + +Note that the `scenedetect` command output is generated as a post-processing step, after scene detection completes. Most commands require the ability for the input to be replayed, and preferably it should also support seeking. Network streams and other input types are supported with certain backends, however integration with live streams requires use of the Python API. + + +======================================================================= +OpenCV +======================================================================= + +*[Default]* +The `OpenCV `_ backend (usually `opencv-python `_) uses OpenCV's ``VideoCapture`` for video input. Can be used by specifying ``-b opencv`` via command line, or setting ``backend = opencv`` under the ``[global]`` section of your :ref:`config file `. + +It is mostly reliable and fast, although can occasionally run into issues processing videos with multiple audio tracks or small amounts of frame corruption. You can use a custom version of the ``cv2`` package, or install either the `opencv-python` or `opencv-python-headless` packages from `pip`. + +The OpenCV backend also supports image sequences as inputs (e.g. ``frame%02d.jpg`` if you want to load frame001.jpg, frame002.jpg, frame003.jpg...). Make sure to specify the framerate manually (``-f``/``--frame-rate``) to ensure accurate timing calculations. + +Variable framerate (VFR) video is supported. Scene detection uses PTS-derived timestamps from ``CAP_PROP_POS_MSEC`` for accurate timecodes. Seeking compensates for OpenCV's average-fps-based internal seek approximation, so output timecodes remain accurate across the full video. + + +======================================================================= +PyAV +======================================================================= + +The `PyAV `_ backend (`av package `_) is a more robust backend that handles multiple audio tracks and frame decode errors gracefully. + +Variable framerate (VFR) video is fully supported. PyAV uses native PTS timestamps directly from the container, giving the most accurate timecodes for VFR content. + +This backend can be used by specifying ``-b pyav`` via command line, or setting ``backend = pyav`` under the ``[global]`` section of your :ref:`config file `. + + +======================================================================= +MoviePy +======================================================================= + +MoviePy launches ffmpeg as a subprocess, and can be used with various types of inputs. If the input supports seeking it should work fine with most operations, for example, image sequences or AviSynth scripts. + +.. warning:: + + The MoviePy backend is still under development and is not included with current Windows distribution. To enable MoviePy support, you must install PySceneDetect using `python` and `pip`. + + Variable framerate (VFR) video is **not supported**. MoviePy assumes a fixed framerate, so timecodes for VFR content will be inaccurate. Use the PyAV or OpenCV backend instead. + +This backend can be used by specifying ``-b moviepy`` via command line, or setting ``backend = moviepy`` under the ``[global]`` section of your :ref:`config file `. diff --git a/manual/cli/config_file.rst b/docs/cli/config_file.rst similarity index 72% rename from manual/cli/config_file.rst rename to docs/cli/config_file.rst index 57ecd6d8..95fd9135 100644 --- a/manual/cli/config_file.rst +++ b/docs/cli/config_file.rst @@ -17,9 +17,7 @@ A configuration file path can be specified using the ``-c``/``--config`` argumen * Mac: * ``~/Library/Preferences/PySceneDetect/scenedetect.cfg`` -Run `scenedetect help` to see the exact path on your system which will be used. Values set on the command line take precedence over those set in the config file. - -Most command line parameters can be set using a configuration file. See the :ref:`Template ` below for an example ``scenedetect.cfg`` file containing every possible option, along with comments that describe each one. Note that lines starting with a ``#`` are comments and will be ignored. +Run `scenedetect --help` to see the exact path on your system which will be used. Values set on the command line take precedence over those set in the config file. Most (but not all) command line parameters can be set using a configuration file, and some options can *only* be set using a config file. See the :ref:`Template ` below for a ``scenedetect.cfg`` file that describes each option, which you can use to create a new config file. Note that lines starting with a ``#`` are comments and will be ignored. The syntax of a configuration file is: @@ -38,6 +36,7 @@ Example .. code:: ini [global] + default-detector = detect-content min-scene-len = 0.8s [detect-content] @@ -61,7 +60,7 @@ Example Template ======================================================================= -This template shows every possible configuration option and default values. It can be used as a ``scenedetect.cfg`` file. You can also `download it from Github `_. +This template shows every possible configuration option and default values. It can be used as a ``scenedetect.cfg`` file. You can also `download it from Github `_. .. literalinclude:: ../../scenedetect.cfg :language: ini diff --git a/manual/conf.py b/docs/conf.py similarity index 62% rename from manual/conf.py rename to docs/conf.py index 7cd07426..a73c362c 100644 --- a/manual/conf.py +++ b/docs/conf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # @@ -15,88 +14,75 @@ import os import sys +sys.path.insert(0, os.path.abspath("..")) -sys.path.insert(0, os.path.abspath('..')) - +from scenedetect import __version__ as scenedetect_version # -- Project information ----------------------------------------------------- -project = 'PySceneDetect' -copyright = '2014-2022, Brandon Castellano' -author = 'Brandon Castellano' +project = "PySceneDetect" +copyright = "2014, Brandon Castellano" +author = "Brandon Castellano" # The short X.Y version -version = '0.6.1' +version = scenedetect_version # The full version, including alpha/beta/rc tags -release = 'v0.6.1' - +release = scenedetect_version # -- General configuration --------------------------------------------------- -# If your documentation needs a minimal Sphinx version, state it here. -# -# needs_sphinx = '1.0' - # 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', + "sphinx.ext.napoleon", + "sphinx.ext.autodoc", + "sphinx_copybutton", ] autoclass_content = "both" +autodoc_member_order = "groupwise" +autodoc_typehints = "description" +autodoc_typehints_format = "short" -autodoc_typehints = 'description' -autodoc_typehints_format = 'short' +add_module_names = False +python_use_unqualified_type_names = True # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - +templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] -source_suffix = '.rst' +source_suffix = ".rst" -# The master toctree document. -master_doc = 'index' +# 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 = None +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'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - +pygments_style = "sphinx" # -- Options for HTML output ------------------------------------------------- -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -#html_theme = 'alabaster' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# -# html_theme_options = {} - # 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_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. @@ -108,12 +94,10 @@ # # html_sidebars = {} - # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. -htmlhelp_basename = 'PySceneDetectdoc' - +htmlhelp_basename = "PySceneDetectdoc" # -- Options for LaTeX output ------------------------------------------------ @@ -121,15 +105,12 @@ # 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', @@ -139,20 +120,14 @@ # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'PySceneDetect.tex', 'PySceneDetect Documentation', - 'Brandon Castellano', 'manual'), + (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 = [ - (master_doc, 'pyscenedetect', 'PySceneDetect Documentation', - [author], 1) -] - +man_pages = [(root_doc, "pyscenedetect", "PySceneDetect Documentation", [author], 1)] # -- Options for Texinfo output ---------------------------------------------- @@ -160,34 +135,38 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'PySceneDetect', 'PySceneDetect Documentation', - author, 'PySceneDetect', 'One line description of project.', - 'Miscellaneous'), + ( + root_doc, + "PySceneDetect", + "PySceneDetect Documentation", + author, + "PySceneDetect", + "Python API and `scenedetect` command reference.", + "Miscellaneous", + ), ] +# -- Theme ------------------------------------------------- -# -- Extension configuration ------------------------------------------------- +# TODO: Consider switching to sphinx_material. -html_theme = 'alabaster' +html_theme = "alabaster" html_theme_options = { - 'sidebar_width': '235px', - 'description': 'CLI/API Reference Manual [%s]' % (release), - 'show_relbar_bottom': True, - 'show_relbar_top': False, - - 'github_user': 'Breakthrough', - 'github_repo': 'PySceneDetect', - 'github_type': 'star', - - 'tip_bg': '#f0f6fa', - 'tip_border': '#c2dcf2', - 'hint_bg': '#f0faf0', - 'hint_border': '#d3ebdc', - 'warn_bg': '#f5ebd0', - 'warn_border': '#f2caa2', - 'attention_bg': '#f5dcdc', - 'attention_border': '#ffaaaa', - 'logo': 'pyscenedetect_logo.png', - 'logo_name': False, - #'logo_name': True, + "sidebar_width": "235px", + "description": f"Version: [{release}]", + "show_relbar_bottom": True, + "show_relbar_top": False, + "github_user": "Breakthrough", + "github_repo": "PySceneDetect", + "github_type": "star", + "tip_bg": "#f0f6fa", + "tip_border": "#c2dcf2", + "hint_bg": "#f0faf0", + "hint_border": "#d3ebdc", + "warn_bg": "#f5ebd0", + "warn_border": "#f2caa2", + "attention_bg": "#f5dcdc", + "attention_border": "#ffaaaa", + "logo": "pyscenedetect_logo.png", + "logo_name": False, } diff --git a/docs/contributing.md b/docs/contributing.md deleted file mode 100644 index ddeecc60..00000000 --- a/docs/contributing.md +++ /dev/null @@ -1,40 +0,0 @@ - -##   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). Provide as much detail as you can - include an example that clearly demonstrates the problem (if possible), and make sure to include any/all relevant program output or error messages. - -When submitting bug reports, please add the command-line options `-v debug -l BUG_REPORT.txt` to the very beginning of the `scenedetect` command you are using, and attach the generated `BUG_REPORT.txt` file. - -Before opening a new issue, please do [search for any existing issues](https://github.com/Breakthrough/PySceneDetect/issues?q=) (both open and closed) which might report similar issues/bugs to avoid creating duplicate entries. If you do find a duplicate report, feel free to add any additional information you feel may be relevant. - -##   Contributing to Development - -The development of PySceneDetect is done on the Github Repo, guided by [the feature roadmap](features.md). Code you wish to submit should be attached to a dedicated entry in [the issue tracker](https://github.com/Breakthrough/PySceneDetect/issues?q=) (with the appropriate tags for bugfixes, new features, enhancements, etc...), and allows for easier communication regarding development structure. Feel free to create a new entry if required, as some planned features or bugs/issues may not yet exist in the tracker. - -All submitted code should be linted with pylint, and follow the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html) as closely as possible. Also, ensure that you search through [all existing issues](https://github.com/Breakthrough/PySceneDetect/issues?q=) (both open and closed) beforehand to avoid creating duplicate entries. - -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 - -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. - -### GUI - -A graphical user interface will be crucial for making PySceneDetect approchable 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. - -### Automatic Threshold / Peak Detection - -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. - -### Advanced Detection Strategies - -Research into advanced scene detection for content detection would be most useful, perhaps in terms of histogram analysis or edge detection. This could be integrated into the existing `detect-content` command, or be a separate command. The real blocker here is achieving reasonable performance utilizing the current software architecture. - -There are many open issues on the issue tracker that contain reference implementations contributed by various community members. There are already several concepts which are proven to be viable candidates for production, but still require some degree optimization. diff --git a/docs/download.md b/docs/download.md deleted file mode 100644 index d2a69b6c..00000000 --- a/docs/download.md +++ /dev/null @@ -1,76 +0,0 @@ - -# Obtaining PySceneDetect - -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.6 or higher. - -## Download and Installation - -### Install via pip       - -
-

Including OpenCV (recommended):

-

pip install --upgrade scenedetect[opencv]

-

Including Headless OpenCV (servers):

-

pip install --upgrade scenedetect[opencv-headless]

-
- -PySceneDetect is available via `pip` as [the `scenedetect` package](https://pypi.org/project/scenedetect/). - -### Windows Build (64-bit Only)   - -
-

Latest Release: v0.6.1

-

  Release Date:  November 28, 2022

-  Installer  (recommended)      -  Portable .zip      -  Getting Started -
- -### Post Installation - -After installation, you can call PySceneDetect from any terminal/command prompt by typing `scenedetect` (try running `scenedetect help`, or `scenedetect version`). - -To get familiar with PySceneDetect, try running `scenedetect help`, or continue onwards to the [Getting Started: Basic Usage](examples/usage.md) section. 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. - - -## Dependencies - -### Python Packages - -PySceneDetect requires [Python 3](https://www.python.org/) and the following packages: - - - [OpenCV](http://opencv.org/): `pip install opencv-python` - - [Numpy](https://numpy.org/): `pip install numpy` - - [Click](https://click.palletsprojects.com): `pip install Click` - - [tqdm](https://github.com/tqdm/tqdm): `pip install tqdm` - - [appdirs](https://github.com/ActiveState/appdirs): `pip install appdirs` - -Optional packages: - - - [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) - -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. - -If you have trouble getting PySceneDetect to find `ffmpeg` or `mkvmerge`, see the section on Manually Enabling `split-video` Support on [Getting Started: Video Splitting Support Requirements](examples/video-splitting). - -### 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. - -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/docs/examples/usage-example.md b/docs/examples/usage-example.md deleted file mode 100644 index ebd4c43e..00000000 --- a/docs/examples/usage-example.md +++ /dev/null @@ -1,67 +0,0 @@ - -# Getting Started - -As a concrete example to become familiar with PySceneDetect, let's use the following short clip from the James Bond movie, GoldenEye (Copyright © 1995 MGM): - -[https://www.youtube.com/watch?v=OMgIPnCnlbQ](https://www.youtube.com/watch?v=OMgIPnCnlbQ) - -You can [download the clip from here](https://github.com/Breakthrough/PySceneDetect/raw/resources/tests/resources/goldeneye/goldeneye.mp4) (may have to right-click and save-as, put the video in your working directory as `goldeneye.mp4`). - - -## Content-Aware Detection - -In this case, we want to split this clip up into each individual scene - at each location where a fast cut occurs. This means we need to use content-aware detecton 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. - -Using the following command, let's run PySceneDetect on the video, and also save a scene list CSV file and some images of each scene: - -```rst -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 as `goldeneye-XXXX-00/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 | | - - -## Splitting Video into Clips - -The `split-video` command can be used to automatically split the input video using `ffmpeg` or `mkvmerge`. For example: - -```rst -scenedetect -i goldeneye.mp4 detect-adaptive split-video -``` - -Type `scenedetect help split-video` 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`). - - -## Tweaking Detection Parameters - -Detectors take a variety of parameters, which can be [configured via command-line](http://scenedetect.com/projects/Manual/en/latest/cli/detectors.html) or by [using a config file](http://scenedetect.com/projects/Manual/en/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: - -```rst -scenedetect --input goldeneye.mp4 --stats goldeneye.stats.csv detect-adaptive -``` - -We can then plot the values of the `content_val` column: - -goldeneye.mp4 statistics graph - -The peaks in values correspond to the scene breaks in the input video. In some cases the threshold may need to be raised or lowered accordingly. diff --git a/docs/examples/usage.md b/docs/examples/usage.md deleted file mode 100644 index 0ecb6113..00000000 --- a/docs/examples/usage.md +++ /dev/null @@ -1,197 +0,0 @@ - -# PySceneDetect Command-Line Usage - -This page outlines the most commonly used command-line options for using PySceneDetect. Basic usage of PySceneDetect (`scenedetect`) is: - -```rst -scenedetect [global options] [commands + command options] -``` - -You can also print the usage/help manual of PySceneDetect with the `help` command: - -```rst -scenedetect help -``` - -
-The complete PySceneDetect Command-Line Interface (CLI) Reference can be found in the PySceneDetect Manual, located at scenedetect.com/projects/Manual/en/latest/. -
- - -## Quick Example - -Split the input video wherever a new scene is detected: - -```rst -scenedetect -i video.mp4 detect-adaptive split-video -``` - -Print a table of detected scenes to the terminal, and save an image -at the start, middle, and end frame of each scene: - -```rst -scenedetect -i video.mp4 detect-adaptive list-scenes -n save-images -``` - -Skip the first 10 seconds of the input video: - -```rst -scenedetect -i video.mp4 time -s 10s detect-adaptive -``` - -There are many other options and commands. To show a summary of available options/arguments, and a list of all commands: - -```rst -scenedetect help -``` - -You can also type `help command` where `command` is a specific command (e.g. `list-scenes`, `detect-adaptive`). Also, to show a complete help listing for every command: - -```rst -scenedetect help all -``` - -## Getting Started - -To start off, let's perform adaptive scene detection on a video `my_video.mp4` ([example](usage-example.md)) with the default threshold, and display a list of detected scenes: - -```rst -scenedetect --input my_video.mp4 detect-adaptive list-scenes -``` - -Next, the same, but also split the input video into individual clips (starting from `my_video-Scene-001.mp4`): - -```rst -scenedetect --input my_video.mp4 detect-adaptive list-scenes split-video -``` - -The `split-video` command requires either `ffmpeg` or `mkvmerge` to be available, depending on the options used. You can override the exact arguments passed to `ffmpeg`: - -```rst -scenedetect --input my_video.mp4 detect-adaptive list-scenes split-video --args "-c:v libx264 -crf 20 -c:a aac" -``` - -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` (call `scenedetect help split-video` for details). - -Note that descriptions for all command-line arguments, as well as their default values, can be obtained by running `scenedetect help` for global options, `scenedetect help [command]` for a specific command, or `help all` for a complete help and command listing. - - -## Detection Methods - -There are two main detection methods PySceneDetect uses: `detect-threshold` (comparing each frame to a set black level, useful for detecting cuts and fades to/from black), and `detect-content` (compares each frame sequentially looking for changes in content, useful for detecting fast cuts between video scenes, although slower to process). There also is `detect-adaptive`, which uses the same frame score 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](http://scenedetect.com/projects/Manual/en/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 paramters - 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 default threshold value (`-t` / `--threshold`), which is good for a first try when using content-aware mode (`detect-content`), is `30`. Thus: - -```rst -scenedetect -i my_video.mp4 -s my_video.stats.csv list-scenes detect-content -``` - -Is the equivalent of: - -```rst -scenedetect -i my_video.mp4 -s my_video.stats.csv list-scenes detect-content -t 30 -``` - -Remember to supply the `list-scenes` command, after all main program options, to show which scenes were generated, as well as optionally the `save-images` command to save images for each scene, and/or the `split-video` command to split the input video automatically. - -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. 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). - -You can supply the same stats file in subsequent calls to `scenedetect` with different threshold values to speed the processing time up significantly when experimenting with different values on the **same** video (or set of videos). You *can* use multiple detectors with the same stats file, so long as you supply the *exact* same `-i` / `--input` video file(s) each time. - -*Remember*: once a stats file is created, it can only be used with the **same** input video. If you want to process a different input video (or set of videos), change the name of the stats file supplied to `-s` / `--stats`, or delete the existing stats file on disk. - - -### 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. - -```rst -scenedetect -i my_video.mp4 -s my_video.stats.mp4 detect-threshold -``` - -```rst -scenedetect -i my_video.mp4 -s my_video.stats.mp4 detect-threshold -t 12 -p 95 -``` - -For most videos, the minimum percentage (`-p` / `--min-percent`) should always be at *least* 90% (`-p 90`, the default value is `95`). Also, using values for threshold less than `8` may cause problems with some videos, especially those encoded at lower bitrates or with limited dynamic range. - -As with `detect-content`, 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). - - -### 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`. - - -## Actions / Commands - -After setting the detection method(s), there are several commands that can be used. Type `scenedetect help [command]` for help/arguments of a specific command listed below: - - - `time`: Used to set input video duration/length or start/end time (discussed below). - - `list-scenes`: Print and save a list of all scenes in table and CSV format. - - `split-video`: Split input video into scenes automatically. - - `save-images`: Save images from the video for each scene. - - `export-html`: Exports scene list to an HTML file. - - `help`: Print help for PySceneDetect or a particular command. No processing is done if present. - - `version`: Print PySceneDetect release version. No processing is done if present. - - `about`: Print PySceneDetect license agreement and application information. No processing is done if present. - -You can also type `scenedetect help all` for the full CLI reference or [view it here](../reference/command-line.md). - - -## 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 three formats: exact frame number (e.g. `12345`), number of seconds followed by `s` (e.g. `123s`, `123.45s`), or standard format (HH:MM:SS[.nnn], e.g. `12:34:56`, `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): - -```rst -scenedetect -i my_video.mp4 time --start 00:05:00 --end 00:06:30 detect-adaptive -``` - -```rst -scenedetect -i my_video.mp4 time --start 300s --end 390s detect-adaptive -``` - -```rst -scenedetect -i my_video.mp4 time --start 300s --duration 90s detect-adaptive -``` - -```rst -scenedetect -i my_video.mp4 time --start 300s --duration 2700 detect-adaptive -``` - -This demonstrates the different timecode formats, interchanging end time with duration and vice-versa, and precedence of setting duration over end time. - - -## Saving Image Previews of Detected Scenes - -PySceneDetect can automatically save the beginning and ending frame of each detected scene by using the `save-images` command. If present, the first and last frames of each scene will be saved in the current working directory, using the filename of the input video. - -Files marked `00` represent the starting frame of the scene, and those marked `01` represent the last frame (e.g. `testvideo.mp4.Scene-4-01.jpg`). By default, two images are generated. - -Coming soon: If more are specified via the `-n` flag, they will start from `00` (the first frame) and be evenly spaced throughout the scene until the last frame, which will be numbered `N-1`. - - -## Improving Processing Speed/Performance - -The following arguments are global program options, and need to be applied before any commands (e.g. `detect-content`, `list-scenes`). They can be used to achieve performance gains for some source material with a variable loss of accuracy. - -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 overriden 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. - -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. diff --git a/docs/generate_cli_docs.py b/docs/generate_cli_docs.py new file mode 100644 index 00000000..68542292 --- /dev/null +++ b/docs/generate_cli_docs.py @@ -0,0 +1,284 @@ +# Generate formatted CLI documentation for PySceneDetect. +# +# Inspired by sphinx-click: https://github.com/click-contrib/sphinx-click +# +# Copyright (C) 2023 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. +"""Generates CLI reference documentation file docs/cli.rst. + +Run from main repo folder as working directory.""" + +import inspect +import os +import re +import sys +import typing as ty +from dataclasses import dataclass + +# Add parent folder to path so we can resolve `scenedetect` imports. +currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) +parentdir = os.path.dirname(currentdir) +sys.path.insert(0, parentdir) +# Third-party imports (must follow sys.path mutation above). +import click # noqa: E402 + +from scenedetect._cli import scenedetect # noqa: E402 + +StrGenerator = ty.Generator[str, None, None] + +INDENT = " " * 4 + +PAGE_SEP = "*" * 72 +TITLE_SEP = "=" * 72 +HEADING_SEP = "-" * 72 + +OPTION_HELP_OVERRIDES = { + "scenedetect": { + "config": "Path to config file. See :ref:`config file reference ` for details." + }, +} + +TITLE_LEVELS = ["*", "=", "-"] + +INFO_COMMANDS = ["help", "about", "version"] + +INFO_COMMAND_OVERRIDE = """ +.. _command-help: + +``help``, ``version``, and ``about`` +======================================================================= + +.. program:: scenedetect help + +``scenedetect --help`` will print PySceneDetect options, commands, and examples. You can also specify: + + * ``scenedetect [command] --help`` to show options and examples *for* a command or detector + + * ``scenedetect help`` command to print full reference of all options, commands, and examples + +.. program:: scenedetect version + +``scenedetect version`` prints the version of PySceneDetect that is installed, as well as system dependencies. + +.. program:: scenedetect about + +``scenedetect about`` prints PySceneDetect copyright, licensing, and redistribution information. This includes a list of all third-party software components that PySceneDetect uses or interacts with, as well as a reference to the license and copyright information for each component. +""" + + +def patch_help(s: str, commands: list[str]) -> str: + # Patch some TODOs still not handled correctly below. + pos = 0 + while True: + pos = s.find("global option :option:", pos) + if pos < 0: + break + pos = s.find("<-", pos) + assert pos > 0 + s = s[: pos + 1] + "scenedetect " + s[pos + 1 :] + + for command in [command for command in commands if command not in INFO_COMMANDS]: + + def add_link(_match: re.Match, command: str = command) -> str: + return f":ref:`{command} `" + + s = re.sub(f"``{command}``(?!\\n)", add_link, s) + return s + + +def generate_title(s: str, level: int = 0, len: int = 72) -> StrGenerator: + yield "\n" + if level == 0: + yield TITLE_LEVELS[level] * len + "\n" + yield s + "\n" + yield TITLE_LEVELS[level] * len + "\n\n" + + +@dataclass +class ReplaceWithReference: + range: tuple[int, int] + ref: str + ref_type: str + + +def transform_backquotes(s: str) -> str: + return s.replace("``", "`").replace("`", "``") + + +def add_backquotes(match: re.Match) -> str: + return f"``{match.string[match.start() : match.end()]}``" + + +def add_backquotes_with_refs(refs: set[str]) -> ty.Callable[[str], str]: + """Returns a transformation function that backquotes command examples, adding backquotes and + 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: + # add cross reference + cross_ref = flag.string[flag.start() : flag.end()] + option = s.string[s.start() : s.end()] + return f":option:`{option} <{cross_ref}>`" + else: + return add_backquotes(s) + + return _add_backquotes + + +def extract_default_value(s: str) -> tuple[str, str | None]: + default = re.search(r"\[default: .*\]", s) + if default is not None: + span = default.span() + assert span[1] == len(s) + s, default = s[: span[0]].strip(), s[span[0] : span[1]][len("[default: ") : -1] + # Double-quote any default values that contain spaces. + if " " in default and '"' not in default and "," not in default: + default = f'"{default}"' + return (s, default) + + +def transform_add_option_refs(s: str, refs: list[str]) -> str: + transform = add_backquotes_with_refs(refs) + # TODO: Match prefix of `global option` and add ref to parent `scenedetect` command option. + # Replace patch to complete this. + # -c/--command + s = re.sub(r"-\w/--\w[\w-]*", transform, s) + # --arg=value, --arg=1.2.3, --arg=1,2,3 + s = re.sub(r'-+[\w-]+=[^"\s\)]+(? StrGenerator: + if isinstance(opt, click.Argument): + yield f"\n.. option:: {opt.name}\n" + return + yield "\n.. option:: {}\n".format( + ", ".join( + arg if opt.metavar is None else f"{arg} {opt.metavar}" + for arg in sorted(opt.opts, reverse=True) + ) + ) + + help = ( + OPTION_HELP_OVERRIDES[command.name][opt.name] + if command.name in OPTION_HELP_OVERRIDES and opt.name in OPTION_HELP_OVERRIDES[command.name] + else opt.help.strip() + ) + + # TODO: Make metavars link to the option as well. + help, default = extract_default_value(help) + help = transform_add_option_refs(help, flags) + + yield f"\n {help}\n" + if default is not None: + yield f"\n Default: ``{default}``\n" + + +def generate_command_help( + ctx: click.Context, command: click.Command, parent_name: str | None = None +) -> StrGenerator: + # TODO: Add references to long options. Requires splitting out examples. + # TODO: Add references to subcommands. Need to add actual refs, since programs can't be ref'd. + # TODO: Handle dollar signs in examples by having both escaped and unescaped versions + yield f"\n.. _command-{command.name}:\n" + yield "\n.. program:: %s\n\n" % ( + command.name if parent_name is None else f"{parent_name} {command.name}" + ) + if parent_name: + yield from generate_title(f"``{command.name}``", 1) + + replacements = [ + opt + for opts in [param.opts for param in command.params if hasattr(param, "opts")] + for opt in opts + ] + + help = command.help + help = help.replace( + "Examples:\n", "".join(generate_title("Examples", 0 if not parent_name else 2)) + ) + help = help.replace("\b\n", "") + help = help.format(scenedetect="scenedetect", scenedetect_with_video="scenedetect -i video.mp4") + help = transform_backquotes(help) + help = transform_add_option_refs(help, replacements) + + for line in help.strip().splitlines(): + if line.startswith(INDENT): + indent = line.count(INDENT) + line = line.strip() + yield f"{indent * INDENT}``{line}``\n" if line else "\n" + else: + yield f"{line}\n" + + if command.params: + yield "\n" + yield from generate_title("Options", 0 if not parent_name else 2) + for param in command.params: + yield from format_option(command, param, replacements) + yield "\n" + + +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) + yield INFO_COMMAND_OVERRIDE + + yield from generate_title("Detectors", 0) + 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 from generate_title("Commands", 0) + 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) + + 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) + ) + # ctx.to_info_dict lacks metavar so we have to use the context directly. + actions = [ + generate_title("``scenedetect`` \N{CLAPPER BOARD} Command", level=0), + generate_command_help(ctx, ctx.command), + generate_subcommands(ctx, commands), + ] + lines = [] + for action in actions: + lines.extend(action) + return "".join(lines), commands + + +def main(): + help, commands = create_help() + help = patch_help(help, commands) + help = ( + ".. NOTE: This file is auto-generated by docs/generate_cli_docs.py and should not be modified.\n" + + help + ) + with open("docs/cli.rst", "wb") as f: + f.write(help.encode()) + + +if __name__ == "__main__": + main() diff --git a/docs/img/pyscenedetect_logo.png b/docs/img/pyscenedetect_logo.png deleted file mode 100644 index 66038a07..00000000 Binary files a/docs/img/pyscenedetect_logo.png and /dev/null differ diff --git a/docs/img/pyscenedetect_logo_small.png b/docs/img/pyscenedetect_logo_small.png deleted file mode 100644 index 334bf655..00000000 Binary files a/docs/img/pyscenedetect_logo_small.png and /dev/null differ diff --git a/manual/index.rst b/docs/index.rst similarity index 52% rename from manual/index.rst rename to docs/index.rst index 3554eb30..1fc92ea0 100644 --- a/manual/index.rst +++ b/docs/index.rst @@ -1,18 +1,20 @@ .. PySceneDetect documentation index file (contains toctree directive). - Copyright (C) 2014-2022 Brandon Castellano. All rights reserved. + Copyright (C) 2014 Brandon Castellano. All rights reserved. ####################################################################### -PySceneDetect Manual +PySceneDetect Documentation ####################################################################### -This manual refers to both the PySceneDetect command-line interface (the `scenedetect` command) and the PySceneDetect Python API (the `scenedetect` module). The latest release of PySceneDetect can be installed via `pip install scenedetect[opencv]`, or Windows builds and source releases can be found at `scenedetect.com `_. Note that PySceneDetect requires `ffmpeg` or `mkvmerge` for video splitting support. +Welcome to the PySceneDetect docs. The docs are split into two separate parts: one for the command-line interface (the `scenedetect` command) and another for the Python API (the `scenedetect` module). + +You can install the latest release of PySceneDetect by running `pip install scenedetect` (or `pip install scenedetect-headless` on servers without GUI libraries), or by downloading the Windows build from `scenedetect.com/download `_. PySceneDetect requires `ffmpeg` or `mkvmerge` for video splitting support. .. note:: - If you see any errors in this manual, or have any recommendations, feel free to raise an issue on `the PySceneDetect issue tracker `_. + If you see any errors in the documentation, or want to suggest improvements, feel free to raise an issue on `the PySceneDetect issue tracker `_. -The latest source code for PySceneDetect can be found on Github at `github.com/Breakthrough/PySceneDetect `_. +PySceneDetect development happens on Github at `github.com/Breakthrough/PySceneDetect `_. *********************************************************************** @@ -25,12 +27,10 @@ Table of Contents .. toctree:: :maxdepth: 2 - :caption: Command-Line Interface [CLI]: + :caption: Command-Line Interface: :name: clitoc - cli/global_options - cli/commands - cli/detectors + cli cli/config_file cli/backends @@ -40,19 +40,19 @@ Table of Contents ======================================================================= .. toctree:: - :maxdepth: 3 - :caption: Python API Documentation: + :maxdepth: 2 + :caption: API Documentation: :name: apitoc api - api/scene_manager api/detectors + api/output api/backends - api/video_splitter - api/frame_timecode - api/scene_detector - api/stats_manager + api/common + api/scene_manager + api/detector api/video_stream + api/stats_manager api/platform api/migration_guide diff --git a/manual/make.bat b/docs/make.bat similarity index 100% rename from manual/make.bat rename to docs/make.bat diff --git a/docs/other/similar.md b/docs/other/similar.md deleted file mode 100644 index baf8c2d8..00000000 --- a/docs/other/similar.md +++ /dev/null @@ -1,11 +0,0 @@ - -## Alternative Scene Cut/Change Detection Programs - -The following is a list of programs or commands also performing scene cut analysis of some kind on video files. In the future, this may be replaced with a table comparing PySceneDetect's features with these various alternatives. - - - 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 - -This list is not guaranteed to be complete, although [additions/contributions are most welcome](../contributing.md). - diff --git a/docs/reference/command-line.md b/docs/reference/command-line.md deleted file mode 100644 index 80d82a6e..00000000 --- a/docs/reference/command-line.md +++ /dev/null @@ -1,18 +0,0 @@ - -## PySceneDetect CLI Reference - -The `scenedetect` command reference is available as part of [the PySceneDetect Manual](http://manual.scenedetect.com/): - - - [`scenedetect` Options](http://scenedetect.com/projects/Manual/en/latest/cli/global_options.html): - - Input video, stats file, config file, backend, and more - - - [Command Reference](http://scenedetect.com/projects/Manual/en/latest/cli/commands.html): - - Print scenes to terminal and save to CSV (`list-scenes`) - - Video splitting with ffmpeg/mkvmerge (`split-video`) - - Saving images for each scene (`save-images`) - - Exporting scene list as HTML (`export-html`) - - - [Detector Reference](http://scenedetect.com/projects/Manual/en/latest/cli/detectors.html): - - Detectors, e.g. `detect-content`, `detect-threshold`, `detect-adaptive` - -You can also run `scenedetect help all` locally for the full `scenedetect command reference. diff --git a/docs/reference/config.md b/docs/reference/config.md deleted file mode 100644 index ee8b62b0..00000000 --- a/docs/reference/config.md +++ /dev/null @@ -1,51 +0,0 @@ - -## Settings 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` - -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.1-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. - -The syntax of a configuration file is: - -``` -[command] -option_a = value -#comment -option_b = 1 -``` - -### Example - -``` -[global] -min-scene-len = 0.8s - -[detect-content] -threshold = 32 -weights = 1.0 0.5 1.0 0.2 - -[split-video] -preset = slow -rate-factor = 17 -# Don't need to use quotes even if filename contains spaces -filename = $VIDEO_NAME-Clip-$SCENE_NUMBER - -[save-images] -format = jpeg -quality = 80 -num-images = 3 -``` - -See the `scenedetect.cfg` file in the location you installed PySceneDetect or [download it from Github](https://raw.githubusercontent.com/Breakthrough/PySceneDetect/v0.6.1-release/scenedetect.cfg) for a complete listing of all configuration options. diff --git a/docs/reference/python-api.md b/docs/reference/python-api.md deleted file mode 100644 index 69dcbfbf..00000000 --- a/docs/reference/python-api.md +++ /dev/null @@ -1,4 +0,0 @@ - -## API Reference - -The [`scenedetect` API reference](https://scenedetect.com/projects/Manual/en/latest/api.html) is available as part of the [PySceneDetect Manual](http://manual.scenedetect.com/). See the [Quickstart](https://scenedetect.com/projects/Manual/en/latest/api.html#quickstart) and [Example](https://scenedetect.com/projects/Manual/en/latest/api.html#example) sections to get started. diff --git a/docs/reference/video-splitting.md b/docs/reference/video-splitting.md deleted file mode 100644 index e9aa7fdc..00000000 --- a/docs/reference/video-splitting.md +++ /dev/null @@ -1,33 +0,0 @@ - -##   Video Splitting Support 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. - - -### 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. - - -### 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. - - -## 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. - diff --git a/docs/requirements.txt b/docs/requirements.txt deleted file mode 100644 index d4493d23..00000000 --- a/docs/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -mkdocs==1.2.3 -jinja2==3.0.3 diff --git a/manual/_static/pyscenedetect_logo.png b/manual/_static/pyscenedetect_logo.png deleted file mode 100644 index 63471a6a..00000000 Binary files a/manual/_static/pyscenedetect_logo.png and /dev/null differ diff --git a/manual/_static/pyscenedetect_logo_small.png b/manual/_static/pyscenedetect_logo_small.png deleted file mode 100644 index 43365948..00000000 Binary files a/manual/_static/pyscenedetect_logo_small.png and /dev/null differ diff --git a/manual/api.rst b/manual/api.rst deleted file mode 100644 index 23f2e210..00000000 --- a/manual/api.rst +++ /dev/null @@ -1,146 +0,0 @@ - -*********************************************************************** -``scenedetect`` 🎬 Package -*********************************************************************** - -======================================================================= -Overview -======================================================================= - -The `scenedetect` API is designed to be extensible and easy to integrate with most application workflows. Many use cases are covered by the `Quickstart`_ and `Example`_ sections below. The `scenedetect` package provides: - - * :ref:`scenedetect.scene_manager 🎞️ `: The :py:class:`SceneManager ` class applies `SceneDetector` objects on video frames from a :ref:`VideoStream `. Also contains the :py:func:`save_images ` and :py:func:`write_scene_list ` / :py:func:`write_scene_list_html ` functions to export information about the detected scenes in various formats. - - * :ref:`scenedetect.detectors 🕵️ `: Scene/shot detection algorithms: - - * :py:mod:`ContentDetector `: detects fast changes/cuts in video content. - - * :py:mod:`ThresholdDetector `: detects changes in video brightness/intensity. - - * :py:mod:`AdaptiveDetector `: similar to `ContentDetector` but may result in less false negatives during rapid camera movement. - - * :ref:`scenedetect.video_stream 🎥 `: Contains :py:class:`VideoStream ` interface for video decoding using different backends (:py:mod:`scenedetect.backends`). Current supported backends: - - * OpenCV: :py:class:`VideoStreamCv2 ` - * PyAV: In Development - - * :ref:`scenedetect.video_splitter ✂️ `: Contains :py:func:`split_video_ffmpeg ` and :py:func:`split_video_mkvmerge ` to split a video based on the detected scenes. - - * :ref:`scenedetect.frame_timecode ⏱️ `: Contains - :py:class:`FrameTimecode ` - class for storing, converting, and performing arithmetic on timecodes - with frame-accurate precision. - - * :ref:`scenedetect.scene_detector 🌐 `: Contains :py:class:`SceneDetector ` base class for implementing scene detection algorithms. - - * :ref:`scenedetect.stats_manager 🧮 `: Contains :py:class:`StatsManager ` class for caching frame metrics and loading/saving them to disk in CSV format for analysis. Also used as a persistent cache to make multiple passes on the same video significantly faster. - - * :ref:`scenedetect.platform 🐱‍💻 `: Logging and utility functions. - - -Most types/functions are also available directly from the `scenedetect` package to make imports simpler. - -.. note:: - - The PySceneDetect API is still under development. It is recommended that you pin the `scenedetect` version in your requirements to below the next major release: - - .. code:: python - - scenedetect<0.7 - - -.. _scenedetect-quickstart: - -======================================================================= -Quickstart -======================================================================= - -To get started, the :py:func:`scenedetect.detect` function takes a path to a video and a :ref:`scene detector object`, and returns a list of start/end timecodes. For detecting fast cuts (shot changes), we use the :py:class:`ContentDetector `: - -.. code:: python - - from scenedetect import detect, ContentDetector - scene_list = detect('my_video.mp4', ContentDetector()) - -``scene_list`` is now a list of :py:class:`FrameTimecode ` pairs representing the start/end of each scene (try calling ``print(scene_list)``). Note that you can set ``show_progress=True`` when calling :py:func:`detect ` to display a progress bar with estimated time remaining. - -Next, let's print the scene list in a more readable format by iterating over it: - -.. code:: python - - for i, scene in enumerate(scene_list): - print('Scene %2d: Start %s / Frame %d, End %s / Frame %d' % ( - i+1, - scene[0].get_timecode(), scene[0].get_frames(), - scene[1].get_timecode(), scene[1].get_frames(),)) - -Now that we know where each scene is, we can also :ref:`split the input video ` automatically using `ffmpeg` (`mkvmerge` is also supported): - -.. code:: python - - from scenedetect import detect, ContentDetector, split_video_ffmpeg - scene_list = detect('my_video.mp4', ContentDetector()) - split_video_ffmpeg('my_video.mp4', scene_list) - -This is just a small snippet of what PySceneDetect offers. The library is very modular, and can integrate with most application workflows easily. - -In the next example, we show how the library components can be used to create a more customizable scene cut/shot detection pipeline. Additional demonstrations/recipes can be found in the `tests/test_api.py `_ file. - - -.. _scenedetect-detailed_example: - -======================================================================= -Example -======================================================================= - -In this example, we create a function ``find_scenes()`` which will load a video, detect the scenes, and return a list of tuples containing the (start, end) timecodes of each detected scene. Note that you can modify the `threshold` argument to modify the sensitivity of the :py:class:`ContentDetector `, or use other detection algorithms (e.g. :py:class:`ThresholdDetector `, :py:class:`AdaptiveDetector `). - -.. code:: python - - from scenedetect import SceneManager, open_video, ContentDetector - - def find_scenes(video_path, threshold=27.0): - video = open_video(video_path) - scene_manager = SceneManager() - scene_manager.add_detector( - ContentDetector(threshold=threshold)) - # Detect all scenes in video from current position to end. - scene_manager.detect_scenes(video) - # `get_scene_list` returns a list of start/end timecode pairs - # for each scene that was found. - return scene_manager.get_scene_list() - -Using a :py:class:`SceneManager ` directly allows tweaking the Parameters passed to :py:meth:`detect_scenes ` including setting a limit to the number of frames to process, which is useful for live streams/camera devices. You can also combine detection algorithms or create new ones from scratch. - -For a more advanced example of using the PySceneDetect API to with a stats file (to save per-frame metrics to disk and/or speed up multiple passes of the same video), take a look at the :ref:`example in the SceneManager reference`. - -In addition to module-level examples, demonstrations of some common use cases can be found in the `tests/test_api.py `_ file. - - -======================================================================= -Migrating From 0.5 -======================================================================= - -PySceneDetect 0.6 introduces several breaking changes which are incompatible with 0.5. See :ref:`Migration Guide ` for details on how to update your application. In addition, demonstrations of common use cases can be found in the `tests/test_api.py `_ file. - - -======================================================================= -Module-Level Functions -======================================================================= - - -`detect` -=============================================================== - -.. autofunction:: scenedetect.detect - -`open_video` -=============================================================== -.. autofunction:: scenedetect.open_video - - -======================================================================= -Logging -======================================================================= - -PySceneDetect outputs messages to a logger named ``pyscenedetect`` which does not have any default handlers. You can use :py:func:`scenedetect.init_logger ` with ``show_stdout=True`` or specify a log file (verbosity can also be specified) to attach some common handlers, or use ``logging.getLogger('pyscenedetect')`` and attach log handlers manually. diff --git a/manual/api/backends.rst b/manual/api/backends.rst deleted file mode 100644 index a9405a6c..00000000 --- a/manual/api/backends.rst +++ /dev/null @@ -1,37 +0,0 @@ - -.. _scenedetect-backends: - ----------------------------------------- -Backends ----------------------------------------- - -.. automodule:: scenedetect.backends - :members: - :undoc-members: - - -========================================= -OpenCV -========================================= - -.. automodule:: scenedetect.backends.opencv - :members: - :undoc-members: - - -========================================= -PyAV -========================================= - -.. automodule:: scenedetect.backends.pyav - :members: - :undoc-members: - - -========================================= -MoviePy -========================================= - -.. automodule:: scenedetect.backends.moviepy - :members: - :undoc-members: diff --git a/manual/api/detectors.rst b/manual/api/detectors.rst deleted file mode 100644 index 2ff02890..00000000 --- a/manual/api/detectors.rst +++ /dev/null @@ -1,38 +0,0 @@ - -.. _scenedetect-detectors: - ----------------------------------------- -Detection Algorithms ----------------------------------------- - -.. automodule:: scenedetect.detectors - :members: - :undoc-members: - - -========================================= -ContentDetector -========================================= - -.. automodule:: scenedetect.detectors.content_detector - :members: - :undoc-members: - - -========================================= -AdaptiveDetector -========================================= - -.. automodule:: scenedetect.detectors.adaptive_detector - :members: - :undoc-members: - - -========================================= -ThresholdDetector -========================================= - -.. automodule:: scenedetect.detectors.threshold_detector - :members: - :undoc-members: - diff --git a/manual/api/frame_timecode.rst b/manual/api/frame_timecode.rst deleted file mode 100644 index bef60c13..00000000 --- a/manual/api/frame_timecode.rst +++ /dev/null @@ -1,22 +0,0 @@ - -.. _scenedetect-frame_timecode: - ---------------------------------------------------------------- -FrameTimecode ---------------------------------------------------------------- - -.. automodule:: scenedetect.frame_timecode - -=============================================================== -``FrameTimecode`` Class -=============================================================== - -.. autoclass:: scenedetect.frame_timecode.FrameTimecode - :members: - :undoc-members: - -=============================================================== -Constants -=============================================================== - -.. autodata:: scenedetect.frame_timecode.MAX_FPS_DELTA diff --git a/manual/api/migration_guide.rst b/manual/api/migration_guide.rst deleted file mode 100644 index d453bc1e..00000000 --- a/manual/api/migration_guide.rst +++ /dev/null @@ -1,136 +0,0 @@ - -.. _scenedetect-migration_guide: - ---------------------------------------------------------------- -Migration Guide ---------------------------------------------------------------- - -This page details how to transition a program written using PySceneDetect 0.5 to the new 0.6 API. It is recommended to review the new :ref:`Quickstart ` and :ref:`Example ` sections first, as they should cover the majority of use cases. Also see `tests/test_api.py `_ for a set of demonstrations covering many high level use cases. - -PySceneDetect v0.6 is a major step towards a more stable and simplified API. The biggest change to existing workflows is how video input is handled, and that Python 3.6 or above is now required. - -This page covers commonly used APIs which require updates to work with v0.6. Note that this page is not an exhaustive set of changes. For a complete list of breaking API changes, see `the changelog `_. - -In some places, a backwards compatibility layer has been added to avoid breaking most applications upon release. This should not be relied upon, and will be removed in the future. You can call ``scenedetect.platform.init_logger(show_stdout=True)`` or attach a custom log handler to the ``'pyscenedetect'`` logger to help find these cases. - - -=============================================================== -`VideoManager` Class -=============================================================== - -`VideoManager` has been deprecated and replaced with :py:mod:`scenedetect.backends`. For most applications, the :py:func:`open_video ` function should be used instead: - -.. code:: python - - from scenedetect import open_video - video = open_video(video.mp4') - -The resulting object can then be passed to a :py:class:`SceneManager ` when calling :py:meth:`detect_scenes `, or any other function/method that used to take a `VideoManager`, e.g.: - -.. code:: python - - from scenedetect import open_video, SceneManager, ContentDetector - video = open_video('video.mp4') - scene_manager = SceneManager() - scene_manager.add_detector(ContentDetector(threshold=threshold)) - scene_manager.detect_scenes(video) - print(scene_manager.get_scene_list()) - -See :py:mod:`scenedetect.backends` for examples of how to create specific backends. Where previously a list of paths was accepted, now only a single string should be provided. - - -Seeking and Start/End Times -=============================================================== - -Instead of setting the start time via the `VideoManager`, now :py:meth:`seek ` to the starting time on the :py:class:`VideoStream ` object. - -Instead of setting the duration or end time via the `VideoManager`, now set the `duration` or `end_time` parameters when calling :py:meth:`detect_scenes `. - -.. code:: python - - from scenedetect import open_video, SceneManager, ContentDetector - video = open_video('video.mp4') - # Can be seconds (float), frame # (int), or FrameTimecode - start_time, end_time = 2.5, 5.0 - scene_manager = SceneManager() - scene_manager.add_detector(ContentDetector(threshold=threshold)) - video.seek(start_time) - # Note there is also a `duration` parameter that can also be set. - # If neither `duration` nor `end_time` is provided, the video will - # be processed from its current position until the end. - scene_manager.detect_scenes(video, end_time=end_time) - print(scene_manager.get_scene_list()) - - -=============================================================== -`SceneManager` Class -=============================================================== - -The first argument of the :py:meth:`detect_scenes ` method has been renamed to `video` and should now be a :py:class:`VideoStream ` object (see above). - - -=============================================================== -`save_images` Function -=============================================================== - -The second argument of :py:func:`save_images ` in :py:mod:`scenedetect.scene_manager` has been renamed from `video_manager` to `video`. - -The `downscale_factor` parameter has been removed from :py:func:`save_images ` (use the `scale` parameter instead). To achieve the same result as the previous version, set `scale` to `1.0 / downscale_factor`. - - -=============================================================== -`split_video_*` Functions -=============================================================== - -The the :py:mod:`scenedetect.video_splitter` functions :py:func:`split_video_ffmpeg ` and :py:func:`split_video_mkvmerge ` now only accept a single path as the input (first) argument. - -The `suppress_output` and `hide_progress` arguments to the :py:func:`split_video_ffmpeg ` and :py:func:`split_video_mkvmerge ` have been removed, and two new options have been added: - - * `suppress_output` is now `show_output`, default is `False` - * `hide_progress` is now `show_progress`, default is `False` - -This makes the API consistent with that of :py:class:`SceneManager `. - - -=============================================================== -`StatsManager` Class -=============================================================== - -The :py:func:`save_to_csv ` and :py:func:`load_from_csv ` methods now accept either a `path` or an open `file` handle. - -The `base_timecode` argument has been removed from :py:func:`save_to_csv `. It is no longer required. - - -=============================================================== -`AdaptiveDetector` Class -=============================================================== - -The `video_manager` parameter has been removed and is no longer required when constructing an :py:class:`AdaptiveDetector ` object. - - -=============================================================== -Other -=============================================================== - -`ThresholdDetector` Class -=============================================================== - -The `block_size` argument has been removed from the :py:class:`ThresholdDetector ` constructor. It is no longer required. - - -`ContentDetector` Class -=============================================================== - -The `calculate_frame_score` method of :py:class:`ContentDetector ` has been renamed to :py:meth:`_calculate_frame_score `. Use new global function :py:func:`calculate_frame_score ` to achieve the same result. - - -`MINIMUM_FRAMES_PER_SECOND_*` Constants -=============================================================== - -In :py:mod:`scenedetect.frame_timecode` the constants `MINIMUM_FRAMES_PER_SECOND_FLOAT` and `MINIMUM_FRAMES_PER_SECOND_DELTA_FLOAT` have been replaced with :py:data:`MAX_FPS_DELTA `. - - -`get_aspect_ratio` Function -=============================================================== - - The `get_aspect_ratio` function has been removed from `scenedetect.platform`. Use the :py:attr:`aspect_ratio ` property from the :py:class:`VideoStream ` object instead. diff --git a/manual/api/platform.rst b/manual/api/platform.rst deleted file mode 100644 index 663a4efc..00000000 --- a/manual/api/platform.rst +++ /dev/null @@ -1,29 +0,0 @@ - -.. _scenedetect-platform: - ---------------------------------------------------------------- -Platform & Logging ---------------------------------------------------------------- - -.. automodule:: scenedetect.platform - - -=============================================================== -Functions -=============================================================== - -.. autofunction:: scenedetect.platform.get_and_create_path - -.. autofunction:: scenedetect.platform.get_file_name - -.. autofunction:: scenedetect.platform.init_logger - -.. autofunction:: scenedetect.platform.invoke_command - - -=============================================================== -Exceptions -=============================================================== - -.. autoexception:: scenedetect.platform.CommandTooLong - diff --git a/manual/api/scene_detector.rst b/manual/api/scene_detector.rst deleted file mode 100644 index b9a2dc78..00000000 --- a/manual/api/scene_detector.rst +++ /dev/null @@ -1,11 +0,0 @@ - -.. _scenedetect-scene_detector: - -------------------------------------------------- -SceneDetector -------------------------------------------------- - -.. automodule:: scenedetect.scene_detector - :members: - :undoc-members: - :private-members: diff --git a/manual/api/scene_manager.rst b/manual/api/scene_manager.rst deleted file mode 100644 index cac35af4..00000000 --- a/manual/api/scene_manager.rst +++ /dev/null @@ -1,56 +0,0 @@ - -.. _scenedetect-scene_manager: - ------------------------------------------------------------------------ -SceneManager ------------------------------------------------------------------------ - -.. automodule:: scenedetect.scene_manager - - -.. _scenemanager-example: - -======================================================================= -Storing Per-Frame Statistics -======================================================================= - -A `SceneManager` can use an optional :py:class:`StatsManager ` to save per-frame statistics to disk: - -.. code:: python - - from scenedetect import open_video, ContentDetector, SceneManager, StatsManager - video = open_video(test_video_file) - scene_manager = SceneManager(stats_manager=StatsManager()) - scene_manager.add_detector(ContentDetector()) - scene_manager.detect_scenes(video=video) - scene_list = scene_manager.get_scene_list() - print_scenes(scene_list=scene_list) - # Save per-frame statistics to disk. - scene_manager.stats_manager.save_to_csv(csv_file=STATS_FILE_PATH) - - -The statsfile can be used to find a better threshold for certain inputs, or perform further statistical analysis. The use of a :py:class:`StatsManager ` also allows certain detectors to operate faster on subsequent passes by caching calculations. Statsfiles can be persisted on disk and loaded again, which helps avoid unnecessary calculations in applications where multiple passes are expected (e.g. interactively selecting a threshold). - - -======================================================================= -``SceneManager`` Class -======================================================================= - -.. autoclass:: scenedetect.scene_manager.SceneManager - :members: - :undoc-members: - - -.. _scenedetect-scene_manager-functions: - -======================================================================= -``scene_manager`` Functions -======================================================================= - -.. autofunction:: scenedetect.scene_manager.save_images - -.. autofunction:: scenedetect.scene_manager.write_scene_list - -.. autofunction:: scenedetect.scene_manager.write_scene_list_html - -.. autofunction:: scenedetect.scene_manager.get_scenes_from_cuts diff --git a/manual/api/stats_manager.rst b/manual/api/stats_manager.rst deleted file mode 100644 index 6765dc47..00000000 --- a/manual/api/stats_manager.rst +++ /dev/null @@ -1,28 +0,0 @@ - -.. _scenedetect-stats_manager: - ------------------------------------------------------------------------ -StatsManager ------------------------------------------------------------------------ - -.. automodule:: scenedetect.stats_manager - - -======================================================================= -``StatsManager`` Class -======================================================================= - -.. autoclass:: scenedetect.stats_manager.StatsManager - :members: - :undoc-members: - - -======================================================================= -Exceptions -======================================================================= - -.. autoexception:: scenedetect.stats_manager.FrameMetricRegistered - -.. autoexception:: scenedetect.stats_manager.FrameMetricNotRegistered - -.. autoexception:: scenedetect.stats_manager.StatsFileCorrupt diff --git a/manual/api/video_splitter.rst b/manual/api/video_splitter.rst deleted file mode 100644 index 79d404d7..00000000 --- a/manual/api/video_splitter.rst +++ /dev/null @@ -1,11 +0,0 @@ - - -.. _scenedetect-video_splitter: - ---------------------------------------------------------------- -Video Splitting ---------------------------------------------------------------- - -.. automodule:: scenedetect.video_splitter - :members: - :undoc-members: diff --git a/manual/api/video_stream.rst b/manual/api/video_stream.rst deleted file mode 100644 index c2806287..00000000 --- a/manual/api/video_stream.rst +++ /dev/null @@ -1,41 +0,0 @@ - -.. _scenedetect-video_stream: - ---------------------------------------------------------------- -VideoStream ---------------------------------------------------------------- - -.. automodule:: scenedetect.video_stream - - -=============================================================== -``VideoStream`` Interface -=============================================================== - -.. autoclass:: scenedetect.video_stream.VideoStream - :members: - :undoc-members: - - -=============================================================== -``video_stream`` Functions and Constants -=============================================================== - -The following functions and constants are available in the ``scenedetect.video_stream`` module. - -.. autodata:: scenedetect.video_stream.DEFAULT_MIN_WIDTH - -.. autofunction:: scenedetect.video_stream.compute_downscale_factor - - -=============================================================== -Exceptions -=============================================================== - -.. autoexception:: scenedetect.video_stream.VideoOpenFailure - -.. autoexception:: scenedetect.video_stream.SeekError - - - - diff --git a/manual/cli/backends.rst b/manual/cli/backends.rst deleted file mode 100644 index 4a457451..00000000 --- a/manual/cli/backends.rst +++ /dev/null @@ -1,29 +0,0 @@ - -.. _cli-backends: - -*********************************************************************** -Backends -*********************************************************************** - -PySceneDetect supports multiple backends for video input. Some can be configured by using :ref:`a config file `. Installed backends can be verified by running ``scenedetect version --all``. - - -======================================================================= -OpenCV -======================================================================= - -*[Default]* -The `OpenCV `_ backend (usually `opencv-python `_) uses an underlying ``cv2.VideoCapture object`` for video input. Can be used by specifying ``-b opencv`` via command line, or setting ``backend = opencv`` under the ``[global]`` section of your :ref:`config file `. - -It is mostly reliable and fast, although can occasionally run into issues processing videos with multiple audio tracks or small amounts of frame corruption. You can use a custom version of the ``cv2`` package, or install either the `opencv-python` or `opencv-python-headless` packages from `pip`. - -The OpenCV backend also supports image sequences as inputs (e.g. ``frame%02d.jpg`` if you want to load frame001.jpg, frame002.jpg, frame003.jpg...). Make sure to specify the framerate manually (``-f``/``--framerate``) to ensure accurate timing calculations. - - -======================================================================= -PyAV -======================================================================= - -The `PyAV `_ backend (package `av _`) is a more robust backend that handles multiple audio tracks and frame decode errors gracefully. - -This backend can be used by specifying ``-b pyav`` via command line, or setting ``backend = pyav`` under the ``[global]`` section of your :ref:`config file `. diff --git a/manual/cli/commands.rst b/manual/cli/commands.rst deleted file mode 100644 index 87ff4c55..00000000 --- a/manual/cli/commands.rst +++ /dev/null @@ -1,356 +0,0 @@ - -.. _cli-commands: - -*********************************************************************** -Commands -*********************************************************************** - -The following commands are available when using ``scenedetect``. Several commands can be combined together (the order does not matter) to control various input/output options. - -The following is a list of the available commands along with a brief description of the command's function and an example. - - -Help/information commands: - - - :ref:`help ` - Prints help and usage information for commands - ``help`` or ``help split-video`` or ``help all`` - - :ref:`about ` - Prints license and copyright information about PySceneDetect - - :ref:`version ` - Print PySceneDetect version Number - -Input/output commands (applies to input videos and detected scenes): - - - :ref:`time