Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[PyOV] Migrate from pre-commit git hook to automatic PR for stubs generation (#30744)

Przemyslaw Wysocki72f7800af0b0
diff --git a/.github/actions/validate_pyi_files/action.yml b/.github/actions/validate_pyi_files/action.yml
deleted file mode 100644
index a3c5065535c..00000000000
--- a/.github/actions/validate_pyi_files/action.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-name: 'Verify that Python stub .pyi files are up to date'
-description: 'Generates .pyi files and compares them to the committed files'
-runs:
- using: 'composite'
- steps:
- - name: Verify .pyi files
- shell: bash
- if: runner.os != 'Windows'
- run: |
- python3 action_root/src/bindings/python/scripts/generate_pyapi_stubs.py \
- "${{ runner.temp }}/generated_pyi_files"
- python3 action_root/.github/actions/validate_pyi_files/compare_pyi_files.py \
- "${{ runner.temp }}/generated_pyi_files" \
- "action_root/src/bindings/python/src"
diff --git a/.github/actions/validate_pyi_files/compare_pyi_files.py b/.github/actions/validate_pyi_files/compare_pyi_files.py
deleted file mode 100644
index a01b4c85a45..00000000000
--- a/.github/actions/validate_pyi_files/compare_pyi_files.py
+++ /dev/null
@@ -1,122 +0,0 @@
-# -*- coding: utf-8 -*-
-# Copyright (C) 2018-2025 Intel Corporation
-# SPDX-License-Identifier: Apache-2.0
-
-# This script is used in the CI to compare the generated .pyi files with the committed .pyi files
-
-import os
-import sys
-import filecmp
-import difflib
-
-# Due to numerous issues with stub generation reproducibility we need some skips.
-# The inconsistencies between generations most likely come from different environment/CMake setups.
-SKIPS = [
- # This file contains constant.def_buffer(), which pybind11-stubgen generates methods for on CI
- # but not locally (__buffer__(), __release_buffer__())
- "openvino/_pyopenvino/op/__init__.pyi",
-
- # The IOType class sometimes has a docstring, breaking the CI check
- "openvino/tools/ovc/moc_frontend/extractor.pyi"
-]
-
-def find_pyi_files(directory: str) -> set[str]:
- """Recursively find all .pyi files in a directory."""
- pyi_files: list[str] = []
- for root, _, files in os.walk(directory):
- for file in files:
- if file.endswith(".pyi"):
- relative_path = os.path.relpath(os.path.join(root, file), directory)
- pyi_files.append(relative_path)
- return set(pyi_files)
-
-
-def compare_pyi_files(generated_dir: str, committed_dir: str) -> None:
- """Compare .pyi files between two directories."""
- # Find all .pyi files in both directories
- generated_files: set[str] = find_pyi_files(generated_dir)
- committed_files: set[str] = find_pyi_files(committed_dir)
-
- # Assert that the number of .pyi files matches
- if len(generated_files) != len(committed_files):
- # TF FE stubs can be generated on not depending on the CMake flags in CI
- committed_files = {file for file in committed_files if not file.startswith("openvino/frontend/tensorflow")}
-
- # Check again after removal
- if len(generated_files) != len(committed_files):
- print(f"Error: Number of .pyi files does not match. "
- f"Generated (reference): {len(generated_files)}, Committed: {len(committed_files)}")
- if generated_files - committed_files:
- print(f"Files found only in generated (reference) files: {generated_files - committed_files}")
- if committed_files - generated_files:
- print(f"Files found only in committed files: {committed_files - generated_files}")
- sys.exit(1)
-
- # Assert that each file has a pair
- if generated_files != committed_files:
- if generated_files - committed_files:
- print(f"Error: One or more .pyi files are missing from the PR: {generated_files - committed_files}")
- if committed_files - generated_files:
- print(f"Error: One or more extra .pyi files are present in the PR: {committed_files - generated_files}")
- sys.exit(1)
-
- # Compare file contents
- outdated_files = []
- for relative_path in generated_files:
- if relative_path in SKIPS:
- continue
- generated_file: str = os.path.join(generated_dir, relative_path)
- committed_file: str = os.path.join(committed_dir, relative_path)
- if not filecmp.cmp(generated_file, committed_file, shallow=False):
- with open(generated_file, 'r') as gen_file, open(committed_file, 'r') as com_file:
- gen_lines = [line.lstrip() for line in gen_file.readlines()]
- com_lines = [line.lstrip() for line in com_file.readlines()]
- diff = list(difflib.unified_diff(
- gen_lines, com_lines,
- fromfile=f"Generated: {relative_path}",
- tofile=f"Committed: {relative_path}",
- lineterm=''
- ))
- if diff:
- changes = [
- line.lstrip('+- ') for line in diff
- if line.startswith(('+', '-')) # Changes only
- and not line.startswith(('+++ Committed:', '--- Generated:')) # Disregard diff headers
- ]
- if changes and not all(
- change.startswith(("import", "from", "__all__")) or # Import order is irrelevant
- change.startswith('"""') or # Ignore docstring changes
- change.strip() == "" # Ignore whitespace-only changes
- for change in changes
- ):
- outdated_files.append((relative_path, "".join(diff)))
-
- # Display all outdated files and their diffs
- if outdated_files:
- print("Error: The following stub files are outdated:")
- for relative_path, diff in outdated_files:
- print(f"\nOutdated file: {relative_path}")
- print(diff)
- sys.exit(1)
-
- print("All .pyi files match.")
- sys.exit(0)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print("Usage: python compare_pyi_files.py <generated_dir> <committed_dir>")
- sys.exit(1)
-
- generated_dir: str = sys.argv[1]
- committed_dir: str = sys.argv[2]
-
- if not os.path.isdir(generated_dir):
- print(f"Error: Generated directory does not exist: {generated_dir}")
- sys.exit(1)
-
- if not os.path.isdir(committed_dir):
- print(f"Error: Committed directory does not exist: {committed_dir}")
- sys.exit(1)
-
- compare_pyi_files(generated_dir, committed_dir)
diff --git a/.github/workflows/job_python_api_tests.yml b/.github/workflows/job_python_api_tests.yml
index f15ae8ca6a3..7caead73d3d 100644
--- a/.github/workflows/job_python_api_tests.yml
+++ b/.github/workflows/job_python_api_tests.yml
@@ -94,10 +94,6 @@ jobs:
- name: Install Python API tests dependencies
run: python3 -m pip install -r ${INSTALL_TEST_DIR}/bindings/python/requirements_test.txt
- - name: Verify Python stub .pyi files
- uses: ./.github/actions/validate_pyi_files
- continue-on-error: true
-
#
# Tests
#
diff --git a/.github/workflows/update_pyapi_stubs.yml b/.github/workflows/update_pyapi_stubs.yml
new file mode 100644
index 00000000000..4dd2a525bf0
--- /dev/null
+++ b/.github/workflows/update_pyapi_stubs.yml
@@ -0,0 +1,63 @@
+name: Update Python API Stubs
+
+permissions:
+ contents: write
+ pull-requests: write
+
+on:
+ schedule:
+ - cron: "0 2 * * 1-5"
+ workflow_dispatch: # Allow manual triggering
+
+jobs:
+ update-stubs:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+
+ - name: Set up Python
+ uses: actions/setup-python@0ae58361cdfd39e2950bed97a1e26aa20c3d8955 # v4
+ with:
+ python-version: '3.10'
+
+ - name: Get latest OpenVINO artifacts
+ id: openvino_download
+ uses: openvinotoolkit/openvino/.github/actions/openvino_provider@master
+ with:
+ platform: 'ubuntu22'
+ revision: latest_available_commit
+
+ - name: Install OpenVINO and stubgen
+ run: |
+ python -m pip install openvino==${{ steps.openvino_download.outputs.ov_version }} ${{ steps.openvino_download.outputs.ov_wheel_source }}
+ STUBGEN_VERSION=$(grep pybind11-stubgen src/bindings/python/requirements_test.txt)
+ python -m pip install "$STUBGEN_VERSION"
+
+ - name: Regenerate Python API stubs
+ run: |
+ find ./ -name "*.pyi" -delete
+ python src/bindings/python/scripts/generate_pyapi_stubs.py
+
+ - name: Add and commit .pyi files
+ run: |
+ git config --local user.email "[email protected]"
+ git config --local user.name "GitHub Action"
+ find src/bindings/python -name "*.pyi" -exec git add {} \;
+ git diff --quiet && git diff --staged --quiet || git commit -m "Update Python API stub files"
+
+ - name: Create Pull Request
+ uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ commit-message: Update Python API stub files
+ title: "[PyOV] Update Python API stub files"
+ signoff: true
+ sign-commits: true
+ reviewers: openvinotoolkit/openvino-ie-python-api-maintainers
+ body: |
+ - Updated Python API stub (.pyi) files from the latest available artifacts
+
+ Auto-generated by GitHub Actions
+ branch: update-pyapi-stubs
+ base: master
diff --git a/src/bindings/python/CMakeLists.txt b/src/bindings/python/CMakeLists.txt
index 03ae9d18c69..12acbc0af42 100644
--- a/src/bindings/python/CMakeLists.txt
+++ b/src/bindings/python/CMakeLists.txt
@@ -416,6 +416,7 @@ if(OpenVINODeveloperPackage_FOUND)
endif()
# only for developers, skip on CI
+# to be removed once developers remove hook from their .git: CVS-168334
if(NOT (DEFINED ENV{CI} OR DEFINED ENV{TF_BUILD} OR DEFINED ENV{JENKINS_URL}))
# check pybind11-stubgen package
@@ -436,15 +437,15 @@ if(NOT (DEFINED ENV{CI} OR DEFINED ENV{TF_BUILD} OR DEFINED ENV{JENKINS_URL}))
message(WARNING "pre-commit package is not installed or version is not detected. This package is necessary for developing Python API.")
endif()
- # attach the pre-commit hook for Python stub generation
- execute_process(COMMAND pre-commit install -c "${CMAKE_CURRENT_SOURCE_DIR}/scripts/stub_generation_precommit.yaml"
- RESULT_VARIABLE precommit_install_result
- ERROR_VARIABLE precommit_install_error
+ # uninstall the pre-commit hook for Python stub generation (now handled by GitHub Actions)
+ execute_process(COMMAND pre-commit uninstall
+ RESULT_VARIABLE precommit_uninstall_result
+ ERROR_VARIABLE precommit_uninstall_error
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_STRIP_TRAILING_WHITESPACE)
- if(NOT precommit_install_result EQUAL "0")
- message(WARNING "Python stub generation pre-commit hook install failed with error: ${precommit_install_error}. It is necessary for developing Python API.")
+ if(NOT precommit_uninstall_result EQUAL "0")
+ message(WARNING "Failed to uninstall Python stub generation pre-commit hook: ${precommit_uninstall_error}")
else()
- message(STATUS "pre-commit hook for Python API stub generation has been installed")
+ message(STATUS "Pre-commit hook for Python API stub generation has been uninstalled. Stubs are now generated by GitHub Actions workflow.")
endif()
endif()
diff --git a/src/bindings/python/docs/stubs.md b/src/bindings/python/docs/stubs.md
index fdb87d284fe..42b53da35ec 100644
--- a/src/bindings/python/docs/stubs.md
+++ b/src/bindings/python/docs/stubs.md
@@ -6,20 +6,9 @@ Stub files (`.pyi`) are used to provide type hints for Python code. They describ
## Automation of stub file generation in OpenVINO
-In OpenVINO, the generation of stub files is automated as part of the development workflow. When building the Python API for the first time, a Git pre-commit hook is installed into the OpenVINO repository's `.git` directory. The related Python dependencies are `pybind11-stubgen` for stub generation and `pre-commit` for automating git hooks.
+In OpenVINO, the generation of stub files is automated as part of the development workflow. This is now handled by a GitHub Actions workflow that runs on a schedule (weekdays at 2:00 AM UTC) and can be triggered manually when needed. The workflow is defined in [.github/workflows/update_pyapi_stubs.yml](../../../../.github/workflows/update_pyapi_stubs.yml). The related Python dependency is `pybind11-stubgen` for stub generation.
-### What is a git pre-commit hook?
-
-A Git pre-commit hook is a script that runs automatically before a commit is finalized. It allows developers to enforce specific checks or perform automated tasks, such as code formatting, linting, or file generation, ensuring that the repository maintains a consistent and high-quality state.
-
-### What happens during the pre-commit hook?
-
-When the pre-commit hook is triggered, the following steps occur:
-
-1. **Stub file generation**: The `pybind11-stubgen` tool is executed to generate new `.pyi` stub files for the OpenVINO Python API. This tool uses the Python package `openvino` to extract type information and create the stub files, so it's important that currently installed OpenVINO version contains all changes related to your Pull Request.
-2. **Automatic addition to commit**: The newly generated `.pyi` files are automatically staged and added to the current commit. This ensures that the stub files are always up-to-date with the latest changes in the Python API.
-
-### Ensuring changes are installed
+### Running stub generation manually
To ensure that `pybind11-stubgen` works correctly, the `openvino` Python package must include your latest changes. This can be achieved by:
@@ -31,23 +20,10 @@ To ensure that `pybind11-stubgen` works correctly, the `openvino` Python package
- Installing an up-to-date wheel containing your changes using `pip install`.
-### Skipping the pre-commit hook
-
-If you need to skip the pre-commit hook for any reason, you can do so by setting the `SKIP` environment variable before running the `git commit` command:
-
-```bash
-SKIP=generate_stubs git commit -m "Your commit message"
-```
-
-This bypasses the stub file generation process, allowing you to commit without triggering the hook.
-
-### Uninstalling the pre-commit hook
-
-If you wish to remove the hook, you can run:
-
-```bash
-pre-commit uninstall
-```
+Then, to run stub generation manually, ensure your changes are installed and run:
+ ```bash
+ python openvino/src/bindings/python/scripts/generate_pyapi_stubs.py
+ ```
## See also
diff --git a/src/bindings/python/scripts/stub_generation_precommit.yaml b/src/bindings/python/scripts/stub_generation_precommit.yaml
deleted file mode 100644
index af55159bf3a..00000000000
--- a/src/bindings/python/scripts/stub_generation_precommit.yaml
+++ /dev/null
@@ -1,18 +0,0 @@
-repos:
- - repo: local
- hooks:
- - id: generate_stubs
- name: Generate .pyi files
- language: system
- entry: >
- bash -c '
- $(which python) "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/src/bindings/python/scripts/generate_pyapi_stubs.py";
- if [ $? -ne 0 ]; then
- echo "Stub generation failed. Aborting commit.";
- exit 1;
- fi;
- git add ./*.pyi'
- files: .*src/bindings/python/.*|.*tools/ovc.*
- pass_filenames: false
- verbose: true
- stages: [pre-commit]