name: PyPI release

on:
  workflow_dispatch:
  push:
    tags:
      - v*
    branches:
      - 'v*-release'

permissions:
  contents: read

jobs:
  build-and-test:
    runs-on: ubuntu-22.04
    steps:
      - name: Checkout repo
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd  # v6.0.2

      - name: Set up Python
        uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065  # v5
        with:
          python-version: "3.10"

      - name: Install build dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -U build
          pip install -U torch --index-url https://download.pytorch.org/whl/cpu

      - name: Build the dist files
        run: python -m build

      - name: Validate dist metadata
        run: |
          pip install twine
          twine check --strict dist/*

      - name: Install from built wheel
        run: pip install dist/*.whl

      - name: Test installing diffusers and importing
        run: |
          pip install -U transformers
          uv pip uninstall tokenizers && uv pip install "tokenizers<=0.23.0"
          python -c "from diffusers import __version__; print(__version__)"
          python -c "from diffusers import DiffusionPipeline; pipe = DiffusionPipeline.from_pretrained('fusing/unet-ldm-dummy-update'); pipe()"
          python -c "from diffusers import DiffusionPipeline; pipe = DiffusionPipeline.from_pretrained('hf-internal-testing/tiny-stable-diffusion-pipe', safety_checker=None); pipe('ah suh du')"
          python -c "from diffusers import *"

      - name: Upload build artifacts
        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02  # v4
        with:
          name: python-dist
          path: dist/

  publish-to-pypi:
    needs: build-and-test
    if: startsWith(github.ref, 'refs/tags/')
    runs-on: ubuntu-latest
    environment: pypi-release
    permissions:
      id-token: write

    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd  # v6.0.2
      
      - name: Download build artifacts
        uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093  # v4
        with:
          name: python-dist
          path: dist/

      - name: Publish package distributions to TestPyPI
        uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e  # release/v1
        with:
          verbose: true
