├── .dockerignore ├── .github ├── dependabot.yml └── workflows │ ├── pre-commit.yaml │ ├── publish_image.yaml │ ├── semgrep.yaml │ └── unittests.yaml ├── .gitignore ├── .gitmodules ├── .pre-commit-config.yaml ├── .semgrepignore ├── Dockerfile ├── LICENSE ├── README.md ├── docker-compose.yml ├── media └── coverage_badge.svg ├── pyproject.toml ├── requirements-dev.txt ├── requirements.txt ├── tests └── test_conversion.py └── tools ├── .DS_Store ├── main.py ├── modules ├── __init__.py ├── backbones.py ├── exporter.py ├── heads.py └── stage2.py ├── utils ├── __init__.py ├── config.py ├── constants.py ├── filesystem_utils.py ├── in_channels.py └── version_detection.py ├── yolo ├── .DS_Store ├── __init__.py ├── yolov10_exporter.py ├── yolov5_exporter.py ├── yolov6_exporter.py └── yolov8_exporter.py ├── yolov6r1 ├── .DS_Store └── yolov6_r1_exporter.py ├── yolov6r3 ├── .DS_Store ├── gold_yolo_exporter.py └── yolov6_r3_exporter.py └── yolov7 └── yolov7_exporter.py /.dockerignore: -------------------------------------------------------------------------------- 1 | venv 2 | yolo/YoloV5_export_playground.ipynb 3 | tmp 4 | export 5 | client/node_modules 6 | client/build 7 | *.pt 8 | docker-compose.yml 9 | Dockerfile 10 | .gitignore 11 | .dockerignore 12 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "pip" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | target-branch: "main" 8 | # Labels on pull requests for version updates only 9 | labels: 10 | - "pip dependencies" -------------------------------------------------------------------------------- /.github/workflows/pre-commit.yaml: -------------------------------------------------------------------------------- 1 | name: pre-commit 2 | 3 | on: 4 | pull_request: 5 | branches: [main] 6 | 7 | jobs: 8 | pre-commit: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v3 12 | - uses: actions/setup-python@v3 13 | with: 14 | python-version: '3.8' 15 | - uses: pre-commit/action@v3.0.0 -------------------------------------------------------------------------------- /.github/workflows/publish_image.yaml: -------------------------------------------------------------------------------- 1 | name: Publishing a docker image 2 | 3 | on: 4 | push: 5 | branches: ['main'] 6 | 7 | env: 8 | NAME: luxonis/tools_cli 9 | 10 | jobs: 11 | ghcr-publish: 12 | runs-on: ubuntu-latest 13 | 14 | permissions: 15 | contents: read 16 | packages: write 17 | 18 | steps: 19 | - name: Checkout code 20 | uses: actions/checkout@v4 21 | 22 | - name: Get tools-cli version 23 | id: commit 24 | run: echo "sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT 25 | 26 | - name: Docker login to GHCR 27 | uses: docker/login-action@v3 28 | with: 29 | registry: ghcr.io 30 | username: ${{ github.actor }} 31 | password: ${{ secrets.GITHUB_TOKEN }} 32 | 33 | - name: Publish latest 34 | run: | 35 | git submodule update --init --recursive 36 | docker build -t $NAME:latest . 37 | docker tag $NAME:latest ghcr.io/$NAME:latest 38 | docker push ghcr.io/$NAME:latest 39 | 40 | - name: Publish tagged 41 | run: | 42 | VERSION=${{ steps.commit.outputs.sha }} 43 | docker tag $NAME:latest ghcr.io/$NAME:$VERSION 44 | docker push ghcr.io/$NAME:$VERSION 45 | -------------------------------------------------------------------------------- /.github/workflows/semgrep.yaml: -------------------------------------------------------------------------------- 1 | name: Semgrep SAST Scan 2 | 3 | on: 4 | pull_request: 5 | 6 | jobs: 7 | semgrep: 8 | # User definable name of this GitHub Actions job. 9 | name: semgrep/ci 10 | # If you are self-hosting, change the following `runs-on` value: 11 | runs-on: ubuntu-latest 12 | container: 13 | # A Docker image with Semgrep installed. Do not change this. 14 | image: returntocorp/semgrep 15 | # Skip any PR created by dependabot to avoid permission issues: 16 | if: (github.actor != 'dependabot[bot]') 17 | permissions: 18 | # required for all workflows 19 | security-events: write 20 | # only required for workflows in private repositories 21 | actions: read 22 | contents: read 23 | 24 | steps: 25 | # Fetch project source with GitHub Actions Checkout. 26 | - name: Checkout repository 27 | uses: actions/checkout@v4 28 | 29 | - name: Perform Semgrep Analysis 30 | # @NOTE: This is the actual semgrep command to scan your code. 31 | # Modify the --config option to 'r/all' to scan using all rules, 32 | # or use multiple flags to specify particular rules, such as 33 | # --config r/all --config custom/rules 34 | run: semgrep scan -q --sarif --config auto --config "p/secrets" . > semgrep-results.sarif 35 | 36 | - name: Pretty-Print SARIF Output 37 | run: | 38 | jq . semgrep-results.sarif > formatted-semgrep-results.sarif || echo "{}" 39 | echo "Formatted SARIF Output (First 20 lines):" 40 | head -n 20 formatted-semgrep-results.sarif || echo "{}" 41 | 42 | - name: Validate JSON Output 43 | run: | 44 | if ! jq empty formatted-semgrep-results.sarif > /dev/null 2>&1; then 45 | echo "⚠️ Semgrep output is not valid JSON. Skipping annotations." 46 | exit 0 47 | fi 48 | 49 | - name: Add PR Annotations for Semgrep Findings 50 | run: | 51 | total_issues=$(jq '.runs[0].results | length' formatted-semgrep-results.sarif) 52 | if [[ "$total_issues" -eq 0 ]]; then 53 | echo "✅ No Semgrep issues found!" 54 | exit 0 55 | fi 56 | 57 | jq -c '.runs[0].results[]' formatted-semgrep-results.sarif | while IFS= read -r issue; do 58 | file=$(echo "$issue" | jq -r '.locations[0].physicalLocation.artifactLocation.uri') 59 | line=$(echo "$issue" | jq -r '.locations[0].physicalLocation.region.startLine') 60 | message=$(echo "$issue" | jq -r '.message.text') 61 | 62 | if [[ -n "$file" && -n "$line" && -n "$message" ]]; then 63 | echo "::error file=$file,line=$line,title=Semgrep Issue::${message}" 64 | fi 65 | done -------------------------------------------------------------------------------- /.github/workflows/unittests.yaml: -------------------------------------------------------------------------------- 1 | name: Unit Tests 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | paths: 8 | - 'tests/**' 9 | - 'tools/**' 10 | - '.github/workflows/unittests.yaml' 11 | 12 | workflow_call: 13 | inputs: 14 | ml_ref: 15 | description: 'luxonis-ml version (branch/tag/SHA)' 16 | required: true 17 | type: string 18 | tools_ref: 19 | description: 'tools version (branch/tag/SHA)' 20 | required: true 21 | type: string 22 | 23 | jobs: 24 | run_tests: 25 | strategy: 26 | fail-fast: false 27 | matrix: 28 | os: [ubuntu-latest, windows-latest, macOS-latest] 29 | version: ['3.10', '3.11'] 30 | 31 | runs-on: ${{ matrix.os }} 32 | 33 | steps: 34 | - name: Checkout at tools_ref 35 | if: ${{ inputs.tools_ref != '' }} 36 | uses: actions/checkout@v4 37 | with: 38 | repository: Luxonis/tools 39 | ref: ${{ inputs.tools_ref }} 40 | path: tools 41 | submodules: recursive # Ensures submodules are cloned 42 | 43 | - name: Checkout 44 | if: ${{ inputs.tools_ref == '' && inputs.ml_ref == '' }} 45 | uses: actions/checkout@v4 46 | with: 47 | ref: ${{ github.head_ref }} 48 | submodules: recursive # Ensures submodules are cloned 49 | 50 | - name: Set up Python 51 | uses: actions/setup-python@v5 52 | with: 53 | python-version: ${{ matrix.version }} 54 | cache: pip 55 | 56 | - name: Install dependencies 57 | working-directory: ${{ inputs.tools_ref != '' && 'tools' || '' }} 58 | run: | 59 | pip install -e .[dev] 60 | pip install coverage-badge>=1.1.0 pytest-cov>=4.1.0 61 | 62 | - name: Install specified luxonis-ml 63 | shell: bash 64 | if: inputs.ml_ref != '' 65 | working-directory: tools 66 | env: 67 | ML_REF: ${{ inputs.ml_ref }} 68 | run: | 69 | pip uninstall luxonis-ml -y 70 | pip install \ 71 | "luxonis-ml[data,nn_archive,utils] @ git+https://github.com/luxonis/luxonis-ml.git@${ML_REF}" \ 72 | --upgrade --force-reinstall 73 | 74 | - name: Run tests with coverage [Ubuntu] 75 | if: matrix.os == 'ubuntu-latest' && matrix.version == '3.10' 76 | working-directory: ${{ inputs.tools_ref != '' && 'tools' || '' }} 77 | run: pytest tests --cov=tools --cov-report xml --junit-xml pytest.xml 78 | 79 | - name: Run tests [Windows, macOS] 80 | if: matrix.os != 'ubuntu-latest' || matrix.version != '3.10' 81 | working-directory: ${{ inputs.tools_ref != '' && 'tools' || '' }} 82 | run: pytest tests --junit-xml pytest.xml 83 | 84 | - name: Generate coverage badge [Ubuntu] 85 | if: matrix.os == 'ubuntu-latest' && matrix.version == '3.10' && inputs.tools_ref == '' && inputs.ml_ref == '' 86 | run: coverage-badge -o media/coverage_badge.svg -f 87 | 88 | - name: Generate coverage report [Ubuntu] 89 | if: matrix.os == 'ubuntu-latest' && matrix.version == '3.10' && inputs.tools_ref == '' && inputs.ml_ref == '' 90 | uses: orgoro/coverage@v3.1 91 | with: 92 | coverageFile: coverage.xml 93 | token: ${{ secrets.GITHUB_TOKEN }} 94 | 95 | - name: Commit coverage badge [Ubuntu] 96 | if: matrix.os == 'ubuntu-latest' && matrix.version == '3.10' && inputs.tools_ref == '' && inputs.ml_ref == '' 97 | run: | 98 | git config --global user.name 'GitHub Actions' 99 | git config --global user.email 'actions@github.com' 100 | git diff --quiet media/coverage_badge.svg || { 101 | git add media/coverage_badge.svg 102 | git commit -m "[Automated] Updated coverage badge" 103 | } 104 | - name: Push changes [Ubuntu] 105 | if: matrix.os == 'ubuntu-latest' && matrix.version == '3.10' && inputs.tools_ref == '' && inputs.ml_ref == '' 106 | uses: ad-m/github-push-action@master 107 | with: 108 | branch: ${{ github.head_ref }} 109 | 110 | - name: Upload Test Results 111 | if: always() && inputs.tools_ref == '' && inputs.ml_ref == '' 112 | uses: actions/upload-artifact@v4 113 | with: 114 | name: Test Results [${{ matrix.os }}] (Python ${{ matrix.version }}) 115 | path: pytest.xml 116 | retention-days: 10 117 | if-no-files-found: error 118 | 119 | publish-test-results: 120 | name: "Publish Tests Results" 121 | needs: run_tests 122 | runs-on: ubuntu-latest 123 | permissions: 124 | checks: write 125 | pull-requests: write 126 | if: always() && inputs.tools_ref == '' && inputs.ml_ref == '' 127 | 128 | steps: 129 | - name: Checkout 130 | uses: actions/checkout@v4 131 | with: 132 | ref: ${{ github.head_ref }} 133 | 134 | - name: Download Artifacts 135 | uses: actions/download-artifact@v4 136 | with: 137 | path: artifacts 138 | 139 | - name: Publish Test Results 140 | uses: EnricoMi/publish-unit-test-result-action@v2 141 | with: 142 | files: "artifacts/**/*.xml" -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/jupyternotebooks,python,visualstudiocode 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=jupyternotebooks,python,visualstudiocode 4 | 5 | ### JupyterNotebooks ### 6 | # gitignore template for Jupyter Notebooks 7 | # website: http://jupyter.org/ 8 | 9 | .ipynb_checkpoints 10 | */.ipynb_checkpoints/* 11 | 12 | # IPython 13 | profile_default/ 14 | ipython_config.py 15 | 16 | tools/.DS_Store 17 | 18 | # Remove previous ipynb_checkpoints 19 | # git rm -r .ipynb_checkpoints/ 20 | 21 | ### Python ### 22 | # Byte-compiled / optimized / DLL files 23 | __pycache__/ 24 | *.py[cod] 25 | *$py.class 26 | 27 | # C extensions 28 | *.so 29 | 30 | # Distribution / packaging 31 | .Python 32 | build/ 33 | develop-eggs/ 34 | dist/ 35 | downloads/ 36 | eggs/ 37 | .eggs/ 38 | lib/ 39 | lib64/ 40 | parts/ 41 | sdist/ 42 | var/ 43 | wheels/ 44 | share/python-wheels/ 45 | *.egg-info/ 46 | .installed.cfg 47 | *.egg 48 | MANIFEST 49 | 50 | # PyInstaller 51 | # Usually these files are written by a python script from a template 52 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 53 | *.manifest 54 | *.spec 55 | 56 | # Installer logs 57 | pip-log.txt 58 | pip-delete-this-directory.txt 59 | 60 | # Unit test / coverage reports 61 | htmlcov/ 62 | .tox/ 63 | .nox/ 64 | .coverage 65 | .coverage.* 66 | .cache 67 | nosetests.xml 68 | coverage.xml 69 | *.cover 70 | *.py,cover 71 | .hypothesis/ 72 | .pytest_cache/ 73 | cover/ 74 | 75 | # Translations 76 | *.mo 77 | *.pot 78 | 79 | # Django stuff: 80 | *.log 81 | local_settings.py 82 | db.sqlite3 83 | db.sqlite3-journal 84 | 85 | # Flask stuff: 86 | instance/ 87 | .webassets-cache 88 | 89 | # Scrapy stuff: 90 | .scrapy 91 | 92 | # Sphinx documentation 93 | docs/_build/ 94 | 95 | # PyBuilder 96 | .pybuilder/ 97 | target/ 98 | 99 | # Jupyter Notebook 100 | 101 | # IPython 102 | 103 | # pyenv 104 | # For a library or package, you might want to ignore these files since the code is 105 | # intended to run in multiple environments; otherwise, check them in: 106 | # .python-version 107 | 108 | # pipenv 109 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 110 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 111 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 112 | # install all needed dependencies. 113 | #Pipfile.lock 114 | 115 | # poetry 116 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 117 | # This is especially recommended for binary packages to ensure reproducibility, and is more 118 | # commonly ignored for libraries. 119 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 120 | #poetry.lock 121 | 122 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 123 | __pypackages__/ 124 | 125 | # Celery stuff 126 | celerybeat-schedule 127 | celerybeat.pid 128 | 129 | # SageMath parsed files 130 | *.sage.py 131 | 132 | # Environments 133 | .env 134 | .venv 135 | env/ 136 | venv/ 137 | ENV/ 138 | env.bak/ 139 | venv.bak/ 140 | 141 | # Spyder project settings 142 | .spyderproject 143 | .spyproject 144 | 145 | # Rope project settings 146 | .ropeproject 147 | 148 | # mkdocs documentation 149 | /site 150 | 151 | # mypy 152 | .mypy_cache/ 153 | .dmypy.json 154 | dmypy.json 155 | 156 | # Pyre type checker 157 | .pyre/ 158 | 159 | # pytype static type analyzer 160 | .pytype/ 161 | 162 | # Cython debug symbols 163 | cython_debug/ 164 | 165 | # PyCharm 166 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 167 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 168 | # and can be added to the global gitignore or merged into this file. For a more nuclear 169 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 170 | #.idea/ 171 | 172 | ### VisualStudioCode ### 173 | .vscode/* 174 | !.vscode/settings.json 175 | !.vscode/tasks.json 176 | !.vscode/launch.json 177 | !.vscode/extensions.json 178 | !.vscode/*.code-snippets 179 | 180 | # Local History for Visual Studio Code 181 | .history/ 182 | 183 | # Built Visual Studio Code Extensions 184 | *.vsix 185 | 186 | ### VisualStudioCode Patch ### 187 | # Ignore all local history of files 188 | .history 189 | .ionide 190 | 191 | # Support for Project snippet scope 192 | 193 | # End of https://www.toptal.com/developers/gitignore/api/jupyternotebooks,python,visualstudiocode 194 | tmp/ 195 | export/ 196 | 197 | tests/weights/* -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "yolov5"] 2 | path = tools/yolo/yolov5 3 | url = https://github.com/ultralytics/yolov5 4 | [submodule "YOLOv6"] 5 | path = tools/yolo/YOLOv6 6 | url = https://github.com/meituan/YOLOv6 7 | branch = main 8 | [submodule "yolov7"] 9 | path = tools/yolov7/yolov7 10 | url = https://github.com/WongKinYiu/yolov7.git 11 | branch = main 12 | [submodule "tools/yolo/ultralytics"] 13 | path = tools/yolo/ultralytics 14 | url = https://github.com/ultralytics/ultralytics 15 | [submodule "YOLOv6R1"] 16 | path = tools/yolov6r1/YOLOv6R1 17 | url = https://github.com/meituan/YOLOv6 18 | branch = main 19 | [submodule "GoldYolo"] 20 | path = tools/yolov6r3/Efficient-Computing 21 | url = https://github.com/huawei-noah/Efficient-Computing 22 | [submodule "ultralytics"] 23 | path = tools/yolo/ultralytics 24 | url = https://github.com/ultralytics/ultralytics 25 | [submodule "YOLOv6R3"] 26 | path = tools/yolov6r3/YOLOv6R3 27 | url = https://github.com/meituan/YOLOv6 28 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/astral-sh/ruff-pre-commit 3 | rev: v0.1.2 4 | hooks: 5 | - id: ruff 6 | args: [--fix, --exit-non-zero-on-fix] 7 | types_or: [python, pyi] 8 | 9 | - repo: https://github.com/ambv/black 10 | rev: 23.3.0 11 | hooks: 12 | - id: black 13 | language_version: python3.8 14 | exclude: 'tools/yolov7/yolov7/' 15 | 16 | - repo: https://github.com/pre-commit/pre-commit-hooks 17 | rev: v4.4.0 18 | hooks: 19 | - id: no-commit-to-branch 20 | args: ['--branch', 'main'] 21 | 22 | - repo: https://github.com/executablebooks/mdformat 23 | rev: 0.7.10 24 | hooks: 25 | - id: mdformat 26 | additional_dependencies: 27 | - mdformat-gfm 28 | - mdformat-toc 29 | exclude: '.github/' -------------------------------------------------------------------------------- /.semgrepignore: -------------------------------------------------------------------------------- 1 | tools/yolov7/yolov7 -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.11-bullseye 2 | 3 | ## Set working directory 4 | WORKDIR /app 5 | 6 | ## Install dependencies (including required libraries) 7 | RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 build-essential cmake git -y 8 | 9 | ## Add necessary files and set permissions 10 | ADD tools /app/tools 11 | ADD pyproject.toml /app 12 | ADD requirements.txt /app 13 | 14 | ## Create non-root user and set ownership of the working directory 15 | RUN adduser --disabled-password --gecos "" --no-create-home non-root && \ 16 | chown -R non-root:non-root /app 17 | 18 | ## Install Python dependencies 19 | RUN pip install . 20 | 21 | ## Switch to non-root user 22 | USER non-root 23 | 24 | ## Set PATH for the installed executable 25 | ENV PATH="/home/non-root/.local/bin:/usr/local/bin:$PATH" 26 | 27 | ## Define image execution 28 | ENTRYPOINT ["tools"] 29 | -------------------------------------------------------------------------------- /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 637 | by 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 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tools-CLI 2 | 3 | > \[!NOTE\]\ 4 | > This is the latest version of tools CLI. If you are looking for the tools web application, please refer to the [web-app](https://github.com/luxonis/tools/tree/web-app) branch. 5 | 6 | This is a command-line tool that simplifies the conversion process of YOLO models. It supports the conversion of YOLOs ranging from V5 through V11 and Gold Yolo including oriented bounding boxes object detection (OBB), pose estimation, and instance segmentation variants of YOLOv8 and YOLO11 to ONNX format and archiving them in the NN Archive format. 7 | 8 | > \[!WARNING\]\ 9 | > Please note that for the moment, we support conversion of YOLOv9 weights only from [Ultralytics](https://docs.ultralytics.com/models/yolov9/#performance-on-ms-coco-dataset). 10 | 11 | ## 📜 Table of contents 12 | 13 | - [💻 How to run](#run) 14 | - [⚙️ Arguments](#arguments) 15 | - [🧰 Supported Models](#supported-models) 16 | - [📝 Credits](#credits) 17 | - [📄 License](#license) 18 | - [🤝 Contributing](#contributing) 19 | 20 | 21 | 22 | ## 💻 How to run 23 | 24 | You can either export a model stored on the cloud (e.g. S3) or locally. You can choose to install the toolkit through pip or using Docker. In the sections below, we'll describe both options. 25 | 26 | ### Prerequisites 27 | 28 | ```bash 29 | # Cloning the tools repository and all submodules 30 | git clone --recursive https://github.com/luxonis/tools.git 31 | # Change folder 32 | cd tools 33 | ``` 34 | 35 | ### Using Python package 36 | 37 | ```bash 38 | # Install the package 39 | pip install . 40 | # Running the package 41 | tools yolov6nr4.pt --imgsz "416" 42 | ``` 43 | 44 | ### Using Docker or Docker Compose 45 | 46 | This option requires you to have Docker installed on your device. Additionally, to export a local model, please put it inside a `shared-component/models/` folder in the root folder of the project. 47 | 48 | #### Using Docker 49 | 50 | ```bash 51 | # Building Docker image 52 | docker build -t tools_cli . 53 | # Running the image 54 | docker run -v "${PWD}/shared_with_container:/app/shared_with_container" tools_cli shared_with_container/models/yolov8n-seg.pt --imgsz "416" 55 | ``` 56 | 57 | #### Using Docker compose 58 | 59 | ```bash 60 | # Building Docker image 61 | docker compose build 62 | # Running the image 63 | docker compose run tools_cli shared_with_container/models/yolov6nr4.pt 64 | ``` 65 | 66 | The output files are going to be in `shared-component/output` folder. 67 | 68 | 69 | 70 | ## ⚙️ Arguments 71 | 72 | - `model: str` = Path to the model. 73 | - `imgsz: str` = Image input shape in the format `width height` or `width`. Default value `"416 416"`. 74 | - `version: Optional[str]` = Version of the YOLO model. Default value `None`. If not specified, the version will be detected automatically. Supported versions: `yolov5`, `yolov6r1`, `yolov6r3`, `yolov6r4`, `yolov7`, `yolov8`, `yolov9`, `yolov10`, `yolov11`, `goldyolo`. 75 | - `use_rvc2: bool` = Whether to export for RVC2 or RVC3 devices. Default value `True`. 76 | - `class_names: Optional[str]` = Optional list of classes separated by a comma, e.g. `"person, dog, cat"` 77 | - `output_remote_url: Optional[str]` = Remote output url for the output .onnx model. 78 | - `config_path: Optional[str]` = Optional path to an optional config. 79 | - `put_file_plugin: Optional[str]` = Which plugin to use. Optional. 80 | 81 | 82 | 83 | ## 🧰 Supported models 84 | 85 | Currently, the following models are supported: 86 | 87 | | Model Version | Supported versions | 88 | | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 89 | | `yolov5` | YOLOv5n, YOLOv5s, YOLOv5m, YOLOv5l, YOLOv5x, YOLOv5n6, YOLOv5s6, YOLOv5m6, YOLOv5l6 | 90 | | `yolov6r1` | **v1.0 release:** YOLOv6n, YOLOv6t, YOLOv6s | 91 | | `yolov6r3` | **v2.0 release:** YOLOv6n, YOLOv6t, YOLOv6s, YOLOv6m, YOLOv6l
**v2.1 release:** YOLOv6n, YOLOv6s, YOLOv6m, YOLOv6l
**v3.0 release:** YOLOv6n, YOLOv6s, YOLOv6m, YOLOv6l | 92 | | `yolov6r4` | **v4.0 release:** YOLOv6n, YOLOv6s, YOLOv6m, YOLOv6l | 93 | | `yolov7` | YOLOv7-tiny, YOLOv7, YOLOv7x | 94 | | `yolov8` | **Detection:** YOLOv8n, YOLOv8s, YOLOv8m, YOLOv8l, YOLOv8x, YOLOv3-tinyu, YOLOv5nu, YOLOv5n6u, YOLOv5s6u, YOLOv5su, YOLOv5m6u, YOLOv5mu, YOLOv5l6u, YOLOv5lu
**Instance Segmentation, Pose, Oriented Detection, Classification:** YOLOv8n, YOLOv8s, YOLOv8m, YOLOv8l, YOLOv8x | 95 | | `yolov9` | YOLOv9t, YOLOv9s, YOLOv9m, YOLOv9c | 96 | | `yolov10` | YOLOv10n, YOLOv10s, YOLOv10m, YOLOv10b, YOLOv10l, YOLOv10x | 97 | | `yolov11` | **Detection, Instance Segmentation, Pose, Oriented Detection, Classification:** YOLO11n, YOLO11s, YOLO11m, YOLO11l, YOLO11x | 98 | | `goldyolo` | Gold-YOLO-N, Gold-YOLO-S, Gold-YOLO-M, Gold-YOLO-L | 99 | 100 | If you don't find your model in the list, it is possible that it can be converted, however, this is not guaranteed. 101 | 102 | 103 | 104 | ## 📝 Credits 105 | 106 | This application uses source code of the following repositories: [YOLOv5](https://github.com/ultralytics/yolov5), [YOLOv6](https://github.com/meituan/YOLOv6), [GoldYOLO](https://github.com/huawei-noah/Efficient-Computing) [YOLOv7](https://github.com/WongKinYiu/yolov7), and [Ultralytics](https://github.com/ultralytics/ultralytics) (see each of them for more information). 107 | 108 | 109 | 110 | ## 📄 License 111 | 112 | This application is available under **AGPL-3.0 License** license (see [LICENSE](https://github.com/luxonis/tools/blob/master/LICENSE) file for details). 113 | 114 | 115 | 116 | ## 🤝 Contributing 117 | 118 | We welcome contributions! Whether it's reporting bugs, adding features or improving documentation, your help is much appreciated. Please create a pull request ([here](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request)'s how to do it) and assign anyone from the Luxonis team to review the suggested changes. Cheers! 119 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '1' 2 | 3 | services: 4 | tools-cli: 5 | build: . 6 | environment: 7 | AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY} 8 | AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID} 9 | AWS_S3_ENDPOINT_URL: ${AWS_S3_ENDPOINT_URL} 10 | GOOGLE_APPLICATION_CREDENTIALS: /run/secrets/gcp-credentials 11 | MONGO_URI: ${MONGO_URI} 12 | AWS_BUCKET: ${AWS_BUCKET} 13 | MLFLOW_S3_BUCKET: luxonis-mlflow 14 | MLFLOW_S3_ENDPOINT_URL: ${AWS_S3_ENDPOINT_URL} 15 | volumes: 16 | - ${PWD}/shared_with_container:/app/shared_with_container 17 | 18 | -------------------------------------------------------------------------------- /media/coverage_badge.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | coverage 17 | coverage 18 | 22% 19 | 22% 20 | 21 | 22 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "tools" 3 | version = "0.2.5" 4 | description = "Converter for YOLO models into .ONNX format." 5 | readme = "README.md" 6 | requires-python = ">=3.8" 7 | authors = [{ name = "Luxonis", email = "support@luxonis.com" }] 8 | maintainers = [{ name = "Luxonis", email = "support@luxonis.com" }] 9 | keywords = ["ml", "onnx", "YOLO", "computer vision", "object detection", "instance segmentation", "keypoint detection", "OBB"] 10 | dynamic = ["dependencies", "optional-dependencies"] 11 | classifiers = [ 12 | "Development Status :: 3 - Alpha", 13 | "Programming Language :: Python :: 3.8", 14 | "Topic :: Scientific/Engineering :: Artificial Intelligence", 15 | "Topic :: Scientific/Engineering :: Image Processing", 16 | "Topic :: Scientific/Engineering :: Image Recognition", 17 | ] 18 | 19 | [project.scripts] 20 | tools = "tools.main:app" 21 | 22 | [project.urls] 23 | repository = "https://github.com/luxonis/tools" 24 | issues = "https://github.com/luxonis/tools/issues" 25 | 26 | [build-system] 27 | requires = ["setuptools", "wheel"] 28 | build-backend = "setuptools.build_meta" 29 | 30 | [tool.setuptools.packages.find] 31 | where = ["."] 32 | 33 | [tool.setuptools.package-data] 34 | tools = [ 35 | "docker-compose.yaml", 36 | "docker-compose-dev.yaml", 37 | "yolo/ultralytics/ultralytics/cfg/*.yaml", 38 | "yolo/yolov5/models/*.yaml", 39 | "yolov7/yolov7/cfg/**/*.yaml" 40 | ] 41 | 42 | [tool.setuptools.dynamic] 43 | dependencies = { file = ["requirements.txt"] } 44 | optional-dependencies = { dev = { file = ["requirements-dev.txt"] } } 45 | 46 | [tool.ruff] 47 | target-version = "py38" 48 | exclude = ["tools/yolov7/yolov7/"] 49 | 50 | [tool.ruff.lint] 51 | ignore = ["F403", "B028", "B905", "D1"] 52 | select = ["E4", "E7", "E9", "F", "W", "B", "I", "FA"] 53 | 54 | [tool.ruff.pydocstyle] 55 | convention = "google" 56 | 57 | [tool.mypy] 58 | python_version = "3.10" 59 | ignore_missing_imports = true 60 | 61 | [tool.pyright] 62 | typeCheckingMode = "basic" 63 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | pre-commit>=4.1.0 2 | pytest-cov>=4.1.0 3 | docker-squash>=1.1.0 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch>=2.0.0 #,<2.6.0 2 | torchvision>=0.10.1 3 | Pillow>=7.1.2 4 | PyYAML>=5.3.1 5 | gcsfs 6 | luxonis-ml[data,nn_archive,utils]>=0.6.5,<0.7 7 | onnx>=1.17.0 8 | numpy>=1.19.5,<2.1.0 9 | onnxruntime>=1.20.1 10 | onnxsim>=0.4.36 11 | s3fs 12 | tqdm 13 | s3transfer 14 | typer>=0.12.3 15 | psutil 16 | seaborn 17 | mmcv>=1.5.0,<2.0.0 -------------------------------------------------------------------------------- /tests/test_conversion.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | 5 | import requests 6 | 7 | from tools.utils.version_detection import detect_version 8 | from tools.yolo.yolov6_exporter import YoloV6R4Exporter 9 | from tools.yolo.yolov8_exporter import YoloV8Exporter 10 | from tools.yolo.yolov10_exporter import YoloV10Exporter 11 | from tools.yolov7.yolov7_exporter import YoloV7Exporter 12 | 13 | 14 | def _download_file(url: str): 15 | """An util function for downloading file from the given URL and saving it in the current folder.""" 16 | # Send a GET request to the URL 17 | response = requests.get(url) 18 | 19 | # Check if the request was successful 20 | if response.status_code == 200: 21 | # Determine the filename from the URL or use the provided new_filename 22 | filename = url.split("/")[-1] 23 | 24 | # Construct the full path to save the file 25 | file_path = os.path.join("tests", filename) 26 | 27 | # Write the content of the response to the file 28 | with open(file_path, "wb") as file: 29 | file.write(response.content) 30 | print(f"File downloaded and saved as {file_path}") 31 | else: 32 | print("Failed to download the file") 33 | 34 | 35 | def _remove_file(file_path: str): 36 | """An util function for removing a file from the current folder.""" 37 | if os.path.exists(file_path): 38 | os.remove(file_path) 39 | 40 | 41 | def _test_model_conversion(exported_class, model_path, imgsz, use_rvc2): 42 | """Test the conversion of a model.""" 43 | exporter = exported_class(model_path, imgsz, use_rvc2) 44 | exporter.export_onnx() 45 | exporter.export_nn_archive() 46 | 47 | # Check that the output files exist and are not empty 48 | assert os.path.exists(str(exporter.f_onnx)) 49 | assert os.path.exists(str(exporter.f_nn_archive)) 50 | _remove_file(model_path) 51 | 52 | 53 | def test_yolov5n_automatic_version_detection(): 54 | """Test the YOLOv5n autodetection of the model version.""" 55 | _download_file( 56 | "https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n.pt" 57 | ) 58 | assert detect_version("tests/yolov5n.pt") == "yolov5" 59 | _remove_file("tests/yolov5n.pt") 60 | 61 | 62 | def test_yolov5nu_automatic_version_detection(): 63 | """Test the YOLOv5nu autodetection of the model version.""" 64 | _download_file( 65 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolov5nu.pt" 66 | ) 67 | assert detect_version("tests/yolov5nu.pt") == "yolov5u" 68 | _remove_file("tests/yolov5nu.pt") 69 | 70 | 71 | def test_yolov5nu_model_conversion(): 72 | """Test the conversion of an YOLOv5nu model.""" 73 | _download_file( 74 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolov5nu.pt" 75 | ) 76 | _test_model_conversion(YoloV8Exporter, "tests/yolov5nu.pt", (64, 64), True) 77 | 78 | 79 | def test_yolov6nr1_automatic_version_detection(): 80 | """Test the YOLOv6nr1 autodetection of the model version.""" 81 | _download_file( 82 | "https://github.com/meituan/YOLOv6/releases/download/0.1.0/yolov6n.pt" 83 | ) 84 | assert detect_version("tests/yolov6n.pt") == "yolov6r1" 85 | _remove_file("tests/yolov6n.pt") 86 | 87 | 88 | def test_yolov6nr2_automatic_version_detection(): 89 | """Test the YOLOv6nr2 autodetection of the model version.""" 90 | _download_file( 91 | "https://github.com/meituan/YOLOv6/releases/download/0.2.0/yolov6n.pt" 92 | ) 93 | assert detect_version("tests/yolov6n.pt") == "yolov6r3" 94 | _remove_file("tests/yolov6n.pt") 95 | 96 | 97 | def test_yolov6nr3_automatic_version_detection(): 98 | """Test the YOLOv6nr3 autodetection of the model version.""" 99 | _download_file( 100 | "https://github.com/meituan/YOLOv6/releases/download/0.3.0/yolov6n.pt" 101 | ) 102 | assert detect_version("tests/yolov6n.pt") == "yolov6r3" 103 | _remove_file("tests/yolov6n.pt") 104 | 105 | 106 | def test_yolov6nr4_automatic_version_detection(): 107 | """Test the YOLOv6nr4 autodetection of the model version.""" 108 | _download_file( 109 | "https://github.com/meituan/YOLOv6/releases/download/0.4.0/yolov6n.pt" 110 | ) 111 | assert detect_version("tests/yolov6n.pt") == "yolov6r4" 112 | _remove_file("tests/yolov6n.pt") 113 | 114 | 115 | def test_yolov6nr4_model_conversion(): 116 | """Test the conversion of an YOLOv6nr4 model.""" 117 | _download_file( 118 | "https://github.com/meituan/YOLOv6/releases/download/0.4.0/yolov6n.pt" 119 | ) 120 | _test_model_conversion(YoloV6R4Exporter, "tests/yolov6n.pt", (640, 480), True) 121 | 122 | 123 | def test_yolov7t_automatic_version_detection(): 124 | """Test the YOLOv7t autodetection of the model version.""" 125 | _download_file( 126 | "https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-tiny.pt" 127 | ) 128 | assert detect_version("tests/yolov7-tiny.pt") == "yolov7" 129 | _remove_file("tests/yolov7-tiny.pt") 130 | 131 | 132 | def test_yolov7t_model_conversion(): 133 | """Test the conversion of an YOLOv7t model.""" 134 | _download_file( 135 | "https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-tiny.pt" 136 | ) 137 | _test_model_conversion(YoloV7Exporter, "tests/yolov7-tiny.pt", (640, 480), True) 138 | 139 | 140 | def test_yolov8n_automatic_version_detection(): 141 | """Test the YOLOv8n autodetection of the model version.""" 142 | _download_file( 143 | "https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt" 144 | ) 145 | assert detect_version("tests/yolov8n.pt") == "yolov8" 146 | _remove_file("tests/yolov8n.pt") 147 | 148 | 149 | def test_yolov8n_model_conversion(): 150 | """Test the conversion of an YOLOv8n model.""" 151 | _download_file( 152 | "https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt" 153 | ) 154 | _test_model_conversion(YoloV8Exporter, "tests/yolov8n.pt", (640, 480), True) 155 | 156 | 157 | def test_yolov9t_automatic_version_detection(): 158 | """Test the YOLOv9t autodetection of the model version.""" 159 | _download_file( 160 | "https://github.com/ultralytics/assets/releases/download/v8.2.0/yolov9t.pt" 161 | ) 162 | assert detect_version("tests/yolov9t.pt") == "yolov9" 163 | _remove_file("tests/yolov9t.pt") 164 | 165 | 166 | def test_yolov9t_model_conversion(): 167 | """Test the conversion of an YOLOv9t model.""" 168 | _download_file( 169 | "https://github.com/ultralytics/assets/releases/download/v8.2.0/yolov9t.pt" 170 | ) 171 | _test_model_conversion(YoloV8Exporter, "tests/yolov9t.pt", (640, 480), True) 172 | 173 | 174 | def test_yolov10n_automatic_version_detection(): 175 | """Test the YOLOv10n autodetection of the model version.""" 176 | _download_file( 177 | "https://github.com/ultralytics/assets/releases/download/v8.2.0/yolov10n.pt" 178 | ) 179 | assert detect_version("tests/yolov10n.pt") == "yolov10" 180 | _remove_file("tests/yolov10n.pt") 181 | 182 | 183 | def test_yolov10n_model_conversion(): 184 | """Test the conversion of an YOLOv10n model.""" 185 | _download_file( 186 | "https://github.com/ultralytics/assets/releases/download/v8.2.0/yolov10n.pt" 187 | ) 188 | _test_model_conversion(YoloV10Exporter, "tests/yolov10n.pt", (640, 480), True) 189 | 190 | 191 | def test_yolov11n_automatic_version_detection(): 192 | """Test the YOLOv11n autodetection of the model version.""" 193 | _download_file( 194 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n.pt" 195 | ) 196 | assert detect_version("tests/yolo11n.pt") == "yolov11" 197 | _remove_file("tests/yolo11n.pt") 198 | 199 | 200 | def test_yolov11n_model_conversion(): 201 | """Test the conversion of an YOLOv11n model.""" 202 | _download_file( 203 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n.pt" 204 | ) 205 | _test_model_conversion(YoloV8Exporter, "tests/yolo11n.pt", (640, 480), True) 206 | 207 | 208 | def test_yolov11n_cls_automatic_version_detection(): 209 | """Test the YOLOv11n cls autodetection of the model version.""" 210 | _download_file( 211 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n-cls.pt" 212 | ) 213 | assert detect_version("tests/yolo11n-cls.pt") == "yolov11" 214 | _remove_file("tests/yolo11n-cls.pt") 215 | 216 | 217 | def test_yolov11n_cls_model_conversion(): 218 | """Test the conversion of an YOLOv11n cls model.""" 219 | _download_file( 220 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n-cls.pt" 221 | ) 222 | _test_model_conversion(YoloV8Exporter, "tests/yolo11n-cls.pt", (224, 224), True) 223 | 224 | 225 | def test_yolov11n_seg_automatic_version_detection(): 226 | """Test the YOLOv11n seg autodetection of the model version.""" 227 | _download_file( 228 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n-seg.pt" 229 | ) 230 | assert detect_version("tests/yolo11n-seg.pt") == "yolov11" 231 | _remove_file("tests/yolo11n-seg.pt") 232 | 233 | 234 | def test_yolov11n_seg_model_conversion(): 235 | """Test the conversion of an YOLOv11n seg model.""" 236 | _download_file( 237 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n-seg.pt" 238 | ) 239 | _test_model_conversion(YoloV8Exporter, "tests/yolo11n-seg.pt", (640, 480), True) 240 | 241 | 242 | def test_yolov11n_obb_automatic_version_detection(): 243 | """Test the YOLOv11n obb autodetection of the model version.""" 244 | _download_file( 245 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n-obb.pt" 246 | ) 247 | assert detect_version("tests/yolo11n-obb.pt") == "yolov11" 248 | _remove_file("tests/yolo11n-obb.pt") 249 | 250 | 251 | def test_yolov11n_obb_model_conversion(): 252 | """Test the conversion of an YOLOv11n obb model.""" 253 | _download_file( 254 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n-obb.pt" 255 | ) 256 | _test_model_conversion(YoloV8Exporter, "tests/yolo11n-obb.pt", (640, 480), True) 257 | 258 | 259 | def test_yolov11n_kpts_automatic_version_detection(): 260 | """Test the YOLOv11n kpts autodetection of the model version.""" 261 | _download_file( 262 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n-pose.pt" 263 | ) 264 | assert detect_version("tests/yolo11n-pose.pt") == "yolov11" 265 | _remove_file("tests/yolo11n-pose.pt") 266 | 267 | 268 | def test_yolov11n_kpts_model_conversion(): 269 | """Test the conversion of an YOLOv11n kpts model.""" 270 | _download_file( 271 | "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n-pose.pt" 272 | ) 273 | _test_model_conversion(YoloV8Exporter, "tests/yolo11n-pose.pt", (640, 480), True) 274 | -------------------------------------------------------------------------------- /tools/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luxonis/tools/45e4d08df9a4444c6d0b3e9f98e77ef7d8531fef/tools/.DS_Store -------------------------------------------------------------------------------- /tools/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from __future__ import annotations 3 | 4 | from typing import Optional 5 | 6 | import typer 7 | from loguru import logger 8 | from luxonis_ml.utils import setup_logging 9 | from typing_extensions import Annotated 10 | 11 | from tools.utils import ( 12 | GOLD_YOLO_CONVERSION, 13 | YOLOV5_CONVERSION, 14 | YOLOV5U_CONVERSION, 15 | YOLOV6R1_CONVERSION, 16 | YOLOV6R3_CONVERSION, 17 | YOLOV6R4_CONVERSION, 18 | YOLOV7_CONVERSION, 19 | YOLOV8_CONVERSION, 20 | YOLOV9_CONVERSION, 21 | YOLOV10_CONVERSION, 22 | YOLOV11_CONVERSION, 23 | Config, 24 | detect_version, 25 | resolve_path, 26 | upload_file_to_remote, 27 | ) 28 | from tools.utils.constants import MISC_DIR 29 | 30 | setup_logging() 31 | 32 | app = typer.Typer(help="Tools CLI", add_completion=False, rich_markup_mode="markdown") 33 | 34 | 35 | YOLO_VERSIONS = [ 36 | GOLD_YOLO_CONVERSION, 37 | YOLOV5_CONVERSION, 38 | YOLOV5U_CONVERSION, 39 | YOLOV6R1_CONVERSION, 40 | YOLOV6R3_CONVERSION, 41 | YOLOV6R4_CONVERSION, 42 | YOLOV7_CONVERSION, 43 | YOLOV8_CONVERSION, 44 | YOLOV9_CONVERSION, 45 | YOLOV10_CONVERSION, 46 | YOLOV11_CONVERSION, 47 | ] 48 | 49 | 50 | @app.command() 51 | def convert( 52 | model: Annotated[str, typer.Argument(help="Path to the model file.")], 53 | imgsz: Annotated[ 54 | str, typer.Option(help="Input image size [width, height].") 55 | ] = "416 416", 56 | version: Annotated[ 57 | Optional[str], 58 | typer.Option( 59 | help='YOLO version (e.g. `"yolov8"`). If `None`, the toolkit will run an automatic version detector.' 60 | ), 61 | ] = None, 62 | use_rvc2: Annotated[ 63 | bool, typer.Option(help="Whether the target platform is RVC2 or RVC3.") 64 | ] = True, 65 | class_names: Annotated[ 66 | Optional[str], 67 | typer.Option( 68 | help='A list of class names the model is capable of recognizing (e.g. `"person, bicycle, car"`).' 69 | ), 70 | ] = None, 71 | output_remote_url: Annotated[ 72 | Optional[str], typer.Option(help="An URL to upload the output to.") 73 | ] = None, 74 | config_path: Annotated[ 75 | Optional[str], 76 | typer.Option(help="An optional path to a conversion config file."), 77 | ] = None, 78 | put_file_plugin: Annotated[ 79 | Optional[str], 80 | typer.Option( 81 | help="The name of a registered function under the PUT_FILE_REGISTRY." 82 | ), 83 | ] = None, 84 | ): 85 | if version is not None and version not in YOLO_VERSIONS: 86 | logger.error("Wrong YOLO version selected!") 87 | raise typer.Exit(code=1) from None 88 | 89 | try: 90 | imgsz = list(map(int, imgsz.split(" "))) if " " in imgsz else [int(imgsz)] * 2 91 | except ValueError as e: 92 | logger.error('Invalid image size format. Must be "width height" or "width".') 93 | raise typer.Exit(code=1) from e 94 | 95 | if class_names: 96 | class_names = [class_name.strip() for class_name in class_names.split(",")] 97 | logger.info(f"Class names: {class_names}") 98 | 99 | config = Config.get_config( 100 | config_path, 101 | { 102 | "model": model, 103 | "imgsz": imgsz, 104 | "use_rvc2": use_rvc2, 105 | "class_names": class_names, 106 | "output_remote_url": output_remote_url, 107 | "put_file_plugin": put_file_plugin, 108 | }, 109 | ) 110 | 111 | # Resolve model path 112 | model_path = resolve_path(config.model, MISC_DIR) 113 | 114 | if version is None: 115 | version = detect_version(str(model_path)) 116 | version_note = ( 117 | "(This is an anchor-free version of the YOLOv5 model obtained by a more recent version of Ultralytics. Therefore, YOLOv8 conversion will be used instead of the standard YOLOv5 conversion)" 118 | if version == YOLOV5U_CONVERSION 119 | else "" 120 | ) 121 | logger.info(f"Detected version: {version} {version_note}") 122 | 123 | try: 124 | # Create exporter 125 | logger.info("Loading model...") 126 | if version == YOLOV5_CONVERSION: 127 | from tools.yolo.yolov5_exporter import YoloV5Exporter 128 | 129 | exporter = YoloV5Exporter(str(model_path), config.imgsz, config.use_rvc2) 130 | elif version == YOLOV6R1_CONVERSION: 131 | from tools.yolov6r1.yolov6_r1_exporter import YoloV6R1Exporter 132 | 133 | exporter = YoloV6R1Exporter(str(model_path), config.imgsz, config.use_rvc2) 134 | elif version == YOLOV6R3_CONVERSION: 135 | from tools.yolov6r3.yolov6_r3_exporter import YoloV6R3Exporter 136 | 137 | exporter = YoloV6R3Exporter(str(model_path), config.imgsz, config.use_rvc2) 138 | elif version == GOLD_YOLO_CONVERSION: 139 | from tools.yolov6r3.gold_yolo_exporter import GoldYoloExporter 140 | 141 | exporter = GoldYoloExporter(str(model_path), config.imgsz, config.use_rvc2) 142 | elif version == YOLOV6R4_CONVERSION: 143 | from tools.yolo.yolov6_exporter import YoloV6R4Exporter 144 | 145 | exporter = YoloV6R4Exporter(str(model_path), config.imgsz, config.use_rvc2) 146 | elif version == YOLOV7_CONVERSION: 147 | from tools.yolov7.yolov7_exporter import YoloV7Exporter 148 | 149 | exporter = YoloV7Exporter(str(model_path), config.imgsz, config.use_rvc2) 150 | elif version in [ 151 | YOLOV5U_CONVERSION, 152 | YOLOV8_CONVERSION, 153 | YOLOV9_CONVERSION, 154 | YOLOV11_CONVERSION, 155 | ]: 156 | from tools.yolo.yolov8_exporter import YoloV8Exporter 157 | 158 | exporter = YoloV8Exporter(str(model_path), config.imgsz, config.use_rvc2) 159 | elif version == YOLOV10_CONVERSION: 160 | from tools.yolo.yolov10_exporter import YoloV10Exporter 161 | 162 | exporter = YoloV10Exporter(str(model_path), config.imgsz, config.use_rvc2) 163 | else: 164 | logger.error("Unrecognized model version.") 165 | raise typer.Exit(code=1) from None 166 | logger.info("Model loaded.") 167 | except Exception as e: 168 | logger.error(f"Error creating exporter: {e}") 169 | raise typer.Exit(code=1) from e 170 | 171 | # Export model 172 | try: 173 | logger.info("Exporting model...") 174 | exporter.export_onnx() 175 | logger.info("Model exported.") 176 | except Exception as e: 177 | logger.error(f"Error exporting model: {e}") 178 | raise typer.Exit(code=1) from e 179 | # Create NN archive 180 | try: 181 | logger.info("Creating NN archive...") 182 | exporter.export_nn_archive(config.class_names) 183 | logger.info(f"NN archive created in {exporter.output_folder}.") 184 | except Exception as e: 185 | logger.error(f"Error creating NN archive: {e}") 186 | raise typer.Exit(code=1) from e 187 | 188 | # Upload to remote 189 | if config.output_remote_url: 190 | upload_file_to_remote( 191 | exporter.f_nn_archive, config.output_remote_url, config.put_file_plugin 192 | ) 193 | logger.info(f"Uploaded NN archive to {config.output_remote_url}") 194 | 195 | 196 | if __name__ == "__main__": 197 | app() 198 | -------------------------------------------------------------------------------- /tools/modules/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from .backbones import YoloV6BackBone 4 | from .exporter import Exporter 5 | from .heads import ( 6 | OBBV8, 7 | ClassifyV8, 8 | DetectV5, 9 | DetectV6R1, 10 | DetectV6R3, 11 | DetectV6R4m, 12 | DetectV6R4s, 13 | DetectV7, 14 | DetectV8, 15 | DetectV10, 16 | PoseV8, 17 | SegmentV8, 18 | ) 19 | from .stage2 import Multiplier 20 | 21 | __all__ = [ 22 | "YoloV6BackBone", 23 | "DetectV6R1", 24 | "DetectV6R3", 25 | "DetectV6R4s", 26 | "DetectV6R4m", 27 | "DetectV8", 28 | "Exporter", 29 | "PoseV8", 30 | "OBBV8", 31 | "SegmentV8", 32 | "ClassifyV8", 33 | "Multiplier", 34 | "DetectV5", 35 | "DetectV7", 36 | "DetectV10", 37 | ] 38 | -------------------------------------------------------------------------------- /tools/modules/backbones.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from torch import nn 4 | 5 | 6 | class YoloV6BackBone(nn.Module): 7 | """Backbone of YoloV6 model, it takes the model's original backbone and wraps it in 8 | this universal class. 9 | 10 | This was created for backwards compatibility with R2 models. 11 | """ 12 | 13 | def __init__( 14 | self, old_layer, uses_fuse_P2: bool = True, uses_6_erblock: bool = False 15 | ): 16 | super().__init__() 17 | 18 | self.uses_fuse_P2 = uses_fuse_P2 19 | self.uses_6_erblock = uses_6_erblock 20 | 21 | self.fuse_P2 = old_layer.fuse_P2 if hasattr(old_layer, "fuse_P2") else False 22 | 23 | self.stem = old_layer.stem 24 | self.ERBlock_2 = old_layer.ERBlock_2 25 | self.ERBlock_3 = old_layer.ERBlock_3 26 | self.ERBlock_4 = old_layer.ERBlock_4 27 | self.ERBlock_5 = old_layer.ERBlock_5 28 | if uses_6_erblock: 29 | self.ERBlock_6 = old_layer.ERBlock_6 30 | 31 | def forward(self, x): 32 | outputs = [] 33 | x = self.stem(x) 34 | x = self.ERBlock_2(x) 35 | if self.uses_fuse_P2 and self.fuse_P2: 36 | outputs.append(x) 37 | elif not self.uses_fuse_P2: 38 | outputs.append(x) 39 | x = self.ERBlock_3(x) 40 | outputs.append(x) 41 | x = self.ERBlock_4(x) 42 | outputs.append(x) 43 | x = self.ERBlock_5(x) 44 | outputs.append(x) 45 | if self.uses_6_erblock: 46 | x = self.ERBlock_6(x) 47 | outputs.append(x) 48 | 49 | return tuple(outputs) 50 | -------------------------------------------------------------------------------- /tools/modules/exporter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | from datetime import datetime 5 | from typing import List, Optional, Tuple 6 | 7 | import onnx 8 | import onnxsim 9 | import torch 10 | from luxonis_ml.nn_archive import ArchiveGenerator 11 | from luxonis_ml.nn_archive.config_building_blocks import ( 12 | DataType, 13 | Head, 14 | InputType, 15 | ) 16 | from luxonis_ml.nn_archive.config_building_blocks.base_models.head_metadata import ( 17 | HeadYOLOMetadata, 18 | ) 19 | 20 | from tools.utils.constants import OUTPUTS_DIR 21 | 22 | 23 | class Exporter: 24 | """Exporter class to export models to ONNX and NN archive formats.""" 25 | 26 | def __init__( 27 | self, 28 | model_path: str, 29 | imgsz: Tuple[int, int], 30 | use_rvc2: bool, 31 | subtype: str, 32 | output_names: List[str] = None, 33 | all_output_names: Optional[List[str]] = None, 34 | ): 35 | """ 36 | Initialize the Exporter class. 37 | 38 | Args: 39 | model_path (str): Path to the model's weights 40 | imgsz (Tuple[int, int]): Image size [width, height] 41 | use_rvc2 (bool): Whether to use RVC2 42 | subtype (str): Subtype of the model 43 | output_names (List[str]): List of output names. Defaults to ["output"]. 44 | all_output_names (Optional[List[str]]): List of all output names. Defaults to None. 45 | """ 46 | # Set up variables 47 | self.model_path = model_path 48 | self.imgsz = imgsz 49 | self.model_name = os.path.basename(self.model_path).split(".")[0] 50 | self.model = None 51 | # Set up file paths 52 | self.f_onnx = None 53 | self.f_nn_archive = None 54 | self.use_rvc2 = use_rvc2 55 | self.number_of_channels = None 56 | self.subtype = subtype 57 | self.output_names = output_names 58 | self.all_output_names = ( 59 | all_output_names if all_output_names is not None else output_names 60 | ) 61 | self.output_folder = ( 62 | OUTPUTS_DIR 63 | / f"{self.model_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}" 64 | ).resolve() 65 | # If output directory does not exist, create it 66 | if not self.output_folder.exists(): 67 | self.output_folder.mkdir(parents=True) 68 | 69 | def export_onnx(self) -> os.PathLike: 70 | """Export the model to ONNX format. 71 | 72 | Returns: 73 | Path: Path to the exported ONNX model 74 | """ 75 | self.f_onnx = (self.output_folder / f"{self.model_name}.onnx").resolve() 76 | im = torch.zeros(1, self.number_of_channels, *self.imgsz[::-1]) 77 | # export onnx model 78 | torch.onnx.export( 79 | self.model, 80 | im, 81 | self.f_onnx, 82 | verbose=False, 83 | opset_version=12, 84 | training=torch.onnx.TrainingMode.EVAL, 85 | do_constant_folding=True, 86 | input_names=["images"], 87 | output_names=self.all_output_names, 88 | dynamic_axes=None, 89 | ) 90 | 91 | # check if the arhcitecture is correct 92 | model_onnx = onnx.load(self.f_onnx) # load onnx model 93 | onnx.checker.check_model(model_onnx) # check onnx model 94 | 95 | # simplify the moodel 96 | onnx_model, check = onnxsim.simplify(model_onnx) 97 | assert check, "Simplified ONNX model could not be validated" 98 | 99 | # Save onnx model 100 | onnx.save(onnx_model, self.f_onnx) 101 | 102 | return self.f_onnx 103 | 104 | def make_nn_archive( 105 | self, 106 | class_list: List[str], 107 | n_classes: int, 108 | iou_threshold: float = 0.5, 109 | conf_threshold: float = 0.5, 110 | max_det: int = 300, 111 | parser: str = "YOLO", 112 | stage2_executable_path: Optional[str] = None, 113 | postprocessor_path: Optional[str] = None, 114 | n_prototypes: Optional[int] = None, 115 | n_keypoints: Optional[int] = None, 116 | is_softmax: Optional[bool] = None, 117 | anchors: Optional[List[List[List[float]]]] = None, 118 | output_kwargs: Optional[dict] = None, 119 | ): 120 | """Export the model to NN archive format. 121 | 122 | Args: 123 | class_list (List[str], optional): List of class names 124 | n_classes (int): Number of classes 125 | iou_threshold (float): Intersection over Union threshold 126 | conf_threshold (float): Confidence threshold 127 | max_det (int): Maximum number of detections 128 | parser (str): Parser type, defaults to "YOLO" 129 | 2stage_executable_path (Optional[str], optional): Path to the executables. Defaults to None. 130 | postprocessor_path (Optional[str], optional): Path to the postprocessor. Defaults to None. 131 | n_prototypes (Optional[int], optional): Number of prototypes. Defaults to None. 132 | n_keypoints (Optional[int], optional): Number of keypoints. Defaults to None. 133 | is_softmax (Optional[bool], optional): Whether to use softmax. Defaults to None. 134 | anchors (Optional[List[List[List[float]]]], optional): Anchors. Defaults to None. 135 | output_kwargs (Optional[dict], optional): Output keyword arguments. Defaults to None. 136 | """ 137 | self.f_nn_archive = (self.output_folder / f"{self.model_name}.tar.xz").resolve() 138 | if stage2_executable_path is not None: 139 | executables_paths = [str(self.f_onnx), stage2_executable_path] 140 | else: 141 | executables_paths = [str(self.f_onnx)] 142 | 143 | if output_kwargs is None: 144 | output_kwargs = {} 145 | 146 | archive = ArchiveGenerator( 147 | archive_name=self.model_name, 148 | save_path=str(self.output_folder), 149 | cfg_dict={ 150 | "config_version": "1.0", 151 | "model": { 152 | "metadata": { 153 | "name": self.model_name, 154 | "path": f"{self.model_name}.onnx", 155 | }, 156 | "inputs": [ 157 | { 158 | "name": "images", 159 | "dtype": DataType.FLOAT32, 160 | "input_type": InputType.IMAGE, 161 | "shape": [1, self.number_of_channels, *self.imgsz[::-1]], 162 | "preprocessing": { 163 | "mean": [0, 0, 0], 164 | "scale": [255, 255, 255], 165 | }, 166 | } 167 | ], 168 | "outputs": [ 169 | { 170 | "name": output, 171 | "dtype": DataType.FLOAT32, 172 | } 173 | for output in self.all_output_names 174 | ], 175 | "heads": [ 176 | Head( 177 | parser=parser, 178 | metadata=HeadYOLOMetadata( 179 | yolo_outputs=self.output_names, 180 | subtype=self.subtype, 181 | n_classes=n_classes, 182 | classes=class_list, 183 | iou_threshold=iou_threshold, 184 | conf_threshold=conf_threshold, 185 | max_det=max_det, 186 | postprocessor_path=postprocessor_path, 187 | n_prototypes=n_prototypes, 188 | n_keypoints=n_keypoints, 189 | is_softmax=is_softmax, 190 | anchors=anchors, 191 | **output_kwargs, 192 | ), 193 | outputs=self.all_output_names, 194 | ) 195 | ], 196 | }, 197 | }, 198 | executables_paths=executables_paths, 199 | ) 200 | archive.make_archive() 201 | 202 | def export_nn_archive(self, class_names: Optional[List[str]] = None): 203 | """ 204 | Export the model to NN archive format. 205 | 206 | Args: 207 | class_list (Optional[List[str]], optional): List of class names. Defaults to None. 208 | """ 209 | nc = self.model.detect.nc 210 | # If class names are provided, use them 211 | if class_names is not None: 212 | assert ( 213 | len(class_names) == nc 214 | ), f"Number of the given class names {len(class_names)} does not match number of classes {nc} provided in the model!" 215 | names = class_names 216 | else: 217 | # Check if the model has a names attribute 218 | if hasattr(self.model, "names"): 219 | names = self.model.names 220 | else: 221 | names = [f"Class_{i}" for i in range(nc)] 222 | 223 | self.make_nn_archive(names, nc) 224 | -------------------------------------------------------------------------------- /tools/modules/heads.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import math 4 | 5 | import torch 6 | import torch.nn as nn 7 | import torch.nn.functional as F 8 | 9 | 10 | def make_anchors(feats, strides, grid_cell_offset=0.5): 11 | """Generate anchors from features.""" 12 | anchor_points, stride_tensor = [], [] 13 | assert feats is not None 14 | dtype, device = feats[0].dtype, feats[0].device 15 | for i, stride in enumerate(strides): 16 | _, _, h, w = feats[i].shape 17 | sx = ( 18 | torch.arange(end=w, device=device, dtype=dtype) + grid_cell_offset 19 | ) # shift x 20 | sy = ( 21 | torch.arange(end=h, device=device, dtype=dtype) + grid_cell_offset 22 | ) # shift y 23 | sy, sx = torch.meshgrid(sy, sx, indexing="ij") 24 | anchor_points.append(torch.stack((sx, sy), -1).view(-1, 2).transpose(0, 1)) 25 | stride_tensor.append( 26 | torch.full((h * w, 1), stride, dtype=dtype, device=device).transpose(0, 1) 27 | ) 28 | return anchor_points, stride_tensor 29 | # return torch.cat(anchor_points), torch.cat(stride_tensor) 30 | 31 | 32 | class DetectV5(nn.Module): 33 | """ 34 | YOLOv5 Detect head for detection models. 35 | """ 36 | 37 | def __init__(self, old_detect): 38 | super().__init__() 39 | self.nc = old_detect.nc # number of classes 40 | self.no = old_detect.no # number of outputs per anchor 41 | self.nl = old_detect.nl # number of detection layers 42 | self.na = old_detect.na 43 | self.grid = old_detect.grid # [torch.zeros(1)] * self.nl 44 | self.anchor_grid = old_detect.anchor_grid 45 | self.m = old_detect.m 46 | self.inplace = old_detect.inplace 47 | self.stride = old_detect.stride 48 | self.anchors = old_detect.anchors 49 | self.f = old_detect.f 50 | self.i = old_detect.i 51 | 52 | def forward(self, x): 53 | outputs = [] 54 | 55 | for i in range(self.nl): 56 | x[i] = self.m[i](x[i]) # conv 57 | channel_output = torch.sigmoid(x[i]) 58 | outputs.append(channel_output) 59 | 60 | return outputs 61 | 62 | 63 | class DetectV7(nn.Module): 64 | """ 65 | YOLOv7 Detect head for detection models. 66 | """ 67 | 68 | def __init__(self, old_detect): 69 | super().__init__() 70 | self.nc = old_detect.nc # number of classes 71 | self.no = old_detect.no # number of outputs per anchor 72 | self.nl = old_detect.nl # number of detection layers 73 | self.na = old_detect.na 74 | self.grid = old_detect.grid 75 | self.anchor_grid = old_detect.anchor_grid 76 | self.m = old_detect.m 77 | self.stride = old_detect.stride 78 | self.anchors = old_detect.anchors 79 | self.f = old_detect.f 80 | self.i = old_detect.i 81 | 82 | def forward(self, x): 83 | outputs = [] 84 | 85 | for i in range(self.nl): 86 | x[i] = self.m[i](x[i]) # conv 87 | channel_output = torch.sigmoid(x[i]) 88 | outputs.append(channel_output) 89 | 90 | return outputs 91 | 92 | 93 | class DetectV6R1(nn.Module): 94 | """Efficient Decoupled Head 95 | With hardware-aware degisn, the decoupled head is optimized with 96 | hybridchannels methods. 97 | """ 98 | 99 | # def __init__(self, num_classes=80, anchors=1, num_layers=3, inplace=True, head_layers=None, use_dfl=True, reg_max=16): # detection layer 100 | def __init__(self, old_detect): # detection layer 101 | super().__init__() 102 | self.nc = old_detect.nc # number of classes 103 | self.no = old_detect.no # number of outputs per anchor 104 | self.nl = old_detect.nl # number of detection layers 105 | self.na = old_detect.na 106 | self.anchors = old_detect.anchors 107 | self.grid = old_detect.grid # [torch.zeros(1)] * self.nl 108 | self.prior_prob = 1e-2 109 | self.inplace = old_detect.inplace 110 | stride = [8, 16, 32] # strides computed during build 111 | self.stride = torch.tensor(stride) 112 | 113 | # Init decouple head 114 | self.stems = old_detect.stems 115 | self.cls_convs = old_detect.cls_convs 116 | self.reg_convs = old_detect.reg_convs 117 | self.cls_preds = old_detect.cls_preds 118 | self.reg_preds = old_detect.reg_preds 119 | # New 120 | self.obj_preds = old_detect.obj_preds 121 | 122 | def forward(self, x): 123 | outputs = [] 124 | for i in range(self.nl): 125 | x[i] = self.stems[i](x[i]) 126 | cls_x = x[i] 127 | reg_x = x[i] 128 | cls_feat = self.cls_convs[i](cls_x) 129 | cls_output = self.cls_preds[i](cls_feat) 130 | reg_feat = self.reg_convs[i](reg_x) 131 | reg_output = self.reg_preds[i](reg_feat) 132 | obj_output = self.obj_preds[i](reg_feat) 133 | y = torch.cat([reg_output, obj_output.sigmoid(), cls_output.sigmoid()], 1) 134 | outputs.append(y) 135 | return outputs 136 | 137 | 138 | class DetectV6R3(nn.Module): 139 | """Efficient Decoupled Head for YOLOv6 R2&R3 With hardware-aware degisn, the 140 | decoupled head is optimized with hybridchannels methods.""" 141 | 142 | def __init__(self, old_detect, use_rvc2: bool): # detection layer 143 | super().__init__() 144 | self.nc = old_detect.nc # number of classes 145 | self.no = old_detect.no # number of outputs per anchor 146 | self.nl = old_detect.nl # number of detection layers 147 | if hasattr(old_detect, "anchors"): 148 | self.anchors = old_detect.anchors 149 | self.grid = old_detect.grid # [torch.zeros(1)] * self.nl 150 | self.prior_prob = 1e-2 151 | self.inplace = old_detect.inplace 152 | stride = [8, 16, 32] # strides computed during build 153 | self.stride = torch.tensor(stride) 154 | self.use_dfl = old_detect.use_dfl 155 | self.reg_max = old_detect.reg_max 156 | self.proj_conv = old_detect.proj_conv 157 | self.grid_cell_offset = 0.5 158 | self.grid_cell_size = 5.0 159 | 160 | # Init decouple head 161 | self.stems = old_detect.stems 162 | self.cls_convs = old_detect.cls_convs 163 | self.reg_convs = old_detect.reg_convs 164 | if hasattr(old_detect, "cls_preds"): 165 | self.cls_preds = old_detect.cls_preds 166 | elif hasattr(old_detect, "cls_preds_af"): 167 | self.cls_preds = old_detect.cls_preds_af 168 | if hasattr(old_detect, "reg_preds"): 169 | self.reg_preds = old_detect.reg_preds 170 | elif hasattr(old_detect, "reg_preds_af"): 171 | self.reg_preds = old_detect.reg_preds_af 172 | 173 | self.use_rvc2 = use_rvc2 174 | 175 | def forward(self, x): 176 | outputs = [] 177 | for i in range(self.nl): 178 | b, _, h, w = x[i].shape 179 | x[i] = self.stems[i](x[i]) 180 | cls_x = x[i] 181 | reg_x = x[i] 182 | cls_feat = self.cls_convs[i](cls_x) 183 | cls_output = self.cls_preds[i](cls_feat) 184 | reg_feat = self.reg_convs[i](reg_x) 185 | reg_output = self.reg_preds[i](reg_feat) 186 | 187 | if self.use_dfl: 188 | reg_output = reg_output.reshape( 189 | [-1, 4, self.reg_max + 1, h * w] 190 | ).permute(0, 2, 1, 3) 191 | reg_output = self.proj_conv(F.softmax(reg_output, dim=1))[:, 0] 192 | reg_output = reg_output.reshape([-1, 4, h, w]) 193 | 194 | cls_output = torch.sigmoid(cls_output) 195 | # conf, _ = cls_output.max(1, keepdim=True) 196 | if self.use_rvc2: 197 | conf, _ = cls_output.max(1, keepdim=True) 198 | else: 199 | conf = torch.ones( 200 | (cls_output.shape[0], 1, cls_output.shape[2], cls_output.shape[3]), 201 | device=cls_output.device, 202 | ) 203 | output = torch.cat([reg_output, conf, cls_output], axis=1) 204 | outputs.append(output) 205 | 206 | return outputs 207 | 208 | 209 | class DetectV6R4s(nn.Module): 210 | """Efficient Decoupled Head for YOLOv6 R4 nano & small With hardware-aware design, 211 | the decoupled head is optimized with hybridchannels methods.""" 212 | 213 | def __init__(self, old_detect, use_rvc2: bool): # detection layer 214 | super().__init__() 215 | self.nc = old_detect.nc # number of classes 216 | self.no = old_detect.no # number of outputs per anchor 217 | self.nl = old_detect.nl # number of detection layers 218 | if hasattr(old_detect, "anchors"): 219 | self.anchors = old_detect.anchors 220 | self.grid = old_detect.grid # [torch.zeros(1)] * self.nl 221 | self.prior_prob = 1e-2 222 | self.inplace = old_detect.inplace 223 | self.stride = old_detect.stride 224 | if hasattr(old_detect, "use_dfl"): 225 | self.use_dfl = old_detect.use_dfl 226 | # print(old_detect.use_dfl) 227 | if hasattr(old_detect, "reg_max"): 228 | self.reg_max = old_detect.reg_max 229 | if hasattr(old_detect, "proj_conv"): 230 | self.proj_conv = old_detect.proj_conv 231 | self.grid_cell_offset = 0.5 232 | self.grid_cell_size = 5.0 233 | 234 | # Init decouple head 235 | self.stems = old_detect.stems 236 | self.cls_convs = old_detect.cls_convs 237 | self.reg_convs = old_detect.reg_convs 238 | if hasattr(old_detect, "cls_preds"): 239 | self.cls_preds = old_detect.cls_preds 240 | elif hasattr(old_detect, "cls_preds_af"): 241 | self.cls_preds = old_detect.cls_preds_af 242 | if hasattr(old_detect, "reg_preds"): 243 | self.reg_preds = old_detect.reg_preds 244 | elif hasattr(old_detect, "reg_preds_af"): 245 | self.reg_preds = old_detect.reg_preds_af 246 | 247 | self.use_rvc2 = use_rvc2 248 | 249 | def forward(self, x): 250 | outputs = [] 251 | 252 | for i in range(self.nl): 253 | x[i] = self.stems[i](x[i]) 254 | cls_x = x[i] 255 | reg_x = x[i] 256 | cls_feat = self.cls_convs[i](cls_x) 257 | cls_output = self.cls_preds[i](cls_feat) 258 | reg_feat = self.reg_convs[i](reg_x) 259 | reg_output = self.reg_preds[i](reg_feat) 260 | 261 | cls_output = torch.sigmoid(cls_output) 262 | 263 | if self.use_rvc2: 264 | conf, _ = cls_output.max(1, keepdim=True) 265 | else: 266 | conf = torch.ones( 267 | (cls_output.shape[0], 1, cls_output.shape[2], cls_output.shape[3]), 268 | device=cls_output.device, 269 | ) 270 | output = torch.cat([reg_output, conf, cls_output], axis=1) 271 | outputs.append(output) 272 | 273 | return outputs 274 | 275 | 276 | class DetectV6R4m(nn.Module): 277 | """Efficient Decoupled Head for YOLOv6 R4 medium & large With hardware-aware design, 278 | the decoupled head is optimized with hybridchannels methods.""" 279 | 280 | def __init__(self, old_detect, use_rvc2: bool): # detection layer 281 | super().__init__() 282 | self.nc = old_detect.nc # number of classes 283 | self.no = old_detect.no # number of outputs per anchor 284 | self.nl = old_detect.nl # number of detection layers 285 | if hasattr(old_detect, "anchors"): 286 | self.anchors = old_detect.anchors 287 | self.grid = old_detect.grid # [torch.zeros(1)] * self.nl 288 | self.prior_prob = 1e-2 289 | self.inplace = old_detect.inplace 290 | self.stride = old_detect.stride 291 | self.use_dfl = old_detect.use_dfl 292 | # print(old_detect.use_dfl) 293 | self.reg_max = old_detect.reg_max 294 | self.proj_conv = old_detect.proj_conv 295 | self.grid_cell_offset = 0.5 296 | self.grid_cell_size = 5.0 297 | 298 | # Init decouple head 299 | self.stems = old_detect.stems 300 | self.cls_convs = old_detect.cls_convs 301 | self.reg_convs = old_detect.reg_convs 302 | if hasattr(old_detect, "cls_preds"): 303 | self.cls_preds = old_detect.cls_preds 304 | elif hasattr(old_detect, "cls_preds_af"): 305 | self.cls_preds = old_detect.cls_preds_af 306 | if hasattr(old_detect, "reg_preds"): 307 | self.reg_preds = old_detect.reg_preds 308 | elif hasattr(old_detect, "reg_preds_af"): 309 | self.reg_preds = old_detect.reg_preds_af 310 | 311 | self.use_rvc2 = use_rvc2 312 | 313 | def forward(self, x): 314 | outputs = [] 315 | 316 | for i in range(self.nl): 317 | b, _, h, w = x[i].shape 318 | x[i] = self.stems[i](x[i]) 319 | cls_x = x[i] 320 | reg_x = x[i] 321 | cls_feat = self.cls_convs[i](cls_x) 322 | cls_output = self.cls_preds[i](cls_feat) 323 | reg_feat = self.reg_convs[i](reg_x) 324 | reg_output = self.reg_preds[i](reg_feat) 325 | 326 | if self.use_dfl: 327 | reg_output = reg_output.reshape( 328 | [-1, 4, self.reg_max + 1, h * w] 329 | ).permute(0, 2, 1, 3) 330 | reg_output = self.proj_conv(F.softmax(reg_output, dim=1)).reshape( 331 | [-1, 4, h, w] 332 | ) 333 | 334 | cls_output = torch.sigmoid(cls_output) 335 | 336 | if self.use_rvc2: 337 | conf, _ = cls_output.max(1, keepdim=True) 338 | else: 339 | conf = torch.ones( 340 | (cls_output.shape[0], 1, cls_output.shape[2], cls_output.shape[3]), 341 | device=cls_output.device, 342 | ) 343 | output = torch.cat([reg_output, conf, cls_output], axis=1) 344 | outputs.append(output) 345 | 346 | return outputs 347 | 348 | 349 | class DetectV8(nn.Module): 350 | """YOLOv8 Detect head for detection models.""" 351 | 352 | dynamic = False # force grid reconstruction 353 | export = False # export mode 354 | shape = None 355 | anchors = torch.empty(0) # init 356 | strides = torch.empty(0) # init 357 | 358 | def __init__(self, old_detect, use_rvc2: bool): 359 | super().__init__() 360 | self.nc = old_detect.nc # number of classes 361 | self.nl = old_detect.nl # number of detection layers 362 | self.reg_max = ( 363 | old_detect.reg_max 364 | ) # DFL channels (ch[0] // 16 to scale 4/8/12/16/20 for n/s/m/l/x) 365 | self.no = old_detect.no # number of outputs per anchor 366 | self.stride = old_detect.stride # strides computed during build 367 | 368 | self.cv2 = old_detect.cv2 369 | self.cv3 = old_detect.cv3 370 | self.f = old_detect.f 371 | self.i = old_detect.i 372 | 373 | self.use_rvc2 = use_rvc2 374 | 375 | self.proj_conv = nn.Conv2d(old_detect.dfl.c1, 1, 1, bias=False).requires_grad_( 376 | False 377 | ) 378 | x = torch.arange(old_detect.dfl.c1, dtype=torch.float) 379 | self.proj_conv.weight.data[:] = nn.Parameter(x.view(1, old_detect.dfl.c1, 1, 1)) 380 | 381 | def forward(self, x): 382 | bs = x[0].shape[0] # batch size 383 | 384 | outputs = [] 385 | for i in range(self.nl): 386 | box = self.cv2[i](x[i]) 387 | h, w = box.shape[2:] 388 | 389 | # ------------------------------ 390 | # DFL PART 391 | box = box.view(bs, 4, self.reg_max, h * w).permute(0, 2, 1, 3) 392 | box = self.proj_conv(F.softmax(box, dim=1))[:, 0] 393 | box = box.reshape([bs, 4, h, w]) 394 | # ------------------------------ 395 | 396 | cls = self.cv3[i](x[i]) 397 | cls_output = cls.sigmoid() 398 | if self.use_rvc2: 399 | conf, _ = cls_output.max(1, keepdim=True) 400 | else: 401 | conf = torch.ones( 402 | (cls_output.shape[0], 1, cls_output.shape[2], cls_output.shape[3]), 403 | device=cls_output.device, 404 | ) 405 | 406 | output = torch.cat([box, conf, cls_output], axis=1) 407 | outputs.append(output) 408 | 409 | return outputs 410 | 411 | 412 | class OBBV8(DetectV8): 413 | """YOLOv8 OBB detection head for detection with rotation models.""" 414 | 415 | def __init__(self, old_obb, use_rvc2): 416 | super().__init__(old_obb, use_rvc2) 417 | self.ne = old_obb.ne # number of extra parameters 418 | self.cv4 = old_obb.cv4 419 | 420 | def forward(self, x): 421 | # Detection part 422 | outputs = super().forward(x) 423 | 424 | # OBB part 425 | bs = x[0].shape[0] # batch size 426 | angle = torch.cat( 427 | [self.cv4[i](x[i]).view(bs, self.ne, -1) for i in range(self.nl)], 2 428 | ) # OBB theta logits 429 | # NOTE: set `angle` as an attribute so that `decode_bboxes` could use it. 430 | angle = (angle.sigmoid() - 0.25) * math.pi # [-pi/4, 3pi/4] 431 | # Append the angle 432 | outputs.append(angle) 433 | 434 | return outputs 435 | 436 | 437 | class PoseV8(DetectV8): 438 | """YOLOv8 Pose head for keypoints models.""" 439 | 440 | def __init__(self, old_kpts, use_rvc2): 441 | super().__init__(old_kpts, use_rvc2) 442 | self.kpt_shape = ( 443 | old_kpts.kpt_shape 444 | ) # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) 445 | self.nk = old_kpts.nk # number of keypoints total 446 | self.cv4 = old_kpts.cv4 447 | self.use_rvc2 = use_rvc2 448 | 449 | def forward(self, x): 450 | """Perform forward pass through YOLO model and return predictions.""" 451 | bs = x[0].shape[0] # batch size 452 | if self.shape != bs: 453 | self.anchors, self.strides = make_anchors(x, self.stride, 0.5) 454 | self.shape = bs 455 | 456 | # Detection part 457 | outputs = super().forward(x) 458 | 459 | # Pose part 460 | for i in range(self.nl): 461 | kpt = self.cv4[i](x[i]).view(bs, self.nk, -1) 462 | outputs.append(self.kpts_decode(bs, kpt, i)) 463 | 464 | return outputs 465 | 466 | def kpts_decode(self, bs, kpts, i): 467 | """Decodes keypoints.""" 468 | ndim = self.kpt_shape[1] 469 | y = kpts.view(bs, *self.kpt_shape, -1) 470 | a = (y[:, :, :2] * 2.0 + (self.anchors[i] - 0.5)) * self.strides[i] 471 | if ndim == 3: 472 | # a = torch.cat((a, y[:, :, 2:3].sigmoid()*10), 2) 473 | a = torch.cat((a, y[:, :, 2:3]), 2) 474 | return a.view(bs, self.nk, -1) 475 | 476 | 477 | class SegmentV8(DetectV8): 478 | """YOLOv8 Segment head for segmentation models.""" 479 | 480 | def __init__(self, old_segment, use_rvc2): 481 | super().__init__(old_segment, use_rvc2) 482 | self.nm = old_segment.nm # number of masks 483 | self.npr = old_segment.npr # number of protos 484 | self.proto = old_segment.proto # protos 485 | self.cv4 = old_segment.cv4 486 | 487 | def forward(self, x): 488 | # Detection part 489 | outputs = super().forward(x) 490 | # Masks 491 | outputs.extend([self.cv4[i](x[i]) for i in range(self.nl)]) 492 | # Mask protos 493 | outputs.append(self.proto(x[0])) 494 | 495 | return outputs 496 | 497 | 498 | class ClassifyV8(nn.Module): 499 | """YOLOv8 classification head, i.e. x(b,c1,20,20) to x(b,c2).""" 500 | 501 | def __init__(self, old_classify, use_rvc2: bool): 502 | super().__init__() 503 | self.conv = old_classify.conv 504 | self.pool = old_classify.pool 505 | self.drop = old_classify.drop 506 | self.linear = old_classify.linear 507 | self.f = old_classify.f 508 | self.i = old_classify.i 509 | 510 | self.use_rvc2 = use_rvc2 511 | 512 | def forward(self, x): 513 | """Performs a forward pass of the YOLO model on input image data.""" 514 | if isinstance(x, list): 515 | x = torch.cat(x, 1) 516 | x = self.linear(self.drop(self.pool(self.conv(x)).flatten(1))) 517 | return x 518 | 519 | 520 | class DetectV10(DetectV8): 521 | """YOLOv10 Detect head for detection models.""" 522 | 523 | def __init__(self, old_detect, use_rvc2): 524 | super().__init__(old_detect, use_rvc2) 525 | self.cv2 = old_detect.one2one_cv2 526 | self.cv3 = old_detect.one2one_cv3 527 | -------------------------------------------------------------------------------- /tools/modules/stage2.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import torch 4 | import torch.nn as nn 5 | 6 | 7 | class Multiplier(nn.Module): 8 | def forward(self, prototypes, coefficients): 9 | coefficients = coefficients.view(coefficients.shape[0], -1, 1, 1) 10 | x = coefficients * prototypes 11 | res = torch.sigmoid(x.sum(dim=1, keepdim=True)) 12 | return res 13 | -------------------------------------------------------------------------------- /tools/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from .config import Config 4 | from .filesystem_utils import ( 5 | download_from_remote, 6 | get_protocol, 7 | resolve_path, 8 | upload_file_to_remote, 9 | ) 10 | from .in_channels import get_first_conv2d_in_channels 11 | from .version_detection import ( 12 | GOLD_YOLO_CONVERSION, 13 | UNRECOGNIZED, 14 | YOLOV5_CONVERSION, 15 | YOLOV5U_CONVERSION, 16 | YOLOV6R1_CONVERSION, 17 | YOLOV6R3_CONVERSION, 18 | YOLOV6R4_CONVERSION, 19 | YOLOV7_CONVERSION, 20 | YOLOV8_CONVERSION, 21 | YOLOV9_CONVERSION, 22 | YOLOV10_CONVERSION, 23 | YOLOV11_CONVERSION, 24 | detect_version, 25 | ) 26 | 27 | __all__ = [ 28 | "Config", 29 | "detect_version", 30 | "YOLOV5_CONVERSION", 31 | "YOLOV5U_CONVERSION", 32 | "YOLOV6R1_CONVERSION", 33 | "YOLOV6R3_CONVERSION", 34 | "YOLOV6R4_CONVERSION", 35 | "YOLOV7_CONVERSION", 36 | "YOLOV8_CONVERSION", 37 | "YOLOV9_CONVERSION", 38 | "YOLOV10_CONVERSION", 39 | "YOLOV11_CONVERSION", 40 | "GOLD_YOLO_CONVERSION", 41 | "UNRECOGNIZED", 42 | "resolve_path", 43 | "download_from_remote", 44 | "upload_file_to_remote", 45 | "get_protocol", 46 | "get_first_conv2d_in_channels", 47 | ] 48 | -------------------------------------------------------------------------------- /tools/utils/config.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import List, Literal, Optional 4 | 5 | from luxonis_ml.utils import LuxonisConfig 6 | from pydantic import Field, validator 7 | 8 | 9 | class Config(LuxonisConfig): 10 | model: str = Field(..., description="Path to the model's weights") 11 | imgsz: List[int] = Field( 12 | default=[416, 416], 13 | min_length=2, 14 | max_length=2, 15 | min_ledescription="Input image size [width, height].", 16 | ) 17 | class_names: Optional[List[str]] = Field(None, description="List of class names.") 18 | use_rvc2: Literal[False, True] = Field(True, description="Whether to use RVC2.") 19 | output_remote_url: Optional[str] = Field( 20 | None, description="URL to upload the output to." 21 | ) 22 | put_file_plugin: Optional[str] = Field( 23 | None, 24 | description="The name of a registered function under the PUT_FILE_REGISTRY.", 25 | ) 26 | 27 | @validator("imgsz", each_item=True) 28 | def check_imgsz(cls, v): 29 | if v <= 0: 30 | raise ValueError("Image size values must be greater than 0.") 31 | if v % 32 != 0: 32 | raise ValueError("Image size values must be divisible by 32.") 33 | return v 34 | -------------------------------------------------------------------------------- /tools/utils/constants.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from pathlib import Path 4 | from typing import Final 5 | 6 | SHARED_DIR: Final[Path] = Path("shared_with_container") 7 | OUTPUTS_DIR: Final[Path] = SHARED_DIR / "outputs" 8 | MISC_DIR: Final[Path] = SHARED_DIR / "misc" 9 | 10 | __all__ = ["SHARED_DIR", "OUTPUTS_DIR", "MISC_DIR"] 11 | -------------------------------------------------------------------------------- /tools/utils/filesystem_utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from pathlib import Path 4 | from typing import Optional, Union 5 | 6 | from luxonis_ml.utils import LuxonisFileSystem 7 | 8 | from tools.utils.constants import SHARED_DIR 9 | 10 | 11 | def resolve_path(string: str, dest: Path) -> Path: 12 | """Downloads the file from remote or returns the path otherwise.""" 13 | protocol = get_protocol(string) 14 | if protocol != "file": 15 | path = download_from_remote(string, dest) 16 | else: 17 | path = Path(string) 18 | if not path.exists(): 19 | path = SHARED_DIR / path 20 | if not path.exists(): 21 | raise ValueError(f"Path `{string}` does not exist.") 22 | return path 23 | 24 | 25 | def download_from_remote(url: str, dest: Union[Path, str], max_files: int = -1) -> Path: 26 | """Downloads file(s) from remote bucket storage. 27 | 28 | It could be single file, entire direcory, or `max_files` within a directory 29 | """ 30 | 31 | absolute_path, remote_path = LuxonisFileSystem.split_full_path(url) 32 | if isinstance(dest, str): 33 | dest = Path(dest) 34 | local_path = dest / remote_path 35 | fs = LuxonisFileSystem(absolute_path) 36 | 37 | if fs.is_directory(remote_path): 38 | for i, remote_file in enumerate(fs.walk_dir(remote_path)): 39 | if i == max_files: 40 | break 41 | if not local_path.exists(): 42 | fs.get_file(remote_file, str(local_path / Path(remote_file).name)) 43 | 44 | else: 45 | if not local_path.exists(): 46 | fs.get_file(remote_path, str(local_path)) 47 | 48 | return local_path 49 | 50 | 51 | def upload_file_to_remote( 52 | local_path: Union[Path, str], url: str, put_file_plugin: Optional[str] = None 53 | ) -> None: 54 | """Uploads a file to remote bucket storage.""" 55 | 56 | absolute_path, remote_path = LuxonisFileSystem.split_full_path(url) 57 | fs = LuxonisFileSystem(absolute_path, put_file_plugin=put_file_plugin) 58 | 59 | fs.put_file(str(local_path), remote_path) 60 | 61 | 62 | def get_protocol(url: str) -> str: 63 | """Returns LuxonisFileSystem protocol.""" 64 | 65 | return LuxonisFileSystem.get_protocol(url) 66 | -------------------------------------------------------------------------------- /tools/utils/in_channels.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import torch 4 | 5 | 6 | def get_first_conv2d_in_channels(model): 7 | """Get the number of input channels of the first Conv2d layer in the model.""" 8 | for layer in model.modules(): 9 | if isinstance(layer, torch.nn.Conv2d): 10 | return layer.in_channels 11 | return None 12 | -------------------------------------------------------------------------------- /tools/utils/version_detection.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import platform 4 | import shutil 5 | import subprocess 6 | from os import listdir 7 | from os.path import exists, isdir, join 8 | 9 | YOLOV5_CONVERSION = "yolov5" 10 | YOLOV5U_CONVERSION = "yolov5u" 11 | YOLOV6R1_CONVERSION = "yolov6r1" 12 | YOLOV6R3_CONVERSION = "yolov6r3" 13 | YOLOV6R4_CONVERSION = "yolov6r4" 14 | YOLOV7_CONVERSION = "yolov7" 15 | YOLOV8_CONVERSION = "yolov8" 16 | YOLOV9_CONVERSION = "yolov9" 17 | YOLOV10_CONVERSION = "yolov10" 18 | YOLOV11_CONVERSION = "yolov11" 19 | GOLD_YOLO_CONVERSION = "goldyolo" 20 | UNRECOGNIZED = "none" 21 | 22 | 23 | def detect_version(path: str, debug: bool = False) -> str: 24 | """Detect the version of the model weights. 25 | 26 | Args: 27 | path (str): Path to the model weights 28 | 29 | Returns: 30 | str: The detected version 31 | """ 32 | try: 33 | # Remove and recreate the extracted_model directory 34 | if exists("extracted_model"): 35 | shutil.rmtree("extracted_model") 36 | subprocess.check_output("mkdir extracted_model", shell=True) 37 | 38 | # Extract the tar file into the extracted_model directory 39 | if platform.system() == "Windows": 40 | subprocess.check_output(["tar", "-xf", path, "-C", "extracted_model"]) 41 | else: 42 | subprocess.check_output(["unzip", path, "-d", "extracted_model"]) 43 | 44 | folder = [ 45 | f for f in listdir("extracted_model") if isdir(join("extracted_model", f)) 46 | ][0] 47 | 48 | if "yolov8" in folder.lower(): 49 | return YOLOV8_CONVERSION 50 | 51 | # open a file, where you stored the pickled data 52 | with open(f"extracted_model/{folder}/data.pkl", "rb") as file: 53 | data = file.read() 54 | if debug: 55 | print(data.decode(errors="replace")) 56 | content = data.decode("latin1") 57 | if "yolo11" in content: 58 | return YOLOV11_CONVERSION 59 | elif "yolov10" in content or "v10DetectLoss" in content: 60 | return YOLOV10_CONVERSION 61 | elif "yolov9" in content or ( 62 | "v9-model" in content and "ultralytics" in content 63 | ): 64 | return YOLOV9_CONVERSION 65 | elif ( 66 | "yolov8" in content 67 | or ( 68 | "YOLOv8" in content and "yolov5" not in content 69 | ) # the second condition is to avoid yolov5u being detected as yolov8 70 | or ("v8DetectionLoss" in content and "ultralytics" in content) 71 | ): 72 | return YOLOV8_CONVERSION 73 | elif "yolov6" in content: 74 | if "yolov6.models.yolo\nDetect" in content: 75 | return YOLOV6R1_CONVERSION 76 | elif "CSPSPPFModule" in content or "ConvBNReLU" in content: 77 | return YOLOV6R4_CONVERSION 78 | elif "gold_yolo" in content: 79 | return GOLD_YOLO_CONVERSION 80 | return YOLOV6R3_CONVERSION 81 | elif "yolov7" in content: 82 | return YOLOV7_CONVERSION 83 | elif "yolov5u" in content or ( 84 | "yolov5" in content 85 | and "ultralytics.nn.modules" in content 86 | # the second condition checks if the new version of the Ultralytics package was used to build the model which signals the "u" variant 87 | ): 88 | return YOLOV5U_CONVERSION 89 | elif ( 90 | "yolov5" in content 91 | or "SPPF" in content 92 | or ( 93 | "models.yolo.Detectr1" in content 94 | and "models.common.SPPr" in content 95 | ) 96 | ): 97 | return YOLOV5_CONVERSION 98 | 99 | except subprocess.CalledProcessError as e: 100 | raise RuntimeError() from e 101 | finally: 102 | # Ensure the extracted_model directory is removed after processing 103 | if exists("extracted_model"): 104 | shutil.rmtree("extracted_model") 105 | 106 | return UNRECOGNIZED 107 | -------------------------------------------------------------------------------- /tools/yolo/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luxonis/tools/45e4d08df9a4444c6d0b3e9f98e77ef7d8531fef/tools/yolo/.DS_Store -------------------------------------------------------------------------------- /tools/yolo/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import sys 4 | 5 | sys.path.append("./yolo") 6 | -------------------------------------------------------------------------------- /tools/yolo/yolov10_exporter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import sys 5 | from typing import List, Optional, Tuple 6 | 7 | from loguru import logger 8 | 9 | from tools.modules import DetectV10, Exporter 10 | from tools.utils import get_first_conv2d_in_channels 11 | 12 | current_dir = os.path.dirname(os.path.abspath(__file__)) 13 | yolo_path = os.path.join(current_dir, "ultralytics") 14 | sys.path.append(yolo_path) 15 | 16 | from ultralytics.nn.modules import Detect # noqa: E402 17 | from ultralytics.nn.tasks import attempt_load_one_weight # noqa: E402 18 | 19 | 20 | class YoloV10Exporter(Exporter): 21 | def __init__( 22 | self, 23 | model_path: str, 24 | imgsz: Tuple[int, int], 25 | use_rvc2: bool, 26 | ): 27 | super().__init__( 28 | model_path, 29 | imgsz, 30 | use_rvc2, 31 | subtype="yolov10", 32 | output_names=["output1_yolov10", "output2_yolov10", "output3_yolov10"], 33 | ) 34 | self.load_model() 35 | 36 | def load_model(self): 37 | # load the model 38 | model, _ = attempt_load_one_weight( 39 | self.model_path, device="cpu", inplace=True, fuse=True 40 | ) 41 | 42 | if isinstance(model.model[-1], (Detect)): 43 | model.model[-1] = DetectV10(model.model[-1], self.use_rvc2) 44 | 45 | self.names = ( 46 | model.module.names if hasattr(model, "module") else model.names 47 | ) # get class names 48 | # check num classes and labels 49 | assert model.yaml["nc"] == len( 50 | self.names 51 | ), f'Model class count {model.yaml["nc"]} != len(names) {len(self.names)}' 52 | 53 | try: 54 | self.number_of_channels = get_first_conv2d_in_channels(model) 55 | # print(f"Number of channels: {self.number_of_channels}") 56 | except Exception as e: 57 | logger.error(f"Error while getting number of channels: {e}") 58 | 59 | # check if image size is suitable 60 | gs = max(int(model.stride.max()), 32) # model stride 61 | if isinstance(self.imgsz, int): 62 | self.imgsz = [self.imgsz, self.imgsz] 63 | for sz in self.imgsz: 64 | if sz % gs != 0: 65 | raise ValueError(f"Image size is not a multiple of maximum stride {gs}") 66 | 67 | # ensure correct length 68 | if len(self.imgsz) != 2: 69 | raise ValueError("Image size must be of length 1 or 2.") 70 | 71 | model.eval() 72 | self.model = model 73 | 74 | def export_nn_archive(self, class_names: Optional[List[str]] = None): 75 | """ 76 | Export the model to NN archive format. 77 | 78 | Args: 79 | class_list (Optional[List[str]], optional): List of class names. Defaults to None. 80 | """ 81 | names = list(self.model.names.values()) 82 | 83 | if class_names is not None: 84 | assert len(class_names) == len( 85 | names 86 | ), f"Number of the given class names {len(class_names)} does not match number of classes {len(names)} provided in the model!" 87 | names = class_names 88 | 89 | self.f_nn_archive = (self.output_folder / f"{self.model_name}.tar.xz").resolve() 90 | 91 | self.make_nn_archive(names, self.model.model[-1].nc) 92 | -------------------------------------------------------------------------------- /tools/yolo/yolov5_exporter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import sys 5 | from typing import List, Optional, Tuple 6 | 7 | import torch 8 | import torch.nn as nn 9 | from loguru import logger 10 | 11 | from tools.modules import DetectV5, Exporter 12 | from tools.utils import get_first_conv2d_in_channels 13 | 14 | current_dir = os.path.dirname(os.path.abspath(__file__)) 15 | yolov5_path = os.path.join(current_dir, "yolov5") 16 | sys.path.append(yolov5_path) 17 | 18 | import models.experimental # noqa: E402 19 | from models.common import Conv # noqa: E402 20 | from models.yolo import Detect as DetectYOLOv5 # noqa: E402 21 | from utils.activations import SiLU # noqa: E402 22 | 23 | 24 | def attempt_load_yolov5(weights, device=None, inplace=True, fuse=True): 25 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a 26 | from models.yolo import Detect, Model # noqa: E402 27 | 28 | model = models.experimental.Ensemble() 29 | for w in weights if isinstance(weights, list) else [weights]: 30 | ckpt = torch.load( 31 | models.experimental.attempt_download(w), 32 | map_location="cpu", 33 | weights_only=False, 34 | ) # load 35 | ckpt = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model 36 | 37 | # Model compatibility updates 38 | if not hasattr(ckpt, "stride"): 39 | ckpt.stride = torch.tensor([32.0]) 40 | if hasattr(ckpt, "names") and isinstance(ckpt.names, (list, tuple)): 41 | ckpt.names = dict(enumerate(ckpt.names)) # convert to dict 42 | 43 | model.append( 44 | ckpt.fuse().eval() if fuse and hasattr(ckpt, "fuse") else ckpt.eval() 45 | ) # model in eval mode 46 | 47 | # Module compatibility updates 48 | for m in model.modules(): 49 | t = type(m) 50 | if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model): 51 | m.inplace = inplace # torch 1.7.0 compatibility 52 | if t is Detect and not isinstance(m.anchor_grid, list): 53 | delattr(m, "anchor_grid") 54 | m.anchor_grid = [torch.zeros(1)] * m.nl 55 | elif t is nn.Upsample and not hasattr(m, "recompute_scale_factor"): 56 | m.recompute_scale_factor = None # torch 1.11.0 compatibility 57 | 58 | # Return model 59 | if len(model) == 1: 60 | return model[-1] 61 | 62 | # Return detection ensemble 63 | print(f"Ensemble created with {weights}\n") 64 | for k in "names", "nc", "yaml": 65 | setattr(model, k, getattr(model[0], k)) 66 | model.stride = model[ 67 | torch.argmax(torch.tensor([m.stride.max() for m in model])).int() 68 | ].stride # max stride 69 | assert all( 70 | model[0].nc == m.nc for m in model 71 | ), f"Models have different class counts: {[m.nc for m in model]}" 72 | return model 73 | 74 | 75 | # Replace the original function 76 | models.experimental.attempt_load = attempt_load_yolov5 77 | 78 | 79 | class YoloV5Exporter(Exporter): 80 | def __init__( 81 | self, 82 | model_path: str, 83 | imgsz: Tuple[int, int], 84 | use_rvc2: bool, 85 | ): 86 | super().__init__( 87 | model_path, 88 | imgsz, 89 | use_rvc2, 90 | subtype="yolov5", 91 | output_names=["output1_yolov5", "output2_yolov5", "output3_yolov5"], 92 | ) 93 | self.load_model() 94 | 95 | def load_model(self): 96 | # code based on export.py from YoloV5 repository 97 | # load the model 98 | model = attempt_load_yolov5(self.model_path, device="cpu") # load FP32 model 99 | 100 | # check num classes and labels 101 | assert model.nc == len( 102 | model.names 103 | ), f"Model class count {model.nc} != len(names) {len(model.names)}" 104 | 105 | # check if image size is suitable 106 | gs = int(max(model.stride)) # grid size (max stride) 107 | if isinstance(self.imgsz, int): 108 | self.imgsz = [self.imgsz, self.imgsz] 109 | for sz in self.imgsz: 110 | if sz % gs != 0: 111 | raise ValueError(f"Image size is not a multiple of maximum stride {gs}") 112 | 113 | # ensure correct length 114 | if len(self.imgsz) != 2: 115 | raise ValueError("Image size must be of length 1 or 2.") 116 | 117 | inplace = True 118 | 119 | for _, m in model.named_modules(): 120 | if isinstance(m, Conv): # assign export-friendly activations 121 | if isinstance(m.act, nn.SiLU): 122 | m.act = SiLU() 123 | elif isinstance(m, DetectYOLOv5): 124 | m.inplace = inplace 125 | m.onnx_dynamic = False 126 | if hasattr(m, "forward_export"): 127 | m.forward = m.forward_export # assign custom forward (optional) 128 | 129 | if hasattr(model, "module"): 130 | model.module.model[-1] = DetectV5(model.module.model[-1]) 131 | else: 132 | model.model[-1] = DetectV5(model.model[-1]) 133 | 134 | model.eval() 135 | self.model = model 136 | 137 | try: 138 | self.number_of_channels = get_first_conv2d_in_channels(model) 139 | # print(f"Number of channels: {self.number_of_channels}") 140 | except Exception as e: 141 | logger.error(f"Error while getting number of channels: {e}") 142 | 143 | self.m = model.module.model[-1] if hasattr(model, "module") else model.model[-1] 144 | self.num_branches = len(self.m.anchor_grid) 145 | 146 | def export_nn_archive(self, class_names: Optional[List[str]] = None): 147 | """ 148 | Export the model to NN archive format. 149 | 150 | Args: 151 | class_list (Optional[List[str]], optional): List of class names. Defaults to None. 152 | """ 153 | names = list(self.model.names.values()) 154 | 155 | if class_names is not None: 156 | assert ( 157 | len(class_names) == self.model.nc 158 | ), f"Number of the given class names {len(class_names)} does not match number of classes {self.model.nc} provided in the model!" 159 | names = class_names 160 | 161 | anchors = [ 162 | self.m.anchor_grid[i][0, :, 0, 0].numpy().tolist() 163 | for i in range(self.num_branches) 164 | ] 165 | self.make_nn_archive( 166 | names, self.model.nc, parser="YOLOExtendedParser", anchors=anchors 167 | ) 168 | -------------------------------------------------------------------------------- /tools/yolo/yolov6_exporter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import sys 5 | from typing import Tuple 6 | 7 | import torch 8 | from loguru import logger 9 | 10 | from tools.modules import DetectV6R4m, DetectV6R4s, Exporter 11 | from tools.utils import get_first_conv2d_in_channels 12 | 13 | current_dir = os.path.dirname(os.path.abspath(__file__)) 14 | yolov6_path = os.path.join(current_dir, "YOLOv6") 15 | sys.path.append(yolov6_path) 16 | 17 | import yolov6.utils.checkpoint # noqa: E402 18 | from yolov6.layers.common import RepVGGBlock # noqa: E402 19 | from yolov6.models.heads.effidehead_distill_ns import Detect # noqa: E402 20 | 21 | 22 | # Override with your custom implementation 23 | def load_checkpoint(weights, map_location=None, inplace=True, fuse=True): 24 | """Load model from checkpoint file.""" 25 | from yolov6.utils.events import LOGGER # noqa: E402 26 | from yolov6.utils.torch_utils import fuse_model # noqa: E402 27 | 28 | LOGGER.info("Loading checkpoint from {}".format(weights)) 29 | ckpt = torch.load(weights, map_location=map_location, weights_only=False) # load 30 | model = ckpt["ema" if ckpt.get("ema") else "model"].float() 31 | if fuse: 32 | LOGGER.info("\nFusing model...") 33 | model = fuse_model(model).eval() 34 | else: 35 | model = model.eval() 36 | return model 37 | 38 | 39 | # Replace the original function 40 | yolov6.utils.checkpoint.load_checkpoint = load_checkpoint 41 | 42 | 43 | class YoloV6R4Exporter(Exporter): 44 | def __init__( 45 | self, 46 | model_path: str, 47 | imgsz: Tuple[int, int], 48 | use_rvc2: bool, 49 | ): 50 | super().__init__( 51 | model_path, 52 | imgsz, 53 | use_rvc2, 54 | subtype="yolov6r2", 55 | output_names=["output1_yolov6r2", "output2_yolov6r2", "output3_yolov6r2"], 56 | ) 57 | self.load_model() 58 | 59 | def load_model(self): 60 | # code based on export.py from YoloV5 repository 61 | # load the model 62 | model = load_checkpoint( 63 | self.model_path, 64 | map_location="cpu", 65 | inplace=True, 66 | fuse=True, 67 | ) # load FP32 model 68 | 69 | for layer in model.modules(): 70 | if isinstance(layer, RepVGGBlock): 71 | layer.switch_to_deploy() 72 | 73 | if isinstance(model.detect, Detect): 74 | model.detect = DetectV6R4s(model.detect, self.use_rvc2) 75 | else: 76 | model.detect = DetectV6R4m(model.detect, self.use_rvc2) 77 | 78 | try: 79 | self.number_of_channels = get_first_conv2d_in_channels(model) 80 | # print(f"Number of channels: {self.number_of_channels}") 81 | except Exception as e: 82 | logger.error(f"Error while getting number of channels: {e}") 83 | 84 | self.num_branches = len(model.detect.grid) 85 | 86 | # check if image size is suitable 87 | gs = 2 ** (2 + self.num_branches) # 1 = 8, 2 = 16, 3 = 32 88 | if isinstance(self.imgsz, int): 89 | self.imgsz = [self.imgsz, self.imgsz] 90 | for sz in self.imgsz: 91 | if sz % gs != 0: 92 | raise ValueError(f"Image size is not a multiple of maximum stride {gs}") 93 | 94 | # ensure correct length 95 | if len(self.imgsz) != 2: 96 | raise ValueError("Image size must be of length 1 or 2.") 97 | 98 | model.eval() 99 | self.model = model 100 | -------------------------------------------------------------------------------- /tools/yolo/yolov8_exporter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import sys 5 | from typing import List, Optional, Tuple 6 | 7 | import torch 8 | from loguru import logger 9 | from luxonis_ml.nn_archive import ArchiveGenerator 10 | from luxonis_ml.nn_archive.config_building_blocks import ( 11 | DataType, 12 | Head, 13 | InputType, 14 | ) 15 | from luxonis_ml.nn_archive.config_building_blocks.base_models.head_metadata import ( 16 | HeadClassificationMetadata, 17 | ) 18 | 19 | from tools.modules import ( 20 | OBBV8, 21 | ClassifyV8, 22 | DetectV8, 23 | Exporter, 24 | Multiplier, 25 | PoseV8, 26 | SegmentV8, 27 | ) 28 | from tools.utils import get_first_conv2d_in_channels 29 | 30 | current_dir = os.path.dirname(os.path.abspath(__file__)) 31 | yolo_path = os.path.join(current_dir, "ultralytics") 32 | sys.path.append(yolo_path) 33 | 34 | from ultralytics.nn.modules import OBB, Classify, Detect, Pose, Segment # noqa: E402 35 | from ultralytics.nn.tasks import attempt_load_one_weight # noqa: E402 36 | 37 | DETECT_MODE = 0 38 | SEGMENT_MODE = 1 39 | OBB_MODE = 2 40 | CLASSIFY_MODE = 3 41 | POSE_MODE = 4 42 | 43 | 44 | def get_output_names(mode: int) -> List[str]: 45 | """ 46 | Get the output names based on the mode. 47 | 48 | Args: 49 | mode (int): Mode of the model 50 | 51 | Returns: 52 | List[str]: List of output names 53 | """ 54 | if mode == DETECT_MODE: 55 | return ["output1_yolov6r2", "output2_yolov6r2", "output3_yolov6r2"] 56 | elif mode == SEGMENT_MODE: 57 | return [ 58 | "output1_yolov8", 59 | "output2_yolov8", 60 | "output3_yolov8", 61 | "output1_masks", 62 | "output2_masks", 63 | "output3_masks", 64 | "protos_output", 65 | ] 66 | elif mode == OBB_MODE: 67 | return ["output1_yolov8", "output2_yolov8", "output3_yolov8", "angle_output"] 68 | elif mode == POSE_MODE: 69 | return [ 70 | "output1_yolov8", 71 | "output2_yolov8", 72 | "output3_yolov8", 73 | "kpt_output1", 74 | "kpt_output2", 75 | "kpt_output3", 76 | ] 77 | return ["output"] 78 | 79 | 80 | class YoloV8Exporter(Exporter): 81 | def __init__( 82 | self, 83 | model_path: str, 84 | imgsz: Tuple[int, int], 85 | use_rvc2: bool, 86 | ): 87 | super().__init__( 88 | model_path, 89 | imgsz, 90 | use_rvc2, 91 | subtype="yolov8", 92 | output_names=["output1_yolov6r2", "output2_yolov6r2", "output3_yolov6r2"], 93 | ) 94 | self.load_model() 95 | 96 | def load_model(self): 97 | # load the model 98 | model, _ = attempt_load_one_weight( 99 | self.model_path, device="cpu", inplace=True, fuse=True 100 | ) 101 | 102 | self.mode = -1 103 | if isinstance(model.model[-1], (Segment)): 104 | model.model[-1] = SegmentV8(model.model[-1], self.use_rvc2) 105 | self.mode = SEGMENT_MODE 106 | # self.export_stage2_multiplier() 107 | elif isinstance(model.model[-1], (OBB)): 108 | model.model[-1] = OBBV8(model.model[-1], self.use_rvc2) 109 | self.mode = OBB_MODE 110 | elif isinstance(model.model[-1], (Pose)): 111 | model.model[-1] = PoseV8(model.model[-1], self.use_rvc2) 112 | self.mode = POSE_MODE 113 | elif isinstance(model.model[-1], (Classify)): 114 | model.model[-1] = ClassifyV8(model.model[-1], self.use_rvc2) 115 | self.mode = CLASSIFY_MODE 116 | elif isinstance(model.model[-1], (Detect)): 117 | model.model[-1] = DetectV8(model.model[-1], self.use_rvc2) 118 | self.mode = DETECT_MODE 119 | 120 | if self.mode in [DETECT_MODE, SEGMENT_MODE, OBB_MODE, POSE_MODE]: 121 | self.names = ( 122 | model.module.names if hasattr(model, "module") else model.names 123 | ) # get class names 124 | # check num classes and labels 125 | assert model.nc == len( 126 | self.names 127 | ), f"Model class count {model.nc} != len(names) {len(self.names)}" 128 | 129 | try: 130 | self.number_of_channels = get_first_conv2d_in_channels(model) 131 | # print(f"Number of channels: {self.number_of_channels}") 132 | except Exception as e: 133 | logger.error(f"Error while getting number of channels: {e}") 134 | 135 | # Get output names 136 | self.all_output_names = get_output_names(self.mode) 137 | 138 | # check if image size is suitable 139 | gs = max(int(model.stride.max()), 32) # model stride 140 | if isinstance(self.imgsz, int): 141 | self.imgsz = [self.imgsz, self.imgsz] 142 | for sz in self.imgsz: 143 | if sz % gs != 0: 144 | raise ValueError(f"Image size is not a multiple of maximum stride {gs}") 145 | 146 | # ensure correct length 147 | if len(self.imgsz) != 2: 148 | raise ValueError("Image size must be of length 1 or 2.") 149 | 150 | model.eval() 151 | self.model = model 152 | 153 | def export_stage2_multiplier(self): 154 | """Export the stage 2 multiplier to ONNX format.""" 155 | stage2_w = self.imgsz[0] // 4 156 | stage2_h = self.imgsz[1] // 4 157 | self.stage2_filename = f"mult_{str(self.imgsz[0])}x{str(self.imgsz[1])}.onnx" 158 | self.f_stage2_onnx = (self.output_folder / self.stage2_filename).resolve() 159 | torch.onnx.export( 160 | Multiplier(), 161 | (torch.randn(1, 32, stage2_h, stage2_w), torch.randn(1, 32)), 162 | self.f_stage2_onnx, 163 | input_names=["prototypes", "coeffs"], 164 | output_names=["mask"], 165 | ) 166 | 167 | def export_nn_archive(self, class_names: Optional[List[str]] = None): 168 | """ 169 | Export the model to NN archive format. 170 | 171 | Args: 172 | class_list (Optional[List[str]], optional): List of class names. Defaults to None. 173 | """ 174 | names = list(self.model.names.values()) 175 | 176 | if class_names is not None: 177 | assert len(class_names) == len( 178 | names 179 | ), f"Number of the given class names {len(class_names)} does not match number of classes {len(names)} provided in the model!" 180 | names = class_names 181 | 182 | self.f_nn_archive = (self.output_folder / f"{self.model_name}.tar.xz").resolve() 183 | 184 | if self.mode == DETECT_MODE: 185 | self.make_nn_archive(names, self.model.model[-1].nc) 186 | elif self.mode == SEGMENT_MODE: 187 | self.make_nn_archive( 188 | names, 189 | self.model.model[-1].nc, 190 | parser="YOLOExtendedParser", 191 | # stage2_executable_path=str(self.f_stage2_onnx), 192 | # postprocessor_path=self.stage2_filename, 193 | n_prototypes=32, 194 | is_softmax=True, 195 | output_kwargs={ 196 | "mask_outputs": ["output1_masks", "output2_masks", "output3_masks"], 197 | "protos_outputs": "protos_output", 198 | }, 199 | ) 200 | elif self.mode == OBB_MODE: 201 | self.make_nn_archive( 202 | names, 203 | self.model.model[-1].nc, 204 | output_kwargs={"angles_outputs": ["angle_output"]}, 205 | ) 206 | elif self.mode == POSE_MODE: 207 | self.make_nn_archive( 208 | names, 209 | self.model.model[-1].nc, 210 | parser="YOLOExtendedParser", 211 | n_keypoints=17, 212 | output_kwargs={"keypoints_outputs": ["kpt_output"]}, 213 | ) 214 | elif self.mode == CLASSIFY_MODE: 215 | self.make_cls_nn_archive(names, len(self.model.names)) 216 | 217 | def make_cls_nn_archive(self, class_list: List[str], n_classes: int): 218 | """Export the model to NN archive format. 219 | 220 | Args: 221 | class_list (List[str], optional): List of class names 222 | n_classes (int): Number of classes 223 | """ 224 | archive = ArchiveGenerator( 225 | archive_name=self.model_name, 226 | save_path=str(self.output_folder), 227 | cfg_dict={ 228 | "config_version": "1.0", 229 | "model": { 230 | "metadata": { 231 | "name": self.model_name, 232 | "path": f"{self.model_name}.onnx", 233 | }, 234 | "inputs": [ 235 | { 236 | "name": "images", 237 | "dtype": DataType.FLOAT32, 238 | "input_type": InputType.IMAGE, 239 | "shape": [1, self.number_of_channels, *self.imgsz[::-1]], 240 | "preprocessing": { 241 | "mean": [0, 0, 0], 242 | "scale": [255, 255, 255], 243 | }, 244 | } 245 | ], 246 | "outputs": [ 247 | { 248 | "name": output, 249 | "dtype": DataType.FLOAT32, 250 | } 251 | for output in self.all_output_names 252 | ], 253 | "heads": [ 254 | Head( 255 | parser="ClassificationParser", 256 | metadata=HeadClassificationMetadata( 257 | is_softmax=False, 258 | n_classes=n_classes, 259 | classes=class_list, 260 | ), 261 | outputs=self.all_output_names, 262 | ) 263 | ], 264 | }, 265 | }, 266 | executables_paths=[str(self.f_onnx)], 267 | ) 268 | archive.make_archive() 269 | -------------------------------------------------------------------------------- /tools/yolov6r1/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luxonis/tools/45e4d08df9a4444c6d0b3e9f98e77ef7d8531fef/tools/yolov6r1/.DS_Store -------------------------------------------------------------------------------- /tools/yolov6r1/yolov6_r1_exporter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import sys 5 | from typing import Tuple 6 | 7 | import torch 8 | from loguru import logger 9 | 10 | from tools.modules import DetectV6R1, Exporter 11 | from tools.utils import get_first_conv2d_in_channels 12 | 13 | current_dir = os.path.dirname(os.path.abspath(__file__)) 14 | yolo_path = os.path.join(current_dir, "YOLOv6R1") 15 | sys.path.append(yolo_path) 16 | 17 | import yolov6.utils.checkpoint # noqa: E402 18 | from yolov6.layers.common import RepVGGBlock # noqa: E402 19 | 20 | 21 | # Override with your custom implementation 22 | def load_checkpoint(weights, map_location=None, inplace=True, fuse=True): 23 | """Load model from checkpoint file.""" 24 | from yolov6.utils.events import LOGGER # noqa: E402 25 | from yolov6.utils.torch_utils import fuse_model # noqa: E402 26 | 27 | LOGGER.info("Loading checkpoint from {}".format(weights)) 28 | ckpt = torch.load(weights, map_location=map_location, weights_only=False) # load 29 | model = ckpt["ema" if ckpt.get("ema") else "model"].float() 30 | if fuse: 31 | LOGGER.info("\nFusing model...") 32 | model = fuse_model(model).eval() 33 | else: 34 | model = model.eval() 35 | return model 36 | 37 | 38 | # Replace the original function 39 | yolov6.utils.checkpoint.load_checkpoint = load_checkpoint 40 | 41 | 42 | class YoloV6R1Exporter(Exporter): 43 | def __init__( 44 | self, 45 | model_path: str, 46 | imgsz: Tuple[int, int], 47 | use_rvc2: bool, 48 | ): 49 | super().__init__( 50 | model_path, 51 | imgsz, 52 | use_rvc2, 53 | subtype="yolov6", 54 | output_names=["output1_yolov6", "output2_yolov6", "output3_yolov6"], 55 | ) 56 | self.load_model() 57 | 58 | def load_model(self): 59 | # code based on export.py from YoloV5 repository 60 | # load the model 61 | model = load_checkpoint( 62 | self.model_path, map_location="cpu", inplace=True, fuse=True 63 | ) # load FP32 model 64 | 65 | for layer in model.modules(): 66 | if isinstance(layer, RepVGGBlock): 67 | layer.switch_to_deploy() 68 | 69 | if hasattr(model.detect, "obj_preds"): 70 | model.detect = DetectV6R1(model.detect) 71 | else: 72 | raise ValueError( 73 | "Error while loading model (This may be caused by trying to convert either the latest release 4.0 that isn't supported yet, or by releases 2.0 or 3.0, in which case, try to convert using the 'YoloV6 (R2, R3)' option)." 74 | ) 75 | 76 | self.num_branches = len(model.detect.grid) 77 | 78 | try: 79 | self.number_of_channels = get_first_conv2d_in_channels(model) 80 | # print(f"Number of channels: {self.number_of_channels}") 81 | except Exception as e: 82 | logger.error(f"Error while getting number of channels: {e}") 83 | 84 | # check if image size is suitable 85 | gs = 2 ** (2 + self.num_branches) # 1 = 8, 2 = 16, 3 = 32 86 | if isinstance(self.imgsz, int): 87 | self.imgsz = [self.imgsz, self.imgsz] 88 | for sz in self.imgsz: 89 | if sz % gs != 0: 90 | raise ValueError(f"Image size is not a multiple of maximum stride {gs}") 91 | 92 | # ensure correct length 93 | if len(self.imgsz) != 2: 94 | raise ValueError("Image size must be of length 1 or 2.") 95 | 96 | model.eval() 97 | self.model = model 98 | -------------------------------------------------------------------------------- /tools/yolov6r3/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luxonis/tools/45e4d08df9a4444c6d0b3e9f98e77ef7d8531fef/tools/yolov6r3/.DS_Store -------------------------------------------------------------------------------- /tools/yolov6r3/gold_yolo_exporter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import sys 5 | from typing import Tuple 6 | 7 | import torch 8 | from loguru import logger 9 | 10 | from tools.modules import DetectV6R3, Exporter 11 | from tools.utils import get_first_conv2d_in_channels 12 | 13 | current_dir = os.path.dirname(os.path.abspath(__file__)) 14 | sys.path.append(os.path.join(current_dir, "Efficient-Computing/Detection/Gold-YOLO/")) 15 | sys.path.append( 16 | os.path.join(current_dir, "Efficient-Computing/Detection/Gold-YOLO/gold_yolo/") 17 | ) 18 | sys.path.append( 19 | os.path.join(current_dir, "Efficient-Computing/Detection/Gold-YOLO/yolov6/utils/") 20 | ) 21 | 22 | import checkpoint # noqa: E402 23 | from switch_tool import switch_to_deploy # noqa: E402 24 | 25 | 26 | # Override with your custom implementation 27 | def load_checkpoint_gold_yolo(weights, map_location=None, inplace=True, fuse=True): 28 | """Load model from checkpoint file.""" 29 | from yolov6.utils.events import LOGGER # noqa: E402 30 | from yolov6.utils.torch_utils import fuse_model # noqa: E402 31 | 32 | LOGGER.info("Loading checkpoint from {}".format(weights)) 33 | ckpt = torch.load(weights, map_location=map_location, weights_only=False) # load 34 | model = ckpt["ema" if ckpt.get("ema") else "model"].float() 35 | if fuse: 36 | LOGGER.info("\nFusing model...") 37 | model = fuse_model(model).eval() 38 | else: 39 | model = model.eval() 40 | return model 41 | 42 | 43 | # Replace the original function 44 | checkpoint.load_checkpoint = load_checkpoint_gold_yolo 45 | 46 | 47 | class GoldYoloExporter(Exporter): 48 | def __init__( 49 | self, 50 | model_path: str, 51 | imgsz: Tuple[int, int], 52 | use_rvc2: bool, 53 | ): 54 | super().__init__( 55 | model_path, 56 | imgsz, 57 | use_rvc2, 58 | subtype="yolov6r2", 59 | output_names=["output1_yolov6r2", "output2_yolov6r2", "output3_yolov6r2"], 60 | ) 61 | self.load_model() 62 | 63 | def load_model(self): 64 | # Load the model 65 | model = load_checkpoint_gold_yolo(self.model_path, map_location="cpu") 66 | 67 | model.detect = DetectV6R3(model.detect, self.use_rvc2) 68 | self.num_branches = len(model.detect.grid) 69 | 70 | # switch to deploy 71 | model = switch_to_deploy(model) 72 | 73 | try: 74 | self.number_of_channels = get_first_conv2d_in_channels(model) 75 | # print(f"Number of channels: {self.number_of_channels}") 76 | except Exception as e: 77 | logger.error(f"Error while getting number of channels: {e}") 78 | 79 | # check if image size is suitable 80 | gs = 2 ** (2 + self.num_branches) # 1 = 8, 2 = 16, 3 = 32 81 | if isinstance(self.imgsz, int): 82 | self.imgsz = [self.imgsz, self.imgsz] 83 | for sz in self.imgsz: 84 | if sz % gs != 0: 85 | raise ValueError(f"Image size is not a multiple of maximum stride {gs}") 86 | 87 | # ensure correct length 88 | if len(self.imgsz) != 2: 89 | raise ValueError("Image size must be of length 1 or 2.") 90 | 91 | model.eval() 92 | self.model = model 93 | -------------------------------------------------------------------------------- /tools/yolov6r3/yolov6_r3_exporter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import sys 5 | from typing import Tuple 6 | 7 | import torch 8 | from loguru import logger 9 | 10 | from tools.modules import DetectV6R3, Exporter, YoloV6BackBone 11 | from tools.utils import get_first_conv2d_in_channels 12 | 13 | current_dir = os.path.dirname(os.path.abspath(__file__)) 14 | yolo_path = os.path.join(current_dir, "YOLOv6R3") 15 | sys.path.append(yolo_path) # noqa: E402 16 | 17 | import yolov6.utils.checkpoint # noqa: E402 18 | from yolov6.layers.common import RepVGGBlock # noqa: E402 19 | 20 | try: 21 | from yolov6.models.efficientrep import ( 22 | CSPBepBackbone, # noqa: E402 23 | CSPBepBackbone_P6, # noqa: E402 24 | EfficientRep, # noqa: E402 25 | EfficientRep6, # noqa: E402 26 | ) 27 | except Exception as e: 28 | raise ImportError( 29 | "Error while importing EfficientRep, CSPBepBackbone, CSPBepBackbone_P6 or EfficientRep6: {e}" 30 | ) from e 31 | 32 | 33 | # Override with your custom implementation 34 | def load_checkpoint(weights, map_location=None, inplace=True, fuse=True): 35 | """Load model from checkpoint file.""" 36 | from yolov6.utils.events import LOGGER # noqa: E402 37 | from yolov6.utils.torch_utils import fuse_model # noqa: E402 38 | 39 | LOGGER.info("Loading checkpoint from {}".format(weights)) 40 | ckpt = torch.load(weights, map_location=map_location, weights_only=False) # load 41 | model = ckpt["ema" if ckpt.get("ema") else "model"].float() 42 | if fuse: 43 | LOGGER.info("\nFusing model...") 44 | model = fuse_model(model).eval() 45 | else: 46 | model = model.eval() 47 | return model 48 | 49 | 50 | # Replace the original function 51 | yolov6.utils.checkpoint.load_checkpoint = load_checkpoint 52 | 53 | 54 | class YoloV6R3Exporter(Exporter): 55 | def __init__( 56 | self, 57 | model_path: str, 58 | imgsz: Tuple[int, int], 59 | use_rvc2: bool, 60 | ): 61 | super().__init__( 62 | model_path, 63 | imgsz, 64 | use_rvc2, 65 | subtype="yolov6r2", 66 | output_names=["output1_yolov6r2", "output2_yolov6r2", "output3_yolov6r2"], 67 | ) 68 | self.load_model() 69 | 70 | def load_model(self): 71 | # Code based on export.py from YoloV5 repository 72 | # load the model 73 | model = load_checkpoint( 74 | self.model_path, 75 | map_location="cpu", 76 | inplace=True, 77 | fuse=True, 78 | ) # load FP32 model 79 | 80 | for layer in model.modules(): 81 | if isinstance(layer, RepVGGBlock): 82 | layer.switch_to_deploy() 83 | 84 | for n, module in model.named_children(): 85 | if isinstance(module, EfficientRep) or isinstance(module, CSPBepBackbone): 86 | setattr(model, n, YoloV6BackBone(module)) 87 | elif isinstance(module, EfficientRep6): 88 | setattr(model, n, YoloV6BackBone(module, uses_6_erblock=True)) 89 | elif isinstance(module, CSPBepBackbone_P6): 90 | setattr( 91 | model, 92 | n, 93 | YoloV6BackBone(module, uses_fuse_P2=False, uses_6_erblock=True), 94 | ) 95 | 96 | if not hasattr(model.detect, "obj_preds"): 97 | model.detect = DetectV6R3(model.detect, self.use_rvc2) 98 | 99 | self.num_branches = len(model.detect.grid) 100 | 101 | try: 102 | self.number_of_channels = get_first_conv2d_in_channels(model) 103 | # print(f"Number of channels: {self.number_of_channels}") 104 | except Exception as e: 105 | logger.error(f"Error while getting number of channels: {e}") 106 | 107 | # check if image size is suitable 108 | gs = 2 ** (2 + self.num_branches) # 1 = 8, 2 = 16, 3 = 32 109 | if isinstance(self.imgsz, int): 110 | self.imgsz = [self.imgsz, self.imgsz] 111 | for sz in self.imgsz: 112 | if sz % gs != 0: 113 | raise ValueError(f"Image size is not a multiple of maximum stride {gs}") 114 | 115 | # ensure correct length 116 | if len(self.imgsz) != 2: 117 | raise ValueError("Image size must be of length 1 or 2.") 118 | 119 | model.eval() 120 | self.model = model 121 | -------------------------------------------------------------------------------- /tools/yolov7/yolov7_exporter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import sys 5 | from typing import List, Optional, Tuple 6 | 7 | import torch 8 | import torch.nn as nn 9 | from loguru import logger 10 | 11 | from tools.modules import DetectV7, Exporter 12 | from tools.utils import get_first_conv2d_in_channels 13 | 14 | current_dir = os.path.dirname(os.path.abspath(__file__)) 15 | yolo_path = os.path.join(current_dir, "yolov7") 16 | sys.path.append(yolo_path) 17 | 18 | import models.experimental # noqa: E402 19 | 20 | 21 | def attempt_load(weights, map_location=None): 22 | from models.common import Conv # noqa: E402 23 | from utils.google_utils import attempt_download # noqa: E402 24 | 25 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a 26 | model = models.experimental.Ensemble() 27 | for w in weights if isinstance(weights, list) else [weights]: 28 | attempt_download(w) 29 | ckpt = torch.load(w, map_location=map_location, weights_only=False) # load 30 | model.append( 31 | ckpt["ema" if ckpt.get("ema") else "model"].float().fuse().eval() 32 | ) # FP32 model 33 | 34 | # Compatibility updates 35 | for m in model.modules(): 36 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]: 37 | m.inplace = True # pytorch 1.7.0 compatibility 38 | elif type(m) is nn.Upsample: 39 | m.recompute_scale_factor = None # torch 1.11.0 compatibility 40 | elif type(m) is Conv: 41 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility 42 | 43 | if len(model) == 1: 44 | return model[-1] # return model 45 | else: 46 | print("Ensemble created with %s\n" % weights) 47 | for k in ["names", "stride"]: 48 | setattr(model, k, getattr(model[-1], k)) 49 | return model # return ensemble 50 | 51 | 52 | models.experimental.attempt_load = attempt_load 53 | 54 | 55 | class YoloV7Exporter(Exporter): 56 | def __init__( 57 | self, 58 | model_path: str, 59 | imgsz: Tuple[int, int], 60 | use_rvc2: bool, 61 | ): 62 | super().__init__( 63 | model_path, 64 | imgsz, 65 | use_rvc2, 66 | subtype="yolov7", 67 | output_names=["output1_yolov7", "output2_yolov7", "output3_yolov7"], 68 | ) 69 | self.load_model() 70 | 71 | def load_model(self): 72 | # code based on export.py from YoloV5 repository 73 | # load the model 74 | model = attempt_load(self.model_path, map_location="cpu") 75 | # check num classes and labels 76 | assert model.nc == len( 77 | model.names 78 | ), f"Model class count {model.nc} != len(names) {len(model.names)}" 79 | 80 | if hasattr(model, "module"): 81 | model.module.model[-1] = DetectV7(model.module.model[-1]) 82 | # self.number_of_channels = model.module.model[0].conv.in_channels 83 | else: 84 | model.model[-1] = DetectV7(model.model[-1]) 85 | # self.number_of_channels = model.model[0].conv.in_channels 86 | 87 | try: 88 | self.number_of_channels = get_first_conv2d_in_channels(model) 89 | # print(f"Number of channels: {self.number_of_channels}") 90 | except Exception as e: 91 | logger.error(f"Error while getting number of channels: {e}") 92 | 93 | # check if image size is suitable 94 | gs = int(max(model.stride)) # grid size (max stride) 95 | if isinstance(self.imgsz, int): 96 | self.imgsz = [self.imgsz, self.imgsz] 97 | for sz in self.imgsz: 98 | if sz % gs != 0: 99 | raise ValueError(f"Image size is not a multiple of maximum stride {gs}") 100 | 101 | # ensure correct length 102 | if len(self.imgsz) != 2: 103 | raise ValueError("Image size must be of length 1 or 2.") 104 | 105 | model.eval() 106 | 107 | self.model = model 108 | 109 | self.m = model.module.model[-1] if hasattr(model, "module") else model.model[-1] 110 | self.num_branches = len(self.m.anchor_grid) 111 | 112 | def export_nn_archive(self, class_names: Optional[List[str]] = None): 113 | """ 114 | Export the model to NN archive format. 115 | 116 | Args: 117 | class_list (Optional[List[str]], optional): List of class names. Defaults to None. 118 | """ 119 | names = self.model.names 120 | 121 | if class_names is not None: 122 | assert ( 123 | len(class_names) == self.model.nc 124 | ), f"Number of the given class names {len(class_names)} does not match number of classes {self.model.nc} provided in the model!" 125 | names = class_names 126 | 127 | anchors = self.m.anchor_grid[:, 0, :, 0, 0].numpy().tolist() 128 | self.make_nn_archive( 129 | names, self.model.nc, parser="YOLOExtendedParser", anchors=anchors 130 | ) 131 | --------------------------------------------------------------------------------