# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license

# Publish pip package to PyPI https://pypi.org/project/ultralytics/

name: Publish to PyPI

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

concurrency:
  group: ${{ github.workflow }}
  queue: max

jobs:
  check:
    if: github.repository == 'ultralytics/ultralytics' && github.actor == 'glenn-jocher' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    permissions:
      contents: write
    outputs:
      increment: ${{ steps.check_pypi.outputs.increment }}
      current_tag: ${{ steps.check_pypi.outputs.current_tag }}
      previous_tag: ${{ steps.check_pypi.outputs.previous_tag }}
    steps:
      - uses: actions/checkout@v7
      - uses: ultralytics/actions/setup-uv@main
      - run: uv pip install --no-cache ultralytics-actions
      - name: Check PyPI version and publish flag
        id: check_pypi
        shell: python
        env:
          PYPI_DISPATCH: ${{ github.event.inputs.pypi }}
        run: |
          import os
          from actions.utils import check_pypi_version
          local_version, online_version, publish = check_pypi_version()
          publish = publish or os.environ.get("PYPI_DISPATCH") == "true"  # manual recovery re-run
          os.system(f'echo "increment={publish}" >> $GITHUB_OUTPUT')
          os.system(f'echo "current_tag=v{local_version}" >> $GITHUB_OUTPUT')
          if online_version != local_version:  # empty on recovery re-runs so summarize falls back to the true previous tag
              os.system(f'echo "previous_tag=v{online_version}" >> $GITHUB_OUTPUT')
          if publish:
              print('Ready to publish new version to PyPI ✅.')
      - name: Tag and Release
        if: steps.check_pypi.outputs.increment == 'True'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          CURRENT_TAG: ${{ steps.check_pypi.outputs.current_tag }}
          PREVIOUS_TAG: ${{ steps.check_pypi.outputs.previous_tag }}
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          if [ -z "$(git ls-remote --tags origin "refs/tags/$CURRENT_TAG")" ]; then
            git config --global user.name "UltralyticsAssistant"
            git config --global user.email "web@ultralytics.com"
            git tag -a "$CURRENT_TAG" -m "$(git log -1 --pretty=%B)"
            git push origin "$CURRENT_TAG"
          fi
          if ! gh release view "$CURRENT_TAG" >/dev/null 2>&1; then
            [ -n "$PREVIOUS_TAG" ] || git fetch --unshallow --tags # summarize resolves the previous tag from git history
            ultralytics-actions-summarize-release
          fi
          uv cache prune --ci

  build:
    needs: check
    if: needs.check.outputs.increment == 'True'
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v7
      - uses: ultralytics/actions/setup-uv@main
      - name: Build ultralytics
        run: uv build --out-dir dist/
      - name: Build ultralytics-opencv-headless
        run: |
          python - <<'PY'
          from pathlib import Path

          path = Path("pyproject.toml")
          text = path.read_text()
          text = text.replace('name = "ultralytics"', 'name = "ultralytics-opencv-headless"', 1)
          text = "\n".join(
              (
                  'description = "Ultralytics YOLO 🚀 for SOTA computer vision in server, container, and headless environments."'
                  if line.startswith("description = ")
                  else line
              )
              for line in text.splitlines()
          ) + "\n"
          text = text.replace('"opencv-python>=', '"opencv-python-headless>=', 1)
          path.write_text(text)
          PY
          uv build --out-dir dist/
          git checkout pyproject.toml
      - uses: actions/upload-artifact@v7
        with:
          name: dist
          path: dist/
      - run: uv cache prune --ci

  publish:
    needs: [check, build]
    if: needs.check.outputs.increment == 'True'
    runs-on: ubuntu-latest
    environment: # for GitHub Deployments tab
      name: Release - PyPI
      url: https://pypi.org/p/ultralytics
    permissions:
      id-token: write # for PyPI trusted publishing
    steps:
      - uses: actions/download-artifact@v8
        with:
          name: dist
          path: dist/
      - uses: pypa/gh-action-pypi-publish@release/v1
        id: publish
        continue-on-error: true
        with:
          skip-existing: true # tolerate recovery re-runs after partial failures
      - name: Clean partial attestations # leftover *.publish.attestation files make the retry fail pre-existence checks
        if: steps.publish.outcome == 'failure'
        run: |
          rm -f dist/*.publish.attestation
          sleep 120
      - name: Retry publish # transient sigstore/Rekor or PyPI network failures
        id: retry
        if: steps.publish.outcome == 'failure'
        continue-on-error: true
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          skip-existing: true
      - name: Clean partial attestations before final retry # PyPI 502 outages can outlast the first retry
        if: steps.retry.outcome == 'failure'
        run: |
          rm -f dist/*.publish.attestation
          sleep 600
      - name: Final retry publish
        if: steps.retry.outcome == 'failure'
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          skip-existing: true

  sbom:
    needs: [check, build, publish]
    if: needs.check.outputs.increment == 'True'
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v7
      - uses: ultralytics/actions/setup-uv@main
        with:
          python-version: "3.14"
      - run: uv pip install -e .
      - uses: anchore/sbom-action@v0
        with:
          format: spdx-json
          output-file: sbom.spdx.json
          path: ${{ env.VIRTUAL_ENV }}
        env:
          SYFT_SOURCE_NAME: ${{ github.repository }} # name the SBOM after the repo, not the venv path
      - run: gh release upload ${{ needs.check.outputs.current_tag }} sbom.spdx.json --clobber
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  notify:
    needs: [check, publish, sbom]
    if: always() && needs.check.outputs.increment == 'True'
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Get release title
        id: release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GH_REPO: ${{ github.repository }}
          TAG: ${{ needs.check.outputs.current_tag }}
        run: |
          TITLE=$(gh release view "$TAG" --json name -q .name 2>/dev/null | tr -d '\n\r"\\') || TITLE=""
          TITLE=$(printf '%s' "$TITLE" | sed -E "s@#([0-9]+)@<https://github.com/$GH_REPO/pull/\1|#\1>@g")
          echo "title=$TITLE" >> "$GITHUB_OUTPUT"
      - name: Notify Success
        if: needs.publish.result == 'success' && needs.sbom.result == 'success' && github.event_name == 'push'
        uses: slackapi/slack-github-action@v4.0.0
        with:
          webhook-type: incoming-webhook
          webhook: ${{ secrets.SLACK_WEBHOOK_URL_YOLO }}
          payload: |
            text: "<!subteam^S082BPCRAJ3> *${{ github.workflow }}* ✅ `${{ github.repository }}` ${{ steps.release.outputs.title || needs.check.outputs.current_tag }}  <https://github.com/${{ github.repository }}/releases/tag/${{ needs.check.outputs.current_tag }}|*Release*>  ·  <https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}|*Run*>"
      - name: Notify Failure # automatic first attempts only; manual dispatches and re-runs stay quiet
        if: (needs.publish.result != 'success' || needs.sbom.result != 'success') && github.event_name == 'push' && github.run_attempt == '1'
        uses: slackapi/slack-github-action@v4.0.0
        with:
          webhook-type: incoming-webhook
          webhook: ${{ secrets.SLACK_WEBHOOK_URL_YOLO }}
          payload: |
            text: "<!subteam^S082BPCRAJ3> *${{ github.workflow }}* ❌ `${{ github.repository }}` ${{ needs.check.outputs.current_tag }}  <https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}|*Run*>"
