├── tests ├── benchmarks │ ├── __init__.py │ ├── test_benchmark_vpdqpy.py │ └── profile_vpdq.py ├── unit_tests │ ├── __init__.py │ ├── README.md │ ├── test_db.py │ └── test_vpdqpy.py ├── acceptance_tests │ ├── __init__.py │ ├── README.md │ ├── test_dedupe.py │ └── test_main_vcr.py ├── __init__.py ├── check_testdb.py └── tests.md ├── src └── hydrusvideodeduplicator │ ├── __init__.py │ ├── vpdqpy │ ├── __init__.py │ ├── typing_utils.py │ └── vpdqpy.py │ ├── __about__.py │ ├── __main__.py │ ├── typing_utils.py │ ├── hydrus_api │ ├── README.md │ ├── utils.py │ └── LICENSE │ ├── winexe_entrypoint.py │ ├── hashing.py │ ├── config.py │ ├── page_logger.py │ ├── dedup_util.py │ ├── client.py │ ├── entrypoint.py │ ├── dedup.py │ └── db │ └── DedupeDB.py ├── .editorconfig ├── docs ├── img │ ├── preview.png │ └── reset_duplicates.png ├── contact.md ├── credits.md ├── theory.md ├── index.md ├── installation.md ├── usage.md ├── development.md └── faq.md ├── .gitmodules ├── .gitattributes ├── mkdocs-gh-pages.yml ├── .vscode ├── settings.json └── launch.json ├── Dockerfile ├── docker-compose.yml ├── .github └── workflows │ ├── docs-publish.yml │ ├── build-docker.yml │ ├── windows-publish.yml │ ├── python-publish.yml │ └── test.yml ├── mkdocs.yml ├── LICENSE ├── docker-entrypoint.sh ├── README.md ├── .gitignore └── pyproject.toml /tests/benchmarks/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/unit_tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/acceptance_tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.py] 2 | profile = black 3 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/vpdqpy/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/__about__.py: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: MIT 2 | __version__ = "0.10.0" 3 | -------------------------------------------------------------------------------- /tests/unit_tests/README.md: -------------------------------------------------------------------------------- 1 | # Unit Tests 2 | 3 | The unit tests only test segments of the program. 4 | -------------------------------------------------------------------------------- /docs/img/preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hydrusvideodeduplicator/hydrus-video-deduplicator/HEAD/docs/img/preview.png -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023-present appleappleapplenanner <> 2 | # 3 | # SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "testdb"] 2 | path = tests/testdb 3 | url = https://github.com/hydrusvideodeduplicator/testdb.git 4 | -------------------------------------------------------------------------------- /docs/img/reset_duplicates.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hydrusvideodeduplicator/hydrus-video-deduplicator/HEAD/docs/img/reset_duplicates.png -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/__main__.py: -------------------------------------------------------------------------------- 1 | from hydrusvideodeduplicator.entrypoint import run_main 2 | 3 | if __name__ == "__main__": 4 | run_main() 5 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/typing_utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from dataclasses import dataclass 4 | 5 | 6 | @dataclass 7 | class ValueRange: 8 | lo: int 9 | hi: int 10 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.mkv filter=lfs diff=lfs merge=lfs -text 2 | *.mp4 filter=lfs diff=lfs merge=lfs -text 3 | *.gif filter=lfs diff=lfs merge=lfs -text 4 | *.webm filter=lfs diff=lfs merge=lfs -text 5 | 6 | *.svg text 7 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/vpdqpy/typing_utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from dataclasses import dataclass 4 | 5 | 6 | @dataclass 7 | class ValueRange: 8 | lo: int 9 | hi: int 10 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/hydrus_api/README.md: -------------------------------------------------------------------------------- 1 | This module, hydrus-api, is written by cryzed and licensed under AGPLv3. 2 | 3 | You can find the license in LICENSE. 4 | 5 | Repository: https://gitlab.com/cryzed/hydrus-api -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/winexe_entrypoint.py: -------------------------------------------------------------------------------- 1 | from hydrusvideodeduplicator import config 2 | from hydrusvideodeduplicator.entrypoint import run_main 3 | 4 | if __name__ == "__main__": 5 | config.set_windows_exe() 6 | run_main() 7 | -------------------------------------------------------------------------------- /mkdocs-gh-pages.yml: -------------------------------------------------------------------------------- 1 | INHERIT: mkdocs.yml 2 | 3 | site_url: https://hydrusvideodeduplicator.github.io/hydrus-video-deduplicator/ 4 | 5 | plugins: 6 | - search 7 | - git-revision-date-localized: 8 | exclude: 9 | - index.md 10 | -------------------------------------------------------------------------------- /tests/acceptance_tests/README.md: -------------------------------------------------------------------------------- 1 | # Acceptance Tests 2 | 3 | The acceptance tests ensure that all the videos which are similar have been marked similar in Hydrus, 4 | and all the videos which are not similar have not been marked similar in Hydrus. 5 | 6 | This is different than unit tests, which only test smaller parts of the program. 7 | -------------------------------------------------------------------------------- /docs/contact.md: -------------------------------------------------------------------------------- 1 | # Contact 2 | 3 | Create an issue on GitHub for any problems/concerns. Provide as much detail as possible in your issue. 4 | 5 | Email `hydrusvideodeduplicator@gmail.com` for other general questions/concerns. 6 | 7 | Message `@applenanner` on the [Hydrus Discord](https://discord.gg/wPHPCUZ) for other general questions/concerns. 8 | -------------------------------------------------------------------------------- /tests/check_testdb.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | 4 | 5 | def check_testdb_exists(): 6 | """ 7 | Check if the testdb submodule is pulled. 8 | Throws RuntimeError if it's not updated. 9 | """ 10 | testdb_dir = Path(__file__).parent / "testdb" 11 | if len(os.listdir(testdb_dir)) == 0: 12 | raise RuntimeError("Video hashes dir is missing. Is the testdb submodule pulled?") 13 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.testing.unittestArgs": [ 3 | "-v", 4 | "-s", 5 | "./tests", 6 | "-p", 7 | "test_*.py" 8 | ], 9 | "python.testing.pytestEnabled": false, 10 | "python.testing.unittestEnabled": true, 11 | "[python]": { 12 | "editor.defaultFormatter": "ms-python.black-formatter", 13 | "editor.formatOnSave": true, 14 | "editor.codeActionsOnSave": { 15 | "source.organizeImports": "explicit" 16 | }, 17 | }, 18 | } -------------------------------------------------------------------------------- /docs/credits.md: -------------------------------------------------------------------------------- 1 | # Credits 2 | 3 | [Hydrus Network](https://github.com/hydrusnetwork/hydrus) (DWTFYWTPL) by Hydrus dev 4 | 5 | [Hydrus API Library](https://gitlab.com/cryzed/hydrus-api) (GNU AGPLv3) by cryzed 6 | 7 | [pdq](https://github.com/facebook/ThreatExchange/tree/main/pdq) (BSD) by Meta 8 | 9 | [vpdq](https://github.com/facebook/ThreatExchange/tree/main/vpdq) (BSD) by Meta 10 | 11 | [Big Buck Bunny](https://peach.blender.org/about), [Sintel](https://durian.blender.org/about/) (CC BY 3.0) clips by Blender Foundation 12 | -------------------------------------------------------------------------------- /docs/theory.md: -------------------------------------------------------------------------------- 1 | # Theory 2 | 3 | ![Hydrus Video Deduplicator High Level Diagram](img/hvd_high_level_diagram.drawio.svg) 4 | 5 | 1. First, video files are perceptually hashed. These perceptual hashes are cached in a local database. 6 | 7 | 1. Then, a similarity search cache is built using the perceptual hashes to make it possible to compare video similarities very quickly. 8 | 9 | 1. Finally, the search cache is queried for a given relative similarity threshold, and video pairs that exceed that that threshold 10 | will be marked as potential duplicates in Hydrus via the Hydrus Client API. 11 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:24.04 2 | WORKDIR /usr/src/app 3 | RUN apt-get update && apt-get install -y \ 4 | python3 \ 5 | python3-pip \ 6 | python3-venv \ 7 | git \ 8 | ffmpeg \ 9 | && rm -rf /var/lib/apt/lists/* 10 | 11 | # Need to make a venv because Ubuntu doesn't allow globally installed Python packages anymore (PEP 668) 12 | ENV VIRTUAL_ENV=/opt/venv 13 | RUN python3 -m venv $VIRTUAL_ENV 14 | ENV PATH="$VIRTUAL_ENV/bin:$PATH" 15 | 16 | RUN python -m pip install hydrusvideodeduplicator 17 | COPY ./docker-entrypoint.sh ./entrypoint.sh 18 | 19 | ENV DEDUP_DATABASE_DIR=/usr/src/app/db 20 | ENV API_URL=https://host.docker.internal:45869 21 | CMD ["./entrypoint.sh"] 22 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # Home 2 | 3 | ![hydrus video deduplicator running in terminal](./img/preview.png) 4 | 5 | Hydrus Video Deduplicator finds potential duplicate videos through the Hydrus API and marks them as potential duplicates to allow manual filtering through the Hydrus Client GUI. 6 | 7 | Hydrus Video Deduplicator **does not modify your files**. It only marks videos as `potential duplicates` through the Hydrus API so that you can personally filter them in the duplicates processing page. 8 | 9 | [See the Hydrus documentation for how duplicates are managed in Hydrus](https://hydrusnetwork.github.io/hydrus/duplicates.html). 10 | 11 | See the [Theory](theory.md) for an in-depth explanation for how it all works. 12 | -------------------------------------------------------------------------------- /tests/tests.md: -------------------------------------------------------------------------------- 1 | # testdb 2 | 3 | testdb is a submodule that contains the Hydrus DB and videos for testing purposes. 4 | 5 | It is a submodule to avoid bloating this repo with large media files used for testing. 6 | 7 | ## Instructions 8 | 9 | To checkout the submodule: 10 | 11 | ```sh 12 | git submodule update --init --recursive 13 | ``` 14 | 15 | To run tests: 16 | 17 | ```sh 18 | hatch run test:all 19 | ``` 20 | 21 | To run only specific tests, e.g., vcr: 22 | 23 | ```sh 24 | hatch run test:vcr 25 | ``` 26 | 27 | See [pyproject.toml](../pyproject.toml) test.scripts for full list of test groups. 28 | 29 | --- 30 | 31 | HVD DEV ONLY: 32 | 33 | To update the submodule to main: 34 | 35 | ```sh 36 | git submodule foreach git pull origin main 37 | ``` 38 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python Debugger: Module", 9 | "type": "debugpy", 10 | "request": "launch", 11 | "module": "hydrusvideodeduplicator", 12 | // You may want to customize these args or use a dotenv. 13 | // Below API key may need to be configured to your own. This is the testdb api key. 14 | "args": "--api-key='3b3cf10cc13862818ea95ddecfe434bed0828fb319b1ff56413917b471b566ab'" 15 | } 16 | ] 17 | } -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | # Example compose file 2 | 3 | services: 4 | hydrusvideodeduplicator: 5 | build: . 6 | container_name: hydrusvideodeduplicator 7 | volumes: 8 | - ./db:/usr/src/app/db # Database directory 9 | # - :/usr/src/app/cert # Optional, SSL cert 10 | environment: 11 | API_KEY: 12 | # API_URL: https://localhost:45869 # Optional, default is Docker host 13 | # HYDRUS_QUERY: '["system:limit is 2", "character:edward"]' # Optional, JSON array of search parameters 14 | # VERBOSE: 'true' 15 | # See full list of options on the wiki 16 | 17 | # If default API_URL does not connect to Hydrus on Docker host, 18 | # try using network_mode: host and set API_URL to https://localhost:45869 19 | network_mode: host 20 | 21 | -------------------------------------------------------------------------------- /.github/workflows/docs-publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Docs 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | workflow_dispatch: 8 | 9 | concurrency: 10 | group: publish-docs 11 | cancel-in-progress: true 12 | 13 | permissions: 14 | contents: write 15 | pages: write 16 | 17 | jobs: 18 | deploy: 19 | runs-on: ubuntu-latest 20 | steps: 21 | - uses: actions/checkout@v5 22 | with: 23 | fetch-depth: 0 24 | 25 | - name: Setup python 26 | uses: actions/setup-python@v6 27 | with: 28 | python-version: "3.14" 29 | 30 | - name: Install dependencies 31 | run: | 32 | python -m pip install uv 33 | uv venv 34 | uv pip install hatch 35 | 36 | - name: Deploy documentation 37 | run: | 38 | uv run hatch run docs:gh-deploy 39 | -------------------------------------------------------------------------------- /.github/workflows/build-docker.yml: -------------------------------------------------------------------------------- 1 | # Test that the Dockerfile builds successfully. 2 | # This does not test that the newest Python changes work, since the package is installed from pypi. 3 | 4 | on: 5 | push: 6 | branches: 7 | - main 8 | - develop 9 | paths: 10 | - Dockerfile 11 | - docker-entrypoint.sh 12 | - .github/workflows/build-docker.yml 13 | pull_request: 14 | branches: 15 | - main 16 | - develop 17 | paths: 18 | - Dockerfile 19 | - docker-entrypoint.sh 20 | - .github/workflows/build-docker.yml 21 | workflow_dispatch: 22 | 23 | jobs: 24 | docker: 25 | runs-on: ubuntu-latest 26 | steps: 27 | - name: Setup Docker Buildx 28 | uses: docker/setup-buildx-action@v3 29 | 30 | - name: Build image 31 | uses: docker/build-push-action@v6 32 | with: 33 | push: false 34 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: Hydrus Video Deduplicator 2 | site_description: "Video Deduplicator for the Hydrus Network." 3 | repo_name: hydrusvideodeduplicator/hydrus-video-deduplicator 4 | repo_url: https://github.com/hydrusvideodeduplicator/hydrus-video-deduplicator 5 | 6 | nav: 7 | - Home: index.md 8 | - Installation: installation.md 9 | - Usage: usage.md 10 | - FAQ: faq.md 11 | - Theory: theory.md 12 | - Development: development.md 13 | - Contact: contact.md 14 | - Credits: credits.md 15 | 16 | theme: 17 | name: material 18 | palette: 19 | - media: "(prefers-color-scheme: light)" 20 | scheme: default 21 | primary: lime 22 | accent: lime 23 | toggle: 24 | icon: material/toggle-switch-off-outline 25 | name: Switch to dark mode 26 | - media: "(prefers-color-scheme: dark)" 27 | scheme: slate 28 | primary: black 29 | accent: lime 30 | toggle: 31 | icon: material/toggle-switch 32 | name: Switch to light mode 33 | 34 | markdown_extensions: 35 | - pymdownx.superfences # Allow codeblock nested in list 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 hydrusvideodeduplicator 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/windows-publish.yml: -------------------------------------------------------------------------------- 1 | name: Windows publish 2 | 3 | on: 4 | release: 5 | types: [published] 6 | workflow_dispatch: 7 | 8 | permissions: 9 | contents: write 10 | 11 | jobs: 12 | build-windows: 13 | name: Build windows exe 14 | runs-on: windows-2025 15 | steps: 16 | - name: Checkout 17 | uses: actions/checkout@v5 18 | with: 19 | fetch-depth: 0 20 | 21 | - name: Setup Python 22 | uses: actions/setup-python@v5 23 | with: 24 | python-version: "3.14" 25 | 26 | - name: Install dependencies 27 | run : | 28 | python -m pip install uv 29 | uv venv 30 | uv pip install pyinstaller 31 | uv pip install . 32 | 33 | - name: Build 34 | run: uv run pyinstaller build_files/windows/hydrusvideodeduplicator.spec 35 | 36 | - name: Upload 37 | uses: softprops/action-gh-release@37fd9d0351a2df198244c8ef9f56d02d1f921e20 38 | if: startsWith(github.ref, 'refs/tags/') 39 | with: 40 | files: | 41 | dist/hydrusvideodeduplicator.exe 42 | env: 43 | GITHUB_TOKEN: ${{ secrets.GH_PAT }} 44 | -------------------------------------------------------------------------------- /docker-entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | Command="python -m hydrusvideodeduplicator" 4 | [[ -n "${API_KEY}" ]] && Command="${Command} --api-key='${API_KEY}'" 5 | [[ -n "${API_URL}" ]] && Command="${Command} --api-url='${API_URL}'" 6 | [[ -n "${THRESHOLD}" ]] && Command="${Command} --threshold=${THRESHOLD}" 7 | [[ -n "${JOB_COUNT}" ]] && Command="${Command} --job-count=${JOB_COUNT}" 8 | [[ -n "${FAILED_PAGE_NAME}" ]] && Command="${Command} --failed-page-name=${FAILED_PAGE_NAME}" 9 | [[ -n "${DEDUP_DATABASE_DIR}" ]] && Command="${Command} --dedup-database-dir=${DEDUP_DATABASE_DIR}" # you probably don't want to do this inside docker... 10 | 11 | [[ ${SKIP_HASHING} = "true" ]] && Command="${Command} --skip-hashing" || Command="${Command} --no-skip-hashing" 12 | [[ ${CLEAR_SEARCH_TREE} = "true" ]] && Command="${Command} --clear-search-tree" || Command="${Command} --no-clear-search-tree" 13 | [[ ${CLEAR_SEARCH_CACHE} = "true" ]] && Command="${Command} --clear-search-cache" || Command="${Command} --no-clear-search-cache" 14 | [[ ${VERBOSE} = "true" ]] && Command="${Command} --verbose" || Command="${Command} --no-verbose" 15 | [[ ${DEBUG} = "true" ]] && Command="${Command} --debug" || Command="${Command} --no-debug" 16 | echo "${Command}" 17 | eval "${Command}" 18 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/hashing.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from pathlib import Path 4 | from typing import TYPE_CHECKING 5 | 6 | if TYPE_CHECKING: 7 | from typing import Annotated 8 | 9 | from .typing_utils import ValueRange 10 | 11 | from .vpdqpy.vpdqpy import Vpdq, VpdqHash 12 | 13 | 14 | def compute_phash(video: Path | str | bytes, num_threads: int = 0) -> VpdqHash: 15 | """ 16 | Calculate the perceptual hash of a video. 17 | 18 | Returns the perceptual hash of the video. 19 | """ 20 | phash = Vpdq.computeHash(video, num_threads) 21 | return phash 22 | 23 | 24 | def encode_phash_to_str(phash: VpdqHash) -> str: 25 | """ 26 | Encode the perceptual hash of a video into a string. 27 | 28 | Returns the perceptual hash encoded as a string. 29 | """ 30 | encoded_phash = str(phash) 31 | return encoded_phash 32 | 33 | 34 | def decode_phash_from_str(phash_str: str) -> VpdqHash: 35 | """ 36 | Encode the perceptual hash of a video into a string. 37 | 38 | Returns the perceptual hash encoded as a string. 39 | """ 40 | return VpdqHash.from_string(phash_str) 41 | 42 | 43 | def get_phash_similarity( 44 | hash_a: VpdqHash, 45 | hash_b: VpdqHash, 46 | ) -> Annotated[float, ValueRange(0.0, 100.0)]: 47 | """ 48 | Check if video is similar by comparing their list of features 49 | Threshold is minimum similarity to be considered similar 50 | """ 51 | similarity = Vpdq.match_hash(query_features=hash_a, target_features=hash_b) 52 | assert similarity >= 0.0 and similarity <= 100.0 53 | return similarity 54 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | name: Upload Python Package to PyPI 2 | 3 | on: 4 | release: 5 | types: [published] 6 | workflow_dispatch: 7 | 8 | permissions: 9 | contents: read 10 | 11 | jobs: 12 | build_sdist: 13 | name: Build source distribution 14 | runs-on: ubuntu-24.04 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v5 18 | with: 19 | fetch-depth: 0 20 | 21 | - name: Setup Python 22 | uses: actions/setup-python@v6 23 | with: 24 | python-version: "3.14" 25 | 26 | - name: Install dependencies 27 | run : | 28 | python -m pip install uv 29 | uv venv 30 | uv pip install hatch 31 | 32 | - name: Build package without Hatch to make sure it works 33 | run: uv build && rm -rf dist 34 | 35 | - name: Build sdist 36 | run: uv run hatch build --clean --target sdist dist 37 | - uses: actions/upload-artifact@v4 38 | with: 39 | name: dist-sdist 40 | path: dist/*.tar.gz 41 | if-no-files-found: error 42 | 43 | deploy: 44 | needs: [build_sdist] 45 | runs-on: ubuntu-24.04 46 | environment: 47 | name: pypi 48 | url: https://pypi.org/p/hydrusvideodeduplicator 49 | permissions: 50 | contents: read 51 | id-token: write # this permission is mandatory for Trusted Publishing 52 | steps: 53 | - name: Download packages 54 | uses: actions/download-artifact@v4 55 | with: 56 | name: dist-sdist 57 | path: dist/ 58 | merge-multiple: true 59 | 60 | - name: Display downloaded packages 61 | run: ls -R dist/ 62 | 63 | - name: Publish package 64 | uses: pypa/gh-action-pypi-publish@76f52bc884231f62b9a034ebfe128415bbaabdfc 65 | -------------------------------------------------------------------------------- /docs/installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | ## Windows 4 | 5 | For Windows, you can get the [latest release directly from the github releases page](https://github.com/hydrusvideodeduplicator/hydrus-video-deduplicator/releases). 6 | 7 | You should now be good to go. Proceed to [usage.](./usage.md) 8 | 9 | --- 10 | 11 | ## Linux 12 | 13 | The following instructions are written for Ubuntu, but should be similar for most distros. 14 | 15 | > **Note:** [uv](https://docs.astral.sh/uv/) is the preferred package manager instead of pip for a development install due to its speed and ease of use. If it isn't supported by your distribution or you are using another OS like FreeBSD, then follow the steps below but use the usual Python venv and pip instead of uv. 16 | 17 | ### Dependencies 18 | 19 | - Python >=3.10 20 | 21 | ### Steps 22 | 23 | 1. Update system packages: 24 | 25 | ```sh 26 | sudo apt-get update && sudo apt-get upgrade 27 | ``` 28 | 29 | 1. Install system dependencies (just pip): 30 | 31 | ```sh 32 | sudo apt-get install -y python3-pip 33 | ``` 34 | 35 | 1. Create and activate a virtual environment: 36 | 37 | ```sh 38 | pip install uv 39 | uv venv # Create a virtual environment somewhere to avoid system dependency conflicts 40 | .venv/bin/activate # Activate the virtual environment (run the command uv suggests after running uv venv) 41 | ``` 42 | 43 | 1. Install the program: 44 | 45 | ```sh 46 | uv pip install hydrusvideodeduplicator 47 | ``` 48 | 49 | You should now be good to go. Proceed to [usage.](./usage.md) 50 | 51 | > **Note:** Any time you want to run the program again you will have to run the command to activate the virtual environment first. 52 | 53 | ## macos 54 | 55 | Same directions as Linux but using your preferred package manager for system dependencies e.g. [brew](https://brew.sh/). 56 | -------------------------------------------------------------------------------- /docs/usage.md: -------------------------------------------------------------------------------- 1 | # Usage 2 | 3 | ## Creating a Hydrus API Key 4 | 5 | 1. [Enable the Hydrus Client API service](https://hydrusnetwork.github.io/hydrus/client_api.html#enabling_the_api). Ensure `use https` is enabled for the client api service. 6 | 7 | - If you need http for some reason instead of https, you must specify your Hydrus API URL directly with `--api-url` 8 | - Ex. `python -m hydrusvideodeduplicator --api-url=http://localhost:45869` 9 | 10 | - Enable `allow non-local connections` in `manage services->client api` if you are running under [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/), or the connection will fail. 11 | 12 | - ⚠️ For https, SSL cert is **not verified** by default unless you enter the cert's file path with `--verify-cert` 13 | 14 | 2. Create a client api service key with `permits everything` enabled. 15 | 16 | - Do NOT set blacklist/whitelist filters for the API token. 17 | 18 | > **Example**: The API key should look something vaguely like `78d2fcc9fe1f43c5008959ed1abfe38ffedcfa127d4f051a1038e068d3e32656` 19 | 20 | > **Note**: You will need this API key in the next step, so you should probably copy this API key to your clipboard. 21 | 22 | After getting your API key, continue to [Running Video Dedupe](#running-video-dedupe). 23 | 24 | ## Running Video Dedupe 25 | 26 |
27 | Windows 28 |
29 | 30 | Run hydrusvideodeduplicator.exe and enter the Hydrus API key you created previously when prompted. 31 | 32 |
33 | 34 |
35 | 36 |
37 | Linux and macos 38 | 39 | Run the program and enter the Hydrus API key you created previously. 40 | 41 |
42 | 43 | Example: 44 | 45 | ```sh 46 | python -m hydrusvideodeduplicator --api-key="78d2fcc9fe1f43c5008959ed1abfe38ffedcfa127d4f051a1038e068d3e32656" 47 | ``` 48 | 49 |
50 | 51 |
52 | 53 | To cancel any stage of processing at any time, press CTRL+C. 54 | 55 | You may want to cancel the first step, perceptually hashing, before it's finished in order to search for duplicates on that subset of videos that have been hashed. The next time you run the program it will continue where you left off. This may be useful for large databases that may take forever to perceptually hash. 56 | 57 | See the full list of options with `--help`. 58 | 59 | See the [FAQ](./faq.md) for more information. 60 | 61 | ### Advanced Usage 62 | 63 | You can select certain files with queries just like Hydrus. e.g. `--query="character:batman"` 64 | 65 |
66 | Example 67 |
68 | 69 | ```sh 70 | python -m hydrusvideodeduplicator --api-key="..." --query="character:batman" 71 | ``` 72 | 73 |
74 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | 8 | permissions: 9 | contents: read 10 | 11 | jobs: 12 | linter: 13 | name: Linter and Formatter 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - name: Checkout code 18 | uses: actions/checkout@v4 19 | - name: Set up Python 20 | uses: actions/setup-python@v5 21 | with: 22 | python-version: "3.14" 23 | 24 | - name: Install dependencies 25 | run: | 26 | python -m pip install uv 27 | uv venv 28 | uv pip install hatch 29 | uv pip install -e . 30 | 31 | - name: Lint with Ruff 32 | run: uv run hatch run lint:lint 33 | 34 | - name: Format check with black 35 | run: uv run hatch run lint:format 36 | 37 | unittest: 38 | name: Unit Test 39 | strategy: 40 | matrix: 41 | python-version: ['3.10', '3.11', '3.12', '3.13', '3.14', '3.x'] 42 | os: ['ubuntu-latest', 'windows-2025', 'macos-14'] 43 | runs-on: ${{ matrix.os }} 44 | 45 | steps: 46 | - name: Checkout code 47 | uses: actions/checkout@v5 48 | with: 49 | lfs: 'false' 50 | submodules: 'recursive' 51 | 52 | - name: Set up Python 53 | uses: actions/setup-python@v6 54 | with: 55 | python-version: ${{ matrix.python-version }} 56 | 57 | - name: Install dependencies 58 | run: | 59 | python -m pip install uv 60 | uv venv 61 | uv pip install hatch 62 | 63 | - name: Unit test 64 | run: | 65 | uv run hatch env create test 66 | uv run hatch run test:all 67 | 68 | benchmark: 69 | name: Benchmark 70 | runs-on: ubuntu-latest 71 | strategy: 72 | matrix: 73 | python-version: ['3.10', '3.11', '3.12', '3.13', '3.14'] 74 | 75 | steps: 76 | - name: Checkout code 77 | uses: actions/checkout@v5 78 | with: 79 | lfs: 'false' 80 | submodules: 'recursive' 81 | 82 | - name: Set up Python 83 | uses: actions/setup-python@v5 84 | with: 85 | python-version: ${{ matrix.python-version }} 86 | 87 | - name: Install dependencies 88 | run: | 89 | python -m pip install uv 90 | uv venv 91 | uv pip install hatch 92 | 93 | - name: Create benchmark env 94 | run: | 95 | uv run hatch env create benchmark 96 | 97 | - name: Benchmark 98 | run: | 99 | uv run hatch run benchmark:vpdq --benchmark-json "${{ matrix.python-version }}.json" 100 | 101 | - name: Profile 102 | run: | 103 | uv run hatch run benchmark:profile_vpdq 104 | -------------------------------------------------------------------------------- /tests/benchmarks/test_benchmark_vpdqpy.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | These tests use clips from the Big Buck Bunny movie and Sintel movie, 4 | which are licensed under Creative Commons Attribution 3.0 5 | (https://creativecommons.org/licenses/by/3.0/). 6 | (c) copyright 2008, Blender Foundation / www.bigbuckbunny.org 7 | (c) copyright Blender Foundation | durian.blender.org 8 | Blender Foundation | www.blender.org 9 | 10 | """ 11 | 12 | from __future__ import annotations 13 | 14 | from pathlib import Path 15 | from typing import TYPE_CHECKING 16 | 17 | import pytest 18 | 19 | from hydrusvideodeduplicator.vpdqpy.vpdqpy import Vpdq, VpdqHash 20 | from hvdaccelerators import vpdq 21 | 22 | from ..check_testdb import check_testdb_exists 23 | 24 | if TYPE_CHECKING: 25 | pass 26 | 27 | 28 | @pytest.mark.benchmark(group="hashing", min_time=0.1, max_time=0.5, min_rounds=1, disable_gc=False, warmup=False) 29 | def test_vpdq_hashing(benchmark): 30 | """Benchmark VPDQ hashing""" 31 | """Currently around 7.5 seconds on my PC""" 32 | all_vids_dir = Path(__file__).parents[1] / "testdb" / "videos" 33 | 34 | vids_dirs = ["sintel"] 35 | similarity_vids: list[Path] = [] 36 | for vids_dir in vids_dirs: 37 | similarity_vids.extend(Path(all_vids_dir / vids_dir).glob("*")) 38 | vids_hashes = {} 39 | assert len(similarity_vids) > 0 40 | 41 | @benchmark 42 | def run(): 43 | for vid in similarity_vids: 44 | perceptual_hash = Vpdq.computeHash(vid) 45 | vids_hashes[vid] = perceptual_hash 46 | assert len(perceptual_hash) > 0 47 | 48 | 49 | @pytest.mark.benchmark(group="similarity", min_time=0.1, max_time=0.5, min_rounds=1, disable_gc=False, warmup=False) 50 | def test_vpdq_similarity(benchmark): 51 | """Benchmark VPDQ similarity""" 52 | all_phashes_dir = Path(__file__).parents[1] / "testdb" / "video hashes" 53 | 54 | video_hashes_paths: list[Path] = [] 55 | video_hashes_paths.extend(Path(all_phashes_dir).glob("*")) 56 | video_phashes: list[VpdqHash] = list() 57 | for video_hash_file in video_hashes_paths: 58 | with open(video_hash_file) as file: 59 | video_hash = vpdq.VpdqHash.from_string(file.readline()) 60 | video_phashes.append(video_hash) 61 | 62 | pairs = [] 63 | for i, phash1 in enumerate(video_phashes): 64 | for j, phash2 in enumerate(video_phashes): 65 | if j < i: 66 | continue 67 | pairs.append((phash1, phash2)) 68 | assert len(pairs) > 0 69 | 70 | @benchmark 71 | def run(): 72 | for pair in pairs: 73 | _ = Vpdq.is_similar(pair[0], pair[1], threshold=75) 74 | 75 | 76 | if __name__ == "__main__": 77 | check_testdb_exists() 78 | test_vpdq_hashing() 79 | test_vpdq_similarity() 80 | -------------------------------------------------------------------------------- /tests/acceptance_tests/test_dedupe.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | import time 5 | import unittest 6 | from typing import TYPE_CHECKING 7 | 8 | from hydrusvideodeduplicator.client import HVDClient 9 | from hydrusvideodeduplicator.dedup import HydrusVideoDeduplicator 10 | 11 | if TYPE_CHECKING: 12 | pass 13 | 14 | TEST_API_URL = "https://localhost:45869" 15 | TEST_API_ACCESS_KEY = "3b3cf10cc13862818ea95ddecfe434bed0828fb319b1ff56413917b471b566ab" 16 | 17 | 18 | @unittest.skip("Skipped Hydrus dedupe: implementation not finished") 19 | class TestDedupe(unittest.TestCase): 20 | log = logging.getLogger(__name__) 21 | log.setLevel(logging.WARNING) 22 | logging.basicConfig() 23 | 24 | def setUp(self): 25 | """TODO: Check if Hydrus Docker container is accessible before this.""" 26 | """TODO: Clear database before this for repeated runs.""" 27 | 28 | # Try to connect to Hydrus 29 | connect_attempts = 0 30 | max_attempts = 3 31 | while connect_attempts < max_attempts: 32 | TestDedupe.log.info(f"Attempting connection to Hydrus... {connect_attempts}/{max_attempts}") 33 | try: 34 | # Create Hydrus connection 35 | self.hvdclient = HVDClient( 36 | file_service_keys=None, 37 | api_url=TEST_API_URL, 38 | access_key=TEST_API_ACCESS_KEY, 39 | verify_cert=False, 40 | ) 41 | except Exception as exc: 42 | connect_attempts += 1 43 | time.sleep(0.5) 44 | TestDedupe.log.warning(exc) 45 | 46 | else: 47 | break 48 | if connect_attempts == max_attempts: 49 | TestDedupe.log.error(f"Failed to connect to Hydrus client after {connect_attempts} tries.") 50 | self.fail("Failed to connect to Hydrus.") 51 | try: 52 | self.assertNotEqual(self.hvdclient, None) 53 | except AttributeError: 54 | self.fail("Failed to connect to Hydrus.") 55 | 56 | self.hvd = HydrusVideoDeduplicator( 57 | self.hvdclient, 58 | # job_count=-2, # TODO: Do tests for single and multi-threaded. 59 | ) 60 | 61 | initial_dedupe_count = self.hvdclient.get_potential_duplicate_count_hydrus() 62 | self.assertEqual( 63 | initial_dedupe_count, 64 | 0, 65 | f"Initial potential duplicates must be 0." 66 | f"Potential duplicates: {initial_dedupe_count}. Reset the database before running tests.", 67 | ) 68 | 69 | def test_temp(self): 70 | self.assertTrue(True) 71 | 72 | 73 | if __name__ == "__main__": 74 | unittest.main(module="test_dedupe") 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hydrus Video Deduplicator 2 | 3 |
4 | 5 | ![hydrus video deduplicator running in terminal](./docs/img/preview.png) 6 | 7 | Hydrus Video Deduplicator finds potential duplicate videos through the Hydrus API and marks them as potential duplicates to allow manual filtering through the Hydrus Client GUI. 8 | 9 | [![PyPI - Version](https://img.shields.io/pypi/v/hydrusvideodeduplicator.svg)](https://pypi.org/project/hydrusvideodeduplicator) 10 | [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hydrusvideodeduplicator.svg)](https://pypi.org/project/hydrusvideodeduplicator) 11 | [![PyPI downloads](https://img.shields.io/pypi/dm/hydrusvideodeduplicator.svg)](https://pypistats.org/packages/hydrusvideodeduplicator) 12 | [![GitHub Repo stars](https://img.shields.io/github/stars/hydrusvideodeduplicator/hydrus-video-deduplicator)](https://github.com/hydrusvideodeduplicator/hydrus-video-deduplicator/stargazers) 13 | 14 |
15 | 16 | --- 17 | 18 | Hydrus Video Deduplicator **does not modify your files**. It only marks videos as `potential duplicates` through the Hydrus API so that you can filter them manually in the duplicates processing page. 19 | 20 | [See the Hydrus documentation for how duplicates are managed in Hydrus](https://hydrusnetwork.github.io/hydrus/duplicates.html). 21 | 22 | This program contains no telemetry. It only makes requests to the Hydrus API URL which you specify. 23 | 24 | ## [Installation](./docs/installation.md) 25 | 26 | For Windows, you can get the [latest release directly from the github releases page](https://github.com/hydrusvideodeduplicator/hydrus-video-deduplicator/releases). 27 | 28 | For Linux and macos, see the [Python Install](#python-install). 29 | 30 | > **Note**: Many instructions in this repo are written for the Python install instead of the Windows exe. If you're using the Windows exe, simply replace `python -m hydrusvideodeduplicator` with `hydrusvideodeduplicator.exe` and the instructions will work the same. 31 | 32 | ## [Usage](./docs/usage.md) 33 | 34 | See [Usage](./docs/usage.md) for how to run the program, and [FAQ](./docs/faq.md) for more information. 35 | 36 | ## Python Install 37 | 38 | > **Note**: Windows users do not need the Python install. Download the exe as described in [Installation](#installation) instead. 39 | 40 | ### Dependencies 41 | 42 | - [Python](https://www.python.org/downloads/) >=3.10 43 | 44 | ```sh 45 | python -m pip install hydrusvideodeduplicator 46 | ``` 47 | 48 | Then continue to [Usage](./docs/usage.md). 49 | 50 | --- 51 | 52 | ## [Contact](./docs/contact.md) 53 | 54 | Create an issue on GitHub for any problems/concerns. Provide as much detail as possible in your issue. 55 | 56 | Email `hydrusvideodeduplicator@gmail.com` for other general questions/concerns. 57 | 58 | Message `@applenanner` on the [Hydrus Discord](https://discord.gg/wPHPCUZ) for other general questions/concerns. 59 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/config.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import json 4 | import os 5 | from pathlib import Path 6 | from platform import uname 7 | 8 | from dotenv import load_dotenv 9 | from platformdirs import PlatformDirs 10 | 11 | 12 | class InvalidEnvironmentVariable(Exception): 13 | """Raise for when environment variables are invalid.""" 14 | 15 | def __init__(self, msg): 16 | super().__init__(msg) 17 | print("Exiting due to invalid environment variable.") 18 | 19 | 20 | # Validates that a env var is a valid JSON array 21 | # Program will exit if invalid 22 | # Returns the parsed json array as a list 23 | def validate_json_array_env_var(env_var: str | None, err_msg: str) -> list | None: 24 | if env_var is None: 25 | return None 26 | 27 | try: 28 | env_var_list = json.loads(env_var) 29 | if not isinstance(env_var_list, list): 30 | raise InvalidEnvironmentVariable(f"ERROR: {err_msg}") 31 | except json.decoder.JSONDecodeError as exc: 32 | raise InvalidEnvironmentVariable(f"ERROR: {err_msg}") from exc 33 | 34 | return env_var_list 35 | 36 | 37 | load_dotenv() 38 | HYDRUS_API_KEY = os.getenv("HYDRUS_API_KEY") 39 | 40 | 41 | def in_wsl() -> bool: 42 | return "microsoft-standard" in uname().release 43 | 44 | 45 | _DEFAULT_IP = "localhost" 46 | _DEFAULT_PORT = "45869" 47 | # If you're in WSL you probably want to connect to your Windows Hydrus Client by default 48 | if in_wsl(): 49 | from socket import gethostname 50 | 51 | _DEFAULT_IP = f"{gethostname()}.local" 52 | 53 | HYDRUS_API_URL = os.getenv("HYDRUS_API_URL", f"https://{_DEFAULT_IP}:{_DEFAULT_PORT}") 54 | 55 | # ~/.local/share/hydrusvideodeduplicator/ on Linux 56 | _DEDUP_DATABASE_DIR_ENV = PlatformDirs("hydrusvideodeduplicator").user_data_dir 57 | _DEDUP_DATABASE_DIR_ENV = os.getenv("DEDUP_DATABASE_DIR", _DEDUP_DATABASE_DIR_ENV) 58 | DEDUP_DATABASE_DIR = Path(_DEDUP_DATABASE_DIR_ENV) 59 | 60 | FAILED_PAGE_NAME = os.getenv("FAILED_PAGE_NAME", None) 61 | 62 | REQUESTS_CA_BUNDLE = os.getenv("REQUESTS_CA_BUNDLE") 63 | 64 | # Optional query for selecting files to process 65 | _HYDRUS_QUERY_ENV = os.getenv("HYDRUS_QUERY") 66 | HYDRUS_QUERY = validate_json_array_env_var(_HYDRUS_QUERY_ENV, err_msg="Ensure HYDRUS_QUERY is a JSON formatted array.") 67 | 68 | # Optional service key of local file service/s to fetch files from 69 | _HYDRUS_LOCAL_FILE_SERVICE_KEYS_ENV = os.getenv("HYDRUS_LOCAL_FILE_SERVICE_KEYS") 70 | HYDRUS_LOCAL_FILE_SERVICE_KEYS = validate_json_array_env_var( 71 | _HYDRUS_LOCAL_FILE_SERVICE_KEYS_ENV, err_msg="Ensure HYDRUS_LOCAL_FILE_SERVICE_KEYS is a JSON formatted array" 72 | ) 73 | 74 | _IS_WINDOWS_EXE = False 75 | 76 | 77 | def is_windows_exe(): 78 | global _IS_WINDOWS_EXE 79 | return _IS_WINDOWS_EXE 80 | 81 | 82 | def set_windows_exe(): 83 | global _IS_WINDOWS_EXE 84 | _IS_WINDOWS_EXE = True 85 | -------------------------------------------------------------------------------- /docs/development.md: -------------------------------------------------------------------------------- 1 | # Development 2 | 3 | ## Setup 4 | 5 | [Hatch](https://hatch.pypa.io/latest/) is the Python project manager for this project. 6 | 7 | It is used for packaging and environment management for development. 8 | 9 | There are hatch commands for this project are defined in the [pyproject.toml]. They are just aliases for other commands that run in specific environments. 10 | 11 | For example, to run the command to generate the documentation and serve it locally: 12 | 13 | ```sh 14 | hatch run docs:serve 15 | ``` 16 | 17 | `docs` is the environment and `build` is the command to run. 18 | 19 | For more information, see the Hatch [environment documentation](https://hatch.pypa.io/latest/environment/) 20 | 21 | ### Useful commands 22 | 23 | Run all tests: 24 | 25 | ```sh 26 | hatch run test:all 27 | ``` 28 | 29 | Serve documentation locally: 30 | 31 | ```sh 32 | hatch run docs:serve 33 | ``` 34 | 35 | Build documentation: 36 | 37 | ```sh 38 | hatch run docs:build 39 | ``` 40 | 41 | Check code formatting (doesn't actually run formatting): 42 | 43 | ```sh 44 | hatch run lint:format 45 | ``` 46 | 47 | Lint code: 48 | 49 | ```sh 50 | hatch run lint:lint 51 | ``` 52 | 53 | Format code: 54 | 55 | ```sh 56 | hatch run format:format 57 | ``` 58 | 59 | Benchmark vpdq: 60 | 61 | ```sh 62 | hatch run benchmark:vpdq 63 | ``` 64 | 65 | ### Developing without Hatch (not recommended) 66 | 67 | Alternatively, if you don't want to use hatch and you know what you're doing, you can install and do development the general way. 68 | 69 | 1. Clone or download the repository: 70 | 71 | ```sh 72 | git clone https://github.com/hydrusvideodeduplicator/hydrus-video-deduplicator.git 73 | ``` 74 | 75 | 1. Install local editable package with [uv](https://docs.astral.sh/uv): 76 | 77 | ```sh 78 | cd hydrus-video-deduplicator 79 | pip install uv 80 | uv venv 81 | source .venv/bin/activate # or .venv\Scripts\activate on Windows 82 | uv pip install -e . 83 | ``` 84 | 85 | 1. Now if you run `python -m hydrusvideodeduplicator` there should be no errors. 86 | 87 | --- 88 | 89 | ### Testing 90 | 91 | #### testdb 92 | 93 | testdb is a submodule that contains the Hydrus DB and videos for integration testing purposes. 94 | 95 | It is a submodule to avoid bloating this repo with large media files used for testing. 96 | 97 | To checkout the testdb submodule: 98 | 99 | ```sh 100 | git submodule update --init --recursive 101 | ``` 102 | 103 | Run tests with `hatch run test:all` 104 | 105 | TODO: Explain how to run Hydrus using this DB. 106 | 107 | ## git workflow 108 | 109 | `main` is for releases. It must be committed to through a PR from `develop` by the project maintainer. 110 | 111 | `develop` should have the same history as main unless it has newer commits that have not been merged. When a PR is approved to develop, changes should be squash-merged. 112 | 113 | Create PRs for `develop` if you want to submit changes. 114 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/page_logger.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import TYPE_CHECKING 4 | 5 | if TYPE_CHECKING: 6 | from typing import Any 7 | 8 | from .client import HVDClient 9 | from .dedup_util import print_and_log 10 | 11 | import logging 12 | 13 | 14 | def get_page_key(client: HVDClient, page_name: str) -> str | None: 15 | """Takes the provided page name, and searches through all the pages in the Hydrus client for an appropriate 16 | page with that name. If there are multiple pages with the same name, one of those pages is chosen randomly.""" 17 | response = client.client.get_pages() 18 | page_key = find_page_key_from_name(response["pages"], page_name) 19 | return page_key 20 | 21 | 22 | def find_page_key_from_name(page: dict[str, Any], page_name: str) -> str | None: 23 | """Recursive function to search the response JSON provided by the Hydrus API's get_pages call. Because every 24 | page can potentially contain other pages, a recursive search through the object is necessary. As soon as a 25 | page is found with the correct page name and page type, that page's page_key is returned.""" 26 | if page["name"].lower() == page_name.lower() and page["page_type"] == 6: 27 | return page["page_key"] 28 | elif "pages" in page: 29 | for subpage in page["pages"]: 30 | result = find_page_key_from_name(subpage, page_name) 31 | if result is not None: 32 | return result 33 | return None 34 | 35 | 36 | class HydrusPageLogger: 37 | """Class to add files to pages in Hydrus.""" 38 | 39 | _log = logging.getLogger("HydrusPageLogger") 40 | _log.setLevel(logging.INFO) 41 | 42 | def __init__(self, client: HVDClient, page_name: str): 43 | """Page name must exist in Hydrus or an error will occur.""" 44 | self.client = client 45 | self.page_name = page_name 46 | 47 | def add_failed_video(self, video_hash: str) -> None: 48 | """Try to add a failed video to the Hydrus page.""" 49 | try: 50 | page_key = get_page_key(self.client, self.page_name) 51 | if page_key is None: 52 | raise Exception("page_key is None.") 53 | except Exception as e: 54 | print_and_log(self._log, str(e), logging.ERROR) 55 | print_and_log(self._log, f"Error when trying to get page key for page name {self.page_name}", logging.ERROR) 56 | return None 57 | 58 | try: 59 | self.client.client.add_files_to_page(page_key=page_key, hashes=[video_hash]) 60 | except Exception as e: 61 | print_and_log(self._log, str(e), logging.ERROR) 62 | print_and_log( 63 | self._log, 64 | f"""Error when trying to add file: '{video_hash}' \ 65 | \nto client page: '{self.page_name}' \ 66 | \nwith page_key: '{page_key}' \ 67 | \nEnsure there is a page in Hydrus named '{self.page_name}' \ 68 | """, 69 | logging.ERROR, 70 | ) 71 | -------------------------------------------------------------------------------- /tests/benchmarks/profile_vpdq.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | These tests use clips from the Big Buck Bunny movie and Sintel movie, 4 | which are licensed under Creative Commons Attribution 3.0 5 | (https://creativecommons.org/licenses/by/3.0/). 6 | (c) copyright 2008, Blender Foundation / www.bigbuckbunny.org 7 | (c) copyright Blender Foundation | durian.blender.org 8 | Blender Foundation | www.blender.org 9 | 10 | """ 11 | 12 | from __future__ import annotations 13 | 14 | import os 15 | from pathlib import Path 16 | from typing import TYPE_CHECKING 17 | 18 | from hydrusvideodeduplicator.vpdqpy.vpdqpy import Vpdq, VpdqHash 19 | from hvdaccelerators import vpdq 20 | 21 | if TYPE_CHECKING: 22 | pass 23 | 24 | 25 | def check_testdb_exists(): 26 | """ 27 | Check if the testdb submodule is pulled. 28 | Throws RuntimeError if it's not updated. 29 | """ 30 | testdb_dir = Path(__file__).parents[1] / "testdb" 31 | if len(os.listdir(testdb_dir)) == 0: 32 | raise RuntimeError("Video hashes dir is missing. Is the testdb submodule pulled?") 33 | 34 | 35 | def profile_vpdq_similarity(): 36 | """Profile VPDQ similarity""" 37 | 38 | all_phashes_dir = Path(__file__).parents[1] / "testdb" / "video hashes" 39 | video_hashes_paths: list[Path] = [] 40 | video_hashes_paths.extend(Path(all_phashes_dir).glob("*")) 41 | video_phashes: list[VpdqHash] = list() 42 | for video_hash_file in video_hashes_paths: 43 | with open(video_hash_file) as file: 44 | video_hash = vpdq.VpdqHash.from_string(file.readline()) 45 | video_phashes.append(video_hash) 46 | assert len(video_phashes) > 0 47 | 48 | pairs = [] 49 | for i, phash1 in enumerate(video_phashes): 50 | for j, phash2 in enumerate(video_phashes): 51 | if j < i: 52 | continue 53 | pairs.append((phash1, phash2)) 54 | 55 | profiler = cProfile.Profile() 56 | with profiler: 57 | for pair in pairs: 58 | Vpdq.is_similar(pair[0], pair[1], threshold=75) 59 | stats = pstats.Stats(profiler).sort_stats("cumtime") 60 | stats.print_stats() 61 | 62 | 63 | def profile_vpdq_hashing(): 64 | """Benchmark VPDQ hashing""" 65 | """Currently around 7.5 seconds on my PC""" 66 | all_vids_dir = Path(__file__).parents[1] / "testdb" / "videos" 67 | 68 | vids_dirs = ["sintel"] 69 | similarity_vids: list[Path] = [] 70 | for vids_dir in vids_dirs: 71 | similarity_vids.extend(Path(all_vids_dir / vids_dir).glob("*")) 72 | assert len(similarity_vids) > 0 73 | 74 | profiler = cProfile.Profile() 75 | with profiler: 76 | for vid in similarity_vids: 77 | perceptual_hash = Vpdq.computeHash(vid) 78 | assert len(perceptual_hash) > 0 79 | stats = pstats.Stats(profiler).sort_stats("cumtime") 80 | stats.print_stats() 81 | 82 | 83 | # To use this, run "python profile_vpdq.py" 84 | if __name__ == "__main__": 85 | import cProfile 86 | import pstats 87 | 88 | check_testdb_exists() 89 | 90 | profile_vpdq_similarity() 91 | profile_vpdq_hashing() 92 | -------------------------------------------------------------------------------- /tests/acceptance_tests/test_main_vcr.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import json 4 | import logging 5 | import os 6 | import unittest 7 | import zipfile 8 | from typing import TYPE_CHECKING 9 | 10 | import vcr 11 | 12 | from hydrusvideodeduplicator.entrypoint import main 13 | 14 | from ..check_testdb import check_testdb_exists 15 | 16 | if TYPE_CHECKING: 17 | pass 18 | 19 | import uuid 20 | from pathlib import Path 21 | from tempfile import TemporaryDirectory 22 | 23 | 24 | def somedbdir(): 25 | return str(uuid.uuid4().hex) 26 | 27 | 28 | CASSETTES_DIR = Path(__file__).parents[1] / "testdb/fixtures/vcr_cassettes" 29 | 30 | 31 | def unzip_all(zip_dir: Path, extract_to: Path): 32 | for item in os.listdir(zip_dir): 33 | if item.endswith(".zip"): 34 | zip_file_path = os.path.join(zip_dir, item) 35 | with zipfile.ZipFile(zip_file_path, "r") as zip_ref: 36 | zip_ref.extractall(extract_to) 37 | print(f"Extracted: {item}") 38 | 39 | 40 | class TestMainVcr(unittest.TestCase): 41 | log = logging.getLogger(__name__) 42 | log.setLevel(logging.INFO) 43 | logging.basicConfig() 44 | 45 | def setUp(self): 46 | check_testdb_exists() 47 | # Unzip all the cassettes 48 | # TODO: Check if the corresponding yaml exists and don't overwrite to save disk writes. 49 | unzip_all(CASSETTES_DIR, CASSETTES_DIR) 50 | 51 | def test_main(self): 52 | GENERATE_CASSETTE_RUN = False 53 | record_mode = "all" if GENERATE_CASSETTE_RUN else "none" # see vcrpy docs 54 | cassette_file = CASSETTES_DIR / "main.yaml" 55 | if not GENERATE_CASSETTE_RUN: 56 | self.assertTrue( 57 | cassette_file.exists(), 58 | f"Cassette file: {cassette_file} does not exist. Need to generate it or fix something.", 59 | ) 60 | else: 61 | cassette_file.unlink(missing_ok=True) 62 | with vcr.use_cassette(cassette_file, record_mode=record_mode) as cass: 63 | if not GENERATE_CASSETTE_RUN: 64 | expected_pair_count = int( 65 | json.loads(cass.responses[-1]["body"]["string"])["potential_duplicates_count"] 66 | ) 67 | # sanity check 68 | self.assertGreater( 69 | expected_pair_count, 70 | 0, 71 | "Cassette potential duplicates count is not >0. Something is wrong with the vcr potential duplicates count.", # noqa: E501 72 | ) 73 | 74 | with TemporaryDirectory() as tmpdir: 75 | db_dir = Path(tmpdir) / somedbdir() 76 | 77 | num_similar_pairs = main( 78 | "3b3cf10cc13862818ea95ddecfe434bed0828fb319b1ff56413917b471b566ab", 79 | "https://localhost:45869", 80 | dedup_database_dir=db_dir, 81 | ) 82 | 83 | if not GENERATE_CASSETTE_RUN: 84 | self.assertEqual( 85 | num_similar_pairs, expected_pair_count, "Number of similar files found is unexpected." 86 | ) 87 | self.log.info(f"{num_similar_pairs} similar file pairs found in main test.") 88 | else: 89 | self.assertFalse( 90 | True, "Cassette generated. Change GENERATE_CASSETTE_RUN to False and rerun the test." 91 | ) 92 | 93 | 94 | if __name__ == "__main__": 95 | unittest.main(module="test_main_vcr") 96 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/dedup_util.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | from itertools import islice 5 | from typing import TYPE_CHECKING 6 | 7 | from hydrusvideodeduplicator.hydrus_api import Client 8 | 9 | if TYPE_CHECKING: 10 | from collections.abc import Generator, Iterable 11 | from typing import Any, TypeAlias 12 | 13 | # The logging level for logging e.g. CRITICAL or WARNING 14 | Severity: TypeAlias = int 15 | 16 | from rich import print 17 | 18 | 19 | def batched(iterable: Iterable, batch_size: int) -> Generator[tuple, Any, None]: 20 | """ 21 | Batch data into tuples of length batch_size. The last batch may be shorter." 22 | batched('ABCDEFG', 3) --> ABC DEF G 23 | """ 24 | assert batch_size >= 1 25 | it = iter(iterable) 26 | while batch := tuple(islice(it, batch_size)): 27 | yield batch 28 | 29 | 30 | # Given a lexicographically SORTED list of tags, find the tag given a namespace 31 | def find_tag_in_tags(target_tag_namespace: str, tags: list) -> str: 32 | namespace_len = len(target_tag_namespace) 33 | for tag in tags: 34 | if tag[0:namespace_len] == target_tag_namespace: 35 | return tag[namespace_len:] 36 | return "" 37 | 38 | 39 | # Get the filename from the filename tag if it exists in Hydrus 40 | # This is just used for debugging. 41 | # Note: Hydrus tags and NTFS are case insensitive, but ext4 is not 42 | # But, this shouldn't really matter since Hydrus stores files with lower case names 43 | # TODO: Clean this up it's a mess 44 | def get_file_names_hydrus(client: Client, file_hashes: list[str]) -> list[str]: 45 | err_msg = "Cannot get file name from Hydrus." 46 | result = [] 47 | files_metadata = client.get_file_metadata(hashes=file_hashes, only_return_basic_information=False) 48 | all_known_tags = "all known tags".encode("utf-8").hex() 49 | for file_metadata in files_metadata.get("metadata", []): 50 | # Try to get file extension 51 | try: 52 | ext = file_metadata["ext"] 53 | except KeyError: 54 | ext = "" 55 | 56 | # Try to get the file name 57 | tag = "" 58 | try: 59 | tag_services = file_metadata["tags"] 60 | tags = tag_services[all_known_tags]["storage_tags"]["0"] 61 | tag = find_tag_in_tags(target_tag_namespace="filename:", tags=tags) 62 | # Don't show extension if filename doesn't exist 63 | if tag != "": 64 | tag = f"{tag}{ext}" 65 | except Exception as exc: 66 | logging.error(exc) 67 | logging.error(f"{err_msg} Hash: {file_metadata['hash']}") 68 | 69 | result.append(tag) 70 | 71 | return result 72 | 73 | 74 | # Get the oldest file by import time in list of file_metadata 75 | def get_oldest_imported_file_time(all_files_metadata: list) -> int: 76 | file_import_times = [] 77 | for video_metadata in all_files_metadata: 78 | try: 79 | file_import_times.append(get_file_import_time(video_metadata)) 80 | except KeyError: 81 | continue 82 | return min(file_import_times) 83 | 84 | 85 | # Get the import time of a file from file_metadata request from Hydrus 86 | def get_file_import_time(file_metadata: dict): 87 | for service in file_metadata["file_services"]["current"].values(): 88 | try: 89 | if service["name"] == "all local files": 90 | return service["time_imported"] 91 | except KeyError: 92 | continue 93 | raise KeyError 94 | 95 | 96 | def severity_to_color(severity: Severity) -> str: 97 | if severity > logging.WARNING: 98 | return "[red]" 99 | elif severity == logging.WARNING: 100 | return "[yellow]" 101 | elif severity <= logging.INFO: 102 | return "" # No color 103 | # No color 104 | return "" 105 | 106 | 107 | def print_and_log(logger: logging.Logger, msg: str, severity: Severity = logging.INFO): 108 | """ 109 | Print to the user and log. Changes print color based on the severity. 110 | 111 | The default logger uses the logging module. 112 | """ 113 | print(f"{severity_to_color(severity)}") 114 | print(f"{msg}") 115 | logger.log(severity, msg) 116 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .nox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | *.py,cover 49 | .hypothesis/ 50 | .pytest_cache/ 51 | cover/ 52 | tests/testdb/fixtures/vcr_cassettes/main.yaml 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | # Pickle 163 | *.pkl 164 | 165 | # Created by https://www.toptal.com/developers/gitignore/api/visualstudiocode 166 | # Edit at https://www.toptal.com/developers/gitignore?templates=visualstudiocode 167 | 168 | ### VisualStudioCode ### 169 | .vscode/* 170 | !.vscode/settings.json 171 | !.vscode/tasks.json 172 | !.vscode/launch.json 173 | !.vscode/extensions.json 174 | !.vscode/*.code-snippets 175 | 176 | # Local History for Visual Studio Code 177 | .history/ 178 | 179 | # Built Visual Studio Code Extensions 180 | *.vsix 181 | 182 | ### VisualStudioCode Patch ### 183 | # Ignore all local history of files 184 | .history 185 | .ionide 186 | 187 | # End of https://www.toptal.com/developers/gitignore/api/visualstudiocode 188 | 189 | # Hydrus 190 | !.gitkeep 191 | 192 | ThreatExchange 193 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling"] 3 | build-backend = "hatchling.build" 4 | 5 | [project] 6 | name = "hydrusvideodeduplicator" 7 | dynamic = ["version"] 8 | description = "Video deduplicator utility for Hydrus Network" 9 | readme = "README.md" 10 | requires-python = ">=3.10" 11 | license = "MIT" 12 | keywords = [] 13 | authors = [ 14 | { name = "hydrusvideodeduplicator", email = "hydrusvideodeduplicator@gmail.com" }, 15 | ] 16 | classifiers = [ 17 | "Development Status :: 4 - Beta", 18 | "Programming Language :: Python", 19 | "Programming Language :: Python :: 3.10", 20 | "Programming Language :: Python :: 3.11", 21 | "Programming Language :: Python :: 3.12", 22 | "Programming Language :: Python :: 3.13", 23 | ] 24 | dependencies = [ 25 | "platformdirs", 26 | "rich", 27 | "numpy", 28 | "tqdm", 29 | "python-dotenv", 30 | "typer", 31 | "requests", 32 | "psutil", 33 | # vpdqpy dependencies 34 | "pillow", 35 | "av", 36 | "hvdaccelerators>=0.4.0", 37 | ] 38 | 39 | [project.urls] 40 | Documentation = "https://github.com/hydrusvideodeduplicator/hydrus-video-deduplicator#readme" 41 | Issues = "https://github.com/hydrusvideodeduplicator/hydrus-video-deduplicator/issues" 42 | Source = "https://github.com/hydrusvideodeduplicator/hydrus-video-deduplicator" 43 | 44 | [tool.hatch.build] 45 | exclude = [ 46 | "/.*", 47 | "/docs", 48 | "/tests", 49 | ] 50 | 51 | [tool.hatch.version] 52 | path = "src/hydrusvideodeduplicator/__about__.py" 53 | 54 | # Use uv for better performance compared to pip and virtualenv 55 | [tool.hatch.envs.default] 56 | installer = "uv" 57 | 58 | # Benchmark environment 59 | 60 | [tool.hatch.envs.benchmark] 61 | dependencies = [ 62 | "pytest", 63 | "pytest-benchmark", # a plugin for pytest that enables benchmarking 64 | ] 65 | 66 | [tool.hatch.envs.benchmark.scripts] 67 | vpdq = "python -m pytest tests/benchmarks/test_benchmark_vpdqpy.py {args}" 68 | profile_vpdq = "python tests/benchmarks/profile_vpdq.py" 69 | 70 | # Docs environment 71 | 72 | [tool.hatch.envs.docs] 73 | skip-install = true # Don't install dedupe. We just need to generate docs. 74 | dependencies = [ 75 | "mkdocs", 76 | "mkdocs-material", 77 | "mkdocs-git-revision-date-localized-plugin", 78 | ] 79 | 80 | [tool.hatch.envs.docs.scripts] 81 | build = "mkdocs build --clean --strict" 82 | serve = "mkdocs serve" 83 | gh-deploy = "mkdocs gh-deploy --force --strict --config-file mkdocs-gh-pages.yml" # Deploys to Github pages. Only used by GH Actions. 84 | 85 | # Test environment 86 | 87 | [tool.hatch.envs.test] 88 | dependencies = [ 89 | "pytest", 90 | "vcrpy", # for replaying saved api requests/responses 91 | ] 92 | 93 | [tool.hatch.envs.test.scripts] 94 | all = "python -m pytest tests/unit_tests/test_db.py tests/unit_tests/test_vpdqpy.py tests/acceptance_tests/test_dedupe.py tests/acceptance_tests/test_main_vcr.py --verbose {args}" 95 | db = "python -m pytest tests/unit_tests/test_db.py --verbose {args}" 96 | vpdq = "python -m pytest tests/unit_tests/test_vpdqpy.py --verbose {args}" 97 | vcr = "python -m pytest tests/acceptance_tests/test_main_vcr.py --verbose {args}" 98 | 99 | # Format environment 100 | 101 | [tool.hatch.envs.format] 102 | skip-install = true # Don't install dedupe. We just need to format. 103 | dependencies = [ 104 | "black", 105 | ] 106 | 107 | [tool.hatch.envs.format.scripts] 108 | format = "black src tests {args}" 109 | 110 | # Lint environment 111 | 112 | [tool.hatch.envs.lint] 113 | dependencies = [ 114 | "black", 115 | "ruff", 116 | ] 117 | 118 | [tool.hatch.envs.lint.scripts] 119 | format = "black --check src tests {args}" 120 | lint = "ruff check src tests {args}" 121 | 122 | [tool.black] 123 | target-version = ["py310", "py311", "py312", "py313"] 124 | line-length = 120 125 | skip-string-normalization = true 126 | 127 | [tool.ruff] 128 | # Enable the pycodestyle (`E`) and Pyflakes (`F`) rules by default. 129 | # Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or 130 | # McCabe complexity (`C901`) by default. 131 | lint.select = ["E", "F"] 132 | lint.ignore = [] 133 | 134 | # Allow autofix for all enabled rules (when `--fix`) is provided. 135 | lint.fixable = ["ALL"] 136 | lint.unfixable = [] 137 | 138 | # Exclude a variety of commonly ignored directories. 139 | exclude = [ 140 | ".bzr", 141 | ".direnv", 142 | ".eggs", 143 | ".git", 144 | ".git-rewrite", 145 | ".hg", 146 | ".mypy_cache", 147 | ".nox", 148 | ".pants.d", 149 | ".pytype", 150 | ".ruff_cache", 151 | ".svn", 152 | ".tox", 153 | ".venv", 154 | "__pypackages__", 155 | "_build", 156 | "buck-out", 157 | "build", 158 | "dist", 159 | "node_modules", 160 | "venv", 161 | "ThreatExchange", 162 | ] 163 | lint.per-file-ignores = {"tests/**/*" = ["PLR2004", "S101", "TID252"]} 164 | 165 | # Same as Black. 166 | line-length = 120 167 | 168 | # Allow unused variables when underscore-prefixed. 169 | lint.dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" 170 | 171 | # Assume Python 3.12. 172 | target-version = "py312" 173 | -------------------------------------------------------------------------------- /tests/unit_tests/test_db.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | import unittest 5 | from typing import TYPE_CHECKING 6 | 7 | from hydrusvideodeduplicator import __about__ 8 | from hydrusvideodeduplicator.db import DedupeDB 9 | 10 | if TYPE_CHECKING: 11 | pass 12 | 13 | import sqlite3 14 | from pathlib import Path 15 | from tempfile import TemporaryDirectory 16 | import uuid 17 | 18 | 19 | def somedbdir(): 20 | return str(uuid.uuid4().hex) 21 | 22 | 23 | class TestDedupeDB(unittest.TestCase): 24 | log = logging.getLogger(__name__) 25 | log.setLevel(logging.WARNING) 26 | logging.basicConfig() 27 | 28 | def setUp(self): 29 | pass 30 | 31 | def test_set_get_db_dir(self): 32 | with TemporaryDirectory() as tmpdir: 33 | db_dir = Path(tmpdir) / somedbdir() 34 | DedupeDB.set_db_dir(db_dir) 35 | result = DedupeDB.get_db_dir() 36 | self.assertEqual(result, db_dir) 37 | 38 | def test_get_db_file_path(self): 39 | expected = DedupeDB.get_db_dir() / "videohashes.sqlite" 40 | result = DedupeDB.get_db_file_path() 41 | self.assertEqual(result, expected) 42 | 43 | def test_create_db(self): 44 | with TemporaryDirectory() as tmpdir: 45 | db_dir = Path(tmpdir) / somedbdir() 46 | DedupeDB.set_db_dir(db_dir) 47 | 48 | DedupeDB.create_db() 49 | 50 | # Check file exists 51 | expected = DedupeDB.get_db_dir() / "videohashes.sqlite" 52 | self.assertTrue(Path.exists(expected)) 53 | self.assertTrue(Path.is_file(expected)) 54 | 55 | # Check database 56 | 57 | con = sqlite3.connect(DedupeDB.get_db_file_path(), uri=True) # uri is read-only 58 | cur = con.cursor() 59 | # Check tables 60 | res = cur.execute("SELECT name FROM sqlite_master WHERE type='table'") 61 | self.assertEqual( 62 | set(res.fetchall()), 63 | set( 64 | [ 65 | ("version",), 66 | ("files",), 67 | ("phashed_file_queue",), 68 | ("shape_maintenance_branch_regen",), 69 | ("shape_perceptual_hash_map",), 70 | ("shape_perceptual_hashes",), 71 | ("shape_search_cache",), 72 | ("shape_vptree",), 73 | ] 74 | ), 75 | ) 76 | 77 | # Check the database is queryable (this may be overkill) 78 | with self.assertRaises(sqlite3.OperationalError): 79 | _ = cur.execute("SELECT foo FROM files") 80 | 81 | def check_table_columns(table: str, expected_columns: list[str]): 82 | for column in expected_columns: 83 | res = cur.execute(f"SELECT {column} FROM {table}") 84 | self.assertEqual(len(res.fetchall()), 0) 85 | 86 | expected_tables = { 87 | "files": ["hash_id", "file_hash"], 88 | "phashed_file_queue": ["file_hash", "phash"], 89 | "shape_maintenance_branch_regen": ["phash_id"], 90 | "shape_perceptual_hash_map": ["phash_id", "hash_id"], 91 | "shape_perceptual_hashes": ["phash_id", "phash"], 92 | "shape_search_cache": ["hash_id", "searched_distance"], 93 | "shape_vptree": [ 94 | "phash_id", 95 | "parent_id", 96 | "radius", 97 | "inner_id", 98 | "inner_population", 99 | "outer_id", 100 | "outer_population", 101 | ], 102 | } 103 | for table, cols in expected_tables.items(): 104 | check_table_columns(table, cols) 105 | 106 | # Check version table 107 | res = cur.execute("SELECT version FROM version") 108 | expected_version = __about__.__version__ 109 | self.log.info(f"Expected version: {expected_version}") 110 | self.assertIsNotNone(expected_version) 111 | self.assertEqual( 112 | res.fetchall(), 113 | [ 114 | (expected_version,), 115 | ], 116 | ) 117 | 118 | con.close() 119 | 120 | def test_get_version(self): 121 | with TemporaryDirectory() as tmpdir: 122 | db_dir = Path(tmpdir) / somedbdir() 123 | DedupeDB.set_db_dir(db_dir) 124 | 125 | DedupeDB.create_db() 126 | 127 | db = DedupeDB.DedupeDb(db_dir, DedupeDB.get_db_name()) 128 | db.init_connection() 129 | db.set_version("1.2.3") 130 | version = db.get_version() 131 | self.assertEqual(version, "1.2.3") 132 | 133 | db.conn.close() 134 | 135 | def test_semantic_version(self): 136 | pairs = [("0.1.0", "0.2.0"), ("1.0.1", "1.1.0"), ("1.0.10", "1.1.0")] 137 | for lhs, rhs in pairs: 138 | self.assertLess(DedupeDB.SemanticVersion(lhs), DedupeDB.SemanticVersion(rhs), f"{lhs} not less than {rhs}") 139 | 140 | pairs = [("0.0.0", "0.0.0"), ("1.0.0", "1.0.0"), ("0.1.0", "0.1.0")] 141 | for lhs, rhs in pairs: 142 | self.assertLessEqual( 143 | DedupeDB.SemanticVersion(lhs), DedupeDB.SemanticVersion(rhs), f"{lhs} not less than {rhs}" 144 | ) 145 | 146 | pairs = [("1.0.0", "0.0.100"), ("10.0.0", "1.100.0"), ("0.0.1", "0.0.0")] 147 | for lhs, rhs in pairs: 148 | self.assertGreaterEqual( 149 | DedupeDB.SemanticVersion(lhs), DedupeDB.SemanticVersion(rhs), f"{lhs} not less than {rhs}" 150 | ) 151 | 152 | 153 | if __name__ == "__main__": 154 | unittest.main(module="test_db") 155 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/hydrus_api/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 cryzed 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as 5 | # published by the Free Software Foundation, either version 3 of the 6 | # License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | import collections 17 | import collections.abc as abc 18 | import os 19 | import typing as T 20 | 21 | from hydrusvideodeduplicator.hydrus_api import ( 22 | DEFAULT_API_URL, 23 | HYDRUS_METADATA_ENCODING, 24 | BinaryFileLike, 25 | Client, 26 | ImportStatus, 27 | Permission, 28 | ) 29 | 30 | _X = T.TypeVar("_X") 31 | 32 | 33 | # This is public so other code can import it to annotate their own types 34 | class TextFileLike(T.Protocol): 35 | def read(self) -> str: ... 36 | 37 | 38 | def verify_permissions( 39 | client: Client, permissions: abc.Iterable[T.Union[int, Permission]], exact: bool = False 40 | ) -> bool: 41 | granted_permissions = set(client.verify_access_key()["basic_permissions"]) 42 | return granted_permissions == set(permissions) if exact else granted_permissions.issuperset(permissions) 43 | 44 | 45 | def cli_request_api_key( 46 | name: str, 47 | permissions: abc.Iterable[T.Union[int, Permission]], 48 | verify: bool = True, 49 | exact: bool = False, 50 | api_url: str = DEFAULT_API_URL, 51 | ) -> str: 52 | while True: 53 | input( 54 | 'Navigate to "services->review services->local->client api" in the Hydrus client and click "add->from api ' 55 | 'request". Then press enter to continue...' 56 | ) 57 | access_key = Client(api_url=api_url).request_new_permissions(name, permissions)["access_key"] 58 | input("Press OK and then apply in the Hydrus client dialog. Then press enter to continue...") 59 | 60 | client = Client(access_key, api_url) 61 | if verify and not verify_permissions(client, permissions, exact): 62 | granted = client.verify_access_key()["basic_permissions"] 63 | print( 64 | f"The granted permissions ({granted}) differ from the requested permissions ({permissions}), please " 65 | "grant all requested permissions." 66 | ) 67 | continue 68 | 69 | return access_key 70 | 71 | 72 | def parse_hydrus_metadata(text: str) -> dict[T.Optional[str], set[str]]: 73 | namespaces = collections.defaultdict(set) 74 | for line in (line.strip() for line in text.splitlines()): 75 | if not line: 76 | continue 77 | 78 | parts = line.split(":", 1) 79 | namespace, tag = (None, line) if len(parts) == 1 else parts 80 | namespaces[namespace].add(tag) 81 | 82 | # Ignore type, mypy has trouble figuring out that tag isn't optional 83 | return namespaces # type: ignore 84 | 85 | 86 | def parse_hydrus_metadata_file( 87 | path_or_file: T.Union[str, os.PathLike, TextFileLike], 88 | ) -> dict[T.Optional[str], set[str]]: 89 | if isinstance(path_or_file, (str, os.PathLike)): 90 | with open(path_or_file, encoding=HYDRUS_METADATA_ENCODING) as file: 91 | return parse_hydrus_metadata(file.read()) 92 | 93 | return parse_hydrus_metadata(path_or_file.read()) 94 | 95 | 96 | # Useful for splitting up requests to get_file_metadata() 97 | def yield_chunks(sequence: T.Sequence[_X], chunk_size: int, offset: int = 0) -> T.Generator[T.Sequence[_X], None, None]: 98 | while offset < len(sequence): 99 | yield sequence[offset : offset + chunk_size] 100 | offset += chunk_size 101 | 102 | 103 | def add_and_tag_files( 104 | client: Client, 105 | paths_or_files: abc.Iterable[T.Union[str, os.PathLike, BinaryFileLike]], 106 | tags: abc.Iterable[str], 107 | tag_service_keys: abc.Iterable[str], 108 | ) -> list[dict[str, T.Any]]: 109 | """Convenience function to add and tag multiple files at the same time. 110 | 111 | Returns: 112 | Returns results of all `Client.add_file()` calls, matching the order of the paths_or_files iterable 113 | """ 114 | results = [] 115 | hashes = set() 116 | for path_or_file in paths_or_files: 117 | result = client.add_file(path_or_file) 118 | results.append(result) 119 | if result["status"] != ImportStatus.FAILED: 120 | hashes.add(result["hash"]) 121 | 122 | client.add_tags(hashes, service_keys_to_tags={key: tags for key in tag_service_keys}) 123 | return results 124 | 125 | 126 | def get_page_list(client: Client) -> list[dict[str, T.Any]]: 127 | """Convenience function that returns a flattened version of the page tree from `Client.get_pages()`. 128 | 129 | Returns: 130 | A list of every "pages" value in the page tree in pre-order (NLR) 131 | """ 132 | tree = client.get_pages()["pages"] 133 | pages = [] 134 | 135 | def walk_tree(page: dict[str, T.Any]) -> None: 136 | pages.append(page) 137 | for sub_page in page.get("pages", ()): 138 | walk_tree(sub_page) 139 | 140 | walk_tree(tree) 141 | return pages 142 | 143 | 144 | def get_service_mapping(client: Client) -> dict[str, list[str]]: 145 | mapping = collections.defaultdict(list) 146 | 147 | # Ignore the keys in the JSON which for some reason replaces spaces with underscores 148 | for services in client.get_services().values(): 149 | for service in services: 150 | mapping[service["name"]].append(service["service_key"]) 151 | 152 | return mapping 153 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/vpdqpy/vpdqpy.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import io 4 | import logging 5 | from pathlib import Path 6 | from typing import TYPE_CHECKING 7 | 8 | import av 9 | from hvdaccelerators import vpdq 10 | from PIL import Image 11 | 12 | if TYPE_CHECKING: 13 | from collections.abc import Iterator 14 | from fractions import Fraction 15 | from typing import Annotated, TypeAlias 16 | 17 | from .typing_utils import ValueRange 18 | 19 | log = logging.getLogger(__name__) 20 | log.setLevel(logging.CRITICAL) 21 | 22 | # The dimensions of the image after downscaling for pdq 23 | DOWNSCALE_DIMENSIONS = 512 24 | 25 | VpdqHash: TypeAlias = vpdq.VpdqHash 26 | 27 | 28 | class Vpdq: 29 | @staticmethod 30 | def get_video_bytes(video_file: Path | str | bytes) -> bytes: 31 | """Get the bytes of a video""" 32 | video = bytes() 33 | if isinstance(video_file, (Path, str)): 34 | if not Path(video_file).is_file(): 35 | raise ValueError("Failed to get video file bytes. Video does not exist") 36 | 37 | try: 38 | with open(str(video_file), "rb") as file: 39 | video = file.read() 40 | except OSError as exc: 41 | raise ValueError("Failed to get video file bytes. Invalid object type.") from exc 42 | elif isinstance(video_file, bytes): 43 | video = video_file 44 | else: 45 | raise ValueError("Failed to get video file bytes. Invalid object type.") 46 | 47 | return video 48 | 49 | @staticmethod 50 | def match_hash( 51 | query_features: VpdqHash, 52 | target_features: VpdqHash, 53 | distance_tolerance: float = 31.0, 54 | ): 55 | """Get the similarity of two videos by comparing their list of features""" 56 | return vpdq.matchHash(query_features, target_features, int(distance_tolerance)) 57 | 58 | @staticmethod 59 | def frame_extract_pyav(video_bytes: bytes) -> Iterator[Image.Image]: 60 | """Extract frames from video""" 61 | with av.open(io.BytesIO(video_bytes), metadata_encoding="utf-8", metadata_errors="ignore") as container: 62 | # Check for video in video container 63 | video_streams = container.streams.video 64 | if video_streams is None or len(video_streams) < 1: 65 | log.error("Video stream not found.") 66 | raise ValueError("Video stream not found.") 67 | 68 | video = container.streams.video[0] 69 | video.thread_type = "AUTO" 70 | 71 | raw_average_fps: Fraction = video.average_rate 72 | average_fps: int = 1 73 | # Some videos, like small GIFs, will have a NoneType FPS 74 | if raw_average_fps is None or raw_average_fps < 1: 75 | log.warning("Average FPS is None or less than 1. Every frame will be hashed.") 76 | else: 77 | average_fps = round(raw_average_fps) 78 | 79 | # The following is a very overly complex "for loop" in order to decode frames from the video. 80 | # Why not use a for loop? Because for some reason av>=12 will sometimes throw an 81 | # av.error.InvalidDataError error in container.decode(). I'm not sure why this happens. 82 | # Normally this loop would be written as `for frame_index, frame in container.decode(video)`, 83 | # but to catch the exception I need to wrap the decode call with try/catch and iterate using next(). 84 | frame_generator = container.decode(video) 85 | frame_index = 0 86 | while True: 87 | try: 88 | frame = next(frame_generator) 89 | if frame_index % average_fps == 0: 90 | yield frame.reformat( 91 | width=DOWNSCALE_DIMENSIONS, 92 | height=DOWNSCALE_DIMENSIONS, 93 | format="rgb24", 94 | interpolation=av.video.reformatter.Interpolation.POINT, 95 | ) 96 | frame_index += 1 97 | except StopIteration: 98 | break 99 | except av.error.InvalidDataError as exc: 100 | log.error(f"Skipping bad frame at index {frame_index}: {exc}") 101 | frame_index += 1 102 | 103 | @staticmethod 104 | def computeHash(video_file: Path | str | bytes, num_threads: int = 0) -> VpdqHash: 105 | """Perceptually hash video from a file path or the bytes""" 106 | video = Vpdq.get_video_bytes(video_file) 107 | if video is None: 108 | raise ValueError 109 | 110 | # Average FPS is used by vpdq to calculate the timestamp, but we completely discard 111 | # the timestamp so this value doesn't matter. 112 | average_fps = 1 113 | hasher = vpdq.VideoHasher(average_fps, DOWNSCALE_DIMENSIONS, DOWNSCALE_DIMENSIONS, num_threads) 114 | for frame in Vpdq.frame_extract_pyav(video): 115 | # Note: hash_frame will block if vpdq's internal frame queue is full. This is necessary, 116 | # otherwise if hashing gets too far behind decoding there will be an insane amount of memory 117 | # used to hold the raw frames. 118 | hasher.hash_frame(bytes(frame.planes[0])) 119 | return hasher.finish() 120 | 121 | @staticmethod 122 | def is_similar( 123 | vpdq_features1: VpdqHash, 124 | vpdq_features2: VpdqHash, 125 | threshold: Annotated[float, ValueRange(0.0, 100.0)] = 75.0, 126 | ) -> tuple[bool, float]: 127 | """Check if video is similar by comparing their list of features 128 | Threshold is minimum similarity to be considered similar 129 | """ 130 | similarity = Vpdq.match_hash(query_features=vpdq_features1, target_features=vpdq_features2) 131 | return similarity >= threshold, similarity 132 | -------------------------------------------------------------------------------- /docs/faq.md: -------------------------------------------------------------------------------- 1 | # FAQ 2 | 3 | ## How to update 4 | 5 | I highly recommend backing up your dedupe database folder if it took a long time to hash/search your Hydrus files. 6 | 7 | I will do my best to preserve your database across upgrades, but there are no guarantees. Just back it up. 8 | 9 | See [How to backup my dedupe database](#how-to-backup-my-dedupe-database) for instructions on backups. 10 | 11 | To upgrade: 12 | 13 | ### Windows 14 | 15 | Download the [latest release directly from the github releases page](https://github.com/hydrusvideodeduplicator/hydrus-video-deduplicator/releases). 16 | 17 | ### Linux and macOS 18 | 19 | ```sh 20 | # activate your venv first, e.g., source .venv/bin/activate 21 | # if you aren't using uv, omit it from the command below. 22 | uv pip install hydrusvideodeduplicator --upgrade 23 | ``` 24 | 25 | --- 26 | 27 | ## Can I safely cancel a dedupe in progress? 28 | 29 | Yes. You can safely skip any or all of the dedupe steps in progress by pressing `CTRL+C`. The next time you launch the 30 | program it will continue where you left off. 31 | 32 | --- 33 | 34 | ## How to backup my dedupe database? 35 | 36 | You can backup your dedupe database by copying the database directory somewhere safe. 37 | 38 | See [Where are the video hashes stored?](#where-are-the-video-hashes-stored) location for the database directory. 39 | 40 | --- 41 | 42 | ## How does this work? 43 | 44 | 1. First, the program will perceptually hash all your video files and store them in a database. 45 | 46 | - Initial hashing generally takes longer than searching for duplicates. It will also probably get slower as it progresses, because they are hashed in order of increasing file size. 47 | 48 | 1. Then, the perceptual hashes are put into a data structure to make it fast to search for duplicates. 49 | 50 | - Note: Initial search tree building may take a while, but it should be very fast on subsequent runs when new files are added. 51 | 52 | 1. Finally, it will search the database for potential duplicates and mark them as potential duplicates in Hydrus. 53 | 54 | You can run the program again when you add more files to find more duplicates. 55 | 56 | See the [Theory](theory.md) for an in-depth explanation for how it all works. 57 | 58 | > **Note**: You can skip any of the steps to find duplicates for only a few videos at a time. The next time you 59 | > launch the program it will continue where you left off. 60 | 61 | --- 62 | 63 | ## Where are the video hashes stored? 64 | 65 | Hashes are stored in an sqlite database created in an app dir to speed up processing on subsequent runs. 66 | 67 | On Linux, this directory is likely `~/.local/share/hydrusvideodeduplicator` 68 | 69 | On Windows, this directory is likely `%USERPROFILE%\AppData\Local\hydrusvideodeduplicator` or `%USERPROFILE%\AppData\Roaming\hydrusvideodeduplicator` 70 | 71 | On macos, this directory is likely `/Users//Library/Application Support/hydrusvideodeduplicator` 72 | 73 | The database directory can be set with the `--dedup-database-dir` CLI option, or a `DEDUP_DATABASE_DIR` environment variable. 74 | 75 | --- 76 | 77 | ## I have a big library. How do I test this on just a few files? 78 | 79 | You can use [system predicates](https://hydrusnetwork.github.io/hydrus/developer_api.html#get_files_search_files) and [queries](https://hydrusnetwork.github.io/hydrus/getting_started_searching.html) to limit your search. 80 | 81 | Each query will reduce the number of files you process. By default all videos/animated are processed. 82 | 83 | For example: 84 | 85 | You want to deduplicate files with these requirements: 86 | 87 | - Max of 1000 files 88 | 89 | - <50 MB filesize 90 | - In `system:archive` 91 | 92 | - Has the tags `character:jacob` 93 | 94 | - Imported < 1 hour ago 95 | 96 | Then the arguments for the query would be: 97 | 98 | `--query="system:filesize > 10MB" --query="system:limit 1000" --query="system:archive" --query="character:jacob" --query="system:import time < 1 hour"` 99 | 100 | These are the same queries as would be used in Hydrus. 101 | 102 | --- 103 | 104 | ## I want to search for duplicates without hashing new video files 105 | 106 | You can either use `--skip-hashing`, press CTRL+C while perceptual hashing is running, or use a query limiting when files were imported. 107 | 108 |
109 | Example query that limits import time 110 |
111 | 112 | ```sh 113 | --query="system:import time > 1 day" 114 | ``` 115 | 116 |
117 | 118 | --- 119 | 120 | ## What kind of files does it support? 121 | 122 | Almost all video and animated files e.g. mp4, gif, apng, etc. are supported if they are supported in Hydrus. 123 | 124 | If you find a video that fails to perceptually hash, please create an issue on GitHub with some information about the video or message `@applenanner` on the [Hydrus Discord](https://discord.gg/wPHPCUZ). 125 | 126 | If a bad file crashes the whole program also create an issue. Skipping files is fine, but crashing is not. 127 | 128 | --- 129 | 130 | ## Why does processing slow down the longer it runs? 131 | 132 | The files are retrieved from Hydrus in increasing file size order. Naturally, this would also affect searching because the database is also ordered. 133 | 134 | If this is an issue for you and think this should be changed, please create an issue and explain why. 135 | 136 | --- 137 | 138 | ## I set the threshold too low and now I have too many potential duplicates 139 | 140 | While the perceptual hasher should have very few false-positives, you may accidently get too many if you change your search threshold too low using `--threshold`. 141 | 142 | You can reset your potential duplicates in Hydrus in duplicates processing: 143 | 144 | ![Demonstration of how to reset potential duplicates in Hydrus](./img/reset_duplicates.png) 145 | 146 | Then, you should also reset your search cache with `--clear-search-cache` to search for duplicates from scratch. 147 | 148 | --- 149 | 150 | ## My file failed to hash 151 | 152 | If you find a video that fails to perceptually hash, please create an issue on GitHub with some information about the video or message `@applenanner` on the [Hydrus Discord](https://discord.gg/wPHPCUZ). 153 | 154 | --- 155 | 156 | ## I have some "weird" messages while perceptual hashing 157 | 158 | If you get messages like this: 159 | 160 | > VPS 0 does not exist 161 | > 162 | > SPS 0 does not exist. 163 | 164 | or 165 | 166 | > deprecated pixel format used, make sure you did set range correctly 167 | 168 | Don't worry. These are FFmpeg logs from file decoding. They can be safely ignored. 169 | 170 | These messages are prevalent with certain video codecs, namely AV1 and H.265. 171 | 172 | Unfortunately these obnoxious messages are not able to be silenced yet. 173 | 174 | But if your messages mention perceptual hashing failing then see [My file failed to hash](#my-file-failed-to-hash). 175 | -------------------------------------------------------------------------------- /tests/unit_tests/test_vpdqpy.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | These tests use clips from the Big Buck Bunny movie and Sintel movie, 4 | which are licensed under Creative Commons Attribution 3.0 5 | (https://creativecommons.org/licenses/by/3.0/). 6 | (c) copyright 2008, Blender Foundation / www.bigbuckbunny.org 7 | (c) copyright Blender Foundation | durian.blender.org 8 | Blender Foundation | www.blender.org 9 | 10 | """ 11 | 12 | from __future__ import annotations 13 | 14 | import logging 15 | import unittest 16 | from pathlib import Path 17 | from typing import TYPE_CHECKING 18 | 19 | from hydrusvideodeduplicator.vpdqpy.vpdqpy import Vpdq, VpdqHash 20 | 21 | from hvdaccelerators import vpdq 22 | 23 | from ..check_testdb import check_testdb_exists 24 | 25 | if TYPE_CHECKING: 26 | from collections.abc import Iterable 27 | 28 | 29 | class TestVpdq(unittest.TestCase): 30 | log = logging.getLogger(__name__) 31 | log.setLevel(logging.WARNING) 32 | logging.basicConfig() 33 | 34 | def setUp(self): 35 | check_testdb_exists() 36 | all_vids_dir = Path(__file__).parents[1] / "testdb" / "videos" 37 | self.video_hashes_dir = Path(__file__).parents[1] / "testdb" / "video hashes" 38 | assert all_vids_dir.is_dir() 39 | assert self.video_hashes_dir.is_dir() 40 | 41 | # Similarity videos should be checked for similarity. 42 | # They should be similar to other videos in the same group, but not to videos in other groups. 43 | # They are in separate folders for organizational purposes. 44 | similarity_vids_dirs = ["big_buck_bunny", "sintel"] 45 | self.similarity_vids: list[Path] = [] 46 | for vids_dir in similarity_vids_dirs: 47 | self.similarity_vids.extend(Path(all_vids_dir / vids_dir).glob("*")) 48 | 49 | # Strange videos should hash but not be checked for similarity. 50 | # They're used to test that the program doesn't crash 51 | # when it encounters a video with odd characteristics like extremely short length 52 | # or a video that has tiny dimensions, etc. The more of these added the better. 53 | # They shouldn't be compared because they might be similar to other videos, but not all of them in a group. 54 | strange_vids_dir = "strange" 55 | self.strange_vids: list[Path] = Path(all_vids_dir / strange_vids_dir).glob("*") 56 | 57 | # This should be run with a known good version of Vpdq to generate known good hashes. 58 | # If VPDQ changes, these hashes will need to be updated this needs 59 | # to be run once with overwrite = True to generate new good hashes. 60 | # 61 | # Hashes after changes to Vpdq should be byte-for-byte identical 62 | # to the hashes generated by the current version of Vpdq. 63 | def generate_known_good_hashes(self, vids: Iterable[Path], overwrite: bool = False): 64 | vids_to_be_hashed = [] 65 | for vid in vids: 66 | hash_file = self.video_hashes_dir / Path(f"{vid.name}.txt") 67 | if not hash_file.exists() or overwrite: 68 | vids_to_be_hashed.append(vid) 69 | 70 | vids_hashes = self.calc_hashes(vids_to_be_hashed) 71 | for file, phash in vids_hashes.items(): 72 | with open(self.video_hashes_dir / f"{file.name}.txt", "w") as hashes_file: 73 | hashes_file.write(str(phash)) 74 | 75 | # Return if two videos are supposed to be similar 76 | # This uses the prefix SXX where XX is an arbitrary group number. 77 | # If two videos have the same SXX they should be similar, 78 | # if they don't they should NOT be similar. 79 | def similar_group(self, vid1: Path, vid2: Path) -> bool: 80 | # If either video doesn't have a group, they're not similar 81 | if vid1.name.split("_")[0][0] != "S" or vid2.name.split("_")[0][0] != "S": 82 | return False 83 | 84 | vid1_group = vid1.name.split("_")[0] 85 | vid2_group = vid2.name.split("_")[0] 86 | return vid1_group == vid2_group 87 | 88 | # Hash videos 89 | # Several other functions call this, so it needs to be correct and catch all bad hashes. 90 | def calc_hashes(self, vids: list[Path]) -> dict[Path, VpdqHash]: 91 | vids_hashes = {} 92 | for vid in vids: 93 | perceptual_hash = Vpdq.computeHash(vid) 94 | vids_hashes[vid] = perceptual_hash 95 | self.assertTrue(len(perceptual_hash) > 0) 96 | return vids_hashes 97 | 98 | # Hash all videos. They should all have hashes. 99 | def test_hashing(self): 100 | self.calc_hashes(self.similarity_vids) 101 | self.calc_hashes(self.strange_vids) 102 | 103 | # Hash videos and test if they are identical to the known good hashes. 104 | # Change overwrite to true to generate new hashes, then rerun, but it should always be committed as overwrite=False 105 | def test_hashing_identical(self): 106 | vids = self.similarity_vids 107 | self.generate_known_good_hashes(vids=vids, overwrite=False) 108 | vids_hashes = self.calc_hashes(vids) 109 | 110 | for phash_path, phash in vids_hashes.items(): 111 | with open(self.video_hashes_dir / f"{phash_path.name}.txt", "r") as hashes_file: 112 | expected_phash = vpdq.VpdqHash.from_string(hashes_file.read()) 113 | self.log.error(phash_path.name) # Needs to be error to show up in log 114 | similar, similarity = Vpdq.is_similar(phash, expected_phash) 115 | self.assertTrue((0.0 <= similarity) and (similarity <= 100.0)) 116 | if expected_phash != phash: 117 | # Hashes must be within similarity of 1, even if environmental factors differ (ex. FFmpeg version) 118 | # This heuristic of course depends on similarity to be fully working. 119 | SIMILARITY_DIFFERENCE_THRESHOLD = 1.0 120 | self.log.warning( 121 | f"Video hashes not identical for file {phash_path.name}. \n {expected_phash} \n {phash}. \ 122 | Similarity: {similarity}" 123 | ) 124 | self.assertGreater( 125 | SIMILARITY_DIFFERENCE_THRESHOLD, 126 | (100.0 - similarity), 127 | msg=f"Hash similarity below threshold. Similarity: {similarity}", 128 | ) 129 | 130 | # Compare similar videos. They should be similar if they're in the same similarity group. 131 | def test_compare_similarity_true(self): 132 | vids_hashes = self.calc_hashes(self.similarity_vids) 133 | for vid1 in vids_hashes.items(): 134 | for vid2 in vids_hashes.items(): 135 | if vid1[0] == vid2[0]: 136 | continue 137 | 138 | similar, similarity = Vpdq.is_similar(vid1[1], vid2[1]) 139 | self.assertTrue((0.0 <= similarity) and (similarity <= 100.0)) 140 | 141 | with self.subTest(msg=f"Similar: {similar}", vid1=vid1[0].name, vid2=vid2[0].name): 142 | if self.similar_group(vid1[0], vid2[0]): 143 | self.assertTrue(similar, msg=f"{vid1[1]}, \n {vid2[1]}") 144 | else: 145 | self.assertFalse(similar, msg=f"{vid1[1]}, \n {vid2[1]}") 146 | 147 | 148 | if __name__ == "__main__": 149 | unittest.main(module="test_vpdqpy") 150 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/client.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | from typing import TYPE_CHECKING 5 | 6 | if TYPE_CHECKING: 7 | from collections.abc import Iterable 8 | from typing import TypeAlias 9 | 10 | FileServiceKeys: TypeAlias = list[str] 11 | FileHashes: TypeAlias = Iterable[str] 12 | 13 | from urllib3.connection import NewConnectionError 14 | 15 | import hydrusvideodeduplicator.hydrus_api as hydrus_api 16 | import hydrusvideodeduplicator.hydrus_api.utils as hydrus_api_utils 17 | 18 | 19 | class ClientAPIException(Exception): 20 | """Base exception for HVDClient failures.""" 21 | 22 | def __init__(self, pretty_msg: str = "", real_msg: str = ""): 23 | super().__init__(real_msg) 24 | self.pretty_msg = pretty_msg 25 | 26 | 27 | class FailedHVDClientConnection(ClientAPIException): 28 | """Raise for when HVDClient fails to connect.""" 29 | 30 | 31 | class InsufficientPermissions(ClientAPIException): 32 | """Raise for when Hydrus API key permissions are insufficient.""" 33 | 34 | 35 | class HVDClient: 36 | _log = logging.getLogger("HVDClient") 37 | _log.setLevel(logging.INFO) 38 | 39 | def __init__( 40 | self, 41 | file_service_keys: FileServiceKeys | None, 42 | api_url: str, 43 | access_key: str, 44 | verify_cert: str | None, # None means do not verify SSL. 45 | ): 46 | self.client = hydrus_api.Client(access_key=access_key, api_url=api_url, verify_cert=verify_cert) 47 | self.file_service_keys = ( 48 | [key for key in file_service_keys if key.strip()] 49 | if (file_service_keys and file_service_keys is not None) 50 | else self.get_default_file_service_keys() 51 | ) 52 | self.verify_file_service_keys() 53 | 54 | def get_video(self, video_hash: str) -> bytes: 55 | """ 56 | Retrieves a video from Hydrus by the videos hash. 57 | 58 | Returns the video bytes. 59 | """ 60 | video_response = self.client.get_file(hash_=video_hash) 61 | video = video_response.content 62 | return video 63 | 64 | def get_potential_duplicate_count_hydrus(self) -> int: 65 | return self.client.get_potentials_count(file_service_keys=self.file_service_keys)["potential_duplicates_count"] 66 | 67 | def get_default_file_service_keys(self) -> FileServiceKeys: 68 | services = self.client.get_services() 69 | 70 | # Set the file service keys to be used for hashing 71 | # Default is "all local files" 72 | file_service_keys = [services["all_local_files"][0]["service_key"]] 73 | return file_service_keys 74 | 75 | def verify_file_service_keys(self) -> None: 76 | """Verify that the supplied file_service_key is a valid key for a local file service.""" 77 | valid_service_types = [ 78 | hydrus_api.ServiceType.ALL_LOCAL_FILES, 79 | hydrus_api.ServiceType.FILE_DOMAIN, 80 | ] 81 | services = self.client.get_services() 82 | 83 | for file_service_key in self.file_service_keys: 84 | file_service = services["services"].get(file_service_key) 85 | if file_service is None: 86 | raise KeyError(f"Invalid file service key: '{file_service_key}'") 87 | 88 | service_type = file_service.get("type") 89 | if service_type not in valid_service_types: 90 | raise KeyError("File service key must be a local file service") 91 | 92 | def get_hydrus_api_version(self) -> str: 93 | api_version_req = self.client.get_api_version() 94 | if "version" not in api_version_req: 95 | raise ClientAPIException( 96 | "'version' is not in the Hydrus API version response. Something is terribly wrong." 97 | ) 98 | return api_version_req["version"] 99 | 100 | def get_api_version(self) -> int: 101 | """Get the API version of the API module used to connect to Hydrus.""" 102 | return self.client.VERSION 103 | 104 | def verify_permissions(self): 105 | """ 106 | Verify API permissions. Throws InsufficientPermissions if permissions are insufficient, otherwise nothing. 107 | 108 | Throws ClientAPIException on Hydrus API failure. 109 | """ 110 | try: 111 | permissions = hydrus_api_utils.verify_permissions(self.client, hydrus_api.utils.Permission) 112 | except hydrus_api.HydrusAPIException as exc: 113 | raise ClientAPIException("An error has occurred while trying to verify permissions.", str(exc)) 114 | 115 | if not permissions: 116 | raise ClientAPIException("Insufficient Hydrus permissions.") 117 | 118 | def get_video_hashes(self, search_tags: Iterable[str]) -> Iterable[str]: 119 | """ 120 | Get video hashes from Hydrus from a list of search tags. 121 | 122 | Get video hashes that have the given search tags. 123 | """ 124 | all_video_hashes = self.client.search_files( 125 | tags=search_tags, 126 | file_service_keys=self.file_service_keys, 127 | file_sort_type=hydrus_api.FileSortType.FILE_SIZE, 128 | return_hashes=True, 129 | file_sort_asc=True, 130 | return_file_ids=False, 131 | )["hashes"] 132 | return all_video_hashes 133 | 134 | def are_files_deleted_hydrus(self, file_hashes: FileHashes) -> dict[str, bool]: 135 | """ 136 | Check if files are trashed or deleted in Hydrus 137 | 138 | Returns a dictionary of {hash, trashed_or_not} 139 | """ 140 | videos_metadata = self.client.get_file_metadata(hashes=file_hashes, only_return_basic_information=False)[ 141 | "metadata" 142 | ] 143 | 144 | result: dict[str, bool] = {} 145 | for video_metadata in videos_metadata: 146 | # This should never happen, but it shouldn't break the program if it does 147 | if "hash" not in video_metadata: 148 | self._log.error("Hash not found for potentially trashed file.") 149 | continue 150 | video_hash = video_metadata["hash"] 151 | is_deleted: bool = video_metadata.get("is_deleted", False) 152 | result[video_hash] = is_deleted 153 | 154 | return result 155 | 156 | 157 | def create_client(*args) -> HVDClient: 158 | """ 159 | Try to create a client and connect to Hydrus. 160 | 161 | Throws FailedHVDClientConnection on failure. 162 | 163 | TODO: Try to connect with https first and then fallback to http with a strong warning (GH #58) 164 | """ 165 | connection_failed = True 166 | try: 167 | hvdclient = HVDClient(*args) 168 | except hydrus_api.InsufficientAccess as exc: 169 | pretty_msg = "Invalid Hydrus API key." 170 | real_msg = str(exc) 171 | except hydrus_api.DatabaseLocked as exc: 172 | pretty_msg = "Hydrus database is locked. Try again later." 173 | real_msg = str(exc) 174 | except hydrus_api.ServerError as exc: 175 | pretty_msg = "Unknown Server Error." 176 | real_msg = str(exc) 177 | except hydrus_api.APIError as exc: 178 | pretty_msg = "API Error" 179 | real_msg = str(exc) 180 | except (NewConnectionError, hydrus_api.ConnectionError, hydrus_api.HydrusAPIException) as exc: 181 | # Probably SSL error 182 | if "SSL" in str(exc): 183 | pretty_msg = "Failed to connect to Hydrus. SSL certificate verification failed." 184 | # Probably tried using http instead of https when client is https 185 | elif "Connection aborted" in str(exc): 186 | pretty_msg = ( 187 | "Failed to connect to Hydrus.\nDoes your Hydrus Client API 'http/https' setting match your API URL?" 188 | ) 189 | elif "Connection refused" in str(exc): 190 | pretty_msg = """Failed to connect to Hydrus. 191 | Is your Hydrus instance running? 192 | Is the client API enabled? (hint: services -> manage services -> client api) 193 | Is your port correct? (hint: default is 45869) 194 | """ 195 | else: 196 | pretty_msg = "Failed to connect to Hydrus. Unknown exception occurred." 197 | real_msg = str(exc) 198 | else: 199 | connection_failed = False 200 | 201 | if connection_failed: 202 | raise FailedHVDClientConnection(pretty_msg, real_msg) 203 | 204 | return hvdclient 205 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/entrypoint.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | from typing import TYPE_CHECKING, Annotated, List, Optional 5 | 6 | if TYPE_CHECKING: 7 | from typing import NoReturn 8 | 9 | from pathlib import Path 10 | 11 | import typer 12 | from rich import print 13 | 14 | from hydrusvideodeduplicator.__about__ import __version__ 15 | from hydrusvideodeduplicator.client import ( 16 | ClientAPIException, 17 | FailedHVDClientConnection, 18 | HVDClient, 19 | create_client, 20 | ) 21 | from hydrusvideodeduplicator.config import ( 22 | DEDUP_DATABASE_DIR, 23 | FAILED_PAGE_NAME, 24 | HYDRUS_API_KEY, 25 | HYDRUS_API_URL, 26 | HYDRUS_LOCAL_FILE_SERVICE_KEYS, 27 | HYDRUS_QUERY, 28 | REQUESTS_CA_BUNDLE, 29 | is_windows_exe, 30 | ) 31 | from hydrusvideodeduplicator.db import DedupeDB 32 | from hydrusvideodeduplicator.dedup import HydrusVideoDeduplicator 33 | from hydrusvideodeduplicator.dedup_util import print_and_log 34 | 35 | """ 36 | Parameters: 37 | - api_key will be read from env var $HYDRUS_API_KEY or .env file 38 | - api_url will be read from env var $HYDRUS_API_URL or .env file 39 | - to add custom queries, do 40 | --custom-query="series:twilight" --custom-query="character:edward" ... etc for each query 41 | - threshold is the min % matching to be considered similar. 100% is very very similar. 42 | - verbose turns on logging 43 | - debug turns on logging and sets the logging level to debug 44 | """ 45 | 46 | 47 | def main( 48 | api_key: Annotated[Optional[str], typer.Option(help="Hydrus API Key", prompt=True)] = None, 49 | api_url: Annotated[Optional[str], typer.Option(help="Hydrus API URL")] = HYDRUS_API_URL, 50 | overwrite: Annotated[Optional[Optional[bool]], typer.Option(hidden=True)] = None, # deprecated 51 | query: Annotated[Optional[List[str]], typer.Option(help="Custom Hydrus tag query")] = HYDRUS_QUERY, 52 | threshold: Annotated[ 53 | Optional[float], typer.Option(help="Similarity threshold for a pair of videos where 100 is identical") 54 | ] = 50.0, 55 | skip_hashing: Annotated[ 56 | Optional[bool], typer.Option(help="Skip perceptual hashing and just search for duplicates") 57 | ] = False, 58 | file_service_key: Annotated[ 59 | Optional[List[str]], typer.Option(help="Local file service key") 60 | ] = HYDRUS_LOCAL_FILE_SERVICE_KEYS, 61 | verify_cert: Annotated[ 62 | Optional[str], typer.Option(help="Path to TLS cert. This forces verification.") 63 | ] = REQUESTS_CA_BUNDLE, 64 | clear_search_tree: Annotated[ 65 | Optional[bool], typer.Option(help="Clear the search tree that tracks what files have already been compared.") 66 | ] = False, 67 | clear_search_cache: Annotated[ 68 | Optional[bool], 69 | typer.Option( 70 | help="Clear the search cache that tracks what files have been compared with a given similarity threshold." 71 | ), 72 | ] = False, 73 | failed_page_name: Annotated[ 74 | Optional[str], typer.Option(help="The name of the Hydrus page to add failed files to.") 75 | ] = FAILED_PAGE_NAME, 76 | job_count: Annotated[ 77 | Optional[int], 78 | typer.Option(help="Number of CPU threads to use for perceptual hashing. Default is all but one core."), 79 | ] = -2, 80 | dedup_database_dir: Annotated[ 81 | Optional[Path], typer.Option(help="The directory to store the database used for dedupe.") 82 | ] = DEDUP_DATABASE_DIR, 83 | verbose: Annotated[Optional[bool], typer.Option(help="Verbose logging")] = False, 84 | debug: Annotated[Optional[bool], typer.Option(hidden=True)] = False, 85 | ): 86 | # Fix mypy errors from optional parameters 87 | assert threshold is not None and skip_hashing is not None and job_count is not None 88 | 89 | # CLI debug parameter sets log level to info or debug 90 | loglevel = logging.INFO 91 | if debug: 92 | loglevel = logging.DEBUG 93 | verbose = True 94 | 95 | logging.basicConfig(format=" %(asctime)s - %(name)s: %(message)s", datefmt="%H:%M:%S", level=loglevel) 96 | logger = logging.getLogger("main") 97 | logger.debug("Starting Hydrus Video Deduplicator.") 98 | 99 | def exit_from_failure() -> NoReturn: 100 | print_and_log(logger, "Exiting due to failure...") 101 | raise typer.Exit(code=1) 102 | 103 | # Verbose sets whether logs are shown to the user at all. 104 | # Logs are separate from printing in this program. 105 | if not verbose: 106 | logging.disable() 107 | 108 | DedupeDB.set_db_dir(dedup_database_dir) 109 | 110 | # Print a warning if the deprecated overwrite option is set 111 | if overwrite is not None: 112 | pretty_overwrite = "--" + ("" if overwrite is True else "no-") + "overwrite" 113 | print_and_log( 114 | logger, 115 | f"WARNING: '{pretty_overwrite}' option was deprecated and does nothing as of 0.7.0. Remove it from your args.", # noqa: E501 116 | ) 117 | 118 | # CLI overwrites env vars with no default value 119 | if not api_key: 120 | api_key = HYDRUS_API_KEY 121 | 122 | # Check for necessary variables 123 | if not api_key: 124 | print_and_log(logger, "Hydrus API key is not set. Please set with '--api-key'.") 125 | exit_from_failure() 126 | # This should not happen because there's a default val in config.py 127 | if not api_url: 128 | print_and_log(logger, "Hydrus API URL is not set. Please set with '--api-url'.") 129 | exit_from_failure() 130 | 131 | # Client connection 132 | print_and_log(logger, f"Connecting to Hydrus at {api_url}") 133 | try: 134 | hvdclient = create_client( 135 | file_service_key, 136 | api_url, 137 | api_key, 138 | verify_cert, 139 | ) 140 | api_version = hvdclient.get_api_version() 141 | hydrus_api_version = hvdclient.get_hydrus_api_version() 142 | print_and_log(logger, f"Dedupe API version: 'v{api_version}'") 143 | print_and_log(logger, f"Hydrus API version: 'v{hydrus_api_version}'") 144 | hvdclient.verify_permissions() 145 | except (FailedHVDClientConnection, ClientAPIException) as exc: 146 | print_and_log(logger, str(exc), logging.FATAL) 147 | print_and_log(logger, exc.pretty_msg, logging.FATAL) 148 | exit_from_failure() 149 | 150 | if debug: 151 | HVDClient._log.setLevel(logging.DEBUG) 152 | 153 | # Deduplication 154 | 155 | if DedupeDB.does_db_exist(): 156 | print_and_log(logger, f"Found existing database at '{DedupeDB.get_db_file_path()}'") 157 | db = DedupeDB.DedupeDb(DedupeDB.get_db_dir(), DedupeDB.get_db_name()) 158 | db.init_connection() 159 | # Upgrade the database before doing anything. 160 | db.begin_transaction() 161 | db_upgraded = False 162 | with db.conn: 163 | db_upgraded = db.upgrade_db() 164 | # Vacuum DB after a successful database upgrade. This can reduce space by 1/2 in cases of large 165 | # db migrations. 166 | if db_upgraded: 167 | print_and_log( 168 | logger, 169 | "Database upgraded, vacuuming to save space.", 170 | ) 171 | db_stats = DedupeDB.get_db_stats(db) 172 | print_and_log( 173 | logger, 174 | f"Database filesize before vacuum: {db_stats.file_size} bytes.", 175 | ) 176 | db.vacuum() 177 | db_stats = DedupeDB.get_db_stats(db) 178 | print_and_log( 179 | logger, 180 | f"Database filesize after vacuum: {db_stats.file_size} bytes.", 181 | ) 182 | db_stats = DedupeDB.get_db_stats(db) 183 | 184 | print_and_log( 185 | logger, 186 | f"Database has {db_stats.num_videos} videos already perceptually hashed.", 187 | ) 188 | print_and_log( 189 | logger, 190 | f"Database filesize: {db_stats.file_size} bytes.", 191 | ) 192 | 193 | if clear_search_tree: 194 | db.begin_transaction() 195 | with db.conn: 196 | db.clear_search_tree() 197 | print("[green] Cleared the search tree.") 198 | 199 | if clear_search_cache: 200 | db.begin_transaction() 201 | with db.conn: 202 | db.clear_search_cache() 203 | print("[green] Cleared the search cache.") 204 | 205 | else: 206 | print_and_log(logger, f"Database not found. Creating one at '{DedupeDB.get_db_file_path()}'", logging.INFO) 207 | if not DedupeDB.get_db_dir().exists(): 208 | DedupeDB.create_db_dir() 209 | db = DedupeDB.DedupeDb(DedupeDB.get_db_dir(), DedupeDB.get_db_name()) 210 | db.init_connection() 211 | db.begin_transaction() 212 | with db.conn: 213 | db.create_tables() 214 | db_stats = DedupeDB.get_db_stats(db) 215 | 216 | deduper = HydrusVideoDeduplicator( 217 | db, client=hvdclient, job_count=job_count, failed_page_name=failed_page_name, custom_query=query 218 | ) 219 | 220 | if debug: 221 | deduper.hydlog.setLevel(logging.DEBUG) 222 | deduper._DEBUG = True 223 | 224 | if threshold < 0.0 or threshold > 100.0: 225 | print("[red] ERROR: Invalid similarity threshold. Must be between 0 and 100.") 226 | raise typer.Exit(code=1) 227 | HydrusVideoDeduplicator.threshold = threshold 228 | 229 | num_similar_pairs = deduper.deduplicate( 230 | skip_hashing=skip_hashing, 231 | ) 232 | 233 | db.close() 234 | 235 | return num_similar_pairs 236 | 237 | 238 | def run_main(): 239 | print(f"[blue] Hydrus Video Deduplicator {__version__} [/]") 240 | try: 241 | typer.run(main) 242 | except KeyboardInterrupt as exc: 243 | raise typer.Exit(-1) from exc 244 | finally: 245 | if is_windows_exe(): 246 | # Hang the console window for the Windows exe, because 99% of users will be running this 247 | # interactively and will want this pause to see errors/the final results. The other 1% should file 248 | # a Github issue if this causes them issues and they want some --no-interactive option, or they should just 249 | # run the Python install. 250 | input("Press ENTER to exit...") 251 | 252 | 253 | if __name__ == "__main__": 254 | run_main() 255 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/dedup.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | import time 5 | from dataclasses import dataclass 6 | from typing import TYPE_CHECKING 7 | 8 | from rich import print 9 | from tqdm import tqdm 10 | 11 | if TYPE_CHECKING: 12 | from collections.abc import Sequence 13 | 14 | FileHash = str 15 | 16 | import gc 17 | 18 | import hydrusvideodeduplicator.hydrus_api as hydrus_api 19 | 20 | from .client import HVDClient 21 | from .db import DedupeDB, vptree 22 | from .hashing import compute_phash 23 | from .page_logger import HydrusPageLogger 24 | from hvdaccelerators import vpdq 25 | 26 | 27 | @dataclass 28 | class PerceptuallyHashedFile: 29 | """Class for perceptually hashed files.""" 30 | 31 | file_hash: FileHash 32 | perceptual_hash: bytes 33 | 34 | 35 | @dataclass 36 | class FailedPerceptuallyHashedFile: 37 | """Class for failed perceptually hashed files.""" 38 | 39 | file_hash: FileHash 40 | exc: Exception 41 | 42 | 43 | class HydrusApiException(Exception): 44 | """Wrapper around hydrus_api.HydrusAPIException to avoid some coupling with hydrus_api outside of FileHasher.""" 45 | 46 | 47 | class FailedPerceptualHashException(Exception): 48 | """Exception for when files are failed to be perceptually hashed.""" 49 | 50 | def __init__(self, file_hash: FileHash, other_exc: str = ""): 51 | super().__init__() 52 | self.file_hash = file_hash 53 | self.other_exc = other_exc 54 | 55 | 56 | class FileHasher: 57 | """ 58 | A class to fetch a file from Hydrus and phash it. 59 | """ 60 | 61 | def __init__(self, client: HVDClient, num_threads: int = 0): 62 | self.client = client 63 | self.num_threads = num_threads 64 | 65 | def _fetch_file(self, file_hash: str): 66 | try: 67 | response = self.client.client.get_file(hash_=file_hash) 68 | except hydrus_api.HydrusAPIException as exc: 69 | raise HydrusApiException(exc) 70 | return response.content 71 | 72 | def _phash_file(self, file: bytes) -> bytes: 73 | try: 74 | phash = compute_phash(file, self.num_threads) 75 | phash_bytes: bytes = phash.bytes 76 | except Exception as exc: 77 | raise FailedPerceptualHashException("", str(exc)) 78 | 79 | # sanity check 80 | # Note: Hashes may have 0 bytes if there was no frames that were high enough quality to be used. 81 | if phash_bytes is None or (len(phash_bytes) % vpdq.VpdqHash.bytesPerPdqHash != 0): 82 | raise FailedPerceptualHashException("", "phash_str was None or len not multiple of 32.") 83 | 84 | return phash_bytes 85 | 86 | def fetch_and_phash_file(self, file_hash: str) -> PerceptuallyHashedFile | FailedPerceptuallyHashedFile: 87 | """ 88 | Retrieves the file from Hydrus and calculates its perceptual hash and returns the result. 89 | 90 | Returns FailedPerceptuallyHashedFile with the failed video hash if there are any errors. 91 | """ 92 | try: 93 | file = self._fetch_file(file_hash) 94 | except HydrusApiException as exc: 95 | # Add a delay before turning so that if there is some transient issue 96 | # the next file to be hashed won't also immediately error. 97 | # This is a hack. There should probably be some counter in the result generator 98 | # for the number of failures before hashing is stopped entirely. 99 | time.sleep(3) 100 | return FailedPerceptuallyHashedFile(file_hash, exc) 101 | 102 | try: 103 | phash = self._phash_file(file) 104 | except FailedPerceptualHashException as exc: 105 | return FailedPerceptuallyHashedFile(file_hash, exc) 106 | 107 | return PerceptuallyHashedFile(file_hash, phash) 108 | 109 | 110 | @dataclass 111 | class PerceptualHashingStats: 112 | success_hash_count: int = 0 113 | failed_from_api_errors_count: int = 0 114 | failed_from_phash_count: int = 0 115 | 116 | 117 | class CancelledPerceptualHashException(Exception): 118 | """Exception for when perceptual hashing is cancelled.""" 119 | 120 | def __init__(self, stats: PerceptualHashingStats): 121 | super().__init__() 122 | self.stats = stats 123 | 124 | 125 | class HydrusVideoDeduplicator: 126 | hydlog = logging.getLogger("hvd") 127 | hydlog.setLevel(logging.INFO) 128 | threshold: float = 75.0 129 | _DEBUG = False 130 | 131 | def __init__( 132 | self, 133 | db: DedupeDB.DedupeDb, 134 | client: HVDClient, 135 | job_count: int = -2, 136 | failed_page_name: str | None = None, 137 | custom_query: Sequence[str] | None = None, 138 | ): 139 | self.db = db 140 | self.client = client 141 | self.job_count = job_count 142 | self.page_logger = None if failed_page_name is None else HydrusPageLogger(self.client, failed_page_name) 143 | self.search_tags = self.get_search_tags(custom_query) 144 | 145 | def get_search_tags(self, custom_query: Sequence[str] | None) -> list[str]: 146 | # system:filetype tags are really inconsistent 147 | search_tags = [ 148 | "system:filetype=video, gif, apng", 149 | "system:has duration", 150 | "system:file service is not currently in trash", 151 | ] 152 | 153 | if custom_query is not None: 154 | # Remove whitespace and empty strings 155 | custom_query = [x for x in custom_query if x.strip()] 156 | if len(custom_query) > 0: 157 | search_tags.extend(custom_query) 158 | print(f"[yellow] Custom Query: {custom_query}") 159 | return search_tags 160 | 161 | def deduplicate( 162 | self, 163 | skip_hashing: bool, 164 | ) -> int: 165 | """ 166 | Run all deduplicate functions. 167 | 168 | Dedupe Algorithm: 169 | 1. Perceptually hash the videos. 170 | 2. Insert the perceptual hashes into the vptree 171 | 3. Search for similar videos in the vptree. 172 | 4. Mark the similar videos as potential duplicates in Hydrus. 173 | 174 | Returns the number of similar pairs found during searching. 175 | """ 176 | num_similar_pairs = 0 177 | 178 | if skip_hashing: 179 | print("[yellow] Skipping perceptual hashing") 180 | else: 181 | video_hashes = list(self.client.get_video_hashes(self.search_tags)) 182 | video_hashes = self.filter_unhashed(video_hashes) 183 | print(f"[blue] Found {len(video_hashes)} eligible files to perceptually hash.") 184 | print("\nTip: You can skip perceptual hashing at any time by pressing CTRL+C.") 185 | self.hydlog.info("Starting perceptual hash processing") 186 | self.db.begin_transaction() 187 | with self.db.conn: 188 | stats = PerceptualHashingStats() 189 | try: 190 | stats = self.add_perceptual_hashes_to_db(video_hashes) 191 | except CancelledPerceptualHashException as exc: 192 | # Interrupted, but on purpose. 193 | stats = exc.stats 194 | print("[yellow] Perceptual hash processing was interrupted! Progress was saved.") 195 | else: 196 | print("[green] Finished perceptual hash processing.") 197 | finally: 198 | # Print some useful stats and info for users 199 | total_failures = stats.failed_from_api_errors_count + stats.failed_from_phash_count 200 | if total_failures > 0: 201 | print(f"[yellow] Perceptual hash processing had {total_failures} total failed files.") 202 | 203 | if stats.failed_from_api_errors_count > 0: 204 | print( 205 | f"[yellow] {stats.failed_from_api_errors_count} failures were due to API errors. Ensure Hydrus is running and accessible before trying again." # noqa: E501 206 | ) 207 | 208 | if stats.failed_from_phash_count > 0: 209 | print( 210 | f"[yellow] {stats.failed_from_phash_count} failures were from an error during perceptual hashing. Are the files corrupted?" # noqa: E501 211 | ) 212 | print( 213 | "\nTip: You could have seen which files failed directly in Hydrus by " 214 | "creating a Hydrus page with the name 'failed' and " 215 | "running the program with '--failed-page-name=failed'\n" 216 | ) 217 | print(f"[green] Added {stats.success_hash_count} new perceptual hashes to the database.") 218 | 219 | # Insert the perceptual hashed files into the vptree. 220 | print("\nTip: You can skip building the search tree at any time by pressing CTRL+C.") 221 | self.db.begin_transaction() 222 | with self.db.conn: 223 | try: 224 | self.process_phashed_file_queue() 225 | except KeyboardInterrupt: 226 | print("[yellow] Building the search tree was interrupted! Progress was saved.") 227 | else: 228 | print("[green] Finished fully building the search tree.") 229 | 230 | self.db.begin_transaction() 231 | with self.db.conn: 232 | try: 233 | self.run_maintenance() 234 | except KeyboardInterrupt: 235 | print("[yellow] Maintenance was interrupted!") 236 | else: 237 | print("[green] Finished maintenance.") 238 | 239 | # Number of potential duplicates before adding more. 240 | # This is just to print info for the user. 241 | # Note: This will be inaccurate if the user searches for duplicates in the Hydrus client 242 | # while this is running. 243 | pre_dedupe_count = self.client.get_potential_duplicate_count_hydrus() 244 | 245 | print("\nTip: You can skip finding potential duplicates at any time by pressing CTRL+C.") 246 | self.db.begin_transaction() 247 | with self.db.conn: 248 | try: 249 | num_similar_pairs = self.find_potential_duplicates() 250 | except KeyboardInterrupt: 251 | print("[yellow] Searching for duplicates was interrupted! Progress was saved.") 252 | 253 | # Statistics for user 254 | post_dedupe_count = self.client.get_potential_duplicate_count_hydrus() 255 | new_dedupes_count = post_dedupe_count - pre_dedupe_count 256 | if new_dedupes_count > 0: 257 | print(f"[green] {new_dedupes_count} new potential duplicate pairs marked for manual processing!") 258 | else: 259 | print("[green] No new potential duplicate pairs found.") 260 | 261 | self.hydlog.info(f"{num_similar_pairs} similar file pairs found.") 262 | self.hydlog.info("Deduplication done.") 263 | 264 | return num_similar_pairs 265 | 266 | def filter_unhashed(self, file_hashes: list[FileHash]) -> list[FileHash]: 267 | """ 268 | Get only the files that have not been perceptually hashed in the db from a list of files. 269 | """ 270 | all_phashed_files = self.db.get_phashed_files() 271 | return [file_hash for file_hash in file_hashes if file_hash not in all_phashed_files] 272 | 273 | def add_perceptual_hashes_to_db(self, video_hashes: Sequence[str]) -> PerceptualHashingStats: 274 | """ 275 | Retrieves the video from Hydrus, 276 | calculates the perceptual hash, 277 | and then add it to the database. 278 | """ 279 | stats = PerceptualHashingStats() 280 | try: 281 | with tqdm( 282 | total=len(video_hashes), 283 | desc="Perceptually hashing files", 284 | dynamic_ncols=True, 285 | unit="file", 286 | colour="BLUE", 287 | ) as pbar: 288 | filehasher = FileHasher(self.client, self.job_count) 289 | for video_hash in video_hashes: 290 | result = filehasher.fetch_and_phash_file(video_hash) 291 | if isinstance(result, FailedPerceptuallyHashedFile): 292 | # We only want to add the failure to the page if the file was the actual cause of failure. 293 | if isinstance(result.exc, HydrusApiException): 294 | stats.failed_from_api_errors_count += 1 295 | print("[red] Hydrus API error during perceptual hashing:") 296 | print(f"{result.exc}") 297 | else: 298 | stats.failed_from_phash_count += 1 299 | print("[red] Failed to perceptually hash a file.") 300 | print(f"Failed file SHA256 hash: {result.file_hash}") 301 | print(f"{result.exc}") 302 | if self.page_logger: 303 | self.page_logger.add_failed_video(result.file_hash) 304 | else: 305 | stats.success_hash_count += 1 306 | self.db.add_to_phashed_files_queue(result.file_hash, result.perceptual_hash) 307 | 308 | # Collect garbage now to avoid huge memory usage from the video files and frames. 309 | gc.collect() 310 | pbar.update(1) 311 | except KeyboardInterrupt: 312 | raise CancelledPerceptualHashException(stats) 313 | gc.collect() 314 | return stats 315 | 316 | def mark_videos_as_duplicates(self, video1_hash: str, video2_hash: str): 317 | """Mark a pair of videos as duplicates in Hydrus.""" 318 | new_relationship = { 319 | "hash_a": video1_hash, 320 | "hash_b": video2_hash, 321 | "relationship": int(hydrus_api.DuplicateStatus.POTENTIAL_DUPLICATES), 322 | "do_default_content_merge": True, 323 | } 324 | 325 | self.client.client.set_file_relationships([new_relationship]) 326 | 327 | def process_phashed_file_queue(self): 328 | """ 329 | Process the files in the phashed files queue. 330 | This inserts the queue entries into their respective tables and then inserts the file into the vptree. 331 | """ 332 | results = self.db.execute("SELECT file_hash, phash FROM phashed_file_queue").fetchall() 333 | for file_hash, perceptual_hash in tqdm( 334 | results, dynamic_ncols=True, total=len(results), desc="Building search tree", unit="file", colour="BLUE" 335 | ): 336 | self.db.add_file(file_hash) 337 | self.db.add_perceptual_hash(perceptual_hash) 338 | self.db.associate_file_with_perceptual_hash(file_hash, perceptual_hash) 339 | self.db.execute( 340 | "DELETE FROM phashed_file_queue WHERE file_hash = :file_hash AND phash = :phash", 341 | {"file_hash": file_hash, "phash": perceptual_hash}, 342 | ) 343 | 344 | def run_maintenance(self): 345 | """Run maintenance, if needed.""" 346 | tree = vptree.VpTreeManager(self.db) 347 | search_threshold = vptree.fix_vpdq_similarity((self.threshold)) 348 | assert search_threshold > 0 and isinstance(search_threshold, int) 349 | 350 | if tree.maintenance_due(search_threshold): 351 | # TODO: Do further testing on this. 352 | print("[blue] Running search tree maintenance...") 353 | tree.maintain_tree() 354 | 355 | def find_potential_duplicates( 356 | self, 357 | ) -> int: 358 | """ 359 | Find potential duplicates in the database and mark them as such in Hydrus. 360 | 361 | Returns the number of similar file pairs found. 362 | """ 363 | # TODO: Should we turn the inside of this function into a generator? It might make testing super easy. 364 | tree = vptree.VpTreeManager(self.db) 365 | search_threshold = vptree.fix_vpdq_similarity((self.threshold)) 366 | assert search_threshold > 0 and isinstance(search_threshold, int) 367 | 368 | files = self.db.execute( 369 | "SELECT hash_id FROM shape_search_cache WHERE searched_distance is NULL or searched_distance < :threshold", 370 | {"threshold": search_threshold}, 371 | ).fetchall() 372 | 373 | num_similar_pairs = 0 374 | with tqdm( 375 | dynamic_ncols=True, total=len(files), desc="Finding potential duplicates", unit="file", colour="BLUE" 376 | ) as pbar: 377 | for hash_id in files: 378 | hash_id = hash_id[0] 379 | result = tree.search_file(hash_id, max_hamming_distance=search_threshold) 380 | file_hash_a = self.db.get_file_hash(hash_id) 381 | for similar_hash_id, distance in result: 382 | file_hash_b = self.db.get_file_hash(similar_hash_id) 383 | if hash_id != similar_hash_id: 384 | self.hydlog.info(f'Similar files found: "{file_hash_a}" and "{file_hash_b}"') 385 | self.mark_videos_as_duplicates(file_hash_a, file_hash_b) 386 | num_similar_pairs += 1 387 | 388 | # TODO: 389 | # Do we need to add the below line here? See _PerceptualHashesSearchForPotentialDuplicates in Hydrus. 390 | # group_of_hash_ids = self._STL( self._Execute( 'SELECT hash_id FROM shape_search_cache WHERE searched_distance IS NULL or searched_distance < ?;', ( search_distance, ) ).fetchmany( 10 ) ) # noqa: E501 391 | # Update the search cache 392 | self.db.execute( 393 | "UPDATE shape_search_cache SET searched_distance = ? WHERE hash_id = ?;", 394 | (search_threshold, hash_id), 395 | ) 396 | 397 | pbar.update(1) 398 | return num_similar_pairs // 2 399 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/db/DedupeDB.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | import os 5 | import sqlite3 6 | from dataclasses import dataclass 7 | from pathlib import Path 8 | from typing import TYPE_CHECKING 9 | 10 | from rich import print 11 | 12 | from ..__about__ import __version__ 13 | from .vptree import VpTreeManager 14 | 15 | if TYPE_CHECKING: 16 | from collections.abc import Iterable 17 | from typing import TypeAlias 18 | 19 | FileServiceKeys: TypeAlias = list[str] 20 | FileHashes: TypeAlias = Iterable[str] 21 | 22 | 23 | dedupedblog = logging.getLogger("db") 24 | dedupedblog.setLevel(logging.INFO) 25 | 26 | _db_dir: Path = Path() 27 | _DB_FILE_NAME: str = "videohashes.sqlite" 28 | 29 | 30 | class DedupeDbException(Exception): 31 | """Base class for DedupeDb exceptions.""" 32 | 33 | 34 | def does_db_exist() -> bool: 35 | """ 36 | Check if the database exists. 37 | """ 38 | db_path = get_db_file_path() 39 | try: 40 | _ = db_path.resolve(strict=True) 41 | return True 42 | except FileNotFoundError: 43 | return False 44 | 45 | 46 | def create_db_dir() -> None: 47 | """ 48 | Create the database folder if it doesn't already exist. 49 | """ 50 | try: 51 | db_dir = get_db_file_path().parent 52 | os.makedirs(db_dir, exist_ok=False) 53 | # Exception before this log if directory already exists 54 | dedupedblog.info(f"Created DB dir {db_dir}") 55 | except OSError: 56 | pass 57 | 58 | 59 | @dataclass 60 | class DatabaseStats: 61 | num_videos: int 62 | file_size: int # in bytes 63 | 64 | 65 | def get_db_stats(db: DedupeDb) -> DatabaseStats: 66 | """Get some database stats.""" 67 | num_videos = db.get_num_phashed_files() 68 | file_size = os.path.getsize(get_db_file_path()) 69 | return DatabaseStats(num_videos, file_size) 70 | 71 | 72 | def create_db(): 73 | """ 74 | Create the database files. 75 | """ 76 | if not get_db_dir().exists(): 77 | create_db_dir() 78 | db = DedupeDb(get_db_dir(), get_db_name()) 79 | db.init_connection() 80 | db.create_tables() 81 | db.commit() 82 | db.close() 83 | 84 | 85 | def set_db_dir(dir: Path): 86 | """Set the directory for the database.""" 87 | global _db_dir 88 | _db_dir = dir 89 | 90 | 91 | def get_db_dir(): 92 | """Get the directory of the database.""" 93 | return _db_dir 94 | 95 | 96 | def get_db_name() -> str: 97 | """Get the db file name, e.g. videohashes.sqlite.""" 98 | return _DB_FILE_NAME 99 | 100 | 101 | def get_db_file_path() -> Path: 102 | """ 103 | Get database file path. 104 | 105 | Return the database file path. 106 | """ 107 | return get_db_dir() / get_db_name() 108 | 109 | 110 | class DedupeDb: 111 | def __init__(self, db_dir: Path, db_name: str): 112 | self.db_dir = db_dir 113 | self.db_name = db_name 114 | 115 | self.conn = None 116 | self.cur = None 117 | 118 | """ 119 | Main functions 120 | """ 121 | 122 | def execute(self, query, *query_args) -> sqlite3.Cursor: 123 | return self.cur.execute(query, *query_args) 124 | 125 | def set_cursor(self, cur: sqlite3.Cursor): 126 | self.cur = cur 127 | 128 | def close_cursor(self): 129 | if self.cur is not None: 130 | self.cur.close() 131 | del self.cur 132 | self.cur = None 133 | 134 | def init_connection(self): 135 | db_path = self.db_dir / self.db_name 136 | self.conn = sqlite3.connect(db_path) 137 | cur = self.conn.cursor() 138 | self.set_cursor(cur) 139 | 140 | def commit(self): 141 | self.conn.commit() 142 | 143 | def begin_transaction(self): 144 | self.execute("BEGIN TRANSACTION") 145 | 146 | def close(self): 147 | self.conn.close() 148 | 149 | """ 150 | Tables 151 | """ 152 | 153 | def create_tables(self): 154 | # version table 155 | self.execute("CREATE TABLE IF NOT EXISTS version (version TEXT)") 156 | self.execute("INSERT INTO version (version) VALUES (:version)", {"version": __version__}) 157 | 158 | # files table 159 | self.execute("CREATE TABLE IF NOT EXISTS files ( hash_id INTEGER PRIMARY KEY, file_hash BLOB_BYTES UNIQUE )") 160 | 161 | # phash tables 162 | self.execute( 163 | "CREATE TABLE IF NOT EXISTS shape_perceptual_hashes ( phash_id INTEGER PRIMARY KEY, phash BLOB_BYTES UNIQUE )" # noqa: E501 164 | ) 165 | self.execute( 166 | "CREATE TABLE IF NOT EXISTS shape_perceptual_hash_map ( phash_id INTEGER, hash_id INTEGER, PRIMARY KEY ( phash_id, hash_id ) )" # noqa: E501 167 | ) 168 | 169 | # vptree tables 170 | self.execute( 171 | "CREATE TABLE IF NOT EXISTS shape_vptree ( phash_id INTEGER PRIMARY KEY, parent_id INTEGER, radius INTEGER, inner_id INTEGER, inner_population INTEGER, outer_id INTEGER, outer_population INTEGER )" # noqa: E501 172 | ) 173 | # fmt: off 174 | self.execute( 175 | "CREATE TABLE IF NOT EXISTS shape_maintenance_branch_regen ( phash_id INTEGER PRIMARY KEY )" 176 | ) # noqa: E501 177 | # fmt: on 178 | self.execute( 179 | "CREATE TABLE IF NOT EXISTS shape_search_cache ( hash_id INTEGER PRIMARY KEY, searched_distance INTEGER )" 180 | ) 181 | 182 | # vptree insert queue. this is the list of files and their phashes that need to be inserted into the vptree. 183 | # when entries are added to this queue they don't exist at all in the other tables. they don't have a hash_id 184 | # or phash_id yet, unless those already exist from other files. 185 | # this is just a table to store the phashes until they are properly inserted into the vptree, since inserting 186 | # can take a while. 187 | self.execute( 188 | "CREATE TABLE IF NOT EXISTS phashed_file_queue ( file_hash BLOB_BYTES NOT NULL UNIQUE, phash BLOB_BYTES NOT NULL, PRIMARY KEY ( file_hash, phash ) )" # noqa: E501 189 | ) 190 | 191 | """ 192 | Utility 193 | """ 194 | 195 | def clear_search_tree(self): 196 | """Clear the search tree. The search cache will also be cleared. Does not clear the perceptual hash map.""" 197 | # Note: Need a separate cursor here since we're running queries in the loop that overwrite this cursor. 198 | cur = self.conn.cursor() 199 | cur.execute("SELECT phash_id, hash_id FROM shape_perceptual_hash_map") 200 | 201 | # Move the files back into the queue so that the tree can be rebuilt. 202 | for phash_id, hash_id in cur: 203 | phash_result = self.execute( 204 | "SELECT phash FROM shape_perceptual_hashes WHERE phash_id = :phash_id", {"phash_id": phash_id} 205 | ).fetchone() 206 | if not phash_result: 207 | # This should not happen. Perceptual hashes should always be in the database if there is a phash_id, 208 | # otherwise we have no idea what perceptual hash it is. 209 | print( 210 | f"ERROR clearing search tree while to get perceptual_hash from phash_id {phash_id}. perceptual_hash not found. Your DB may be corrupt." # noqa: E501 211 | ) 212 | continue 213 | perceptual_hash = phash_result[0] 214 | 215 | file_hash_result = self.execute( 216 | "SELECT file_hash FROM files WHERE hash_id = :hash_id", {"hash_id": hash_id} 217 | ).fetchone() 218 | if not file_hash_result: 219 | # This should not happen. File hashes should always be in the database if there is a hash_id, 220 | # otherwise we have no idea what file it is in Hydrus. 221 | print( 222 | f"ERROR clearing search tree while to get file_hash from hash_id {hash_id}. file_hash not found. Your DB may be corrupt." # noqa: E501 223 | ) 224 | continue 225 | file_hash = file_hash_result[0] 226 | 227 | self.add_to_phashed_files_queue(file_hash, perceptual_hash) 228 | 229 | self.execute("DELETE FROM shape_vptree") 230 | self.execute("DELETE FROM shape_search_cache") 231 | self.execute("DELETE FROM shape_maintenance_branch_regen") 232 | 233 | def clear_search_cache(self): 234 | """Clear the search cache for all files.""" 235 | tree = VpTreeManager(self) 236 | result = self.execute("SELECT hash_id FROM shape_search_cache").fetchall() 237 | if result: 238 | hash_ids = [hash_id[0] for hash_id in result] 239 | tree.reset_search(hash_ids) 240 | 241 | def add_file(self, file_hash: str): 242 | """Add a file to the db. If it already exists, do nothing.""" 243 | self.execute("INSERT OR IGNORE INTO files ( file_hash ) VALUES ( :file_hash )", {"file_hash": file_hash}) 244 | 245 | def add_perceptual_hash(self, perceptual_hash: bytes) -> int: 246 | """ 247 | Add a perceptual hash to the db. 248 | If it already exists, do nothing. 249 | 250 | Returns the phash_id of the perceptual hash. 251 | """ 252 | result = self.execute( 253 | "SELECT phash_id FROM shape_perceptual_hashes WHERE phash = :phash;", {"phash": perceptual_hash} 254 | ).fetchone() 255 | 256 | if result is None: 257 | self.execute( 258 | "INSERT INTO shape_perceptual_hashes ( phash ) VALUES ( :phash )", 259 | {"phash": perceptual_hash}, 260 | ) 261 | result = self.execute( 262 | "SELECT phash_id FROM shape_perceptual_hashes WHERE phash = :phash;", {"phash": perceptual_hash} 263 | ).fetchone() 264 | result = result[0] 265 | assert isinstance(result, int) 266 | else: 267 | result = result[0] 268 | # TODO: Double check that the return value here is actually there if the result is not None. 269 | # Remove the assert below if it is. 270 | assert isinstance(result, int) 271 | return result 272 | 273 | def add_to_phashed_files_queue(self, file_hash: str, perceptual_hash: bytes): 274 | """ 275 | Add a file and its corresponding perceptual hash to the queue to be inserted into the vptree. 276 | 277 | We keep the queue of files to be inserted in the vptree in a separate table to avoid any potential issues 278 | with assumptions of what needs to exist when/where for vptree operations. 279 | 280 | If the file hash is already in the queue, it will be replaced with the new perceptual hash. 281 | """ 282 | self.execute( 283 | "REPLACE INTO phashed_file_queue ( file_hash, phash ) VALUES ( :file_hash, :phash )", 284 | {"file_hash": file_hash, "phash": perceptual_hash}, 285 | ) 286 | 287 | def associate_file_with_perceptual_hash(self, file_hash: str, perceptual_hash: bytes): 288 | """ 289 | Associate a file with a perceptual hash in the database. 290 | This will insert the file into the VpTree. 291 | If the file already has a perceptual hash, it will be overwritten. 292 | 293 | Note: 294 | Perceptual hashes are not unique for each file. 295 | Files can have identical perceptual hashes. 296 | This is not even that rare, e.g. a video that is all the same color. 297 | """ 298 | hash_id = self.get_hash_id(file_hash) 299 | 300 | perceptual_hash_id = self.get_phash_id(perceptual_hash) 301 | assert perceptual_hash_id is not None 302 | 303 | tree = VpTreeManager(self) 304 | tree.add_leaf(perceptual_hash_id, perceptual_hash) 305 | 306 | already_exists = self.execute( 307 | "SELECT hash_id FROM shape_perceptual_hash_map WHERE hash_id = :hash_id", {"hash_id": hash_id} 308 | ).fetchone() 309 | 310 | if already_exists: 311 | self.execute("DELETE FROM shape_perceptual_hash_map WHERE hash_id = :hash_id", {"hash_id": hash_id}) 312 | 313 | res = self.execute( 314 | "INSERT INTO shape_perceptual_hash_map ( phash_id, hash_id ) VALUES ( :phash_id, :hash_id )", 315 | {"phash_id": perceptual_hash_id, "hash_id": hash_id}, 316 | ) 317 | 318 | # NOTE: We must fetchone here so that the rowcount is updated. 319 | res.fetchone() 320 | if res.rowcount > 0: 321 | self.execute( 322 | "REPLACE INTO shape_search_cache ( hash_id, searched_distance ) VALUES ( :hash_id, :searched_distance );", # noqa: E501 323 | {"hash_id": hash_id, "searched_distance": None}, 324 | ) 325 | 326 | def get_version(self) -> str: 327 | if self.does_table_exist("version"): 328 | (version,) = self.execute("SELECT version FROM version;").fetchone() 329 | else: 330 | # Old versions of the database did not have a version table. We will assume it's the most recent version 331 | # that had no version table. 332 | version = "0.6.0" 333 | return version 334 | 335 | def set_version(self, version: str): 336 | self.execute("UPDATE version SET version = :version", {"version": version}) 337 | 338 | def does_table_exist(self, table: str) -> bool: 339 | # pls no injection. named placeholders don't work for tables. 340 | res = self.execute(f"SELECT * FROM pragma_table_list WHERE name='{table}'") 341 | return bool(res.fetchall()) 342 | 343 | def get_phash_id(self, perceptual_hash: bytes) -> str | None: 344 | """Get the perceptual hash id from the phash, or None if not found.""" 345 | result = self.execute( 346 | "SELECT phash_id FROM shape_perceptual_hashes WHERE phash = :phash", {"phash": perceptual_hash} 347 | ).fetchone() 348 | perceptual_hash_id = None 349 | if result is not None: 350 | (perceptual_hash_id,) = result 351 | return perceptual_hash_id 352 | 353 | def get_phash_id_from_hash_id(self, hash_id: str) -> str | None: 354 | """Get the phash id from the hash_id, or None if not found.""" 355 | result = self.execute( 356 | "SELECT phash_id FROM shape_perceptual_hash_map WHERE hash_id = :hash_id", {"hash_id": hash_id} 357 | ).fetchone() 358 | perceptual_hash_id = None 359 | if result is not None: 360 | (perceptual_hash_id,) = result 361 | return perceptual_hash_id 362 | 363 | def get_hash_id(self, file_hash: str) -> str | None: 364 | """Get the hash id from the file hash, or None if not found.""" 365 | result = self.execute( 366 | "SELECT hash_id FROM files WHERE file_hash = :file_hash", {"file_hash": file_hash} 367 | ).fetchone() 368 | hash_id = None 369 | if result is not None: 370 | (hash_id,) = result 371 | return hash_id 372 | 373 | def get_phash(self, phash_id: str) -> bytes | None: 374 | """Get the perceptual hash from its phash_id, or None if not found.""" 375 | result = self.execute( 376 | "SELECT phash FROM shape_perceptual_hashes WHERE phash_id = :phash_id", {"phash_id": phash_id} 377 | ).fetchone() 378 | phash = None 379 | if result is not None: 380 | (phash,) = result 381 | return phash 382 | 383 | def get_file_hash(self, hash_id: str) -> str | None: 384 | """Get the file hash from its hash_id, or None if not found.""" 385 | result = self.execute("SELECT file_hash FROM files WHERE hash_id = :hash_id", {"hash_id": hash_id}).fetchone() 386 | file_hash = None 387 | if result is not None: 388 | (file_hash,) = result 389 | return file_hash 390 | 391 | def get_phashed_files(self) -> list[str]: 392 | """Get the file hashes of all files that are phashed. This includes the files in the phashed_file_queue.""" 393 | all_phashed_files_query = ( 394 | "SELECT file_hash FROM files " 395 | "WHERE hash_id IN (SELECT hash_id FROM shape_perceptual_hash_map) " 396 | "UNION " 397 | "SELECT file_hash FROM phashed_file_queue" 398 | ) 399 | all_phashed_files = self.execute(all_phashed_files_query) 400 | all_phashed_files = [row[0] for row in all_phashed_files] 401 | return all_phashed_files 402 | 403 | def get_num_phashed_files(self) -> int: 404 | """Get total number of all files that are phashed. This includes the files in the phashed_file_queue.""" 405 | query = """ 406 | SELECT COUNT(*) FROM ( 407 | SELECT file_hash FROM files 408 | WHERE hash_id IN (SELECT hash_id FROM shape_perceptual_hash_map) 409 | UNION 410 | SELECT file_hash FROM phashed_file_queue 411 | ) 412 | """ 413 | cursor = self.execute(query) 414 | row = cursor.fetchone() 415 | return row[0] if row else 0 416 | 417 | """ 418 | Misc 419 | """ 420 | 421 | def does_need_upgrade(self) -> bool: 422 | db_version = SemanticVersion(self.get_version()) 423 | dedupe_version = SemanticVersion(__version__) 424 | return db_version < dedupe_version 425 | 426 | def vacuum(self): 427 | """ 428 | Vacuum the db. 429 | 430 | Note: Can't vacuum within a transaction. 431 | """ 432 | self.execute("VACUUM") 433 | 434 | def upgrade_db(self) -> bool: 435 | """ 436 | Upgrade the db. 437 | 438 | Returns true if the DB needed to be upgraded and was upgraded. 439 | """ 440 | 441 | # WARNING: 442 | # If any functions change then upgrades may not work! We need to be careful about updating them and what we call. # noqa: E501 443 | # An upgrade cutoff at some point to prevent bitrot is a good idea, which is what Hydrus does. 444 | 445 | def print_upgrade(version: str, new_version: str): 446 | print(f"Upgrading db from {version} to version {new_version}") 447 | 448 | version = self.get_version() 449 | if SemanticVersion(__version__) < SemanticVersion(version): 450 | raise DedupeDbException( 451 | f""" 452 | Database version {version} is newer than the installed hydrusvideodeduplicator version {__version__}.\ 453 | \nPlease upgrade and try again. \ 454 | \nSee documentation for how to upgrade: https://github.com/hydrusvideodeduplicator/hydrus-video-deduplicator/blob/main/docs/faq.md#how-to-update 455 | """ 456 | ) 457 | 458 | if not self.does_need_upgrade(): 459 | return False 460 | 461 | if SemanticVersion(version) < SemanticVersion("0.7.0"): 462 | print_upgrade(version, "0.7.0") 463 | 464 | # Create version table 465 | self.execute("CREATE TABLE IF NOT EXISTS version (version TEXT)") 466 | self.execute("INSERT INTO version (version) VALUES (:version)", {"version": "0.6.0"}) 467 | 468 | # Create the vptree tables 469 | self.execute( 470 | "CREATE TABLE IF NOT EXISTS files ( hash_id INTEGER PRIMARY KEY, file_hash BLOB_BYTES UNIQUE )" 471 | ) 472 | self.execute( 473 | "CREATE TABLE IF NOT EXISTS shape_perceptual_hashes ( phash_id INTEGER PRIMARY KEY, phash BLOB_BYTES UNIQUE )" # noqa: E501 474 | ) 475 | self.execute( 476 | "CREATE TABLE IF NOT EXISTS shape_perceptual_hash_map ( phash_id INTEGER, hash_id INTEGER, PRIMARY KEY ( phash_id, hash_id ) )" # noqa: E501 477 | ) 478 | self.execute( 479 | "CREATE TABLE IF NOT EXISTS shape_vptree ( phash_id INTEGER PRIMARY KEY, parent_id INTEGER, radius INTEGER, inner_id INTEGER, inner_population INTEGER, outer_id INTEGER, outer_population INTEGER )" # noqa: E501 480 | ) 481 | # fmt: off 482 | self.execute( 483 | "CREATE TABLE IF NOT EXISTS shape_maintenance_branch_regen ( phash_id INTEGER PRIMARY KEY )" 484 | ) # noqa: E501 485 | # fmt: on 486 | self.execute( 487 | "CREATE TABLE IF NOT EXISTS shape_search_cache ( hash_id INTEGER PRIMARY KEY, searched_distance INTEGER )" # noqa: E501 488 | ) 489 | 490 | self.execute( 491 | "CREATE TABLE IF NOT EXISTS phashed_file_queue ( file_hash BLOB_BYTES NOT NULL UNIQUE, phash BLOB_BYTES NOT NULL, PRIMARY KEY ( file_hash, phash ) )" # noqa: E501 492 | ) 493 | 494 | # Insert the files from the SqliteDict videos table into the hash queue. 495 | old_videos_data = [] 496 | print( 497 | "Migrating perceptually hashed videos from the old table.\n" 498 | "This may take a bit, depending your db length." 499 | ) 500 | 501 | from pickle import loads 502 | 503 | for key, value in self.execute("SELECT key, value FROM videos"): 504 | # I don't see why value could be None, but if it happens for whatever reason 505 | # we just want to continue. 506 | if value is None: 507 | continue 508 | row = loads(bytes(value)) # this is decode function in SqliteDict 509 | if "perceptual_hash" in row: 510 | video_hash = key 511 | old_videos_data.append((video_hash, row["perceptual_hash"])) 512 | # The farthest search index will not be moved. 513 | 514 | for video_hash, perceptual_hash in old_videos_data: 515 | # Add to phashed file queue 516 | self.execute( 517 | "REPLACE INTO phashed_file_queue ( file_hash, phash ) VALUES ( :file_hash, :phash )", 518 | {"file_hash": video_hash, "phash": str(perceptual_hash)}, 519 | ) 520 | 521 | self.execute("UPDATE version SET version = :version", {"version": "0.7.0"}) 522 | # Note: We need to keep re-running get_version so that we can progressively upgrade. 523 | version = self.get_version() 524 | 525 | if SemanticVersion(version) < SemanticVersion("0.10.0"): 526 | print_upgrade(version, "0.10.0") 527 | 528 | print( 529 | "Migrating perceptually hashed videos from the old format.\n" 530 | "This may take a bit, depending your db length." 531 | ) 532 | 533 | import json 534 | 535 | def convert_old_vpdq_to_new(old_vpdq_phash_json: str) -> bytes: 536 | """Convert <0.9.0 full vpdq hash (json) to 0.10.0 hash""" 537 | 538 | # The old vpdq converted the hashes in reverse order. This has no effect on the similarity 539 | # or anything, but it complicates code in the vpdq implementation, so I changed the order 540 | # to the native byte order of the PDQ hash. 541 | def reverse_byte_order(s: str): 542 | bytes_obj = bytes.fromhex(s) 543 | reversed_bytes = bytes_obj[::-1] 544 | return reversed_bytes.hex() 545 | 546 | j = json.loads(old_vpdq_phash_json) 547 | new_vpdq_hash_str = "" 548 | for vpdq_feature in j: 549 | phash, feature_quality, frame_num = vpdq_feature.split(",") 550 | # Filtering hash quality is done during hashing starting in 0.10.0 instead of during similarity 551 | # comparison because there's no reason to store hashes which will never be used. 552 | if int(feature_quality) >= 31: 553 | new_vpdq_hash_str += reverse_byte_order(phash) 554 | 555 | # In the uncommon scenario that all hashes have all been filtered out due to bad quality, then videos 556 | # will compare as not similar to any other video (including itself, naturally). This matches the same 557 | # behavior as the old algorithm where low quality hashes were filtered before similarity was calculated. 558 | 559 | return bytes.fromhex(new_vpdq_hash_str) 560 | 561 | # Update phashes in phashed_file_queue 562 | for phash_id, phash in self.execute("SELECT phash_id, phash FROM shape_perceptual_hashes").fetchall(): 563 | self.execute( 564 | "REPLACE INTO shape_perceptual_hashes ( phash_id, phash ) VALUES ( :phash_id, :phash )", 565 | {"phash_id": phash_id, "phash": convert_old_vpdq_to_new(phash)}, 566 | ) 567 | 568 | # Update phashes in shape_perceptual_hashes 569 | for file_hash, phash in self.execute("SELECT file_hash, phash FROM phashed_file_queue").fetchall(): 570 | self.execute( 571 | "REPLACE INTO phashed_file_queue ( file_hash, phash ) VALUES ( :file_hash, :phash )", 572 | {"file_hash": file_hash, "phash": convert_old_vpdq_to_new(phash)}, 573 | ) 574 | 575 | self.execute("UPDATE version SET version = :version", {"version": "0.10.0"}) 576 | # Note: We need to keep re-running get_version so that we can progressively upgrade. 577 | version = self.get_version() 578 | 579 | # No db changes in this case, just print a nice message that your DB is upgraded. 580 | if SemanticVersion(version) < SemanticVersion(__version__): 581 | print_upgrade(version, __version__) 582 | 583 | self.set_version(__version__) 584 | return True 585 | 586 | 587 | class SemanticVersion: 588 | """Simple semantic version class. Supports MAJOR.MINOR.PATCH, e.g. 1.2.3""" 589 | 590 | def __init__(self, version: str): 591 | self.version = version 592 | try: 593 | self.parts = list(map(int, version.split("."))) 594 | if len(self.parts) != 3: 595 | raise DedupeDbException("len != 3") 596 | except Exception as exc: 597 | raise DedupeDbException(f"Bad semantic version: {self.version}.\nFull exception: {exc}") 598 | 599 | def __eq__(self, other): 600 | return self.parts == other.parts 601 | 602 | def __lt__(self, other): 603 | return self.parts < other.parts 604 | 605 | def __le__(self, other): 606 | return self.parts <= other.parts 607 | 608 | def __gt__(self, other): 609 | return self.parts > other.parts 610 | 611 | def __ge__(self, other): 612 | return self.parts >= other.parts 613 | 614 | def __repr__(self): 615 | return f"SemanticVersion('{self.version}')" 616 | -------------------------------------------------------------------------------- /src/hydrusvideodeduplicator/hydrus_api/LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . --------------------------------------------------------------------------------