# Ultralytics YOLO 🚀, GPL-3.0 license
# Publish pip package to PyPI https://pypi.org/project/ultralytics/ and Docs to https://docs.ultralytics.com

name: Publish to PyPI and Deploy Docs

on:
  push:
    branches: [main]
  workflow_dispatch:
    inputs:
      pypi:
        type: boolean
        description: Publish to PyPI
      docs:
        type: boolean
        description: Deploy Docs

jobs:
  publish:
    if: github.repository == 'ultralytics/ultralytics' && github.actor == 'glenn-jocher'
    name: Publish
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
      - name: Set up Python environment
        uses: actions/setup-python@v4
        with:
          python-version: '3.10'
          cache: 'pip' # caching pip dependencies
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip wheel build twine
          pip install -e '.[dev]' --extra-index-url https://download.pytorch.org/whl/cpu
      - name: Check PyPI version
        shell: python
        run: |
          import os
          import pkg_resources as pkg
          import ultralytics
          from ultralytics.yolo.utils.checks import check_latest_pypi_version

          v_local = pkg.parse_version(ultralytics.__version__).release
          v_pypi = pkg.parse_version(check_latest_pypi_version()).release
          print(f'Local version is {v_local}')
          print(f'PyPI version is {v_pypi}')
          d = [a - b for a, b in zip(v_local, v_pypi)]  # diff
          increment = (d[0] == d[1] == 0) and d[2] == 1  # only publish if patch version increments by 1
          os.system(f'echo "increment={increment}" >> $GITHUB_OUTPUT')
          if increment:
              print('Local version is higher than PyPI version. Publishing new version to PyPI ✅.')
        id: check_pypi
      - name: Publish to PyPI
        continue-on-error: true
        if: (github.event_name == 'push' || github.event.inputs.pypi == 'true')  && steps.check_pypi.outputs.increment == 'True'
        env:
          PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
        run: |
          python -m build
          python -m twine upload dist/* -u __token__ -p $PYPI_TOKEN
      - name: Deploy Docs
        continue-on-error: true
        if: (github.event_name == 'push' && steps.check_pypi.outputs.increment == 'True') || github.event.inputs.docs == 'true'
        env:
          PERSONAL_ACCESS_TOKEN: ${{ secrets.PERSONAL_ACCESS_TOKEN }}
        run: |
          mkdocs gh-deploy --force || true
          # git checkout gh-pages
          # git push https://$PERSONAL_ACCESS_TOKEN@github.com/ultralytics/docs gh-pages --force