From 206adc083cde1cc9041a559244d38f0500f2f946 Mon Sep 17 00:00:00 2001 From: Jirka Borovec <6035284+Borda@users.noreply.github.com> Date: Mon, 20 Jul 2026 13:35:46 +0200 Subject: [PATCH] ci: add doctest fence hook (#2447) * ci: add doctest fence hook * docs: fence source doctests --------- Co-authored-by: Codex Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .github/scripts/check_doctest_fences.py | 109 ++++++++++++++++++ .pre-commit-config.yaml | 8 ++ src/supervision/dataset/formats/coco.py | 3 + src/supervision/detection/core.py | 15 +++ src/supervision/detection/utils/boxes.py | 3 + src/supervision/detection/utils/internal.py | 6 + .../detection/utils/iou_and_nms.py | 9 ++ src/supervision/detection/utils/masks.py | 3 + src/supervision/detection/utils/polygons.py | 3 + src/supervision/key_points/core.py | 9 ++ 10 files changed, 168 insertions(+) create mode 100644 .github/scripts/check_doctest_fences.py diff --git a/.github/scripts/check_doctest_fences.py b/.github/scripts/check_doctest_fences.py new file mode 100644 index 00000000..231980b6 --- /dev/null +++ b/.github/scripts/check_doctest_fences.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Validate doctest prompt formatting in source docstrings.""" + +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +DOCTEST_PROMPT_RE = re.compile(r"^\s*>>>") +FENCE_RE = re.compile(r"^\s*```(?P[A-Za-z0-9_-]*)\s*$") + + +def _check_content(content: str, path: Path) -> list[str]: + r"""Return doctest fence violations for file content. + + Examples: + ```pycon + >>> from pathlib import Path + >>> _check_content('```pycon\n>>> len([1])\n1\n\n```\n', Path('src/a.py')) + [] + >>> _check_content('>>> len([1])\n1\n', Path('src/a.py')) + ['src/a.py:1: doctest prompt must be inside a ```pycon fenced block'] + >>> violations = _check_content( + ... '```pycon\n>>> len([1])\n1\n```\n', Path('src/a.py') + ... ) + >>> violations == [ + ... 'src/a.py:4: pycon doctest block must include exactly one blank line ' + ... 'before the closing fence' + ... ] + True + + ``` + """ + violations: list[str] = [] + active_fence_language: str | None = None + in_invalid_doctest_block = False + line_before_previous = "" + previous_line = "" + + for line_number, line in enumerate(content.splitlines(), start=1): + fence_match = FENCE_RE.match(line) + if fence_match is not None: + in_invalid_doctest_block = False + if active_fence_language is None: + active_fence_language = fence_match.group("language") + else: + has_exactly_one_blank_line = ( + previous_line.strip() == "" and line_before_previous.strip() != "" + ) + if active_fence_language == "pycon" and not has_exactly_one_blank_line: + violations.append( + f"{path}:{line_number}: pycon doctest block must include " + "exactly one blank line before the closing fence" + ) + active_fence_language = None + line_before_previous = previous_line + previous_line = line + continue + + if not line.strip(): + in_invalid_doctest_block = False + + if ( + DOCTEST_PROMPT_RE.match(line) + and active_fence_language != "pycon" + and not in_invalid_doctest_block + ): + violations.append( + f"{path}:{line_number}: doctest prompt must be inside a " + "```pycon fenced block" + ) + in_invalid_doctest_block = True + + line_before_previous = previous_line + previous_line = line + + return violations + + +def check_file(path: Path) -> list[str]: + """Return doctest fence violations for a single source file.""" + if not path.is_file() or path.suffix != ".py" or "src" not in path.parts: + return [] + + return _check_content(content=path.read_text(encoding="utf-8"), path=path) + + +def main() -> int: + """Run the doctest fence check for pre-commit supplied files.""" + parser = argparse.ArgumentParser( + description="Validate doctest prompts in src/ are fenced as pycon blocks." + ) + parser.add_argument("files", nargs="*", type=Path) + args = parser.parse_args() + + violations = [ + violation for path in args.files for violation in check_file(path=path) + ] + if violations: + print("\n".join(violations)) + return 1 + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 237917e8..bef82826 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -8,6 +8,14 @@ ci: autoupdate_commit_msg: "chore(pre_commit): ⬆ pre_commit autoupdate" repos: + - repo: local + hooks: + - id: check-doctest-fences + name: check doctest fences + entry: python .github/scripts/check_doctest_fences.py + language: python + files: ^src/.*\.py$ + - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 hooks: diff --git a/src/supervision/dataset/formats/coco.py b/src/supervision/dataset/formats/coco.py index 231e6f23..f5888ff6 100644 --- a/src/supervision/dataset/formats/coco.py +++ b/src/supervision/dataset/formats/coco.py @@ -416,6 +416,7 @@ def get_coco_class_index_mapping(annotations_path: str) -> dict[int, int]: to original COCO class id (1 to 90 with skipped ids). Examples: + ```pycon >>> import json >>> import os >>> import tempfile @@ -443,6 +444,8 @@ def get_coco_class_index_mapping(annotations_path: str) -> dict[int, int]: {0: 1, 1: 3} >>> os.path.exists(annotations_path) False + + ``` """ coco_data = read_json_file(annotations_path) classes = coco_categories_to_classes(coco_categories=coco_data["categories"]) diff --git a/src/supervision/detection/core.py b/src/supervision/detection/core.py index ef93548c..d9f4c835 100644 --- a/src/supervision/detection/core.py +++ b/src/supervision/detection/core.py @@ -2260,10 +2260,13 @@ class Detections: An empty Detections object. Example: + ```pycon >>> from supervision import Detections >>> empty_detections = Detections.empty() >>> empty_detections.xyxy.shape (0, 4) + + ``` """ return cls( xyxy=np.empty((0, 4), dtype=np.float32), @@ -2353,6 +2356,7 @@ class Detections: `image_shape` when mixing mask types. Example: + ```pycon >>> import numpy as np >>> import supervision as sv >>> detections_1 = sv.Detections( @@ -2375,6 +2379,8 @@ class Detections: >>> merged_detections.data['feature_vector'] array([0.1, 0.2, 0.3]) + ``` + Compact mask merge example: ```python @@ -2605,6 +2611,7 @@ class Detections: The stored data value, or `None` when the key is absent. Example: + ```pycon >>> import numpy as np >>> from supervision import Detections >>> detections = Detections( @@ -2613,6 +2620,8 @@ class Detections: ... ) >>> detections.get_data("class_name").tolist() ['cat'] + + ``` """ return self.data.get(key) @@ -2631,11 +2640,14 @@ class Detections: even when the selection is empty or the input has zero detections. Example: + ```pycon >>> import numpy as np >>> from supervision import Detections >>> detections = Detections(xyxy=np.array([[0, 0, 1, 1], [1, 1, 2, 2]])) >>> detections.select([1]).xyxy.tolist() [[1, 1, 2, 2]] + + ``` """ mask: npt.NDArray[np.bool_] | CompactMask | None if len(self) == 0: @@ -2808,6 +2820,7 @@ class Detections: where n is the number of detections. Example: + ```pycon >>> import numpy as np >>> import supervision as sv >>> corners = np.array( @@ -2834,6 +2847,8 @@ class Detections: ... ) >>> detections.area array([ 9, 25]) + + ``` """ if self.mask is not None: if isinstance(self.mask, CompactMask): diff --git a/src/supervision/detection/utils/boxes.py b/src/supervision/detection/utils/boxes.py index 767fce59..d97b0a65 100644 --- a/src/supervision/detection/utils/boxes.py +++ b/src/supervision/detection/utils/boxes.py @@ -258,11 +258,14 @@ def obb_polygon_area(corners: npt.NDArray[np.number]) -> npt.NDArray[np.float64] ValueError: If `corners` does not have shape `(N, 4, 2)`. Examples: + ```pycon >>> import numpy as np >>> from supervision.detection.utils.boxes import obb_polygon_area >>> corners = np.array([[[0, 5], [5, 10], [10, 5], [5, 0]]], dtype=np.float32) >>> obb_polygon_area(corners) array([50.]) + + ``` """ corners = cast(npt.NDArray[np.number], np.asarray(corners)) if corners.ndim != 3 or corners.shape[-2:] != (4, 2): diff --git a/src/supervision/detection/utils/internal.py b/src/supervision/detection/utils/internal.py index a4c2266a..c4f6c8bd 100644 --- a/src/supervision/detection/utils/internal.py +++ b/src/supervision/detection/utils/internal.py @@ -327,11 +327,14 @@ def process_roboflow_result( tracker IDs are dropped to preserve alignment with ``xyxy``. Examples: + ```pycon >>> from supervision.detection.utils.internal import process_roboflow_result >>> result = {"predictions": [], "image": {"width": 100, "height": 100}} >>> _, _, _, _, _, data = process_roboflow_result(result) >>> data["class_name"].dtype.kind 'U' + + ``` """ if not roboflow_result["predictions"]: return ( @@ -705,6 +708,7 @@ def cross_product( negative = to the right; zero = on the line. Examples: + ```pycon >>> import numpy as np >>> from supervision.geometry.core import Point, Vector >>> anchors = np.array([[[10.0, 5.0]], [[20.0, 5.0]]]) @@ -712,6 +716,8 @@ def cross_product( >>> cross_product(anchors, vector) array([[5.], [5.]]) + + ``` """ vector_at_zero = np.array( [ diff --git a/src/supervision/detection/utils/iou_and_nms.py b/src/supervision/detection/utils/iou_and_nms.py index 4534bb5e..6ea01fe3 100644 --- a/src/supervision/detection/utils/iou_and_nms.py +++ b/src/supervision/detection/utils/iou_and_nms.py @@ -504,12 +504,15 @@ def oriented_box_iou_batch( :attr:`~supervision.config.OverlapMetric.IOS`. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> a = np.array([[[0, 0], [2, 0], [2, 2], [0, 2]]], dtype=np.float32) >>> b = np.array([[[1, 0], [3, 0], [3, 2], [1, 2]]], dtype=np.float32) >>> sv.oriented_box_iou_batch(a, b) # doctest: +ELLIPSIS array([[0.333...]]) + + ``` """ for name, arr in (("boxes_true", boxes_true), ("boxes_detection", boxes_detection)): @@ -1426,6 +1429,7 @@ def oriented_box_non_max_suppression( mismatched lengths or invalid shapes. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> oriented_boxes = np.array([ @@ -1443,6 +1447,8 @@ def oriented_box_non_max_suppression( ... ) >>> keep array([ True, False]) + + ``` """ _validate_iou_threshold(iou_threshold) for name, arr in (("predictions", predictions), ("oriented_boxes", oriented_boxes)): @@ -1549,6 +1555,7 @@ def oriented_box_non_max_merge( mismatched lengths or invalid shapes. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> oriented_boxes = np.array([ @@ -1566,6 +1573,8 @@ def oriented_box_non_max_merge( ... ) >>> len(groups) 1 + + ``` """ for name, arr in (("predictions", predictions), ("oriented_boxes", oriented_boxes)): if name == "predictions": diff --git a/src/supervision/detection/utils/masks.py b/src/supervision/detection/utils/masks.py index 2e76d2c4..14a5b0b3 100644 --- a/src/supervision/detection/utils/masks.py +++ b/src/supervision/detection/utils/masks.py @@ -21,6 +21,7 @@ def count_mask_pixels(masks: npt.NDArray[np.bool_]) -> npt.NDArray[np.int64]: Int64 array of shape ``(N,)`` with the True-pixel count per mask. Example: + ```pycon >>> import numpy as np >>> from supervision.detection.utils.masks import count_mask_pixels >>> m = np.zeros((2, 4, 4), dtype=bool) @@ -28,6 +29,8 @@ def count_mask_pixels(masks: npt.NDArray[np.bool_]) -> npt.NDArray[np.int64]: >>> m[1, :3, :3] = True # 9 pixels >>> count_mask_pixels(m) array([4, 9]) + + ``` """ return np.fromiter( (np.count_nonzero(m) for m in masks), dtype=np.int64, count=len(masks) diff --git a/src/supervision/detection/utils/polygons.py b/src/supervision/detection/utils/polygons.py index b2545884..a71b6fdb 100644 --- a/src/supervision/detection/utils/polygons.py +++ b/src/supervision/detection/utils/polygons.py @@ -89,6 +89,7 @@ def approximate_polygon( Examples: Reduce a polygon to at most half its original point count: + ```pycon >>> import numpy as np >>> polygon = np.array([[0, 0], [10, 0], [10, 10], [0, 10], ... [5, 10], [5, 5], [3, 7], [1, 9]]) @@ -103,6 +104,8 @@ def approximate_polygon( >>> tiny = np.array([[0, 0], [5, 0], [2, 4]]) >>> approximate_polygon(tiny, percentage=0.5) is tiny True + + ``` """ if percentage < 0 or percentage >= 1: diff --git a/src/supervision/key_points/core.py b/src/supervision/key_points/core.py index e06a9c79..ce3e37a8 100644 --- a/src/supervision/key_points/core.py +++ b/src/supervision/key_points/core.py @@ -931,6 +931,7 @@ class KeyPoints: The stored data value, or `None` when the key is absent. Example: + ```pycon >>> import numpy as np >>> from supervision import KeyPoints >>> key_points = KeyPoints( @@ -939,6 +940,8 @@ class KeyPoints: ... ) >>> key_points.get_data("class_name").tolist() ['person'] + + ``` """ return self.data.get(key) @@ -958,11 +961,14 @@ class KeyPoints: A new `KeyPoints` instance containing the selected rows or anchors. Example: + ```pycon >>> import numpy as np >>> from supervision import KeyPoints >>> key_points = KeyPoints(xy=np.array([[[0, 1]], [[2, 3]]])) >>> key_points.select([1]).xy.tolist() [[[2, 3]]] + + ``` """ if isinstance(index, np.ndarray) and index.ndim == 2 and index.dtype == bool: return self._get_by_2d_bool_mask(cast(npt.NDArray[np.bool_], index)) @@ -1210,6 +1216,7 @@ class KeyPoints: same keys. Example: + ```pycon >>> import numpy as np >>> import supervision as sv >>> key_points_1 = sv.KeyPoints( @@ -1229,6 +1236,8 @@ class KeyPoints: array([0, 1]) >>> merged.data['class_name'] array(['person', 'dog'], dtype='