Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs: publish llms.txt and llms-full.txt at the docs root (#3891)

Dmytro Mishkin3a7853a239a7
diff --git a/.github/scripts/check_doc_links.py b/.github/scripts/check_doc_links.py
index c300ac651..6c01db0d3 100644
--- a/.github/scripts/check_doc_links.py
+++ b/.github/scripts/check_doc_links.py
@@ -1,4 +1,22 @@
#!/usr/bin/env python3
+
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
"""Check that links in the org's markdown documents still resolve.
Written after an audit found several dead pointers in Kornia's docs that
@@ -44,9 +62,7 @@ errors: list[str] = []
notes: list[str] = []
# Things that look like an address but are not a mailbox.
-NOT_MAILBOXES = re.compile(
- r"@(?:\d+x)?\.(?:png|jpe?g|svg|gif|webp|ico)$|^git@", re.I
-)
+NOT_MAILBOXES = re.compile(r"@(?:\d+x)?\.(?:png|jpe?g|svg|gif|webp|ico)$|^git@", re.I)
COMMENT_RE = re.compile(r"<!--.*?-->", re.S)
FENCE_RE = re.compile(r"^```.*?^```", re.S | re.M)
@@ -66,18 +82,23 @@ def strip_noncontent(text: str) -> str:
def markdown_files() -> list[Path]:
+ """Collect the markdown-formatted files whose links should be checked."""
out: list[Path] = []
for p in ROOT.rglob("*.md"):
if any(part in SKIP_DIRS for part in p.parts):
continue
out.append(p)
+ # llms.txt / llms-full.txt are markdown-formatted; keep their links honest too
+ out.extend(ROOT.glob("docs/source/_extra/llms*.txt"))
return sorted(out)
def probe(url: str) -> tuple[str, object]:
- req = urllib.request.Request(url, headers={"User-Agent": UA}, method="GET")
+ """Fetch a URL and classify it as ok, dead, or unverified."""
+ # Only http/https reach this point: callers filter on the parsed scheme.
+ req = urllib.request.Request(url, headers={"User-Agent": UA}, method="GET") # noqa: S310
try:
- with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
+ with urllib.request.urlopen(req, timeout=TIMEOUT) as resp: # noqa: S310
return "ok", resp.status
except urllib.error.HTTPError as exc:
if exc.code in (404, 410):
@@ -92,7 +113,8 @@ def probe(url: str) -> tuple[str, object]:
return "unverified", type(exc).__name__
-def main() -> int:
+def main() -> int: # noqa: C901
+ """Scan the docs for dead links; return a non-zero exit code if any are found."""
# --offline skips every network probe, so pull requests get a fast,
# deterministic check. The networked run is scheduled, where a
# third-party blip costs a red cron job rather than a blocked PR.
@@ -147,10 +169,11 @@ def main() -> int:
emails.setdefault(addr, []).append(str(rel))
mode = "offline" if offline else "networked"
- print(f"{len(files)} markdown file(s), {len(external)} external link(s), "
- f"{len(emails)} email address(es) [{mode}]\n")
+ print(
+ f"{len(files)} markdown file(s), {len(external)} external link(s), {len(emails)} email address(es) [{mode}]\n"
+ )
- for url in (() if offline else sorted(external)):
+ for url in () if offline else sorted(external):
verdict, status = probe(url)
where = ", ".join(sorted(set(external[url])))
if verdict == "dead":
@@ -167,8 +190,9 @@ def main() -> int:
verdict, status = ("skipped", "-") if offline else probe(f"https://{domain}")
flag = " <-- domain does not resolve" if (verdict, status) == ("dead", "DNS") else ""
if flag:
- errors.append(f"{', '.join(sorted(set(emails[addr])))}: "
- f"email domain {domain} does not resolve ({addr})")
+ errors.append(
+ f"{', '.join(sorted(set(emails[addr])))}: email domain {domain} does not resolve ({addr})"
+ )
print(f" {addr:<40} {', '.join(sorted(set(emails[addr])))}{flag}")
if notes:
diff --git a/.github/workflows/doc-links.yml b/.github/workflows/doc-links.yml
index b76fbfb7d..4661ce3ac 100644
--- a/.github/workflows/doc-links.yml
+++ b/.github/workflows/doc-links.yml
@@ -4,6 +4,7 @@ on:
pull_request:
paths:
- '**.md'
+ - 'docs/source/_extra/llms*.txt'
- '.github/scripts/check_doc_links.py'
- '.github/workflows/doc-links.yml'
schedule:
diff --git a/.github/workflows/pr-validation.yml b/.github/workflows/pr-validation.yml
index f853f4e06..7c2976dfe 100644
--- a/.github/workflows/pr-validation.yml
+++ b/.github/workflows/pr-validation.yml
@@ -33,7 +33,26 @@ jobs:
const warnings = [];
- if (issueNumbers.length === 0) {
+ // The assignment/triage guardrails exist for external contributors;
+ // maintainers (write access or above) open PRs from their own judgment.
+ let isMaintainer = false;
+ try {
+ const { data: perm } = await github.rest.repos.getCollaboratorPermissionLevel({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ username: prAuthor
+ });
+ isMaintainer = ['admin', 'maintain', 'write'].includes(perm.permission);
+ if (isMaintainer) {
+ core.info(`@${prAuthor} has ${perm.permission} access; skipping contributor guardrails.`);
+ }
+ } catch (error) {
+ core.warning(`Could not determine permission for @${prAuthor}: ${error.message}`);
+ }
+
+ if (isMaintainer) {
+ // no warnings: fall through so any stale warning comment gets deleted
+ } else if (issueNumbers.length === 0) {
warnings.push('❌ **No linked issue found**: This PR does not reference any issue. Please link to an issue using "Fixes #123" or "Closes #123" in the PR description.');
} else {
// Check each linked issue
diff --git a/docs/source/_extra/llms-full.txt b/docs/source/_extra/llms-full.txt
new file mode 100644
index 000000000..8274852b2
--- /dev/null
+++ b/docs/source/_extra/llms-full.txt
@@ -0,0 +1,155 @@
+# Kornia β€” full reference for language models
+
+> Kornia is a differentiable computer vision library for PyTorch. Classic CV operations (color, filtering, geometric transforms, camera/epipolar geometry, augmentation) are implemented as batched, GPU-ready, autograd-friendly tensor operations. Everything is `torch.Tensor` in, `torch.Tensor` out; PyTorch is the only runtime dependency.
+
+Install: `pip install kornia`
+
+## Tensor and coordinate conventions
+
+These conventions hold library-wide; per-function docs note any exception.
+
+- **Image layout:** float tensors `(B, C, H, W)`, channel order RGB, values in `[0, 1]`. The batched 4D layout is accepted everywhere; some op families (e.g. color conversions) also take `(*, C, H, W)` with arbitrary leading dims. When unsure, use `(B, C, H, W)` β€” add the batch dim with `img[None]`.
+- **Point coordinates:** `(x, y)` order, where x indexes columns and y indexes rows. A point tensor for N points is `(B, N, 2)`.
+- **Sizes:** output sizes and `dsize` arguments are `(h, w)` order β€” the OPPOSITE axis order from points.
+- **Angles:** degrees, not radians. Positive angle = counter-clockwise rotation as displayed, with the origin at the top-left corner (OpenCV convention).
+- **Transformation matrices:** batched. Homographies are `(B, 3, 3)`, affine matrices `(B, 2, 3)`. They act on pixel coordinates unless the function name or a flag says `normalized`. To apply a `(3, 3)` matrix, add the batch dim: `M[None]`.
+- **`align_corners`:** `warp_perspective` and `warp_affine` default to `align_corners=True`; `resize` defaults to `align_corners=None` (PyTorch's native default per interpolation mode). When mixing Kornia warps with `torch.nn.functional.interpolate` or `grid_sample`, pass `align_corners` explicitly everywhere.
+- **Devices/dtypes:** ops run on whatever device/dtype the input tensors carry; there is no implicit `.cuda()` or `.float()`.
+
+## kornia.geometry β€” warps, homographies, camera geometry
+
+The differentiated core: differentiable, batched geometric transforms with no OpenCV/torchvision equivalent.
+
+Key functions:
+
+- `warp_perspective(src, M, dsize, mode="bilinear", padding_mode="zeros", align_corners=True)` β€” src `(B, C, H, W)`, M `(B, 3, 3)` pixel-coordinate homography, dsize `(h, w)`.
+- `warp_affine(src, M, dsize, ...)` β€” M `(B, 2, 3)`.
+- `get_perspective_transform(points_src, points_dst)` β€” both `(B, 4, 2)` in `(x, y)` pixel coords; returns `(B, 3, 3)` mapping src β†’ dst.
+- `get_rotation_matrix2d(center, angle, scale)` β€” center `(B, 2)` in `(x, y)`, angle `(B,)` degrees, scale `(B, 2)`; returns `(B, 2, 3)`.
+- `rotate(tensor, angle)`, `translate`, `scale`, `resize(input, size, interpolation="bilinear", align_corners=None)`.
+- Conversions: `rad2deg`, `deg2rad`, `angle_axis_to_rotation_matrix`, `rotation_matrix_to_quaternion`, and the `So3`/`Se3` Lie group classes.
+- Epipolar: `find_fundamental`, `find_essential`, `sampson_epipolar_distance`, `triangulate_points`.
+
+Example β€” warp an image with a 4-point homography:
+
+```python
+import torch
+import kornia.geometry as KG
+
+img = torch.rand(1, 3, 100, 100) # (B, C, H, W), values in [0, 1]
+# four corners, (x, y) order, pixel coordinates
+points_src = torch.tensor([[[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]]])
+points_dst = torch.tensor([[[10.0, 5.0], [90.0, 10.0], [95.0, 95.0], [5.0, 90.0]]])
+M = KG.get_perspective_transform(points_src, points_dst) # (1, 3, 3)
+out = KG.warp_perspective(img, M, dsize=(100, 100)) # dsize is (h, w)
+```
+
+## kornia.augmentation β€” batched augmentation with transform tracking
+
+`AugmentationSequential` applies the SAME sampled transform to every registered data type and can invert it. This is the correct way to keep images, masks, boxes, and keypoints consistent.
+
+```python
+import torch
+import kornia.augmentation as K
+
+aug = K.AugmentationSequential(
+ K.RandomAffine(degrees=30.0, p=1.0),
+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
+ data_keys=["input", "mask", "keypoints"],
+)
+image = torch.rand(1, 3, 64, 64)
+mask = (torch.rand(1, 1, 64, 64) > 0.5).float()
+keypoints = torch.tensor([[[16.0, 16.0], [48.0, 32.0]]]) # (B, N, 2), (x, y)
+
+img_out, mask_out, kpts_out = aug(image, mask, keypoints)
+# geometric part is inverted for all data types; color ops are skipped on masks/keypoints
+img_back, mask_back, kpts_back = aug.inverse(img_out, mask_out, kpts_out)
+```
+
+Notes:
+
+- `data_keys` order defines the positional argument order.
+- Random parameters are sampled per batch element; `p=1.0` forces application.
+- The last applied transform matrices are available via `aug.transform_matrix` after a forward pass.
+
+## kornia.color β€” color space conversions
+
+`rgb_to_grayscale`, `rgb_to_hsv`, `hsv_to_rgb`, `rgb_to_lab`, `rgb_to_yuv`, `bgr_to_rgb`, etc. All take `(B, C, H, W)` float tensors in `[0, 1]` (except explicitly-ranged spaces like LAB on output).
+
+```python
+import torch
+import kornia.color as KC
+
+rgb = torch.rand(1, 3, 32, 32)
+gray = KC.rgb_to_grayscale(rgb) # (1, 1, 32, 32)
+hsv = KC.rgb_to_hsv(rgb) # hue in radians [0, 2pi], s/v in [0, 1]
+```
+
+## kornia.filters β€” blurring, gradients, edges
+
+- `gaussian_blur2d(input, kernel_size, sigma, border_type="reflect", separable=True)` β€” kernel_size `(ky, kx)` ints, sigma `(sy, sx)` floats or tensor.
+- `sobel(input)`, `spatial_gradient(input)`, `canny(input)`, `median_blur`, `box_blur`, `bilateral_blur`.
+
+```python
+import torch
+import kornia.filters as KF
+
+img = torch.rand(1, 3, 64, 64)
+blurred = KF.gaussian_blur2d(img, kernel_size=(5, 5), sigma=(1.5, 1.5))
+magnitude, edges = KF.canny(img) # gradient magnitudes and thresholded edge map
+```
+
+## kornia.feature β€” detection, description, matching
+
+Classical and learned local features with a common interface: LAFs (local affine frames) of shape `(B, N, 2, 3)`.
+
+```python
+import torch
+import kornia.feature as KF
+
+# LoFTR-style dense matching (downloads pretrained weights at construction)
+matcher = KF.LoFTR(pretrained="outdoor")
+input_dict = {
+ "image0": torch.rand(1, 1, 128, 128), # grayscale (B, 1, H, W)
+ "image1": torch.rand(1, 1, 128, 128),
+}
+with torch.inference_mode():
+ out = matcher(input_dict)
+# out["keypoints0"], out["keypoints1"]: matched (x, y) pixel coords; out["confidence"]
+```
+
+Other entry points: `SIFTDescriptor`, `HardNet`, `DISK`, `LightGlueMatcher`, `match_smnn`, `LAFDescriptor`.
+
+## kornia.enhance / kornia.losses / kornia.metrics / kornia.morphology
+
+- `kornia.enhance`: `normalize`, `denormalize`, `equalize_clahe`, `adjust_gamma`, `adjust_brightness` β€” all differentiable.
+- `kornia.losses`: `ssim_loss`, `psnr_loss`, `dice_loss`, `focal_loss`, `charbonnier_loss` β€” take `(B, C, H, W)` predictions/targets.
+- `kornia.metrics`: `ssim`, `psnr`, `mean_iou`, `accuracy`.
+- `kornia.morphology`: `dilation(tensor, kernel)`, `erosion`, `opening`, `closing` β€” kernel is a 2D `(kH, kW)` tensor of ones/zeros.
+
+## kornia.io β€” image I/O
+
+```python
+import kornia.io as KIO
+
+img = KIO.load_image("photo.jpg", KIO.ImageLoadType.RGB32) # (3, H, W) float32 in [0, 1]
+img = img[None] # most ops want (B, C, H, W)
+```
+
+## Pitfalls checklist
+
+1. Passing `(H, W, C)` NumPy-style arrays β€” convert with `kornia.image.image_to_tensor(np_img)[None]` (or `torch.from_numpy(...).permute(2, 0, 1)[None] / 255`). `kornia.utils.image_to_tensor` is deprecated.
+2. Passing `(w, h)` to `dsize`/`size` arguments β€” they are `(h, w)`.
+3. Passing `(y, x)` (row, col) points β€” point tensors are `(x, y)`.
+4. Assuming `align_corners` defaults are uniform β€” warps default `True`, `resize` defaults `None`.
+5. Using an unbatched `(3, 3)` homography β€” add the batch dim: `M[None]`.
+6. Radians where degrees are expected β€” rotation angles are degrees.
+7. Uint8 `[0, 255]` tensors β€” ops expect float `[0, 1]`; divide by 255 first.
+8. Augmenting image and mask through two separate augmentation calls β€” the random parameters will differ; use one `AugmentationSequential` with `data_keys`.
+
+## Links
+
+- Docs: <https://kornia.readthedocs.io/en/latest/>
+- Machine-readable index: <https://kornia.readthedocs.io/en/latest/llms.txt>
+- Source: <https://github.com/kornia/kornia>
+- Tutorials: <https://kornia.github.io/tutorials/>
diff --git a/docs/source/_extra/llms.txt b/docs/source/_extra/llms.txt
new file mode 100644
index 000000000..fbc55f3fb
--- /dev/null
+++ b/docs/source/_extra/llms.txt
@@ -0,0 +1,42 @@
+# Kornia
+
+> Kornia is a differentiable computer vision library for PyTorch: classic CV operations (color conversion, filtering, geometric transforms, camera/epipolar geometry, augmentation) implemented as batched, GPU-ready, autograd-friendly tensor ops, plus curated local-feature and vision models. There is no NumPy/OpenCV dependency β€” everything is `torch.Tensor` in, `torch.Tensor` out.
+
+Conventions every code generator must know before writing Kornia code:
+
+- Images are float tensors with values in `[0, 1]`; the batched layout `(B, C, H, W)` is accepted everywhere. Some op families (e.g. color conversions) also take `(*, C, H, W)` with arbitrary leading dims. Add a batch dim with `img[None]` if needed.
+- Point coordinates are `(x, y)` ordered (x = column axis, y = row axis); output sizes and `dsize` arguments are `(h, w)` ordered.
+- Angles are in degrees; a positive angle rotates counter-clockwise as displayed (origin at the top-left corner, matching OpenCV).
+- `warp_perspective` / `warp_affine` default to `align_corners=True`; `resize` defaults to `align_corners=None` (the PyTorch interpolation default). Do not assume they match.
+- Transformation matrices are batched: homographies `(B, 3, 3)`, affine `(B, 2, 3)`, operating on pixel coordinates unless the function name or a flag says `normalized`.
+- `kornia.augmentation.AugmentationSequential` applies one sampled transform consistently across image / mask / bbox / keypoints and can invert it with `.inverse()`.
+
+For the full self-contained reference with runnable examples, fetch [llms-full.txt](https://kornia.readthedocs.io/en/latest/llms-full.txt).
+
+## Get started
+
+- [Introduction](https://kornia.readthedocs.io/en/latest/get-started/introduction.html): what Kornia is and the design principles behind it
+- [Installation](https://kornia.readthedocs.io/en/latest/get-started/installation.html): pip/conda/source installation
+- [Tutorials](https://kornia.github.io/tutorials/): runnable end-to-end examples
+
+## Core API
+
+- [kornia.geometry](https://kornia.readthedocs.io/en/latest/geometry.html): warps, homographies, camera models, epipolar geometry, Lie groups, conversions β€” the differentiated core
+- [kornia.augmentation](https://kornia.readthedocs.io/en/latest/augmentation.html): batched differentiable augmentations with transform tracking and inversion
+- [kornia.filters](https://kornia.readthedocs.io/en/latest/filters.html): blur, edges (Sobel, Canny), gradients
+- [kornia.color](https://kornia.readthedocs.io/en/latest/color.html): color space conversions
+- [kornia.feature](https://kornia.readthedocs.io/en/latest/feature.html): detectors, descriptors, and matchers (SIFT, HardNet, DISK, LoFTR, LightGlue, ...)
+- [kornia.enhance](https://kornia.readthedocs.io/en/latest/enhance.html): normalization, histogram, contrast/gamma adjustments
+- [kornia.losses](https://kornia.readthedocs.io/en/latest/losses.html): SSIM, PSNR, Dice, focal, Hausdorff losses
+- [kornia.metrics](https://kornia.readthedocs.io/en/latest/metrics.html): accuracy, IoU, PSNR/SSIM metrics
+- [kornia.morphology](https://kornia.readthedocs.io/en/latest/morphology.html): dilation, erosion, opening, closing
+- [kornia.io](https://kornia.readthedocs.io/en/latest/io.html): image loading/saving to tensors
+- [kornia.contrib](https://kornia.readthedocs.io/en/latest/contrib.html): experimental modules
+
+## Optional
+
+- [Applications](https://kornia.readthedocs.io/en/latest/applications/intro.html): face detection, image matching, stitching, registration, denoising walkthroughs
+- [Models](https://kornia.readthedocs.io/en/latest/models.html): pre-trained model wrappers (SAM, RT-DETR, YuNet, ...)
+- [GitHub repository](https://github.com/kornia/kornia): source, issue tracker
+- [Contributing guide](https://github.com/kornia/kornia/blob/main/CONTRIBUTING.md): contribution protocol
+- [AI usage policy](https://github.com/kornia/kornia/blob/main/AI_POLICY.md): rules for AI-assisted contributions
diff --git a/docs/source/conf.py b/docs/source/conf.py
index f12a9d5d8..c4ee72273 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -217,7 +217,7 @@ gtagjs_ids = [
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
-html_extra_path = []
+html_extra_path = ["_extra"]
# Output file base name for HTML help builder.
htmlhelp_basename = "Kornia"