> built 2026-11-23 07:59 UTC from 686f95c (main) · kodokan 0.0.37. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# kodokan

Study Kodokan Judo throws from video via body-pose analysis: download technique demonstrations, extract two-person (tori/uke) skeletons, split each clip into its repeated demonstrations, visualize them, and compare/score demonstrations.

<!-- wads-docs: skip downloads videos and runs pose estimation -->
```python
from kodokan.acquire import download_techniques
from kodokan.track import estimate_poses_tracked
from kodokan.segment import segment_demonstrations
from kodokan.viz import render_skeleton_video

res = download_techniques(playlist_items="2")[0]  # Seoi-nage (#002), with metadata
seq = estimate_poses_tracked(
    res.path, source_url=res.info["webpage_url"]
)  # tracked tori/uke COCO-17
demos = segment_demonstrations(
    seq, min_two_person_frac=0.3
)  # per-demo (start_s, end_s)
render_skeleton_video(
    seq, out_path="overlay.mp4", source_video=res.path
)  # skeletons on the video
render_skeleton_video(
    seq, out_path="skeleton.mp4", blank_canvas=True
)  # skeletons on blank canvas
```

## What it does

A functional pipeline over the official *Kodokan 100 Techniques* YouTube playlist:

```default
acquire (yb) ─► pose (rtmlib / YOLO, tracked tori/uke) ─► segment (motion-energy)
       └─► dol stores (Parquet pose + JSON segments) ─► visualize (overlay / blank / Rerun)
       └─► compare two demos (joint-angle DTW) ─► score + eval harness
```

YouTube acquisition lives in the [`yb`](https://github.com/thorwhalen/yb) package (`download_youtube_playlist`); `kodokan` is the analysis layer on top.

## Install

`import kodokan` needs only **numpy**; everything heavy is an optional extra (imported lazily on first use), so the import never fails for a missing one:

```bash
pip install -e '.[all]'      # or pick extras: .[pose,track,viz,analysis,storage,acquire]
```

| extra      | for                                                 | brings                                                     | licence               |
|------------|-----------------------------------------------------|------------------------------------------------------------|-----------------------|
| `pose`     | pose estimation (RTMPose, the default backend)      | rtmlib, onnxruntime                                        | permissive            |
| `track`    | stable tori/uke identity (`estimate_poses_tracked`) | ultralytics (+ `ultralytics-thop`, `ultralytics-platform`) | **AGPL-3.0-or-later** |
| `viz`      | rendering                                           | opencv-python, rerun-sdk, supervision, matplotlib          | permissive            |
| `analysis` | segment / compare / score                           | scipy, dtaidistance, pandas, pyarrow                       | permissive            |
| `storage`  | dol stores                                          | dol                                                        | permissive            |
| `acquire`  | YouTube download                                    | yb                                                         | permissive            |

`track` is separated from `pose` on purpose — see [Licensing of extras](). The example at the top of this README uses `estimate_poses_tracked`, so it needs `track`; `estimate_poses` alone does not.

You also need **ffmpeg** on PATH (acquisition/merge). The optional **3D lift** (`scripts/lift_3d_mediapipe.py`) runs in a **separate venv**, because MediaPipe is ABI-incompatible with numpy 2.x:

```bash
python -m venv ~/.kodokan_mp
~/.kodokan_mp/bin/pip install 'mediapipe==0.10.18' 'numpy<2' 'opencv-python-headless==4.10.0.84'
```

Data (videos, keypoints, renders, weights) lives **outside the repo** under `~/kodokan_data` (override with `KODOKAN_DATA_DIR`).

## Licensing of extras

kodokan itself is **MIT**, and `pip install kodokan` installs **numpy and nothing else** — no copyleft reaches you through the core package.

One extra is different, and it is worth reading before you type it:

> **`kodokan[track]` installs [ultralytics](https://github.com/ultralytics/ultralytics),
> which is licensed AGPL-3.0-or-later.** `kodokan[all]` includes it too.

It is three distributions, not one — ultralytics pulls two more of its own, and both carry the same licence, so listing only the first would understate what lands in your environment:

| distribution           | licence           | how it arrives                               |
|------------------------|-------------------|----------------------------------------------|
| `ultralytics`          | AGPL-3.0-or-later | declared by the `track` extra                |
| `ultralytics-thop`     | AGPL-3.0-or-later | hard dependency of `ultralytics`             |
| `ultralytics-platform` | AGPL-3.0-only     | dependency of `ultralytics` on Python ≥ 3.11 |

kodokan imports only the first; the other two arrive with it and are covered by the same adjudication.

The AGPL is not “the GPL but for Python”. Its section 13 adds a **network clause**: if you modify the work and let users interact with it *over a network*, those users are entitled to the complete corresponding source of the whole combined work — even though you never distributed a copy to anyone. Deploying a judo-analysis service built on `kodokan[track]` is exactly that situation. The obligation attaches to the combined work, not to ultralytics alone. That is the conservative reading — the one this project plans around — rather than settled case law, but “we only import it” is not a position worth betting a product on.

If that is not compatible with what you are building, you have two options:

1. **Do not install `track`.** Everything below still works.
2. **Buy an [Ultralytics Enterprise License](https://www.ultralytics.com/license)**, which Ultralytics sells precisely for commercial use that cannot accept the AGPL.

**What you can do without it.** Everything except identity tracking:

- `estimate_poses(...)` — the default `backend="rtmlib"` (RTMPose over onnxruntime) is AGPL-free and is what `kodokan[pose]` installs. It keeps the two highest-confidence people per frame, ordered left→right *per frame*.
- `segment`, `compare`, `score`, `store`, `viz`, `acquire` — all permissive.

**What you give up.** `kodokan.track.estimate_poses_tracked` runs Ultralytics’ built-in BoT-SORT/ByteTrack so tori and uke keep persistent identities across a clip instead of swapping whenever they cross. rtmlib is a pose estimator with no multi-object tracker, so this is a real feature difference, not a packaging one. `estimate_poses(backend="ultralytics")` — the non-default YOLO11-pose backend — also needs it. Both raise an `ImportError` naming the extra and the licence rather than a bare `ModuleNotFoundError`.

The decision to keep this dependency, and the conditions that should reopen it, are recorded in `[tool.wads.licence]` in `pyproject.toml`.

## The pipeline

| module                | purpose                                                                                                                                                                                                                         |
|-----------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `kodokan.acquire`     | download techniques (wraps `yb`), skip the PV, keep source URLs                                                                                                                                                                 |
| `kodokan.pose`        | `estimate_poses` facade (rtmlib / ultralytics backends), COCO-17, `PoseSequence`                                                                                                                                                |
| `kodokan.track`       | `estimate_poses_tracked` — stable tori/uke identity (BoT-SORT + spatial continuity)                                                                                                                                             |
| `kodokan.segment`     | hysteresis motion-energy segmentation + two-person gate + self-similarity                                                                                                                                                       |
| `kodokan.store`       | `pose_store` (tidy Parquet) / `segments_store` (JSON), the analysis SSOT                                                                                                                                                        |
| `kodokan.viz`         | overlay / blank-canvas MP4 + Rerun logging                                                                                                                                                                                      |
| `kodokan.compare`     | joint-angle (soft-)DTW comparison of two demonstrations                                                                                                                                                                         |
| `kodokan.score`       | reference-based 0–100 scoring + per-joint/per-phase feedback                                                                                                                                                                    |
| `kodokan.descriptors` | experimental feature descriptors (for the eval harness)                                                                                                                                                                         |
| `kodokan.recognizer`  | `TechniqueRecognizer` (top-k guesses + every technique’s score), `recognize_segments` (a whole video), `ThrowDetector` / `LiveRecognizer` (rolling pose buffer, one guess per closed throw)                                     |
| `kodokan.coach`       | `coach` (0–100 + per-joint / per-phase deviation + EN/FR advice on the worst dimensions), `LiveCoach` (the same per detected throw on a live stream)                                                                            |
| `kodokan.testmode`    | `TechniqueTest` (random technique from a focus pool; graded on the recognizer’s confidence for it, plus closeness and advice when a reference is given), `LiveTechniqueTest` (the prompt, perform, grade loop on a live stream) |

Runnable end-to-end examples live in `examples/` (`warmup_seoinage.py`, `batch_pipeline.py`, `segment_review.py`, `compare_demos.py`, `score_demos.py`, `eval_features.py`).

## Dataset

`examples/batch_pipeline.py` builds a small dataset (10 techniques · 84 demonstrations · 18.3k frames) into the `dol` stores. Load it:

```python
from kodokan.store import pose_store, segments_store, load_all_tidy

seq = pose_store()["zIq0xI0ogxk"]  # (F, 2, 17, 3) COCO-17 (x, y, conf)
demos = segments_store()["zIq0xI0ogxk"]  # demo intervals + source_url
df = load_all_tidy()  # tidy DataFrame across all clips
```

See [`misc/docs/dataset.md`]().

## Status & honest limits

Works well: acquisition, tracked two-person pose, demo segmentation, the dol stores, visualization, and same-technique demo comparison (joint-angle DTW is speed-invariant) with interpretable per-joint/per-phase feedback.

Does **not** work yet — and this is *measured, not assumed*: **technique recognition / cross-demo scoring**. A feature bake-off ([`misc/docs/feature-bakeoff.md`]()) shows every 2D descriptor *and* MediaPipe 3D joint angles sit at chance (separation AUC ≈ 0.49–0.56). The blockers are noisy monocular 3D under grappling occlusion, tori/uke role inconsistency, and the weakness of hand-crafted angle-DTW for few examples — not viewpoint alone. Recognition needs a **learned** skeleton representation (few-shot JEANIE, or trained PoseC3D/CTR-GCN) and/or cleaner multi-person 3D with role-consistent features. The eval harness (`examples/eval_features*.py`) is ready to validate those.

## Competition calendar

`kodokan.competitions` fetches the French judo federation’s agenda for one département (default: the Bouches-du-Rhône), each event’s detail page and the committee’s season forecast PDF into a snapshot folder, and validates the calendar built from it before it is published. Deciding who may enter each event (open, by qualification, a friendly interclub, by invitation) is reading prose rules; the `kodokan-competitions` skill in `.claude/skills/` is that procedure.

```bash
python -m kodokan.competitions snapshot ./snap      # agenda.json, details/, forecast.txt
python -m kodokan.competitions validate competitions.json
```

## Background & rationale

- [`misc/docs/research-architecture.md`]() — cited tools/architecture research (75 refs).
- [`misc/docs/dataset.md`]() — dataset card.
- [`misc/docs/feature-bakeoff.md`]() — why hand-crafted features don’t discriminate techniques (the empirical finding).

<p class="epythet-aggregates">This documentation as a single file: <a href="kodokan.md">kodokan.md</a> (Markdown, for agents).</p>


# _autosummary/kodokan.acquire.html.md

# kodokan.acquire

Acquire Kodokan technique clips from YouTube (thin wrapper over `yb.download`).

YouTube interaction lives in the `yb` package; this module just points it at the
kodokan data dir and the *Kodokan 100 Techniques* playlist, and keeps the source
URL with every clip (a project requirement). The PV (entry #1, “all techniques
once”) is skipped from the main line by default but can be fetched as a reference.

### Module Attributes

| [`KODOKAN_PLAYLIST_URL`](_autosummary/kodokan.acquire.html.md#kodokan.acquire.KODOKAN_PLAYLIST_URL)   | The official "KODOKAN × IJF ACADEMY 100 Techniques" playlist.                         |
|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| [`SOURCES`](_autosummary/kodokan.acquire.html.md#kodokan.acquire.SOURCES)                | Registered technique-demo sources (for cross-source / leave-one-clip-out validation). |

### Functions

| [`canonical_technique_key`](_autosummary/kodokan.acquire.html.md#kodokan.acquire.canonical_technique_key)(title)                     | Normalize a clip title to a cross-source technique key.                            |
|-----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [`download_source`](_autosummary/kodokan.acquire.html.md#kodokan.acquire.download_source)(source, \*[, playlist_items, ...]) | Download a registered SOURCE playlist into its own clips dir.                      |
| [`download_techniques`](_autosummary/kodokan.acquire.html.md#kodokan.acquire.download_techniques)(\*[, playlist_items, ...])     | Download technique clips into the kodokan clips dir (PV skipped by default).       |
| [`list_techniques`](_autosummary/kodokan.acquire.html.md#kodokan.acquire.list_techniques)(\*[, include_pv])                  | List the playlist's videos (id, title, webpage_url, duration) without downloading. |
| [`local_clips`](_autosummary/kodokan.acquire.html.md#kodokan.acquire.local_clips)([directory])                           | List already-downloaded clips on disk (decouples processing from download).        |
| [`source_clips_dir`](_autosummary/kodokan.acquire.html.md#kodokan.acquire.source_clips_dir)(source)                           | Per-source clips directory (Kodokan keeps the legacy flat `clips/` dir).           |

### kodokan.acquire.KODOKAN_PLAYLIST_URL *= 'https://www.youtube.com/playlist?list=PLtz539PTepc16H2iu5F3Q3D7_He1EYlIQ'*

The official “KODOKAN × IJF ACADEMY 100 Techniques” playlist.

### kodokan.acquire.SOURCES *= {'efficient_judo': 'https://www.youtube.com/playlist?list=PLwd8pJWYTk07K6hDg2_N-9xd31gUCsew7', 'kodokan_ijf': 'https://www.youtube.com/playlist?list=PLtz539PTepc16H2iu5F3Q3D7_He1EYlIQ'}*

Registered technique-demo sources (for cross-source / leave-one-clip-out validation).
Each is an *independent* set of demonstrations (different demonstrators/cameras), so the
SOURCE video can be used as the cross-validation group while `technique_key` is the label.

### kodokan.acquire.canonical_technique_key(title)

Normalize a clip title to a cross-source technique key.

Handles “kanji / Romaji” (Kodokan) and “Romaji - Demo” (Efficient Judo) titles,
the `-barai`/`-harai` spelling, and hyphen/space differences. E.g. both
“大外刈 / O-soto-gari” and “Osoto-gari - Demo” -> “osotogari”.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### kodokan.acquire.download_source(source, , playlist_items=None, download_dir=None, write_info_json=True, \*\*kwargs)

Download a registered SOURCE playlist into its own clips dir.

* **Parameters:**
  * **source** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – a key of [`SOURCES`](_autosummary/kodokan.acquire.html.md#kodokan.acquire.SOURCES) (e.g. `"efficient_judo"`).
  * **playlist_items** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – yt-dlp 1-based selector (default: all entries).
  * **download_dir** ([`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – override (default: [`source_clips_dir()`](_autosummary/kodokan.acquire.html.md#kodokan.acquire.source_clips_dir)).
  * **\*\*kwargs** – forwarded to `yb.download.download_youtube_playlist`.

### kodokan.acquire.download_techniques(, playlist_items=None, skip_pv=True, download_dir=None, write_info_json=True, \*\*kwargs)

Download technique clips into the kodokan clips dir (PV skipped by default).

* **Parameters:**
  * **playlist_items** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – yt-dlp 1-based selector (overrides `skip_pv`), e.g.
    `"2"` (only Seoi-nage), `"2:11"` (the first ten throws), `"2:"` (all).
  * **skip_pv** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – When `playlist_items` is not given, skip entry #1 (the PV).
  * **download_dir** ([`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Destination (default: [`kodokan.config.clips_dir()`](_autosummary/kodokan.config.html.md#kodokan.config.clips_dir)).
  * **write_info_json** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Save each clip’s metadata sidecar (keeps the source URL).
  * **\*\*kwargs** – Forwarded to `yb.download.download_youtube_playlist`.
* **Returns:**
  `list[yb.download.DownloadResult]` — media path + trimmed info + sidecars.

### kodokan.acquire.list_techniques(, include_pv=False, \*\*kwargs)

List the playlist’s videos (id, title, webpage_url, duration) without downloading.

* **Parameters:**
  * **include_pv** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Include entry #1 (the all-techniques PV) if True.
  * **\*\*kwargs** – Forwarded to `yb.download.youtube_playlist_info`.

### kodokan.acquire.local_clips(directory=None)

List already-downloaded clips on disk (decouples processing from download).

Reads each `*.info.json` sidecar and pairs it with its `.mp4`. Returns
dicts with `id`, `title`, `webpage_url`, `path`. Sidecars without a
matching video (e.g. the playlist-level info.json) are skipped.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### kodokan.acquire.source_clips_dir(source)

Per-source clips directory (Kodokan keeps the legacy flat `clips/` dir).

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)


# _autosummary/kodokan.canon3d.html.md

# kodokan.canon3d

Pelvis-frame (Procrustes) canonicalization of 3D world landmarks.

The Stage-5  *“3D refutes viewpoint”* conclusion was **withdrawn** by the
adversarial review (`misc/docs/adversarial-review.md`): MediaPipe per-crop
world landmarks are camera-aligned — not canonicalized — and the bounding-box
crop distorts their scale/orientation, so 3D joint angles computed straight off
them are **not** actually viewpoint-invariant. Before a fair 2D-vs-3D test, each
frame’s landmarks must be expressed in a *subject-centered anatomical frame*:
origin at the pelvis, axes fixed to the body (hip line + spine), scale normalized
by torso length. This module provides that canonicalization as a pure, testable
geometric function.

After [`canonicalize_pose()`](_autosummary/kodokan.canon3d.html.md#kodokan.canon3d.canonicalize_pose), two demonstrations of the same articulated pose
seen from different camera azimuths map to the **same** canonical coordinates
(invariant to camera rotation, translation, and — with `scale=True` — subject
size). Downstream angle/position features are then genuinely viewpoint-invariant.

Indices default to the MediaPipe **BlazePose-33** convention used by the repo’s
3D lift (`scripts/lift_3d_mediapipe.py`); pass `joints=COCO17` (or a custom
[`BodyJoints`](_autosummary/kodokan.canon3d.html.md#kodokan.canon3d.BodyJoints)) to reuse it for any layout exposing both hips and shoulders.

### Module Attributes

| [`BLAZEPOSE33`](_autosummary/kodokan.canon3d.html.md#kodokan.canon3d.BLAZEPOSE33)   | MediaPipe BlazePose-33 (the repo's 3D-lift output format).                   |
|----------------------------------------------------------------|------------------------------------------------------------------------------|
| [`COCO17`](_autosummary/kodokan.canon3d.html.md#kodokan.canon3d.COCO17)        | COCO-17 (the 2D pose format), for reusing the canonicalization on 2.5D data. |

### Functions

| [`canonicalize_pose`](_autosummary/kodokan.canon3d.html.md#kodokan.canon3d.canonicalize_pose)(landmarks, \*[, joints, scale])   | Express one frame's 3D landmarks `(K, C>=3)` in the pelvis frame `(K, 3)`.         |
|------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [`canonicalize_sequence`](_autosummary/kodokan.canon3d.html.md#kodokan.canon3d.canonicalize_sequence)(world, \*[, joints, scale])   | Canonicalize every frame/person of a `(..., K, C)` landmark stack → `(..., K, 3)`. |
| [`pelvis_frame`](_autosummary/kodokan.canon3d.html.md#kodokan.canon3d.pelvis_frame)(landmarks, \*[, joints])               | Anatomical frame of a single pose: `(pelvis_origin, R)`.                           |

### Classes

| [`BodyJoints`](_autosummary/kodokan.canon3d.html.md#kodokan.canon3d.BodyJoints)(l_hip, r_hip, l_shoulder, r_shoulder)   | Landmark indices needed to build the pelvis anatomical frame.   |
|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------|

### kodokan.canon3d.BLAZEPOSE33 *= BodyJoints(l_hip=23, r_hip=24, l_shoulder=11, r_shoulder=12)*

MediaPipe BlazePose-33 (the repo’s 3D-lift output format).

### *class* kodokan.canon3d.BodyJoints(l_hip, r_hip, l_shoulder, r_shoulder)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Landmark indices needed to build the pelvis anatomical frame.

### kodokan.canon3d.COCO17 *= BodyJoints(l_hip=11, r_hip=12, l_shoulder=5, r_shoulder=6)*

COCO-17 (the 2D pose format), for reusing the canonicalization on 2.5D data.

### kodokan.canon3d.canonicalize_pose(landmarks, , joints=BodyJoints(l_hip=23, r_hip=24, l_shoulder=11, r_shoulder=12), scale=True)

Express one frame’s 3D landmarks `(K, C>=3)` in the pelvis frame `(K, 3)`.

Removes camera rotation + translation (and, with `scale=True`, subject size
by dividing by torso length). Columns beyond `xyz` (e.g. visibility) are
dropped; `nan` inputs propagate (so occluded frames stay droppable).

* **Return type:**
  `ndarray`

### kodokan.canon3d.canonicalize_sequence(world, , joints=BodyJoints(l_hip=23, r_hip=24, l_shoulder=11, r_shoulder=12), scale=True)

Canonicalize every frame/person of a `(..., K, C)` landmark stack → `(..., K, 3)`.

Each frame (and person) is canonicalized to *its own* pelvis frame — the
viewpoint-invariant choice for pose-only technique features.

* **Return type:**
  `ndarray`

### kodokan.canon3d.pelvis_frame(landmarks, , joints=BodyJoints(l_hip=23, r_hip=24, l_shoulder=11, r_shoulder=12))

Anatomical frame of a single pose: `(pelvis_origin, R)`.

`R` (shape `(3, 3)`, rows are the new basis) maps world coordinates into
the subject frame: **x** = subject’s right (hip line), **y** = up
(pelvis→neck spine), **z** = forward (`y × x`). The hip line is
orthogonalized against the spine so the basis is orthonormal (Gram-Schmidt).

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[`ndarray`, `ndarray`]


# _autosummary/kodokan.competitions.html.md

# kodokan.competitions

A calendar of upcoming judo competitions in one French département, and who may enter each.

The French judo federation (FFJDA) runs one agenda engine behind every regional and
departmental site. Each site’s `/evenement` page embeds the *whole national agenda* as
JSON in a hidden form field, so one GET gives every published event with its town,
postcode, organiser, level and the extranet registration window; each event also has a
detail page with the birth years, minimum belt and the rules of entry. The department’s
committee additionally publishes a season forecast as a PDF, which is the only source for
events more than four to six weeks ahead.

This module does the deterministic part of refreshing a calendar: fetch the agenda,
select the area, fetch the detail pages and the forecast, and write a *snapshot* folder.
Deciding who may enter each event (open, by qualification, a friendly interclub limited to
named clubs) is reading prose rules, and is left to the person or agent doing the refresh:
the `kodokan-competitions` skill is that procedure. The result is validated with
[`validate_calendar()`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.validate_calendar) before it is published.

```pycon
>>> html = '<input type="hidden" name="evenements" value=\'{"2026": {"11": [{"id_evenement": "1", "titre": "SHIREN", "codePostal": "13015", "date_debut": "1794096000", "date_fin": "1794096000", "libelleType": "COMPETITION", "proprietaire": "Comité X", "slug": "shiren"}]}}\' />'
>>> [e["titre"] for e in parse_agenda(html)]
['SHIREN']
>>> normalise(parse_agenda(html)[0])["date_start"]
'2026-11-08'
```

Nothing here names a club: the home club, the area and the output path are arguments
(or a local config file the skill reads), so the module serves any club in any département.

### Module Attributes

| [`DFLT_SITE`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.DFLT_SITE)          | The Bouches-du-Rhône committee's site; any FFJDA committee or league site has the same engine.   |
|---------------------------------------------------------------------|--------------------------------------------------------------------------------------------------|
| [`DFLT_OWNERS`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.DFLT_OWNERS)        | Organisers whose events count even when held outside the area (regional league, the committee).  |
| [`DFLT_EXCLUDE_TYPES`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.DFLT_EXCLUDE_TYPES) | Event types that are not competitions or events a young judoka enters.                           |
| [`EVENT_FIELDS`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.EVENT_FIELDS)       | Keys of one published event, and the type each must have (`None` allowed where listed).          |

### Functions

| [`detail_text`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.detail_text)(page_html)                             | The readable body of an event detail page: dates, venue, categories, birth years, belts and the free-text rules (weigh-in times, who may not enter, fees).   |
|-----------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `detail_url`(ev, \*[, site])                                                                        |                                                                                                                                                              |
| [`forecast_pdf_url`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.forecast_pdf_url)(calendars_page_html, \*[, site])  | The link to the season's forecast calendar PDF on the committee's calendars page.                                                                            |
| [`http_get`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.http_get)(url, \*[, timeout])                       | GET `url` with an identifying User-Agent (the default fetcher).                                                                                              |
| [`in_area`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.in_area)(ev, \*[, postcode_prefixes, owners, ...])  | Whether an agenda event belongs in the area's calendar.                                                                                                      |
| [`normalise`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.normalise)(ev, \*[, site])                          | The fields of a raw agenda event that a calendar needs, with ISO dates.                                                                                      |
| [`parse_agenda`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.parse_agenda)(page_html)                            | Every event in an FFJDA site's `/evenement` page (the embedded national agenda).                                                                             |
| [`pdf_text`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.pdf_text)(pdf)                                      | The text of a PDF, laid out (`pdftotext -layout`, from poppler).                                                                                             |
| [`snapshot`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.snapshot)(out_dir, \*[, site, calendars_path, ...]) | Fetch everything a calendar refresh reads, into `out_dir`.                                                                                                   |
| [`validate_calendar`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.validate_calendar)(cal)                             | Problems with a calendar about to be published (`[]` means publishable).                                                                                     |
| [`write_calendar`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.write_calendar)(cal, path)                          | Validate `cal` and write it as JSON, events sorted by date.                                                                                                  |

### kodokan.competitions.DFLT_EXCLUDE_TYPES *= ('PASSAGE DE GRADE',)*

Event types that are not competitions or events a young judoka enters.

### kodokan.competitions.DFLT_OWNERS *= ('BOUCHES DU RHONE', 'PACA')*

Organisers whose events count even when held outside the area (regional league, the committee).

### kodokan.competitions.DFLT_SITE *= 'https://comite13judo.ffjudo.com'*

The Bouches-du-Rhône committee’s site; any FFJDA committee or league site has the same engine.

### kodokan.competitions.EVENT_FIELDS *: [Mapping](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[type](https://docs.python.org/3/builtins/functions.html#type), ...]]* *= {'birth_years': (<class 'list'>, <class 'NoneType'>), 'categories': (<class 'list'>,), 'confidence': (<class 'str'>,), 'date_end': (<class 'str'>,), 'date_start': (<class 'str'>,), 'deadline': (<class 'str'>, <class 'NoneType'>), 'eligibility': (<class 'str'>,), 'eligibility_note': (<class 'str'>,), 'eligible_clubs': (<class 'list'>,), 'format': (<class 'str'>, <class 'NoneType'>), 'home_club_eligible': (<class 'bool'>, <class 'NoneType'>), 'id': (<class 'str'>,), 'level': (<class 'str'>,), 'organiser': (<class 'str'>, <class 'NoneType'>), 'registration': (<class 'str'>, <class 'NoneType'>), 'source_url': (<class 'str'>,), 'title': (<class 'str'>,), 'town': (<class 'str'>,), 'venue': (<class 'str'>, <class 'NoneType'>)}*

Keys of one published event, and the type each must have (`None` allowed where listed).

### kodokan.competitions.detail_text(page_html)

The readable body of an event detail page: dates, venue, categories, birth years,
belts and the free-text rules (weigh-in times, who may not enter, fees).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### kodokan.competitions.forecast_pdf_url(calendars_page_html, , site='https://comite13judo.ffjudo.com')

The link to the season’s forecast calendar PDF on the committee’s calendars page.

Its file name changes with every revision, so it is always read from the page.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### kodokan.competitions.http_get(url, , timeout=30.0)

GET `url` with an identifying User-Agent (the default fetcher).

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### kodokan.competitions.in_area(ev, , postcode_prefixes=('13',), owners=('BOUCHES DU RHONE', 'PACA'), exclude_types=('PASSAGE DE GRADE',))

Whether an agenda event belongs in the area’s calendar.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### kodokan.competitions.normalise(ev, , site='https://comite13judo.ffjudo.com')

The fields of a raw agenda event that a calendar needs, with ISO dates.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.competitions.parse_agenda(page_html)

Every event in an FFJDA site’s `/evenement` page (the embedded national agenda).

The JSON sits in `<input name="evenements" value='...'>`; it is decoded with
`raw_decode` from the opening brace, because apostrophes inside the JSON make
searching for the closing quote unreliable.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### kodokan.competitions.pdf_text(pdf)

The text of a PDF, laid out (`pdftotext -layout`, from poppler).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### kodokan.competitions.snapshot(out_dir, \*, site='https://comite13judo.ffjudo.com', calendars_path='/calendriers-8', since=None, get=<function http_get>, details=True, forecast=True, \*\*area)

Fetch everything a calendar refresh reads, into `out_dir`.

Writes `agenda.json` (the area’s events from `since` on, normalised),
`details/<agenda_id>.txt` (each one’s detail page as text) and `forecast.txt`
(the season forecast PDF as text, with `forecast_url.txt`). Returns a summary.
`area` takes [`in_area()`](_autosummary/kodokan.competitions.html.md#kodokan.competitions.in_area)’s keyword arguments.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.competitions.validate_calendar(cal)

Problems with a calendar about to be published (`[]` means publishable).

Checks the envelope and every event’s keys, types, enumerations and dates, so a
hand-edited refresh cannot ship a file the web page would mis-render.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### kodokan.competitions.write_calendar(cal, path)

Validate `cal` and write it as JSON, events sorted by date. Raises on any problem.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)


# _autosummary/kodokan.config.html.md

# kodokan.config

Where kodokan keeps its data (downloaded clips + derived artifacts).

Large/churny artifacts (videos, per-frame keypoints, rendered overlays) live
*outside* the repo by default — under `~/kodokan_data` — so they don’t bloat
the (Dropbox-synced) source tree. Override the root with the
`KODOKAN_DATA_DIR` environment variable.

On the dev Mac `~/kodokan_data` is a symlink into an off-machine-backed data
area; code addresses it transparently through the symlink either way. None of
this data is precious — every subfolder is downloaded or pipeline-derived; see
`misc/docs/regenerate-data.md` for how to rebuild it from scratch.

### Module Attributes

| [`KODOKAN_DATA_ENV`](_autosummary/kodokan.config.html.md#kodokan.config.KODOKAN_DATA_ENV)            | Env var overriding the data root (default `~/kodokan_data`).                                                                                       |
|------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|
| [`SEGMENT_MIN_TWO_PERSON_FRAC`](_autosummary/kodokan.config.html.md#kodokan.config.SEGMENT_MIN_TWO_PERSON_FRAC) | keep a detected demonstration only if both judoka are present for at least this fraction of its frames.                                            |
| [`EVAL_MIN_TWO_PERSON_FRAC`](_autosummary/kodokan.config.html.md#kodokan.config.EVAL_MIN_TWO_PERSON_FRAC)    | Quality gate used when *consuming* stored demos for recognition/scoring/ catalog building: only trust demos where both judoka are clearly visible. |

### Functions

| [`clips_dir`](_autosummary/kodokan.config.html.md#kodokan.config.clips_dir)()   | Directory holding downloaded video clips + their `*.info.json` sidecars.   |
|----------------------------------------------------------------|----------------------------------------------------------------------------|
| [`data_dir`](_autosummary/kodokan.config.html.md#kodokan.config.data_dir)()    | Resolve the kodokan data root (`$KODOKAN_DATA_DIR` or `~/kodokan_data`).   |
| [`models_dir`](_autosummary/kodokan.config.html.md#kodokan.config.models_dir)()  | Directory for downloaded model weights (kept out of the repo).             |
| [`pose_dir`](_autosummary/kodokan.config.html.md#kodokan.config.pose_dir)()    | Directory holding extracted per-clip keypoint sequences (NPZ / Parquet).   |
| [`viz_dir`](_autosummary/kodokan.config.html.md#kodokan.config.viz_dir)()     | Directory holding rendered overlays (MP4) and Rerun recordings (RRD).      |

### kodokan.config.EVAL_MIN_TWO_PERSON_FRAC *: [float](https://docs.python.org/3/builtins/functions.html#float)* *= 0.4*

Quality gate used when *consuming* stored demos for recognition/scoring/
catalog building: only trust demos where both judoka are clearly visible.
Stricter than the segmentation gate on purpose. Used by the eval harnesses,
[`kodokan.flashcards.build_catalog()`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.build_catalog), and scoring.

### kodokan.config.KODOKAN_DATA_ENV *= 'KODOKAN_DATA_DIR'*

Env var overriding the data root (default `~/kodokan_data`).

### kodokan.config.SEGMENT_MIN_TWO_PERSON_FRAC *: [float](https://docs.python.org/3/builtins/functions.html#float)* *= 0.3*

keep a detected demonstration
only if both judoka are present for at least this fraction of its frames.
Deliberately lenient — we would rather store a borderline demo (and filter it
later) than silently drop a real one. Used by the batch/segmentation step.

* **Type:**
  Inclusion gate used when *segmenting* a clip

### kodokan.config.clips_dir()

Directory holding downloaded video clips + their `*.info.json` sidecars.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### kodokan.config.data_dir()

Resolve the kodokan data root (`$KODOKAN_DATA_DIR` or `~/kodokan_data`).

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### kodokan.config.models_dir()

Directory for downloaded model weights (kept out of the repo).

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### kodokan.config.pose_dir()

Directory holding extracted per-clip keypoint sequences (NPZ / Parquet).

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### kodokan.config.viz_dir()

Directory holding rendered overlays (MP4) and Rerun recordings (RRD).

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)


# _autosummary/kodokan.descriptors.html.md

# kodokan.descriptors

Experimental per-demo feature descriptors (to test what makes throws separable).

The Stage-5 eval showed plain single-person joint angles don’t discriminate
technique (dominated by viewpoint + tori/uke role inconsistency). This module
offers alternative descriptors so the eval harness can measure which lever helps:

- `angles`      — primary person’s joint angles (the current baseline).
- `angles_vel`  — angles + their frame-to-frame velocity (dynamics).
- `angles_pos`  — angles + root-centered, torso-scaled keypoint positions.
- `angles_both` — both people’s joint angles, ordered by activity (captures the
  : tori/uke *interaction*, robust to which slot is which).
- `pos_both`    — both people’s normalized positions, activity-ordered.

All are 2D (still viewpoint-variant); the point is to isolate how much of the
failure is role/interaction/descriptor vs genuinely needing 3D.

### Functions

| [`demo_descriptor`](_autosummary/kodokan.descriptors.html.md#kodokan.descriptors.demo_descriptor)(pose_seq, start_s, end_s, \*)   | Per-frame feature matrix for one demo window under the chosen `mode`.   |
|--------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------|

### kodokan.descriptors.demo_descriptor(pose_seq, start_s, end_s, , mode='angles')

Per-frame feature matrix for one demo window under the chosen `mode`.

* **Return type:**
  `ndarray`


# _autosummary/kodokan.flashcards.html.md

# kodokan.flashcards

Technique-recognition learning game (app #6) — logic layer.

Help students learn to recognize/name throws. No throw-detection is needed (ground
truth is known): we generate multiple-choice problems from the clip library —
**name -> pick the video** or **video -> pick the name** — with *confusable*
distractors, log every response (timestamped, with the exact problem) for adaptive
learning, and score with confusion-aware weighting.

“Confusability” between techniques is a **pose-shape similarity** (closeness of their
mean pooled descriptors) — an honest proxy for visual confusability that does NOT
require a working recognizer (the cross-source recognizer is currently at chance). It
can be swapped for the model’s confusion matrix once recognition generalizes.

This module is the (UI-agnostic) logic + storage; a web UI plugs into it later.

### Functions

| [`build_catalog`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.build_catalog)(\*[, min_two_person_frac, ...])      | Build `{technique_key: {"name", "clips":[...]}}` from the pose/segments stores.                                 |
|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------|
| [`build_confusability`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.build_confusability)([catalog, feature])            | Technique×technique similarity (0..1) from mean pooled pose descriptors.                                        |
| [`build_model_confusability`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.build_model_confusability)([catalog, ...])          | Technique×technique confusability from the recognizer's own leave-one-out confusions.                           |
| [`clip_filename`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.clip_filename)(video_id, start_s, dur_s)            | The web-app clip file for one demo segment, named by the segment's IDENTITY.                                    |
| [`confusable_distractors`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.confusable_distractors)(target_key, keys, \*, n)    | Pick `n` distractor keys, preferring those most confusable with the target.                                     |
| [`log_response`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.log_response)(problem, chosen_index, \*[, ...])     | Record a response (datetime + exact problem + choice + correctness + score).                                    |
| [`make_problem`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.make_problem)(catalog, target_key, \*[, mode, ...]) | Build a multiple-choice problem for `target_key` from a technique `catalog`.                                    |
| [`next_target`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.next_target)(keys, history, \*[, focus, rng])       | Pick the next technique to quiz: unseen and often-missed (within `focus`) first.                                |
| [`problem_from_keys`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.problem_from_keys)(catalog, target_key, ...)        | Assemble a [`Problem`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.Problem) from an already-chosen, ordered option set. |
| [`responses_store`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.responses_store)([directory])                       | A dict-like JSON store of logged responses (per-user, timestamped).                                             |
| [`score_response`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.score_response)(correct_key, chosen_key, \*[, ...]) | Confusion-weighted credit in [0, 1].                                                                            |

### Classes

| [`Problem`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.Problem)(problem_id, mode, target_key, ...)   | One multiple-choice flashcard problem.   |
|-----------------------------------------------------------------------------------------------|------------------------------------------|

### *class* kodokan.flashcards.Problem(problem_id, mode, target_key, prompt, choices, correct_index)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One multiple-choice flashcard problem.

### kodokan.flashcards.build_catalog(, min_two_person_frac=None, min_demo_s=1.0, max_demos=None, segments=None)

Build `{technique_key: {"name", "clips":[...]}}` from the pose/segments stores.

Aggregates all sources: each clip contributes its demo intervals (for looping media),
so a technique present in several sources offers varied multiple-choice media.

`max_demos` caps the demos kept per source video (`None`, the default, keeps every
demo that passes the quality gate — #37: the store has 6–8 reps per video and all of
them are worth showing). `segments` is the `{video_id: record}` mapping to read
(default: [`kodokan.store.segments_store()`](_autosummary/kodokan.store.html.md#kodokan.store.segments_store)).

### kodokan.flashcards.build_confusability(catalog=None, , feature='tori_angles_pos')

Technique×technique similarity (0..1) from mean pooled pose descriptors.

`similarity[a][b]` high ⇒ techniques a, b look alike in pose-space (likely
confusable for a learner). An honest, recognizer-free proxy; swap for the model’s
confusion matrix once cross-source recognition works.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.flashcards.build_model_confusability(catalog=None, , feature='tori_angles_pos', method='lda_knn', cross_source=True)

Technique×technique confusability from the recognizer’s own leave-one-out confusions.

Same shape as [`build_confusability()`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.build_confusability). Predictions are leave-one-clip-out
(`cross_source`) or leave-one-sample-out. Techniques the model never confuses get
no row entries; `learning.merge_similarity` / the strategies fall back as usual.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.flashcards.clip_filename(video_id, start_s, dur_s)

The web-app clip file for one demo segment, named by the segment’s IDENTITY.

`{video_id}_{start_ms}_{dur_ms}.mp4`: the name says which time span of which source it
shows, so re-segmenting can never make an existing name show a different cut (#45) — a
changed segment simply gets a new name. Positional names (`{vid}_3.mp4`) could.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### kodokan.flashcards.confusable_distractors(target_key, keys, , n, similarity=None, rng=None)

Pick `n` distractor keys, preferring those most confusable with the target.

The choice is learny’s (`learny.distractors.pick_distractors()`): weighted by
`similarity`, uniform when it knows nothing of the target.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

### kodokan.flashcards.log_response(problem, chosen_index, , user='default', store=None, similarity=None, timestamp=None)

Record a response (datetime + exact problem + choice + correctness + score).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.flashcards.make_problem(catalog, target_key, , mode='video_to_name', n_choices=4, similarity=None, rng=None, clip_for=None)

Build a multiple-choice problem for `target_key` from a technique `catalog`.

`catalog` maps `technique_key -> {"name": str, "clips": [clip dicts]}`.
`clip_for(key)` returns a looping clip for a key (default: first clip); for
`name_to_video` the choices are clips, for `video_to_name` they are names.

* **Return type:**
  [`Problem`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.Problem)

### kodokan.flashcards.next_target(keys, history, , focus=None, rng=None)

Pick the next technique to quiz: unseen and often-missed (within `focus`) first.

Spaced-repetition-ish weight = (wrongs + 1) / (seen + 1): unseen -> 1, frequently
wrong -> high, mastered -> low. `history` is a list of response dicts.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### kodokan.flashcards.problem_from_keys(catalog, target_key, option_keys, , mode='video_to_name', clip_for=None, problem_id)

Assemble a [`Problem`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.Problem) from an already-chosen, ordered option set.

The seam between *choosing* (`make_problem`, or a `learning.Strategy`) and
*presenting*: whoever picks the options, the problem looks the same.

* **Return type:**
  [`Problem`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.Problem)

### kodokan.flashcards.responses_store(directory=None)

A dict-like JSON store of logged responses (per-user, timestamped).

### kodokan.flashcards.score_response(correct_key, chosen_key, , similarity=None, max_partial=0.5)

Confusion-weighted credit in [0, 1].

Correct = 1.0. A wrong answer earns *partial* credit proportional to how confusable
the chosen technique is with the correct one (an honest mistake between look-alike
throws is penalized less than confusing two obviously different throws).

* **Return type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float)


# _autosummary/kodokan.html.md

# kodokan

kodokan — study Kodokan Judo throws from video via body-pose analysis.

A pipeline over the official *Kodokan 100 Techniques* YouTube playlist: acquire
clips + metadata, estimate per-frame two-person skeletons, segment each clip into
its repeated demonstrations, visualize skeletons (overlay-on-video and on a blank
canvas), and — later — recognize, compare, and score throws.

Quick start:

```default
from kodokan.acquire import download_techniques
from kodokan.pose import estimate_poses
from kodokan.viz import render_skeleton_video

res = download_techniques(playlist_items="2")          # Seoi-nage
seq = estimate_poses(res[0].path, source_url=res[0].info["webpage_url"])
render_skeleton_video(seq, out_path="overlay.mp4", source_video=res[0].path)
render_skeleton_video(seq, out_path="skeleton.mp4", blank_canvas=True)
```

See `misc/docs/research-architecture.md` for the tool/architecture rationale.

### Functions

| [`estimate_poses`](_autosummary/kodokan.html.md#kodokan.estimate_poses)(video_path, \*[, backend, ...])     | Estimate per-frame, per-person COCO-17 keypoints for a video clip.                 |
|-----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [`estimate_poses_tracked`](_autosummary/kodokan.html.md#kodokan.estimate_poses_tracked)(video_path, \*[, ...])      | Estimate per-frame keypoints with persistent tori/uke identity.                    |
| [`render_skeleton_video`](_autosummary/kodokan.html.md#kodokan.render_skeleton_video)(pose_seq, \*, out_path)      | Render skeletons to an MP4.                                                        |
| [`log_to_rerun`](_autosummary/kodokan.html.md#kodokan.log_to_rerun)(pose_seq, \*[, source_video, ...])    | Log frames + 2D skeletons to Rerun (overlay-on-video and skeleton-only views).     |
| [`segment_demonstrations`](_autosummary/kodokan.html.md#kodokan.segment_demonstrations)(pose_seq, \*[, ...])        | Find demonstrations, annotate each with its two-person coverage, and gate.         |
| [`compare`](_autosummary/kodokan.html.md#kodokan.compare)(features_a, features_b)                    | DTW-align two angle-feature sequences.                                             |
| [`angle_features`](_autosummary/kodokan.html.md#kodokan.angle_features)(pose_seq, \*[, person, ...])        | Per-frame joint-angle features `(F, n_angles)` for one person.                     |
| [`distance_matrix`](_autosummary/kodokan.html.md#kodokan.distance_matrix)(feature_seqs)                      | Pairwise normalized-DTW distance matrix over a list of feature sequences.          |
| [`pose_store`](_autosummary/kodokan.html.md#kodokan.pose_store)([directory])                            | A dict-like `{video_id: PoseSequence}` store backed by per-clip Parquet.           |
| [`segments_store`](_autosummary/kodokan.html.md#kodokan.segments_store)([directory])                        | A dict-like `{video_id: <json>}` store for demo segments (and metadata).           |
| [`load_all_tidy`](_autosummary/kodokan.html.md#kodokan.load_all_tidy)([store])                             | Concatenate every clip's tidy table (with a `video_id` column) into one DataFrame. |
| [`build_reference`](_autosummary/kodokan.html.md#kodokan.build_reference)(feature_list)                      | Pick the medoid demo as reference and record the baseline distance spread.         |
| [`score`](_autosummary/kodokan.html.md#kodokan.score)(query_features, reference)                   | Score a query against a reference, calibrated to the genuine-demo spread.          |
| [`feedback`](_autosummary/kodokan.html.md#kodokan.feedback)(query_features, reference, \*[, ...])     | Interpretable difference: per joint-angle and per phase (degrees).                 |
| [`demo_features`](_autosummary/kodokan.html.md#kodokan.demo_features)(pose_seq, start_s, end_s, \*[, ...]) | Cleaned joint-angle features for one demo window (primary person by default).      |
| [`recognize_segments`](_autosummary/kodokan.html.md#kodokan.recognize_segments)(pose_seq, recognizer, \*)       | Offline video mode: every detected throw in `pose_seq`, recognized.                |
| [`coach`](_autosummary/kodokan.html.md#kodokan.coach)(query_features, reference, \*[, ...])        | Score `query_features` against `reference` and advise on the worst dimensions.     |
| [`make_problem`](_autosummary/kodokan.html.md#kodokan.make_problem)(catalog, target_key, \*[, mode, ...]) | Build a multiple-choice problem for `target_key` from a technique `catalog`.       |
| [`build_catalog`](_autosummary/kodokan.html.md#kodokan.build_catalog)(\*[, min_two_person_frac, ...])      | Build `{technique_key: {"name", "clips":[...]}}` from the pose/segments stores.    |
| [`clip_filename`](_autosummary/kodokan.html.md#kodokan.clip_filename)(video_id, start_s, dur_s)            | The web-app clip file for one demo segment, named by the segment's IDENTITY.       |
| [`build_confusability`](_autosummary/kodokan.html.md#kodokan.build_confusability)([catalog, feature])            | Technique×technique similarity (0..1) from mean pooled pose descriptors.           |
| [`score_response`](_autosummary/kodokan.html.md#kodokan.score_response)(correct_key, chosen_key, \*[, ...]) | Confusion-weighted credit in [0, 1].                                               |
| [`next_target`](_autosummary/kodokan.html.md#kodokan.next_target)(keys, history, \*[, focus, rng])       | Pick the next technique to quiz: unseen and often-missed (within `focus`) first.   |
| [`log_response`](_autosummary/kodokan.html.md#kodokan.log_response)(problem, chosen_index, \*[, ...])     | Record a response (datetime + exact problem + choice + correctness + score).       |

### Classes

| [`PoseSequence`](_autosummary/kodokan.html.md#kodokan.PoseSequence)(keypoints, frame_indices, fps, ...)   | A per-frame, per-person sequence of COCO-17 keypoints for one clip.                                              |
|-----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------|
| [`Segment`](_autosummary/kodokan.html.md#kodokan.Segment)(index, start_s, end_s, start_frame, ...)   | One detected demonstration interval.                                                                             |
| [`TechniqueRecognizer`](_autosummary/kodokan.html.md#kodokan.TechniqueRecognizer)(\*[, method, temperature])     | Fit on pooled descriptors; recognize with top-k guesses and the full score vector.                               |
| [`Recognition`](_autosummary/kodokan.html.md#kodokan.Recognition)(guesses[, scores])                     | The top-k guesses, best first, and every technique's score.                                                      |
| [`Guess`](_autosummary/kodokan.html.md#kodokan.Guess)(technique, score)                            | One candidate technique and its score (higher is more likely).                                                   |
| [`LiveRecognizer`](_autosummary/kodokan.html.md#kodokan.LiveRecognizer)(recognizer, \*, fps[, k, ...])      | Live mode: each throw a [`ThrowDetector`](_autosummary/kodokan.html.md#kodokan.ThrowDetector) reports, recognized once. |
| [`ThrowDetector`](_autosummary/kodokan.html.md#kodokan.ThrowDetector)(\*, fps[, width, height, ...])       | A rolling pose buffer that reports each throw once, after its segment closes.                                    |
| [`Coaching`](_autosummary/kodokan.html.md#kodokan.Coaching)(technique, lang, score, closer_than_pct)  | A scored performance and the advice drawn from its worst dimensions.                                             |
| [`LiveCoach`](_autosummary/kodokan.html.md#kodokan.LiveCoach)(target, reference, \*, fps[, lang, ...]) | Coach a target technique on a live pose stream, one throw at a time.                                             |
| [`TechniqueTest`](_autosummary/kodokan.html.md#kodokan.TechniqueTest)(recognizer, \*[, pool, ...])         | Prompt a random technique from a focus pool; grade the performance.                                              |
| [`LiveTechniqueTest`](_autosummary/kodokan.html.md#kodokan.LiveTechniqueTest)(test, \*, fps[, featurize, ...]) | The test loop on a live stream: prompt, detect the throw, grade, prompt again.                                   |
| [`TestResult`](_autosummary/kodokan.html.md#kodokan.TestResult)(target, recognition, ...)               | The grade of one performance of the prompted technique.                                                          |

### *class* kodokan.Coaching(technique, lang, score, closer_than_pct, per_joint_deg=dict(), per_phase_deg=dict(), worst_joint=None, worst_phase=None, tips=(), reason=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A scored performance and the advice drawn from its worst dimensions.

#### reason *: [str](https://docs.python.org/3/builtins/stdtypes.html#str) | [None](https://docs.python.org/3/builtins/constants.html#None)* *= None*

`"too_short"` when the throw window had fewer
than two usable frames to compare.

* **Type:**
  Why there is no score or tip

#### *property* text *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

The advice as one paragraph.

### *class* kodokan.Guess(technique, score)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One candidate technique and its score (higher is more likely).

### *class* kodokan.LiveCoach(target, reference, \*, fps, lang='en', n_tips=2, advice={'en': {'close': 'Close to the reference: keep it up.', 'elbow': "Your {side} elbow is {deg:.0f}° off the reference: keep that arm's pull firm and close to your body.", 'headline': '{technique}: {score}/100.', 'hip': 'Your {side} hip is {deg:.0f}° off: bring your hips lower and closer to your partner.', 'kake': 'Most of the difference is in kake: commit through the finish.', 'knee': 'Your {side} knee is {deg:.0f}° off: bend your knees more as you enter, then drive up.', 'kuzushi': "Most of the difference is in kuzushi: break your partner's balance before you turn in.", 'shoulder': "Your {side} shoulder is {deg:.0f}° off: lift and turn that arm with the reference timing to take your partner's balance.", 'tsukuri': 'Most of the difference is in tsukuri: step in faster and closer.'}, 'fr': {'close': 'Proche de la référence : continuez ainsi.', 'elbow': "Votre coude {side} s'écarte de {deg:.0f}° de la référence : gardez la traction de ce bras ferme et près du corps.", 'headline': '{technique} : {score}/100.', 'hip': "Votre hanche {side_f} s'écarte de {deg:.0f}° : placez vos hanches plus bas et plus près de votre partenaire.", 'kake': "L'essentiel de l'écart est dans le kake : allez au bout de la projection.", 'knee': "Votre genou {side} s'écarte de {deg:.0f}° : fléchissez davantage les genoux en entrant, puis poussez vers le haut.", 'kuzushi': "L'essentiel de l'écart est dans le kuzushi : déséquilibrez votre partenaire avant d'entrer.", 'shoulder': "Votre épaule {side_f} s'écarte de {deg:.0f}° : levez et tournez ce bras au rythme de la référence pour déséquilibrer votre partenaire.", 'tsukuri': "L'essentiel de l'écart est dans le tsukuri : entrez plus vite et plus près."}}, featurize=<function demo_features>, \*\*detector_kwargs)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Coach a target technique on a live pose stream, one throw at a time.

[`push()`](_autosummary/kodokan.html.md#kodokan.LiveCoach.push) takes one frame (`(P, 17, 3)` keypoints) and returns
`(segment, coaching)` for each throw that closed with it. The target can be
changed between throws (`target`, `reference`). Detector options
(`buffer_s`, `close_after_s`, `segmenter`, …) pass through.

#### push(keypoints, frame_index=None)

Add one frame; return each throw it closed, coached against the target.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment), [`Coaching`](_autosummary/kodokan.html.md#kodokan.Coaching)]]

### *class* kodokan.LiveRecognizer(recognizer, \*, fps, k=3, featurize=<function pooled_demo_descriptor>, \*\*detector_kwargs)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Live mode: each throw a [`ThrowDetector`](_autosummary/kodokan.html.md#kodokan.ThrowDetector) reports, recognized once.

[`push()`](_autosummary/kodokan.html.md#kodokan.LiveRecognizer.push) takes one frame (`(P, 17, 3)` keypoints) and returns
`(segment, recognition)` for the throws that closed with it. Detector options
(`buffer_s`, `close_after_s`, `segmenter`, `width`, `height`) pass through.

#### push(keypoints, frame_index=None)

Add one frame; return the throws that closed with it, recognized.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment), [`Recognition`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Recognition)]]

### *class* kodokan.LiveTechniqueTest(test, \*, fps, featurize=<function pooled_demo_descriptor>, angle_featurize=<function demo_features>, on_prompt=None, \*\*detector_kwargs)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The test loop on a live stream: prompt, detect the throw, grade, prompt again.

[`push()`](_autosummary/kodokan.html.md#kodokan.LiveTechniqueTest.push) takes one frame and returns `(segment, result)` for each throw that
closed with it; after each graded throw the next technique is drawn
(`prompt`). Detector options pass through.

A throw is graded once it has *closed* (`close_after_s` after it ends), so the
performer should wait for the next prompt before the next throw; any motion the
detector takes for a throw also uses up a prompt.

#### push(keypoints, frame_index=None)

Add one frame; grade each throw it closed and draw the next prompt.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment), [`TestResult`](_autosummary/kodokan.testmode.html.md#kodokan.testmode.TestResult)]]

### *class* kodokan.PoseSequence(keypoints, frame_indices, fps, width, height, backend, video_path, source_url=None, keypoint_names=('nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle'), skeleton=((5, 7), (7, 9), (6, 8), (8, 10), (5, 6), (5, 11), (6, 12), (11, 12), (11, 13), (13, 15), (12, 14), (14, 16), (0, 1), (0, 2), (1, 3), (2, 4), (0, 5), (0, 6)))

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A per-frame, per-person sequence of COCO-17 keypoints for one clip.

#### keypoints

`(F, P, 17, 3)` float array of (x_px, y_px, confidence);
`NaN` for empty person slots.

* **Type:**
  `ndarray`

#### frame_indices

`(F,)` int array of source frame indices analyzed.

* **Type:**
  `ndarray`

#### fps

Source frames-per-second.

* **Type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float)

### width, height

Source frame dimensions in pixels.

#### backend

The estimator backend used.

* **Type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### video_path

Source clip path (provenance).

* **Type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### source_url

Canonical YouTube URL, if known (provenance; required by project).

* **Type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### save_npz(path)

Persist as a compressed `.npz` (the dense numeric cache).

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

#### times()

Timestamp (seconds) of each analyzed frame.

* **Return type:**
  `ndarray`

### *class* kodokan.Recognition(guesses, scores=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The top-k guesses, best first, and every technique’s score.

#### score_of(technique)

The score of `technique` (0 for a technique the recognizer never saw).

* **Return type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float)

### *class* kodokan.Segment(index, start_s, end_s, start_frame, end_frame, peak_activity, two_person_frac=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One detected demonstration interval.

### *class* kodokan.TechniqueRecognizer(, method='lda', temperature=1.0)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Fit on pooled descriptors; recognize with top-k guesses and the full score vector.

* **Parameters:**
  * **method** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – `"lda"` (LDA projection when scikit-learn is installed, else plain
    standardized space) or `"centroid"` (standardized space only).
  * **temperature** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – softmax temperature; higher spreads the scores out.

#### fit(X, y)

Fit on pooled descriptors `X` (one row per demo) and technique labels `y`.

* **Return type:**
  [`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer)

#### fit_demos(feature_seqs, labels, , levels=(1, 2, 4))

Fit on per-frame feature sequences (e.g. [`kodokan.recognize.demo_feature()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.demo_feature)).

* **Return type:**
  [`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer)

#### recognize(x, , k=3)

Top-`k` guesses (best first) and the full score vector for one descriptor.

* **Return type:**
  [`Recognition`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Recognition)

#### recognize_clip(pose_seq, start_s, end_s, \*, k=3, featurize=<function pooled_demo_descriptor>)

Recognize the throw in `pose_seq` between `start_s` and `end_s`.

* **Return type:**
  [`Recognition`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Recognition)

#### scores(x)

Every technique’s score for one pooled descriptor (they sum to 1).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`float`](https://docs.python.org/3/builtins/functions.html#float)]

### *class* kodokan.TechniqueTest(recognizer, , pool=None, references=None, lang='en', confidence_weight=0.5, seed=None, rng=None, advice={'en': {'close': 'Close to the reference: keep it up.', 'elbow': "Your {side} elbow is {deg:.0f}° off the reference: keep that arm's pull firm and close to your body.", 'headline': '{technique}: {score}/100.', 'hip': 'Your {side} hip is {deg:.0f}° off: bring your hips lower and closer to your partner.', 'kake': 'Most of the difference is in kake: commit through the finish.', 'knee': 'Your {side} knee is {deg:.0f}° off: bend your knees more as you enter, then drive up.', 'kuzushi': "Most of the difference is in kuzushi: break your partner's balance before you turn in.", 'shoulder': "Your {side} shoulder is {deg:.0f}° off: lift and turn that arm with the reference timing to take your partner's balance.", 'tsukuri': 'Most of the difference is in tsukuri: step in faster and closer.'}, 'fr': {'close': 'Proche de la référence : continuez ainsi.', 'elbow': "Votre coude {side} s'écarte de {deg:.0f}° de la référence : gardez la traction de ce bras ferme et près du corps.", 'headline': '{technique} : {score}/100.', 'hip': "Votre hanche {side_f} s'écarte de {deg:.0f}° : placez vos hanches plus bas et plus près de votre partenaire.", 'kake': "L'essentiel de l'écart est dans le kake : allez au bout de la projection.", 'knee': "Votre genou {side} s'écarte de {deg:.0f}° : fléchissez davantage les genoux en entrant, puis poussez vers le haut.", 'kuzushi': "L'essentiel de l'écart est dans le kuzushi : déséquilibrez votre partenaire avant d'entrer.", 'shoulder': "Votre épaule {side_f} s'écarte de {deg:.0f}° : levez et tournez ce bras au rythme de la référence pour déséquilibrer votre partenaire.", 'tsukuri': "L'essentiel de l'écart est dans le tsukuri : entrez plus vite et plus près."}})

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Prompt a random technique from a focus pool; grade the performance.

* **Parameters:**
  * **recognizer** ([`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer)) – a fitted [`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer).
  * **pool** ([`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the techniques to draw from (default: all the recognizer knows).
  * **references** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – `{technique: build_reference(...)}`; techniques with one are
    also graded on closeness, with advice.
  * **confidence_weight** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – share of the score from the target’s confidence (the
    rest from closeness to the reference, when there is one).
  * **seed** ([`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – or `rng`, for a reproducible sequence of prompts.

#### grade(descriptor, angle_features=None)

Grade one performance: its pooled `descriptor` and, for closeness, its
per-frame `angle_features` (`kodokan.score.demo_features()`).

* **Return type:**
  [`TestResult`](_autosummary/kodokan.testmode.html.md#kodokan.testmode.TestResult)

#### grade_clip(pose_seq, start_s, end_s, \*, featurize=<function pooled_demo_descriptor>, angle_featurize=<function demo_features>)

Grade the performance in `pose_seq` between `start_s` and `end_s`.

* **Return type:**
  [`TestResult`](_autosummary/kodokan.testmode.html.md#kodokan.testmode.TestResult)

#### next_prompt()

Draw the next technique to perform (never the same one twice in a row).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### *class* kodokan.TestResult(target, recognition, target_confidence, coaching, score)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The grade of one performance of the prompted technique.

#### *property* passed *: [bool](https://docs.python.org/3/builtins/functions.html#bool)*

Whether the recognizer’s best guess is the target.

### *class* kodokan.ThrowDetector(\*, fps, width=0, height=0, buffer_s=20.0, close_after_s=1.0, segmenter=<function motion_segments>)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A rolling pose buffer that reports each throw once, after its segment closes.

Push one frame at a time (`(P, 17, 3)` keypoints, as in [`PoseSequence`](_autosummary/kodokan.html.md#kodokan.PoseSequence)).
[`push()`](_autosummary/kodokan.html.md#kodokan.ThrowDetector.push) returns `(buffer, segment)` for the throws that closed with that
frame. A segment counts as closed when it ends at least `close_after_s` before
the newest frame; the buffer keeps the last `buffer_s` seconds of pushed frames
(at `fps` frames a second: push every analysed frame, or pass the analysed rate
as `fps`). A segment that mostly overlaps a throw already reported is that throw.

#### buffer()

The buffered frames as a [`PoseSequence`](_autosummary/kodokan.html.md#kodokan.PoseSequence) (people padded with NaN).

* **Return type:**
  [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)

#### push(keypoints, frame_index=None)

Add one frame; return `(buffer, segment)` for each throw it closed.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence), [`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment)]]

### kodokan.angle_features(pose_seq, , person=0, frame_range=None)

Per-frame joint-angle features `(F, n_angles)` for one person.

* **Return type:**
  `ndarray`

### kodokan.build_catalog(, min_two_person_frac=None, min_demo_s=1.0, max_demos=None, segments=None)

Build `{technique_key: {"name", "clips":[...]}}` from the pose/segments stores.

Aggregates all sources: each clip contributes its demo intervals (for looping media),
so a technique present in several sources offers varied multiple-choice media.

`max_demos` caps the demos kept per source video (`None`, the default, keeps every
demo that passes the quality gate — #37: the store has 6–8 reps per video and all of
them are worth showing). `segments` is the `{video_id: record}` mapping to read
(default: [`kodokan.store.segments_store()`](_autosummary/kodokan.store.html.md#kodokan.store.segments_store)).

### kodokan.build_confusability(catalog=None, , feature='tori_angles_pos')

Technique×technique similarity (0..1) from mean pooled pose descriptors.

`similarity[a][b]` high ⇒ techniques a, b look alike in pose-space (likely
confusable for a learner). An honest, recognizer-free proxy; swap for the model’s
confusion matrix once cross-source recognition works.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.build_reference(feature_list)

Pick the medoid demo as reference and record the baseline distance spread.

Returns `{medoid, reference, baseline, distance_matrix}` where `baseline` is
the array of normalized-DTW distances from every other demo to the medoid.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.clip_filename(video_id, start_s, dur_s)

The web-app clip file for one demo segment, named by the segment’s IDENTITY.

`{video_id}_{start_ms}_{dur_ms}.mp4`: the name says which time span of which source it
shows, so re-segmenting can never make an existing name show a different cut (#45) — a
changed segment simply gets a new name. Positional names (`{vid}_3.mp4`) could.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### kodokan.coach(query_features, reference, , technique=None, lang='en', n_tips=2, min_deviation_deg=10.0, advice={'en': {'close': 'Close to the reference: keep it up.', 'elbow': "Your {side} elbow is {deg:.0f}° off the reference: keep that arm's pull firm and close to your body.", 'headline': '{technique}: {score}/100.', 'hip': 'Your {side} hip is {deg:.0f}° off: bring your hips lower and closer to your partner.', 'kake': 'Most of the difference is in kake: commit through the finish.', 'knee': 'Your {side} knee is {deg:.0f}° off: bend your knees more as you enter, then drive up.', 'kuzushi': "Most of the difference is in kuzushi: break your partner's balance before you turn in.", 'shoulder': "Your {side} shoulder is {deg:.0f}° off: lift and turn that arm with the reference timing to take your partner's balance.", 'tsukuri': 'Most of the difference is in tsukuri: step in faster and closer.'}, 'fr': {'close': 'Proche de la référence : continuez ainsi.', 'elbow': "Votre coude {side} s'écarte de {deg:.0f}° de la référence : gardez la traction de ce bras ferme et près du corps.", 'headline': '{technique} : {score}/100.', 'hip': "Votre hanche {side_f} s'écarte de {deg:.0f}° : placez vos hanches plus bas et plus près de votre partenaire.", 'kake': "L'essentiel de l'écart est dans le kake : allez au bout de la projection.", 'knee': "Votre genou {side} s'écarte de {deg:.0f}° : fléchissez davantage les genoux en entrant, puis poussez vers le haut.", 'kuzushi': "L'essentiel de l'écart est dans le kuzushi : déséquilibrez votre partenaire avant d'entrer.", 'shoulder': "Votre épaule {side_f} s'écarte de {deg:.0f}° : levez et tournez ce bras au rythme de la référence pour déséquilibrer votre partenaire.", 'tsukuri': "L'essentiel de l'écart est dans le tsukuri : entrez plus vite et plus près."}})

Score `query_features` against `reference` and advise on the worst dimensions.

* **Parameters:**
  * **query_features** (`ndarray`) – per-frame joint angles of the performance
    (`kodokan.score.demo_features()`).
  * **reference** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – the target technique’s `build_reference()`.
  * **lang** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – a key of `advice` (`"en"` or `"fr"` built in).
  * **n_tips** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – joint tips to give, worst first, after the phase tip.
  * **min_deviation_deg** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – a phase or joint closer than this gets no tip; with
    none left, the advice says the performance is close to the reference.
* **Return type:**
  [`Coaching`](_autosummary/kodokan.html.md#kodokan.Coaching)

A window with fewer than two usable frames cannot be compared: it gets a
[`Coaching`](_autosummary/kodokan.html.md#kodokan.Coaching) with no score and `reason="too_short"` rather than an error,
so a live loop goes on.

### kodokan.compare(features_a, features_b)

DTW-align two angle-feature sequences.

Returns a dict with `distance` (total DTW cost), `normalized` (cost per
aligned step — comparable across different-length demos), the warping `path`,
and the cleaned input arrays `a`/`b`.

One DTW pass gives both the path and the distance, on dtaidistance’s C
library when it is available (its pure-Python fallback is ~250x slower).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.demo_features(pose_seq, start_s, end_s, , person=None)

Cleaned joint-angle features for one demo window (primary person by default).

* **Return type:**
  `ndarray`

### kodokan.distance_matrix(feature_seqs)

Pairwise normalized-DTW distance matrix over a list of feature sequences.

The normalized distance is symmetric, so only the upper triangle is computed.

* **Return type:**
  `ndarray`

### kodokan.estimate_poses(video_path, , backend='rtmlib', n_persons=2, conf_thresh=0.3, frame_step=1, frame_range=None, device=None, source_url=None, progress=True, \*\*backend_kwargs)

Estimate per-frame, per-person COCO-17 keypoints for a video clip.

Simplest use: `estimate_poses("clip.mp4")` → a [`PoseSequence`](_autosummary/kodokan.html.md#kodokan.PoseSequence) with the
two highest-confidence people per frame (left→right ordered) via RTMPose.

* **Parameters:**
  * **video_path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Path to the video clip.
  * **backend** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – `"rtmlib"` (RTMPose top-down, CPU/ONNX; default, and the
    only one installed by `kodokan[pose]`) or `"ultralytics"`
    (YOLO11-pose, MPS), which needs `kodokan[track]` — an
    AGPL-3.0-or-later dependency, see the README’s
    “Licensing of extras”.
  * **n_persons** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of person slots to keep per frame (2 for tori+uke).
  * **conf_thresh** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Minimum mean per-person confidence to keep a detection.
  * **frame_step** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Analyze every `frame_step`-th frame (1 = every frame).
  * **frame_range** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Optional `(start, stop)` frame index window.
  * **device** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Backend device (`"cpu"`/`"mps"`); backend default if `None`.
  * **source_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Canonical source URL to record as provenance.
  * **progress** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print a progress line periodically.
  * **\*\*backend_kwargs** – Forwarded to the backend (e.g. `mode="performance"`
    for rtmlib, or `model_name="yolo11m-pose.pt"` for ultralytics).
* **Return type:**
  [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)
* **Returns:**
  A [`PoseSequence`](_autosummary/kodokan.html.md#kodokan.PoseSequence) of shape `(F, n_persons, 17, 3)`.

### kodokan.estimate_poses_tracked(video_path, , n_persons=2, tracker='botsort.yaml', conf_thresh=0.3, max_gap_frac=0.15, stale_after=12, frame_step=1, frame_range=None, device='mps', model_name='yolo11n-pose.pt', source_url=None, progress=True)

Estimate per-frame keypoints with persistent tori/uke identity.

Returns a [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence) whose person slots are *stable*
across the clip (slot 0 = the track that is, on average, further left).

* **Parameters:**
  * **video_path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Path to the clip.
  * **n_persons** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of stable identity slots to keep (2 for tori+uke).
  * **tracker** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Ultralytics tracker config (`"botsort.yaml"` or `"bytetrack.yaml"`).
  * **conf_thresh** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Minimum mean per-person confidence to count a detection.
  * **frame_step** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Analyze every n-th frame.
  * **frame_range** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Optional `(start, stop)` frame window.
  * **device** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Torch device (`"mps"`/`"cpu"`).
  * **model_name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – YOLO-pose weights (resolved under the data models dir).
  * **source_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Provenance URL.
  * **progress** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress.
* **Return type:**
  [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)

### kodokan.feedback(query_features, reference, , n_phases=3)

Interpretable difference: per joint-angle and per phase (degrees).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.load_all_tidy(store=None)

Concatenate every clip’s tidy table (with a `video_id` column) into one DataFrame.

### kodokan.log_response(problem, chosen_index, , user='default', store=None, similarity=None, timestamp=None)

Record a response (datetime + exact problem + choice + correctness + score).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.log_to_rerun(pose_seq, , source_video=None, save=None, spawn=False, blank_canvas=True, frame_scale=0.5, conf_thresh=0.3, entity_prefix='')

Log frames + 2D skeletons to Rerun (overlay-on-video and skeleton-only views).

* **Parameters:**
  * **pose_seq** ([`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)) – The sequence to log.
  * **source_video** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – If given, downscaled frames are logged under `video/` as a backdrop.
  * **save** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Write a standalone `.rrd` recording to this path.
  * **spawn** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Launch the Rerun viewer.
  * **blank_canvas** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Also log a skeleton-only view under `skeleton/`.
  * **frame_scale** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Downscale factor for logged video frames (keypoints scaled to match).
  * **conf_thresh** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Hide keypoints below this confidence.
  * **entity_prefix** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Prefix all entity paths (use distinct prefixes to compare two
    sequences side-by-side in one recording, e.g. `"demoA/"`, `"demoB/"`).
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### kodokan.make_problem(catalog, target_key, , mode='video_to_name', n_choices=4, similarity=None, rng=None, clip_for=None)

Build a multiple-choice problem for `target_key` from a technique `catalog`.

`catalog` maps `technique_key -> {"name": str, "clips": [clip dicts]}`.
`clip_for(key)` returns a looping clip for a key (default: first clip); for
`name_to_video` the choices are clips, for `video_to_name` they are names.

* **Return type:**
  [`Problem`](_autosummary/kodokan.flashcards.html.md#kodokan.flashcards.Problem)

### kodokan.next_target(keys, history, , focus=None, rng=None)

Pick the next technique to quiz: unseen and often-missed (within `focus`) first.

Spaced-repetition-ish weight = (wrongs + 1) / (seen + 1): unseen -> 1, frequently
wrong -> high, mastered -> low. `history` is a list of response dicts.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### kodokan.pose_store(directory=None)

A dict-like `{video_id: PoseSequence}` store backed by per-clip Parquet.

### kodokan.recognize_segments(pose_seq, recognizer, \*, k=3, featurize=<function pooled_demo_descriptor>, segmenter=<function motion_segments>)

Offline video mode: every detected throw in `pose_seq`, recognized.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment), [`Recognition`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Recognition)]]

### kodokan.render_skeleton_video(pose_seq, , out_path, source_video=None, blank_canvas=False, conf_thresh=0.3, fps=None, person_colors=((0, 255, 0), (255, 0, 255), (255, 255, 0), (0, 165, 255)), background=(0, 0, 0), thickness=2, radius=4)

Render skeletons to an MP4.

* **Parameters:**
  * **pose_seq** ([`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)) – The pose sequence to draw.
  * **out_path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Output `.mp4` path.
  * **source_video** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Source clip; required (and used as backdrop) unless
    `blank_canvas=True`.
  * **blank_canvas** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, draw on a solid `background` instead of the video.
  * **conf_thresh** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Hide keypoints/edges below this confidence.
  * **fps** ([`float`](https://docs.python.org/3/builtins/functions.html#float) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Output fps (defaults to the sequence’s source fps).
  * **person_colors** – BGR colors per person slot.
  * **background** – BGR background color for the blank canvas.
  * **thickness** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Edge thickness / joint radius in pixels.
  * **radius** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Edge thickness / joint radius in pixels.
* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)
* **Returns:**
  The output path.

### kodokan.score(query_features, reference)

Score a query against a reference, calibrated to the genuine-demo spread.

`score` is 0–100: 100 ≈ as close as the closest genuine demo, 0 ≈ as far as the
90th-percentile (or worse). `closer_than_pct` is the percent of genuine demos
the query is closer-to-reference than.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.score_response(correct_key, chosen_key, , similarity=None, max_partial=0.5)

Confusion-weighted credit in [0, 1].

Correct = 1.0. A wrong answer earns *partial* credit proportional to how confusable
the chosen technique is with the correct one (an honest mistake between look-alike
throws is penalized less than confusing two obviously different throws).

* **Return type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float)

### kodokan.segment_demonstrations(pose_seq, , video_path=None, use_optical_flow=False, min_two_person_frac=0.0, \*\*find_kwargs)

Find demonstrations, annotate each with its two-person coverage, and gate.

Uses pose motion energy by default (fuse optical flow with `use_optical_flow`).
Segments whose two-person coverage is below `min_two_person_frac` are dropped
(a throw demonstration needs both tori and uke), then re-indexed in time order.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment)]

### kodokan.segments_store(directory=None)

A dict-like `{video_id: <json>}` store for demo segments (and metadata).

### Modules

| [`acquire`](_autosummary/kodokan.acquire.html.md#module-kodokan.acquire)           | Acquire Kodokan technique clips from YouTube (thin wrapper over `yb.download`).                      |
|-------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------|
| [`canon3d`](_autosummary/kodokan.canon3d.html.md#module-kodokan.canon3d)           | Pelvis-frame (Procrustes) canonicalization of 3D world landmarks.                                    |
| [`competitions`](_autosummary/kodokan.competitions.html.md#module-kodokan.competitions) | A calendar of upcoming judo competitions in one French département, and who may enter each.          |
| [`config`](_autosummary/kodokan.config.html.md#module-kodokan.config)             | Where kodokan keeps its data (downloaded clips + derived artifacts).                                 |
| [`descriptors`](_autosummary/kodokan.descriptors.html.md#module-kodokan.descriptors)   | Experimental per-demo feature descriptors (to test what makes throws separable).                     |
| [`flashcards`](_autosummary/kodokan.flashcards.html.md#module-kodokan.flashcards)     | Technique-recognition learning game (app #6) — logic layer.                                          |
| [`pose`](_autosummary/kodokan.pose.html.md#module-kodokan.pose)                 | Body-pose estimation: a video → a sequence of per-person skeletal keypoints.                         |
| [`recognize`](_autosummary/kodokan.recognize.html.md#module-kodokan.recognize)       | Learned-vs-DTW technique recognition experiments (data-appropriate, no GPU).                         |
| [`recognizer`](_autosummary/kodokan.recognizer.html.md#module-kodokan.recognizer)     | Technique recognition for applications: top-k guesses with inspectable scores (#3).                  |
| [`segment`](_autosummary/kodokan.segment.html.md#module-kodokan.segment)           | Segment a clip into its repeated demonstrations of one throw.                                        |
| [`store`](_autosummary/kodokan.store.html.md#module-kodokan.store)               | dol-backed stores for the pipeline's artifacts (the analysis SSOT).                                  |
| [`testmode`](_autosummary/kodokan.testmode.html.md#module-kodokan.testmode)         | Technique test mode: perform the technique the system names, get scored (#5).                        |
| [`tori_labels`](_autosummary/kodokan.tori_labels.html.md#module-kodokan.tori_labels)   | Hand-labelling of the tori heuristic (#49): sample demos, then score agreement.                      |
| [`track`](_autosummary/kodokan.track.html.md#module-kodokan.track)               | Stable tori/uke identity tracking (BoT-SORT / ByteTrack).                                            |
| [`viz`](_autosummary/kodokan.viz.html.md#module-kodokan.viz)                   | Visualize a [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence). |
| [`vocab`](_autosummary/kodokan.vocab.html.md#module-kodokan.vocab)               | Word parts of technique names: which techniques share which part, and how often.                     |


# _autosummary/kodokan.pose.html.md

# kodokan.pose

Body-pose estimation: a video → a sequence of per-person skeletal keypoints.

A single [`estimate_poses()`](_autosummary/kodokan.pose.html.md#kodokan.pose.estimate_poses) facade with a pluggable, multi-person backend
(`rtmlib` = RTMPose top-down, default; or `ultralytics` = YOLO11-pose). Both
emit the **COCO-17** keypoint layout, so downstream code is backend-agnostic.

Judo throws involve two people in close contact, so the default keeps the
`n_persons` highest-confidence detections per frame and orders them left→right
(a crude tori/uke proxy that is good enough for visualization and for the first
“compare two demos” experiments; true identity tracking through the occluded
apex of a throw is a separate, harder problem — see `misc/docs/research-architecture.md`).

Output is a [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence): an `(F, P, 17, 3)` array (x, y, confidence;
`NaN` where a person slot is empty in that frame), plus the frame indices, fps,
and source provenance.

### Module Attributes

| [`COCO17_KEYPOINTS`](_autosummary/kodokan.pose.html.md#kodokan.pose.COCO17_KEYPOINTS)   | COCO-17 keypoint names, in index order.                                     |
|---------------------------------------------------------------------|-----------------------------------------------------------------------------|
| [`COCO17_SKELETON`](_autosummary/kodokan.pose.html.md#kodokan.pose.COCO17_SKELETON)    | COCO-17 skeleton edges (pairs of keypoint indices) for drawing/connections. |

### Functions

| [`estimate_poses`](_autosummary/kodokan.pose.html.md#kodokan.pose.estimate_poses)(video_path, \*[, backend, ...])   | Estimate per-frame, per-person COCO-17 keypoints for a video clip.   |
|---------------------------------------------------------------------------------------------------|----------------------------------------------------------------------|

### Classes

| [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)(keypoints, frame_indices, fps, ...)   | A per-frame, per-person sequence of COCO-17 keypoints for one clip.   |
|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------|

### kodokan.pose.COCO17_KEYPOINTS *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), ...]* *= ('nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle')*

COCO-17 keypoint names, in index order.

### kodokan.pose.COCO17_SKELETON *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[int](https://docs.python.org/3/builtins/functions.html#int), [int](https://docs.python.org/3/builtins/functions.html#int)], ...]* *= ((5, 7), (7, 9), (6, 8), (8, 10), (5, 6), (5, 11), (6, 12), (11, 12), (11, 13), (13, 15), (12, 14), (14, 16), (0, 1), (0, 2), (1, 3), (2, 4), (0, 5), (0, 6))*

COCO-17 skeleton edges (pairs of keypoint indices) for drawing/connections.

### *class* kodokan.pose.PoseSequence(keypoints, frame_indices, fps, width, height, backend, video_path, source_url=None, keypoint_names=('nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle'), skeleton=((5, 7), (7, 9), (6, 8), (8, 10), (5, 6), (5, 11), (6, 12), (11, 12), (11, 13), (13, 15), (12, 14), (14, 16), (0, 1), (0, 2), (1, 3), (2, 4), (0, 5), (0, 6)))

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A per-frame, per-person sequence of COCO-17 keypoints for one clip.

#### keypoints

`(F, P, 17, 3)` float array of (x_px, y_px, confidence);
`NaN` for empty person slots.

* **Type:**
  `ndarray`

#### frame_indices

`(F,)` int array of source frame indices analyzed.

* **Type:**
  `ndarray`

#### fps

Source frames-per-second.

* **Type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float)

### width, height

Source frame dimensions in pixels.

#### backend

The estimator backend used.

* **Type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### video_path

Source clip path (provenance).

* **Type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### source_url

Canonical YouTube URL, if known (provenance; required by project).

* **Type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### save_npz(path)

Persist as a compressed `.npz` (the dense numeric cache).

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

#### times()

Timestamp (seconds) of each analyzed frame.

* **Return type:**
  `ndarray`

### kodokan.pose.estimate_poses(video_path, , backend='rtmlib', n_persons=2, conf_thresh=0.3, frame_step=1, frame_range=None, device=None, source_url=None, progress=True, \*\*backend_kwargs)

Estimate per-frame, per-person COCO-17 keypoints for a video clip.

Simplest use: `estimate_poses("clip.mp4")` → a [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence) with the
two highest-confidence people per frame (left→right ordered) via RTMPose.

* **Parameters:**
  * **video_path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Path to the video clip.
  * **backend** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – `"rtmlib"` (RTMPose top-down, CPU/ONNX; default, and the
    only one installed by `kodokan[pose]`) or `"ultralytics"`
    (YOLO11-pose, MPS), which needs `kodokan[track]` — an
    AGPL-3.0-or-later dependency, see the README’s
    “Licensing of extras”.
  * **n_persons** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of person slots to keep per frame (2 for tori+uke).
  * **conf_thresh** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Minimum mean per-person confidence to keep a detection.
  * **frame_step** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Analyze every `frame_step`-th frame (1 = every frame).
  * **frame_range** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Optional `(start, stop)` frame index window.
  * **device** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Backend device (`"cpu"`/`"mps"`); backend default if `None`.
  * **source_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Canonical source URL to record as provenance.
  * **progress** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print a progress line periodically.
  * **\*\*backend_kwargs** – Forwarded to the backend (e.g. `mode="performance"`
    for rtmlib, or `model_name="yolo11m-pose.pt"` for ultralytics).
* **Return type:**
  [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)
* **Returns:**
  A [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence) of shape `(F, n_persons, 17, 3)`.


# _autosummary/kodokan.recognize.html.md

# kodokan.recognize

Learned-vs-DTW technique recognition experiments (data-appropriate, no GPU).

The feature bake-off showed DTW on hand-crafted angles can’t tell techniques apart.
This module tests whether the bottleneck is the *classifier*, the *features*, or
tori/uke *role inconsistency*, with leave-one-out CV on the small dataset:

- feature modes: `primary_angles` (baseline), `tori_angles` (role-consistent —
  tori picked as the person left standing), `tori_angles_pos`.
- methods: `dtw_1nn` (DTW nearest-neighbour), `pool_centroid` / `pool_knn`
  (temporal-pyramid pooled descriptor + nearest-centroid / kNN), and `pool_lda_knn`
  (LDA-reduced + kNN, if scikit-learn is available).

Everything is numpy (sklearn optional), appropriate for ~80 samples where deep nets
would overfit; the same harness scales to more techniques once more data is collected.

### Functions

| [`classification_metrics`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.classification_metrics)(y_true, y_pred, \*[, ...])   | Top-1, balanced (macro-recall), majority-class baseline, n_classes, n.                                                        |
|------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------|
| [`confusion_pairs`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.confusion_pairs)(y_true, y_pred, \*[, top])          | Most-frequent misclassifications as `{true, pred, count}` (off-diagonal).                                                     |
| [`demo_feature`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.demo_feature)(pose_seq, start_s, end_s, \*, mode)    | Per-frame features for one demo under a role/feature mode.                                                                    |
| `dtw_1nn_accuracy`(feature_seqs, labels)                                                             |                                                                                                                               |
| [`dtw_1nn_predict`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.dtw_1nn_predict)(feature_seqs, labels)               | Leave-one-out 1-NN by DTW distance; returns predicted label per item.                                                         |
| [`loo_medoid_separability`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.loo_medoid_separability)(feats_by_tech, \*, ...)     | Leak-free (leave-one-demo-out medoid) technique-separability report.                                                          |
| [`loo_pooled_predict`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.loo_pooled_predict)(X, y, \*[, method, k, ...])      | Leave-one-out (or leave-one-GROUP-out) predictions; preprocessing fit on train only.                                          |
| [`mirror_feature`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.mirror_feature)(feat, \*, mode)                      | Per-frame features of the horizontally mirrored demo, from [`demo_feature()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.demo_feature)'s. |
| [`paired_bootstrap_separability`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.paired_bootstrap_separability)(rows_a, rows_b, \*)   | 95% percentile-bootstrap CIs for A, B and the PAIRED difference A−B.                                                          |
| `pool_centroid_accuracy`(X, y)                                                                       |                                                                                                                               |
| `pool_knn_accuracy`(X, y[, k])                                                                       |                                                                                                                               |
| `pool_lda_knn_accuracy`(X, y[, k])                                                                   |                                                                                                                               |
| [`pooled_descriptor`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.pooled_descriptor)(feat, \*[, levels])               | Temporal-pyramid pooled fixed-length descriptor (mean+std per segment).                                                       |
| [`roc_auc_distances`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.roc_auc_distances)(genuine, impostor)                | Standard ROC-AUC for a *distance* score: `P(impostor > genuine)` (ties=0.5).                                                  |
| [`similarity_from_confusion`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.similarity_from_confusion)(y_true, y_pred, \*)       | `target -> {other: weight}` (0..1) from a recognizer's confusions.                                                            |
| [`tori_decision`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.tori_decision)(pose_seq, start_s, end_s, \*[, ...])  | Tori (thrower) heuristic with a confidence margin and an abstain flag.                                                        |
| [`tori_decision_stats`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.tori_decision_stats)(decisions)                      | Aggregate fall-back / abstain rates and median margin over decisions.                                                         |
| [`tori_index`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.tori_index)(pose_seq, start_s, end_s)                | Heuristic tori slot (thin wrapper over [`tori_decision()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.tori_decision)).                     |

### Classes

| [`ToriDecision`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.ToriDecision)(index, margin, fell_back, abstained)   | Outcome of the tori/uke role heuristic, with a confidence margin.   |
|------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------|

### *class* kodokan.recognize.ToriDecision(index, margin, fell_back, abstained)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Outcome of the tori/uke role heuristic, with a confidence margin.

The “role-consistency is the dominant recognition lever” claim rests on this
heuristic, so — per the adversarial review — every call is now instrumented.

#### index

Chosen tori slot (always a usable slot, even when abstaining).

* **Type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)

#### margin

Finish-frame hip-y separation between the two judoka in
*torso-length* units (how much lower uke’s hips sit than tori’s).
Larger = more confident; `nan` when the cue was unusable.

* **Type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float)

#### fell_back

The hip-y cue was unusable, so the most-present slot was used.

* **Type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### abstained

Low-confidence decision (`margin` below the abstain
threshold, or a fall-back) — the role label should not be trusted.

* **Type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### kodokan.recognize.classification_metrics(y_true, y_pred, , n_boot=0, seed=0)

Top-1, balanced (macro-recall), majority-class baseline, n_classes, n.

Pass `n_boot > 0` to add 95% percentile-bootstrap confidence intervals
(`top1_ci`/`balanced_ci`) — the rigor the review asked for, so small-n
accuracy differences aren’t over-read. Default `n_boot=0` is unchanged.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.recognize.confusion_pairs(y_true, y_pred, , top=None)

Most-frequent misclassifications as `{true, pred, count}` (off-diagonal).

Per-class confusion that stays readable at many classes: instead of a dense
N×N matrix it returns only the non-zero true→pred error cells, sorted by
count. A `pred` of `-1` means an abstain/no-prediction.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### kodokan.recognize.demo_feature(pose_seq, start_s, end_s, , mode)

Per-frame features for one demo under a role/feature mode.

* **Return type:**
  `ndarray`

### kodokan.recognize.dtw_1nn_predict(feature_seqs, labels)

Leave-one-out 1-NN by DTW distance; returns predicted label per item.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

### kodokan.recognize.loo_medoid_separability(feats_by_tech, , distance, per_demo=False)

Leak-free (leave-one-demo-out medoid) technique-separability report.

The earlier feature bake-off built each technique’s medoid reference from
*all* its demos, including the one being tested — so genuine distances were
optimistically low and needed an ad-hoc self-zero filter. Here a held-out
demo’s GENUINE distance is measured to the medoid of its technique’s *other*
demos (true leave-one-out, no self-zero), and its IMPOSTOR distances to every
other technique’s medoid. Reports leave-one-out nearest-medoid accuracy and
the standard ROC-AUC ([`roc_auc_distances()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.roc_auc_distances)).

* **Parameters:**
  * **feats_by_tech** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)) – per technique, a list of per-demo feature arrays.
  * **distance** – `(feat_a, feat_b) -> float` (e.g. normalized DTW).
  * **per_demo** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – also return `per_demo` — one `{tech, genuine, impostor, correct}`
    per held-out demo, in input order — so callers can bootstrap without
    recomputing distances (see [`paired_bootstrap_separability()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.paired_bootstrap_separability)).
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.recognize.loo_pooled_predict(X, y, , method='lda_knn', k=3, groups=None, X_aug=None)

Leave-one-out (or leave-one-GROUP-out) predictions; preprocessing fit on train only.

If `groups` is given (e.g. source `video_id` per sample), each fold excludes ALL
samples sharing the held-out sample’s group — i.e. **leave-one-clip-out**, which removes
within-clip leakage. Otherwise it is plain leave-one-sample-out.

`X_aug` (same shape as `X`, row `j` an augmented copy of sample `j`, e.g. the
pooled [`mirror_feature()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.mirror_feature)) adds the copies of the TRAIN-fold samples to each
fold’s training set; a held-out sample’s own copy (and its group’s) never trains.

* **Return type:**
  `ndarray`

### kodokan.recognize.mirror_feature(feat, , mode)

Per-frame features of the horizontally mirrored demo, from [`demo_feature()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.demo_feature)’s.

`mirror_feature(demo_feature(seq, ...), mode=m)` equals `demo_feature` of the
mirrored `seq` (tested), so mirrored training copies cost no pose estimation.

* **Return type:**
  `ndarray`

### kodokan.recognize.paired_bootstrap_separability(rows_a, rows_b, , n_boot=2000, seed=0)

95% percentile-bootstrap CIs for A, B and the PAIRED difference A−B.

`rows_a`/`rows_b` are `per_demo` outputs of [`loo_medoid_separability()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.loo_medoid_separability)
over the SAME demos in the same order (e.g. two modalities on identical frames), so
each resample draws the same demos for both — the difference CI then reflects only
the modality, not which demos happened to be drawn. Distances are reused, not
recomputed. A difference CI that straddles 0 means “not distinguishable at this n”.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.recognize.pooled_descriptor(feat, , levels=(1, 2, 4))

Temporal-pyramid pooled fixed-length descriptor (mean+std per segment).

* **Return type:**
  `ndarray`

### kodokan.recognize.roc_auc_distances(genuine, impostor)

Standard ROC-AUC for a *distance* score: `P(impostor > genuine)` (ties=0.5).

Equals the Mann–Whitney U statistic divided by `|genuine|·|impostor|` — the
“standard ROC-AUC” the review asked for (replacing the ad-hoc self-zero-dropping
estimate). Larger = better separation (impostor demos sit farther than genuine
ones). NaNs are dropped; returns `nan` if either side is empty.

* **Return type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float)

### kodokan.recognize.similarity_from_confusion(y_true, y_pred, , symmetric=True)

`target -> {other: weight}` (0..1) from a recognizer’s confusions.

`weight` is the share of `target`’s samples predicted as `other` (off-diagonal
only; abstains and self-predictions are ignored). With `symmetric` (default) the
weight is the mean of both directions, so “a looks like b” implies “b looks like a”,
which suits distractor choice. Same shape as `flashcards.build_confusability`, so it
plugs into `Quiz(similarity=...)`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.recognize.tori_decision(pose_seq, start_s, end_s, , abstain_margin=0.15)

Tori (thrower) heuristic with a confidence margin and an abstain flag.

Tori is the judoka whose hips stay highest (smallest image-y) over the last
third of the demo — uke has been thrown to the ground. The margin is the two
judoka’s finish hip-y separation in torso-length units; below
`abstain_margin` (or when the cue is unusable and we fall back to presence)
the role assignment is unreliable and `abstained` is set. See
[`tori_decision_stats()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.tori_decision_stats) for aggregate fall-back/abstain rates.

* **Return type:**
  [`ToriDecision`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.ToriDecision)

### kodokan.recognize.tori_decision_stats(decisions)

Aggregate fall-back / abstain rates and median margin over decisions.

The instrumentation the review asked for: run this over every demo’s
[`tori_decision()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.tori_decision) to see how often the “dominant lever” heuristic is
actually confident vs. abstaining.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.recognize.tori_index(pose_seq, start_s, end_s)

Heuristic tori slot (thin wrapper over [`tori_decision()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.tori_decision)).

Backward-compatible: returns just the chosen slot. Use [`tori_decision()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.tori_decision)
when you need the confidence margin / abstain flag.

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)


# _autosummary/kodokan.recognizer.html.md

# kodokan.recognizer

Technique recognition for applications: top-k guesses with inspectable scores (#3).

[`kodokan.recognize`](_autosummary/kodokan.recognize.html.md#module-kodokan.recognize) holds the research tools (features, LOO evaluation, metrics).
This module is the application facade over them:

- [`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer) — fit on pooled demo descriptors, then
  [`recognize()`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer.recognize) returns a [`Recognition`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Recognition): the top-k
  [`Guess`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Guess) es *and* the score of every technique (the intermediate vector a UI
  > can show).
- [`recognize_segments()`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.recognize_segments) — offline video: detect the throws in a whole pose
  sequence and recognize each.
- [`ThrowDetector`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.ThrowDetector) — a rolling pose buffer that reports each throw once its
  segment has closed; [`LiveRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.LiveRecognizer) recognizes them (live stream mode).

Scores are a softmax over negative distances to each technique’s centroid, in the
train-standardized (and, when scikit-learn is installed, LDA-projected) descriptor
space, with distances in units of the typical within-technique spread (measured
leave-one-out, as a held-out demo would see it). They rank techniques and sum to 1;
they are not calibrated probabilities. The LDA projection is still fit on every
training demo, so with few demos per technique the spread stays optimistic.

```pycon
>>> rng = np.random.default_rng(0)
>>> X = np.vstack([rng.normal(c, 0.3, size=(5, 4)) for c in (0.0, 3.0, 6.0)])
>>> y = np.repeat(["seoi-nage", "o-goshi", "uchi-mata"], 5)
>>> rec = TechniqueRecognizer(method="centroid").fit(X, y)
>>> r = rec.recognize(np.full(4, 3.1), k=2)
>>> r.guesses[0].technique, len(r.guesses), round(sum(r.scores.values()), 6)
('o-goshi', 2, 1.0)
```

### Module Attributes

| [`Featurizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Featurizer)             | `(pose_seq, start_s, end_s) -> fixed-length descriptor` of one throw window.                                                                                          |
|-------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`DFLT_MIN_PEAK_ACTIVITY`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.DFLT_MIN_PEAK_ACTIVITY) | Smoothed motion energy (keypoint speed, px per analysed frame) a throw must reach; below it a "segment" is pose jitter, which quantile thresholds alone would accept. |

### Functions

| [`loo_top_k_accuracy`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.loo_top_k_accuracy)(X, y, \*[, ks, groups, method])   | Leave-one-out (or leave-one-group-out) top-k accuracy of [`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer).                                                                                                                                                                                          |
|-------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`motion_segments`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.motion_segments)(pose_seq, \*[, min_peak_activity])   | Throw windows by motion energy ([`kodokan.segment.find_segments()`](_autosummary/kodokan.segment.html.md#kodokan.segment.find_segments)), keeping only those whose peak energy reaches `min_peak_activity` (an absolute floor: the hysteresis thresholds are quantiles, so an idle buffer still has "segments"). |
| [`pooled_demo_descriptor`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.pooled_demo_descriptor)(pose_seq, start_s, ...)       | The default [`Featurizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Featurizer): per-frame demo features, temporal-pyramid pooled.                                                                                                                                                                                              |
| [`recognize_segments`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.recognize_segments)(pose_seq, recognizer, \*)         | Offline video mode: every detected throw in `pose_seq`, recognized.                                                                                                                                                                                                                                                     |

### Classes

| [`Guess`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Guess)(technique, score)                        | One candidate technique and its score (higher is more likely).                                                   |
|-------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------|
| [`LiveRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.LiveRecognizer)(recognizer, \*, fps[, k, ...])  | Live mode: each throw a [`ThrowDetector`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.ThrowDetector) reports, recognized once. |
| [`Recognition`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Recognition)(guesses[, scores])                 | The top-k guesses, best first, and every technique's score.                                                      |
| [`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer)(\*[, method, temperature]) | Fit on pooled descriptors; recognize with top-k guesses and the full score vector.                               |
| [`ThrowDetector`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.ThrowDetector)(\*, fps[, width, height, ...])   | A rolling pose buffer that reports each throw once, after its segment closes.                                    |

### kodokan.recognizer.DFLT_MIN_PEAK_ACTIVITY *= 3.0*

Smoothed motion energy (keypoint speed, px per analysed frame) a throw must reach;
below it a “segment” is pose jitter, which quantile thresholds alone would accept.

### kodokan.recognizer.Featurizer

`(pose_seq, start_s, end_s) -> fixed-length descriptor` of one throw window.

alias of [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence), [`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)], `ndarray`]

### *class* kodokan.recognizer.Guess(technique, score)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One candidate technique and its score (higher is more likely).

### *class* kodokan.recognizer.LiveRecognizer(recognizer, \*, fps, k=3, featurize=<function pooled_demo_descriptor>, \*\*detector_kwargs)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Live mode: each throw a [`ThrowDetector`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.ThrowDetector) reports, recognized once.

[`push()`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.LiveRecognizer.push) takes one frame (`(P, 17, 3)` keypoints) and returns
`(segment, recognition)` for the throws that closed with it. Detector options
(`buffer_s`, `close_after_s`, `segmenter`, `width`, `height`) pass through.

#### push(keypoints, frame_index=None)

Add one frame; return the throws that closed with it, recognized.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment), [`Recognition`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Recognition)]]

### *class* kodokan.recognizer.Recognition(guesses, scores=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The top-k guesses, best first, and every technique’s score.

#### score_of(technique)

The score of `technique` (0 for a technique the recognizer never saw).

* **Return type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float)

### *class* kodokan.recognizer.TechniqueRecognizer(, method='lda', temperature=1.0)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Fit on pooled descriptors; recognize with top-k guesses and the full score vector.

* **Parameters:**
  * **method** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – `"lda"` (LDA projection when scikit-learn is installed, else plain
    standardized space) or `"centroid"` (standardized space only).
  * **temperature** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – softmax temperature; higher spreads the scores out.

#### fit(X, y)

Fit on pooled descriptors `X` (one row per demo) and technique labels `y`.

* **Return type:**
  [`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer)

#### fit_demos(feature_seqs, labels, , levels=(1, 2, 4))

Fit on per-frame feature sequences (e.g. [`kodokan.recognize.demo_feature()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.demo_feature)).

* **Return type:**
  [`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer)

#### recognize(x, , k=3)

Top-`k` guesses (best first) and the full score vector for one descriptor.

* **Return type:**
  [`Recognition`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Recognition)

#### recognize_clip(pose_seq, start_s, end_s, \*, k=3, featurize=<function pooled_demo_descriptor>)

Recognize the throw in `pose_seq` between `start_s` and `end_s`.

* **Return type:**
  [`Recognition`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Recognition)

#### scores(x)

Every technique’s score for one pooled descriptor (they sum to 1).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`float`](https://docs.python.org/3/builtins/functions.html#float)]

### *class* kodokan.recognizer.ThrowDetector(\*, fps, width=0, height=0, buffer_s=20.0, close_after_s=1.0, segmenter=<function motion_segments>)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A rolling pose buffer that reports each throw once, after its segment closes.

Push one frame at a time (`(P, 17, 3)` keypoints, as in `PoseSequence`).
[`push()`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.ThrowDetector.push) returns `(buffer, segment)` for the throws that closed with that
frame. A segment counts as closed when it ends at least `close_after_s` before
the newest frame; the buffer keeps the last `buffer_s` seconds of pushed frames
(at `fps` frames a second: push every analysed frame, or pass the analysed rate
as `fps`). A segment that mostly overlaps a throw already reported is that throw.

#### buffer()

The buffered frames as a `PoseSequence` (people padded with NaN).

* **Return type:**
  [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)

#### push(keypoints, frame_index=None)

Add one frame; return `(buffer, segment)` for each throw it closed.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence), [`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment)]]

### kodokan.recognizer.loo_top_k_accuracy(X, y, , ks=(1, 3, 5), groups=None, method='lda')

Leave-one-out (or leave-one-group-out) top-k accuracy of [`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer).

The share of held-out demos whose true technique is among the recognizer’s `k`
best guesses, for each `k` in `ks`: the number the top-k app (#3) shows, next
to top-1 from [`kodokan.recognize.loo_pooled_predict()`](_autosummary/kodokan.recognize.html.md#kodokan.recognize.loo_pooled_predict). Pass `groups` (e.g.
the source clip of each demo) to hold out whole groups. A held-out demo whose
technique is absent from its training fold counts as a miss.

```pycon
>>> rng = np.random.default_rng(0)
>>> X = np.vstack([rng.normal(c, 1.0, size=(4, 3)) for c in (0.0, 1.0, 2.0)])
>>> y = np.repeat(["a", "b", "c"], 4)
>>> acc = loo_top_k_accuracy(X, y, ks=(1, 3), method="centroid")
>>> acc[3]
1.0
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`float`](https://docs.python.org/3/builtins/functions.html#float)]

### kodokan.recognizer.motion_segments(pose_seq, , min_peak_activity=3.0, \*\*segment_kwargs)

Throw windows by motion energy ([`kodokan.segment.find_segments()`](_autosummary/kodokan.segment.html.md#kodokan.segment.find_segments)), keeping
only those whose peak energy reaches `min_peak_activity` (an absolute floor:
the hysteresis thresholds are quantiles, so an idle buffer still has “segments”).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment)]

### kodokan.recognizer.pooled_demo_descriptor(pose_seq, start_s, end_s, , mode='tori_angles_pos', levels=(1, 2, 4))

The default [`Featurizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Featurizer): per-frame demo features, temporal-pyramid pooled.

* **Return type:**
  `ndarray`

### kodokan.recognizer.recognize_segments(pose_seq, recognizer, \*, k=3, featurize=<function pooled_demo_descriptor>, segmenter=<function motion_segments>)

Offline video mode: every detected throw in `pose_seq`, recognized.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment), [`Recognition`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.Recognition)]]


# _autosummary/kodokan.segment.html.md

# kodokan.segment

Segment a clip into its repeated demonstrations of one throw.

A Kodokan demo clip shows the *same* throw several times (varying speed/angle/
position), each demonstration a burst of whole-body motion bracketed by a
low-motion “reset” (walk back, re-grip, bow). Scene-cut detection finds nothing
in a continuous take, so we segment by **rhythm**: build a 1-D motion-energy
signal and take the high-motion runs as demonstrations (research §5).

Robustness pieces:

- **Hysteresis thresholding** — a demo turns *on* above `high_quantile` and stays
  on until energy drops below `low_quantile`. This stops *slow-motion* reps (whose
  absolute energy is low) from being split, while rests still separate demos.
- **Two-person gate** — a throw demonstration needs both tori and uke, so segments
  are filtered by their two-person coverage (drops single-person intro/close-up spans).
- **Self-similarity matrix + autocorrelation period** — a dependency-free,
  RepNet-style cross-check on the rep structure/count (soft, since reps vary in speed).

Energy sources (fusable): [`pose_motion_energy()`](_autosummary/kodokan.segment.html.md#kodokan.segment.pose_motion_energy) (confidence-weighted total
keypoint speed; pose-only) and [`optical_flow_energy()`](_autosummary/kodokan.segment.html.md#kodokan.segment.optical_flow_energy) (dense Farneback; pose-free).

### Functions

| [`estimate_period`](_autosummary/kodokan.segment.html.md#kodokan.segment.estimate_period)(energy, fps, \*[, ...])         | Soft rep-period/count cross-check via autocorrelation of the energy signal.   |
|--------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------|
| [`find_segments`](_autosummary/kodokan.segment.html.md#kodokan.segment.find_segments)(energy, frame_indices, fps, \*)   | Turn a 1-D motion-energy signal into demonstration intervals via hysteresis.  |
| [`optical_flow_energy`](_autosummary/kodokan.segment.html.md#kodokan.segment.optical_flow_energy)(video_path, \*[, ...])      | Per-frame mean dense optical-flow magnitude (Farneback), pose-free.           |
| [`pose_motion_energy`](_autosummary/kodokan.segment.html.md#kodokan.segment.pose_motion_energy)(pose_seq, \*[, conf_thresh]) | Per-frame confidence-weighted total keypoint speed, summed over all people.   |
| [`segment_demonstrations`](_autosummary/kodokan.segment.html.md#kodokan.segment.segment_demonstrations)(pose_seq, \*[, ...])     | Find demonstrations, annotate each with its two-person coverage, and gate.    |
| [`self_similarity_matrix`](_autosummary/kodokan.segment.html.md#kodokan.segment.self_similarity_matrix)(pose_seq, \*[, ...])     | Frame×frame self-similarity on joint-angle features (for rep-structure viz).  |

### Classes

| [`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment)(index, start_s, end_s, start_frame, ...)   | One detected demonstration interval.   |
|-----------------------------------------------------------------------------------------------------|----------------------------------------|

### *class* kodokan.segment.Segment(index, start_s, end_s, start_frame, end_frame, peak_activity, two_person_frac=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One detected demonstration interval.

### kodokan.segment.estimate_period(energy, fps, , smooth_sigma=4.0, min_period_s=1.5, max_period_s=10.0)

Soft rep-period/count cross-check via autocorrelation of the energy signal.

Returns `{period_s, count_est, strength}`. `strength` (0–1) is the
autocorrelation at the chosen lag — low values mean weak periodicity (expected
when reps vary a lot in speed), so treat the count as approximate.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.segment.find_segments(energy, frame_indices, fps, , smooth_sigma=4.0, low_quantile=0.25, high_quantile=0.5, min_duration_s=1.0, merge_gap_s=0.4)

Turn a 1-D motion-energy signal into demonstration intervals via hysteresis.

A demonstration starts when smoothed energy rises above the `high_quantile`
threshold and ends when it falls below the `low_quantile` threshold — so a
slow-motion dip in the middle of a rep does not split it, while the low-motion
rest between reps (below `low_quantile`) does separate them.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment)]

### kodokan.segment.optical_flow_energy(video_path, , frame_range=None, step=1, scale=0.4)

Per-frame mean dense optical-flow magnitude (Farneback), pose-free.

Returns `(energy, frame_indices)`. Frames are downscaled by `scale` for speed.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[`ndarray`, `ndarray`]

### kodokan.segment.pose_motion_energy(pose_seq, , conf_thresh=0.2)

Per-frame confidence-weighted total keypoint speed, summed over all people.

Returns an array aligned to `pose_seq.frame_indices` (first sample is 0).
Robust to missing people/keypoints (NaNs are ignored).

* **Return type:**
  `ndarray`

### kodokan.segment.segment_demonstrations(pose_seq, , video_path=None, use_optical_flow=False, min_two_person_frac=0.0, \*\*find_kwargs)

Find demonstrations, annotate each with its two-person coverage, and gate.

Uses pose motion energy by default (fuse optical flow with `use_optical_flow`).
Segments whose two-person coverage is below `min_two_person_frac` are dropped
(a throw demonstration needs both tori and uke), then re-indexed in time order.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment)]

### kodokan.segment.self_similarity_matrix(pose_seq, , person=None, max_frames=300)

Frame×frame self-similarity on joint-angle features (for rep-structure viz).

Returns `(sim, frame_indices_sub)`; repeated demonstrations appear as
off-diagonal bright blocks. Subsamples to `max_frames` for speed/readability.


# _autosummary/kodokan.store.html.md

# kodokan.store

dol-backed stores for the pipeline’s artifacts (the analysis SSOT).

Two dict-like stores keyed by `video_id`:

- [`pose_store()`](_autosummary/kodokan.store.html.md#kodokan.store.pose_store) — `video_id -> PoseSequence`, each persisted as a tidy/long
  **Parquet** file (columns `fidx, frame, t_sec, person, keypoint, x, y, conf`)
  with sequence metadata (fps, dims, backend, source_url, frame indices) carried in
  the Parquet schema metadata. Tidy/long Parquet is the analysis SSOT — columnar,
  compressed, and pandas/polars/DuckDB-native (research §6).
- [`segments_store()`](_autosummary/kodokan.store.html.md#kodokan.store.segments_store) — `video_id -> list[demo dicts]` as JSON.

[`load_all_tidy()`](_autosummary/kodokan.store.html.md#kodokan.store.load_all_tidy) concatenates every clip’s table (adding a `video_id` column)
into one DataFrame for cross-clip analysis.

### Functions

| [`check_sequence_integrity`](_autosummary/kodokan.store.html.md#kodokan.store.check_sequence_integrity)(seq)                      | Integrity report for a single `PoseSequence` (via its tidy table).                                               |
|-----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------|
| [`check_tidy_integrity`](_autosummary/kodokan.store.html.md#kodokan.store.check_tidy_integrity)(df, \*[, width, height, ...]) | Row-level integrity checks on a tidy pose DataFrame.                                                             |
| [`load_all_tidy`](_autosummary/kodokan.store.html.md#kodokan.store.load_all_tidy)([store])                             | Concatenate every clip's tidy table (with a `video_id` column) into one DataFrame.                               |
| [`parquet_bytes_to_sequence`](_autosummary/kodokan.store.html.md#kodokan.store.parquet_bytes_to_sequence)(data)                    | Reconstruct a `PoseSequence` from Parquet bytes written above.                                                   |
| [`pose_store`](_autosummary/kodokan.store.html.md#kodokan.store.pose_store)([directory])                            | A dict-like `{video_id: PoseSequence}` store backed by per-clip Parquet.                                         |
| [`segments_store`](_autosummary/kodokan.store.html.md#kodokan.store.segments_store)([directory])                        | A dict-like `{video_id: <json>}` store for demo segments (and metadata).                                         |
| [`sequence_to_parquet_bytes`](_autosummary/kodokan.store.html.md#kodokan.store.sequence_to_parquet_bytes)(seq)                     | Serialize a `PoseSequence` to Parquet bytes (tidy + schema metadata).                                            |
| [`sequence_to_tidy_df`](_autosummary/kodokan.store.html.md#kodokan.store.sequence_to_tidy_df)(seq, \*[, video_id, ...])      | Convert a `PoseSequence` to a tidy/long DataFrame.                                                               |
| [`store_integrity_report`](_autosummary/kodokan.store.html.md#kodokan.store.store_integrity_report)([store])                    | Run [`check_sequence_integrity()`](_autosummary/kodokan.store.html.md#kodokan.store.check_sequence_integrity) over every clip in a pose store. |

### kodokan.store.check_sequence_integrity(seq)

Integrity report for a single `PoseSequence` (via its tidy table).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.store.check_tidy_integrity(df, , width=None, height=None, oob_margin_frac=0.05)

Row-level integrity checks on a tidy pose DataFrame.

Returns counts of anomalies (all should be `0` for a clean store):

- `n_duplicate_rows`: rows sharing a `(fidx, person, keypoint)` key (each
  such triple must be unique per clip).
- `n_oob_xy`: keypoints falling outside the frame by more than
  `oob_margin_frac` of its size (only checked when `width`/`height` are
  given; a small margin is tolerated since limbs can extend just past frame).
- `n_bad_conf`: confidences outside `[0, 1]`.
- `n_nan_xy`: non-finite coordinates (occluded rows should have been dropped).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.store.load_all_tidy(store=None)

Concatenate every clip’s tidy table (with a `video_id` column) into one DataFrame.

### kodokan.store.parquet_bytes_to_sequence(data)

Reconstruct a `PoseSequence` from Parquet bytes written above.

* **Return type:**
  [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)

### kodokan.store.pose_store(directory=None)

A dict-like `{video_id: PoseSequence}` store backed by per-clip Parquet.

### kodokan.store.segments_store(directory=None)

A dict-like `{video_id: <json>}` store for demo segments (and metadata).

### kodokan.store.sequence_to_parquet_bytes(seq)

Serialize a `PoseSequence` to Parquet bytes (tidy + schema metadata).

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### kodokan.store.sequence_to_tidy_df(seq, , video_id=None, drop_missing=True)

Convert a `PoseSequence` to a tidy/long DataFrame.

One row per (frame, person, keypoint). `fidx` is the 0-based analyzed-frame
position; `frame` is the source frame index. A `video_id` column is added
when given (used by [`load_all_tidy()`](_autosummary/kodokan.store.html.md#kodokan.store.load_all_tidy)).

### kodokan.store.store_integrity_report(store=None)

Run [`check_sequence_integrity()`](_autosummary/kodokan.store.html.md#kodokan.store.check_sequence_integrity) over every clip in a pose store.

Returns `{video_id: report}`; a clip that fails to load records
`{"error": ...}` rather than aborting the whole sweep.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)


# _autosummary/kodokan.testmode.html.md

# kodokan.testmode

Technique test mode: perform the technique the system names, get scored (#5).

[`TechniqueTest`](_autosummary/kodokan.testmode.html.md#kodokan.testmode.TechniqueTest) draws a technique at random from a focus pool (all the
recognizer knows by default), names it, and grades the next performance on two
things: how confidently the recognizer sees the *target* in it, and, when a reference
for the target is given, how close it is to that reference (`kodokan.coach.coach()`,
with its advice). `TechniqueTest.push()` runs the same loop on a live pose stream.

```pycon
>>> import numpy as np
>>> from kodokan.recognizer import TechniqueRecognizer
>>> X = np.vstack([np.full((3, 4), c) + np.arange(3)[:, None] * 0.1 for c in (0.0, 3.0)])
>>> rec = TechniqueRecognizer(method="centroid").fit(X, ["o-goshi"] * 3 + ["uchi-mata"] * 3)
>>> test = TechniqueTest(rec, pool=["uchi-mata"], seed=1)
>>> test.next_prompt()
'uchi-mata'
>>> result = test.grade(np.full(4, 3.1))
>>> result.passed, result.score > 50
(True, True)
```

### Classes

| [`LiveTechniqueTest`](_autosummary/kodokan.testmode.html.md#kodokan.testmode.LiveTechniqueTest)(test, \*, fps[, featurize, ...])   | The test loop on a live stream: prompt, detect the throw, grade, prompt again.   |
|-------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`TechniqueTest`](_autosummary/kodokan.testmode.html.md#kodokan.testmode.TechniqueTest)(recognizer, \*[, pool, ...])           | Prompt a random technique from a focus pool; grade the performance.              |
| [`TestResult`](_autosummary/kodokan.testmode.html.md#kodokan.testmode.TestResult)(target, recognition, ...)                 | The grade of one performance of the prompted technique.                          |

### *class* kodokan.testmode.LiveTechniqueTest(test, \*, fps, featurize=<function pooled_demo_descriptor>, angle_featurize=<function demo_features>, on_prompt=None, \*\*detector_kwargs)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The test loop on a live stream: prompt, detect the throw, grade, prompt again.

[`push()`](_autosummary/kodokan.testmode.html.md#kodokan.testmode.LiveTechniqueTest.push) takes one frame and returns `(segment, result)` for each throw that
closed with it; after each graded throw the next technique is drawn
(`prompt`). Detector options pass through.

A throw is graded once it has *closed* (`close_after_s` after it ends), so the
performer should wait for the next prompt before the next throw; any motion the
detector takes for a throw also uses up a prompt.

#### push(keypoints, frame_index=None)

Add one frame; grade each throw it closed and draw the next prompt.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`Segment`](_autosummary/kodokan.segment.html.md#kodokan.segment.Segment), [`TestResult`](_autosummary/kodokan.testmode.html.md#kodokan.testmode.TestResult)]]

### *class* kodokan.testmode.TechniqueTest(recognizer, , pool=None, references=None, lang='en', confidence_weight=0.5, seed=None, rng=None, advice={'en': {'close': 'Close to the reference: keep it up.', 'elbow': "Your {side} elbow is {deg:.0f}° off the reference: keep that arm's pull firm and close to your body.", 'headline': '{technique}: {score}/100.', 'hip': 'Your {side} hip is {deg:.0f}° off: bring your hips lower and closer to your partner.', 'kake': 'Most of the difference is in kake: commit through the finish.', 'knee': 'Your {side} knee is {deg:.0f}° off: bend your knees more as you enter, then drive up.', 'kuzushi': "Most of the difference is in kuzushi: break your partner's balance before you turn in.", 'shoulder': "Your {side} shoulder is {deg:.0f}° off: lift and turn that arm with the reference timing to take your partner's balance.", 'tsukuri': 'Most of the difference is in tsukuri: step in faster and closer.'}, 'fr': {'close': 'Proche de la référence : continuez ainsi.', 'elbow': "Votre coude {side} s'écarte de {deg:.0f}° de la référence : gardez la traction de ce bras ferme et près du corps.", 'headline': '{technique} : {score}/100.', 'hip': "Votre hanche {side_f} s'écarte de {deg:.0f}° : placez vos hanches plus bas et plus près de votre partenaire.", 'kake': "L'essentiel de l'écart est dans le kake : allez au bout de la projection.", 'knee': "Votre genou {side} s'écarte de {deg:.0f}° : fléchissez davantage les genoux en entrant, puis poussez vers le haut.", 'kuzushi': "L'essentiel de l'écart est dans le kuzushi : déséquilibrez votre partenaire avant d'entrer.", 'shoulder': "Votre épaule {side_f} s'écarte de {deg:.0f}° : levez et tournez ce bras au rythme de la référence pour déséquilibrer votre partenaire.", 'tsukuri': "L'essentiel de l'écart est dans le tsukuri : entrez plus vite et plus près."}})

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Prompt a random technique from a focus pool; grade the performance.

* **Parameters:**
  * **recognizer** ([`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer)) – a fitted [`TechniqueRecognizer`](_autosummary/kodokan.recognizer.html.md#kodokan.recognizer.TechniqueRecognizer).
  * **pool** ([`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the techniques to draw from (default: all the recognizer knows).
  * **references** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – `{technique: build_reference(...)}`; techniques with one are
    also graded on closeness, with advice.
  * **confidence_weight** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – share of the score from the target’s confidence (the
    rest from closeness to the reference, when there is one).
  * **seed** ([`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – or `rng`, for a reproducible sequence of prompts.

#### grade(descriptor, angle_features=None)

Grade one performance: its pooled `descriptor` and, for closeness, its
per-frame `angle_features` (`kodokan.score.demo_features()`).

* **Return type:**
  [`TestResult`](_autosummary/kodokan.testmode.html.md#kodokan.testmode.TestResult)

#### grade_clip(pose_seq, start_s, end_s, \*, featurize=<function pooled_demo_descriptor>, angle_featurize=<function demo_features>)

Grade the performance in `pose_seq` between `start_s` and `end_s`.

* **Return type:**
  [`TestResult`](_autosummary/kodokan.testmode.html.md#kodokan.testmode.TestResult)

#### next_prompt()

Draw the next technique to perform (never the same one twice in a row).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### *class* kodokan.testmode.TestResult(target, recognition, target_confidence, coaching, score)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The grade of one performance of the prompted technique.

#### *property* passed *: [bool](https://docs.python.org/3/builtins/functions.html#bool)*

Whether the recognizer’s best guess is the target.


# _autosummary/kodokan.tori_labels.html.md

# kodokan.tori_labels

Hand-labelling of the tori heuristic (#49): sample demos, then score agreement.

`recognize.tori_index` decides which tracked judoka is tori (the thrower) from hip
heights alone. There is no ground truth to validate it against, so the owner labels a
stratified sample of demos by eye (in the web app’s owner-only labelling page) and this
module closes the loop:

* [`build_label_manifest()`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.build_label_manifest) – pick ~60 demos (stratified over throw, source and the
  confident/abstain split) and emit, per demo, the two tracked people’s boxes over time,
  normalised to the frame so the page can outline them on the clip in two colours. The
  heuristic’s own answer is stored but the app never sends it to the labelling page.
* [`agreement_report()`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.agreement_report) – given the owner’s labels, the agreement with the heuristic
  (Wilson CI), split by confident/abstained, plus the “can’t tell” rate in each.

Command line:

```default
python -m kodokan.tori_labels build manifest.json --n 60
python -m kodokan.tori_labels report manifest.json labels.jsonl
```

Needs the pose and segment stores (`~/kodokan_data`) for `build` only; `report`
and the pure helpers need nothing but the two files.

### Module Attributes

| [`VERDICTS`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.VERDICTS)          | The verdicts the labelling page records.                                 |
|--------------------------------------------------------------------|--------------------------------------------------------------------------|
| [`MIN_KEYPOINT_CONF`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.MIN_KEYPOINT_CONF) | Minimum keypoint confidence for a joint to count towards a person's box. |
| [`BOX_PAD`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.BOX_PAD)           | Padding added around the joints' extent, as a fraction of the box size.  |

### Functions

| [`agreement_report`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.agreement_report)(manifest, labels)                 | Agreement of `tori_index` with the owner's labels.                                 |
|-----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [`build_label_manifest`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.build_label_manifest)(\*[, n, seed, abstain_share]) | Sample the demos of the local pose/segment stores into a labelling manifest.       |
| [`labelled_slots`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.labelled_slots)(pose_seq, start_s, end_s)           | The two person slots shown to the labeller: the two most present in the window.    |
| [`latest_labels`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.latest_labels)(rows)                                | The most recent label per demo id (the owner may re-label).                        |
| `main`([argv])                                                                                      |                                                                                    |
| [`manifest_entry`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.manifest_entry)(\*, throw, video_id, source, ...)   | One labelling item for a demo, or `None` if it does not have two trackable people. |
| [`person_boxes`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.person_boxes)(pose_seq, start_s, end_s, \*, slots)  | Normalised boxes of the given person *slots* over a demo window.                   |
| [`stratified_sample`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.stratified_sample)(entries[, n, ...])               | Pick *n* entries spread over throws and sources, with a guaranteed abstain share.  |
| [`wilson_interval`](_autosummary/kodokan.tori_labels.html.md#kodokan.tori_labels.wilson_interval)(k, n, \*[, z])                     | Wilson score interval for a proportion (95% by default).                           |

### kodokan.tori_labels.BOX_PAD *= 0.08*

Padding added around the joints’ extent, as a fraction of the box size.

### kodokan.tori_labels.MIN_KEYPOINT_CONF *= 0.1*

Minimum keypoint confidence for a joint to count towards a person’s box.

### kodokan.tori_labels.VERDICTS *= ('A', 'B', 'cant_tell')*

The verdicts the labelling page records.

### kodokan.tori_labels.agreement_report(manifest, labels)

Agreement of `tori_index` with the owner’s labels.

A decided label (“A”/”B”) agrees when the named slot equals the heuristic’s. “Can’t tell”
is excluded from agreement and reported as a rate, overall and per confident/abstained
group – if abstentions are the genuinely ambiguous demos, their can’t-tell rate is higher.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.tori_labels.build_label_manifest(, n=60, seed=0, abstain_share=0.4)

Sample the demos of the local pose/segment stores into a labelling manifest.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### kodokan.tori_labels.labelled_slots(pose_seq, start_s, end_s)

The two person slots shown to the labeller: the two most present in the window.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]

### kodokan.tori_labels.latest_labels(rows)

The most recent label per demo id (the owner may re-label).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### kodokan.tori_labels.manifest_entry(, throw, video_id, source, pose_seq, start_s, end_s, clip_file)

One labelling item for a demo, or `None` if it does not have two trackable people.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### kodokan.tori_labels.person_boxes(pose_seq, start_s, end_s, , slots, min_conf=0.1, pad=0.08, max_frames=120)

Normalised boxes of the given person *slots* over a demo window.

Returns `{"t": [seconds from window start], "boxes": [[ [x0,y0,x1,y1] | None per slot ] per frame]}`
with coordinates as fractions of the frame (so they scale to any rendition of the clip).
Frames are thinned to at most *max_frames*; a slot with no usable joints in a frame is `None`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.tori_labels.stratified_sample(entries, n=60, , abstain_share=0.4, seed=0)

Pick *n* entries spread over throws and sources, with a guaranteed abstain share.

The abstained demos are the ones whose role label is in doubt, so they get at least
`abstain_share` of the sample (fewer only if there are not that many). Within each
half, strata are `(throw, source)` cells drawn round-robin from a seeded shuffle, so
no throw or source dominates.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### kodokan.tori_labels.wilson_interval(k, n, , z=1.96)

Wilson score interval for a proportion (95% by default).

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]


# _autosummary/kodokan.track.html.md

# kodokan.track

Stable tori/uke identity tracking (BoT-SORT / ByteTrack).

The plain [`estimate_poses()`](_autosummary/kodokan.pose.html.md#kodokan.pose.estimate_poses) keeps the top-2 detections and
orders them left→right *per frame*, so the two slots swap whenever tori and uke
cross. This module instead runs a multi-object tracker (Ultralytics’ built-in
BoT-SORT by default — appearance ReID + camera-motion compensation) so each
person keeps a persistent `track_id` across frames; we then bind the two most
persistent tracks to fixed slots for the whole clip (ordered left→right by their
clip-average x), giving a stable identity that does not swap mid-throw.

Limitation: under the heavy mutual occlusion at a throw’s apex a track can
fragment (a person reappears with a new id). Top-2-by-presence captures the
dominant fragments; fragment-merging/ReID-stitching is a later refinement (see
`misc/docs/research-architecture.md` §4).

### Functions

| [`estimate_poses_tracked`](_autosummary/kodokan.track.html.md#kodokan.track.estimate_poses_tracked)(video_path, \*[, ...])   | Estimate per-frame keypoints with persistent tori/uke identity.                  |
|--------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`identity_swap_rate`](_autosummary/kodokan.track.html.md#kodokan.track.identity_swap_rate)(pose_seq)                    | Ground-truth-free track-identity discontinuity rate (a tracking-quality metric). |

### kodokan.track.estimate_poses_tracked(video_path, , n_persons=2, tracker='botsort.yaml', conf_thresh=0.3, max_gap_frac=0.15, stale_after=12, frame_step=1, frame_range=None, device='mps', model_name='yolo11n-pose.pt', source_url=None, progress=True)

Estimate per-frame keypoints with persistent tori/uke identity.

Returns a [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence) whose person slots are *stable*
across the clip (slot 0 = the track that is, on average, further left).

* **Parameters:**
  * **video_path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Path to the clip.
  * **n_persons** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of stable identity slots to keep (2 for tori+uke).
  * **tracker** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Ultralytics tracker config (`"botsort.yaml"` or `"bytetrack.yaml"`).
  * **conf_thresh** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Minimum mean per-person confidence to count a detection.
  * **frame_step** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Analyze every n-th frame.
  * **frame_range** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Optional `(start, stop)` frame window.
  * **device** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Torch device (`"mps"`/`"cpu"`).
  * **model_name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – YOLO-pose weights (resolved under the data models dir).
  * **source_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Provenance URL.
  * **progress** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress.
* **Return type:**
  [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)

### kodokan.track.identity_swap_rate(pose_seq)

Ground-truth-free track-identity discontinuity rate (a tracking-quality metric).

For each consecutive frame pair in which *all* person slots are present, we
solve the minimum-cost assignment between the two frames’ person centroids.
When the optimal assignment is not the identity (slot *i* → slot *i*), the
slots’ spatial positions are better explained by a **label swap** — a proxy
for a tori/uke identity swap that the review asked us to instrument. A stable
tracker trends toward `0`.

Returns `{n_pairs, n_swaps, swap_rate}`.

Caveat (honest): this also fires on a *genuine* physical crossing that the
tracker correctly follows through, so read `swap_rate` as a relative
diagnostic (compare trackers/clips), not an absolute error count.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)


# _autosummary/kodokan.viz.html.md

# kodokan.viz

Visualize a [`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence).

Two outputs, both requested by the project:

- [`render_skeleton_video()`](_autosummary/kodokan.viz.html.md#kodokan.viz.render_skeleton_video) — bake a shareable MP4 with the skeleton drawn
  either *on the original video* (overlay) or *on a blank canvas* (skeleton only).
- [`log_to_rerun()`](_autosummary/kodokan.viz.html.md#kodokan.viz.log_to_rerun) — log frames + 2D skeletons to a Rerun recording for
  interactive, scrubbable inspection (and side-by-side compare of two sequences).

Persons are drawn in distinct colors (slot 0 green, slot 1 magenta) so tori/uke
are visually separable.

### Module Attributes

| [`DEFAULT_PERSON_COLORS`](_autosummary/kodokan.viz.html.md#kodokan.viz.DEFAULT_PERSON_COLORS)   | BGR colors per person slot (green, magenta, cyan, yellow…).   |
|--------------------------------------------------------------------------|---------------------------------------------------------------|

### Functions

| [`log_to_rerun`](_autosummary/kodokan.viz.html.md#kodokan.viz.log_to_rerun)(pose_seq, \*[, source_video, ...])   | Log frames + 2D skeletons to Rerun (overlay-on-video and skeleton-only views).   |
|----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`render_skeleton_video`](_autosummary/kodokan.viz.html.md#kodokan.viz.render_skeleton_video)(pose_seq, \*, out_path)     | Render skeletons to an MP4.                                                      |

### kodokan.viz.DEFAULT_PERSON_COLORS *= ((0, 255, 0), (255, 0, 255), (255, 255, 0), (0, 165, 255))*

BGR colors per person slot (green, magenta, cyan, yellow…).

### kodokan.viz.log_to_rerun(pose_seq, , source_video=None, save=None, spawn=False, blank_canvas=True, frame_scale=0.5, conf_thresh=0.3, entity_prefix='')

Log frames + 2D skeletons to Rerun (overlay-on-video and skeleton-only views).

* **Parameters:**
  * **pose_seq** ([`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)) – The sequence to log.
  * **source_video** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – If given, downscaled frames are logged under `video/` as a backdrop.
  * **save** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Write a standalone `.rrd` recording to this path.
  * **spawn** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Launch the Rerun viewer.
  * **blank_canvas** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Also log a skeleton-only view under `skeleton/`.
  * **frame_scale** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Downscale factor for logged video frames (keypoints scaled to match).
  * **conf_thresh** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Hide keypoints below this confidence.
  * **entity_prefix** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Prefix all entity paths (use distinct prefixes to compare two
    sequences side-by-side in one recording, e.g. `"demoA/"`, `"demoB/"`).
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### kodokan.viz.render_skeleton_video(pose_seq, , out_path, source_video=None, blank_canvas=False, conf_thresh=0.3, fps=None, person_colors=((0, 255, 0), (255, 0, 255), (255, 255, 0), (0, 165, 255)), background=(0, 0, 0), thickness=2, radius=4)

Render skeletons to an MP4.

* **Parameters:**
  * **pose_seq** ([`PoseSequence`](_autosummary/kodokan.pose.html.md#kodokan.pose.PoseSequence)) – The pose sequence to draw.
  * **out_path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Output `.mp4` path.
  * **source_video** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Source clip; required (and used as backdrop) unless
    `blank_canvas=True`.
  * **blank_canvas** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, draw on a solid `background` instead of the video.
  * **conf_thresh** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Hide keypoints/edges below this confidence.
  * **fps** ([`float`](https://docs.python.org/3/builtins/functions.html#float) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Output fps (defaults to the sequence’s source fps).
  * **person_colors** – BGR colors per person slot.
  * **background** – BGR background color for the blank canvas.
  * **thickness** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Edge thickness / joint radius in pixels.
  * **radius** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Edge thickness / joint radius in pixels.
* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)
* **Returns:**
  The output path.


# _autosummary/kodokan.vocab.html.md

# kodokan.vocab

Word parts of technique names: which techniques share which part, and how often.

A Kodokan technique name is a compound of recurring word parts: *Harai-goshi* is
*harai* (sweep) + *goshi* (hip), *O-soto-gari* is *o* (large) + *soto* (outer) + *gari*
(reap). Learning a dozen of those parts makes a hundred names guessable, which is what the
web app’s word-part quizzes train (thorwhalen/kodokan#65).

The same part is spelled differently depending on its position: Japanese *rendaku* voices
the first consonant of a non-initial part, so *koshi* (hip) becomes *goshi* in Harai-goshi
but stays *koshi* in Koshi-guruma; likewise kari/gari, kuruma/guruma, kake/gake,
kaeshi/gaeshi. Those variants are **one** part. A part is keyed by its glossary entry, and
a name token maps to it when it is the entry’s primary romaji or one of its declared
alternate readings (the glossary’s `alts`):

```default
>>> glossary = {
...     "goshi": {"alts": ["koshi"]},
...     "guruma": {"alts": ["kuruma"]},
...     "harai": {"alts": ["barai"]},
...     "gaeshi": {"alts": []},
... }
>>> index = variant_index(glossary)
>>> [index.get(t) for t in ("koshi", "goshi", "barai", "kaeshi", "nage")]
['goshi', 'goshi', 'harai', None, None]
>>> parts_of_name("Koshi-guruma", index)
['goshi', 'guruma']
```

Variants are declared, not guessed: rendaku is regular enough to *suggest* a variant but
not to merge one silently (devoicing *de*, “advancing”, gives *te*, “hand”, a different
word). So [`unmatched_tokens()`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.unmatched_tokens) reports the name tokens no part claims, with the part
they are a rendaku variant of, for a person to add as an `alts` entry:

```default
>>> unmatched_tokens({"kaeshiwaza": "Kaeshi-waza"}, glossary)
{'kaeshi': 'gaeshi', 'waza': None}
```

[`word_throws()`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.word_throws) derives `part -> techniques` by tokenizing the names, rather than
trusting a hand-kept list (which had missed Koshi-guruma under goshi), and
[`part_stats()`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.part_stats) counts the distinct techniques per part. [`MIN_TECHNIQUES`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.MIN_TECHNIQUES) is the
threshold for a part to be offered in the quizzes; its docstring records why.

### Module Attributes

| [`MIN_TECHNIQUES`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.MIN_TECHNIQUES)   | A part is offered in the word-part quizzes when at least this many distinct techniques use it.   |
|-------------------------------------------------------------------|--------------------------------------------------------------------------------------------------|
| [`HOMOGRAPHS`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.HOMOGRAPHS)       | technique names where a token is NOT the glossary part.                                          |

### Functions

| [`devoiced`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.devoiced)(token)                                | The unvoiced (rendaku-undone) form of `token`, or `token` if it starts unvoiced.    |
|-------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|
| [`homographs_by_kanji`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.homographs_by_kanji)(names, kanji, glossary)    | `part key -> technique keys` whose name has the part's spelling but not its kanji.  |
| [`name_tokens`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.name_tokens)(romaji)                            | The lower-cased parts of a romaji name: `"O-soto-gari"` -> `['o', 'soto', 'gari']`. |
| [`part_stats`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.part_stats)(part_throws, \*[, min_techniques])  | One row per part, most-shared first: `{part, n_techniques, offered}`.               |
| [`parts_of_name`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.parts_of_name)(romaji, index)                   | The distinct part keys of a name, in order of appearance.                           |
| [`threshold_table`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.threshold_table)(part_throws, \*[, upto])       | `k -> number of parts shared by at least k techniques`, for choosing a threshold.   |
| [`unmatched_tokens`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.unmatched_tokens)(names, glossary)              | `token -> part it is a rendaku variant of (or None)` for tokens no part claims.     |
| [`variant_index`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.variant_index)(glossary)                        | `spelling -> part key` for every primary key and declared alternate reading.        |
| [`word_throws`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.word_throws)(names, glossary, \*[, homographs]) | `part key -> sorted technique keys` whose name contains the part.                   |

### kodokan.vocab.HOMOGRAPHS *: [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [frozenset](https://docs.python.org/3/builtins/stdtypes.html#frozenset)[[str](https://docs.python.org/3/builtins/stdtypes.html#str)]]* *= {'kata': frozenset({'katajujijime'})}*

technique names where a token is NOT the glossary part.
Kata-juji-jime’s *kata* is 片 (“one-sided”), not the glossary’s 肩 (“shoulder”).
The fallback when no technique kanji is at hand; [`homographs_by_kanji()`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.homographs_by_kanji) finds
these from the kanji instead.

* **Type:**
  Same spelling, different word

### kodokan.vocab.MIN_TECHNIQUES *= 3*

A part is offered in the word-part quizzes when at least this many distinct techniques
use it. Chosen from the statistics of the 68 nage-waza (2026-11-09, kodokan#65):
23 parts are shared by >=2 techniques, 20 by >=3, 16 by >=4, 13 by >=5. A part shared by
only two techniques (obi, sumi, wakare) is a pair to memorize, not a pattern to spot,
while 3 keeps *seoi* (Seoi-nage, Ippon-seoi-nage, Seoi-otoshi), one of the four parts the
owner named as the point of the exercise; 4 would drop it. So 3.

### kodokan.vocab.devoiced(token)

The unvoiced (rendaku-undone) form of `token`, or `token` if it starts unvoiced.

```pycon
>>> devoiced("gaeshi"), devoiced("jime"), devoiced("barai"), devoiced("ashi")
('kaeshi', 'shime', 'harai', 'ashi')
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### kodokan.vocab.homographs_by_kanji(names, kanji, glossary)

`part key -> technique keys` whose name has the part’s spelling but not its kanji.

A name token that is a part’s spelling is another word when the technique’s own kanji
lacks the part’s glossary kanji: *Kata-juji-jime* (片十字絞) has *kata* but not 肩.
Techniques with no kanji in `kanji` are not judged. The result is what
[`word_throws()`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.word_throws) takes as `homographs`, found from the data rather than kept by
hand beside the technique keys.

```pycon
>>> glossary = {"kata": {"kanji": "肩"}, "juji": {"kanji": "十字"}}
>>> names = {"katajujijime": "Kata-juji-jime", "kataguruma": "Kata-guruma"}
>>> kanji = {"katajujijime": "片十字絞", "kataguruma": "肩車"}
>>> homographs_by_kanji(names, kanji, glossary)
{'kata': frozenset({'katajujijime'})}
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`frozenset`](https://docs.python.org/3/builtins/stdtypes.html#frozenset)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### kodokan.vocab.name_tokens(romaji)

The lower-cased parts of a romaji name: `"O-soto-gari"` -> `['o', 'soto', 'gari']`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### kodokan.vocab.part_stats(part_throws, , min_techniques=3)

One row per part, most-shared first: `{part, n_techniques, offered}`.

```pycon
>>> part_stats({"ashi": ["a", "b", "c"], "obi": ["d", "e"], "kani": ["f"]})
...
[{'part': 'ashi', 'n_techniques': 3, 'offered': True},
 {'part': 'obi', 'n_techniques': 2, 'offered': False},
 {'part': 'kani', 'n_techniques': 1, 'offered': False}]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### kodokan.vocab.parts_of_name(romaji, index)

The distinct part keys of a name, in order of appearance.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### kodokan.vocab.threshold_table(part_throws, , upto=6)

`k -> number of parts shared by at least k techniques`, for choosing a threshold.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### kodokan.vocab.unmatched_tokens(names, glossary)

`token -> part it is a rendaku variant of (or None)` for tokens no part claims.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)]

### kodokan.vocab.variant_index(glossary)

`spelling -> part key` for every primary key and declared alternate reading.

`glossary` maps a part key (its primary romaji, lower-case) to a mapping that may hold
`alts`: alternate readings such as `["koshi"]` for `goshi`.

* **Raises:**
  [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – if one spelling would belong to two parts (glossary order must never
  decide which part a name token is).
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### kodokan.vocab.word_throws(names, glossary, , homographs={'kata': frozenset({'katajujijime'})})

`part key -> sorted technique keys` whose name contains the part.

* **Parameters:**
  * **names** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – `technique key -> romaji name`.
  * **glossary** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)]) – as for [`variant_index()`](_autosummary/kodokan.vocab.html.md#kodokan.vocab.variant_index). Every glossary part appears in the
    result, with an empty list if no name uses it.
  * **homographs** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]) – `part key -> technique keys` where the spelling is another word.
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

```pycon
>>> word_throws(
...     {"kataguruma": "Kata-guruma", "katajujijime": "Kata-juji-jime"},
...     {"kata": {}, "guruma": {}},
... )
{'kata': ['kataguruma'], 'guruma': ['kataguruma']}
```


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-11-23 07:59 UTC** from commit <a href="https://github.com/thorwhalen/kodokan/commit/686f95c5da4e5fcaf943c7e518b2fc45284baf85"><code>686f95c</code></a> on branch <code>main</code>, for **kodokan 0.0.37** (from <code>pyproject.toml</code>).

#### NOTE
Nothing suggests a mismatch: the tree was clean at the commit above, and the documented version is the one on PyPI.

## Source

|                     |                                                                                                                                                           |
|---------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/thorwhalen/kodokan/commit/686f95c5da4e5fcaf943c7e518b2fc45284baf85"><code>686f95c5da4e5fcaf943c7e518b2fc45284baf85</code></a> |
| Branch              | <code>main</code>                                                                                                                                         |
| Tags at this commit | none                                                                                                                                                      |
| Working tree        | clean                                                                                                                                                     |
| Remote              | <code>https://github.com/thorwhalen/kodokan</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>thorwhalen/kodokan</code>                                                            |
| Run          | <a href="https://github.com/thorwhalen/kodokan/actions/runs/45134920877">45134920877</a>   |
| Ref          | <code>refs/heads/main</code>                                                               |
| Event commit | <code>686f95c5da4e5fcaf943c7e518b2fc45284baf85</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.25  |
| Sphinx   | 9.1.1   |
| docutils | 0.22.4  |
| Python   | 3.12.16 |

## Configuration as resolved

|               |                                                                   |
|---------------|-------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>pydata_sphinx_theme</code>) |
| accent        | <code>#005b9c</code>                                              |
| api_generator | <code>autosummary</code>                                          |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code>  |
| agent_outputs | <code>true</code>                                                 |
| aggregates    | <code>md</code>                                                   |
| ai_artifacts  | <code>true</code>                                                 |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/kodokan/0.0.37/">0.0.37</a>, the same as the documented version.

## Reproduce

```bash
git clone https://github.com/thorwhalen/kodokan && cd kodokan
git checkout 686f95c5da4e5fcaf943c7e518b2fc45284baf85
pip install "epythet==0.2.25"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# ai-agents.html.md

<!-- generated by epythet -->

# For AI agents

`kodokan` ships artifacts for coding agents alongside its code. This page lists
them, says where each lives in the repository, and points at the
machine-readable copies of this documentation.

## Skills

Skills are folders holding a `SKILL.md` (the [Agent Skills](https://agentskills.io) format): a description that tells an agent when to use it and a body with the procedure. Install one into your agent with `gh skill` (any host: `--agent claude-code`, `copilot`, `cursor`, `codex`, `gemini`), or use the copy bundled in the wheel.

### `kodokan-competitions`

Refresh the calendar of upcoming youth judo competitions in a French département (by default the Bouches-du-Rhône, around Aix-en-Provence) and say, for each, who may enter: open to any licensed judoka, by qualification, a friendly (amical) interclub limited to named clubs, or by invitation, judged against the user’s home club. Publishes the result to the Resources page of judo.thorwhalen.com. Use when asked to “refresh/update the competition calendar”, “which competitions can we go to”, “what judo competitions are coming up in Aix / the 13 / Bouches-du-Rhône”, “is this tournament open to our club”, “add this interclub to the calendar”, or when the calendar on the site looks stale.

Source: [`.claude/skills/kodokan-competitions`](https://github.com/thorwhalen/kodokan/tree/HEAD/.claude/skills/kodokan-competitions).

## Machine-readable documentation

This site publishes the same documentation in forms that fit an agent’s context window:

- [`llms.txt`](https://thorwhalen.github.io/kodokan/llms.txt): an index of every page with a one-line description ([llms.txt](https://llmstxt.org) format)
- [`kodokan.md`](https://thorwhalen.github.io/kodokan/kodokan.md): the whole documentation as one Markdown file
- `<page>.html.md`: a rendered Markdown twin of every page, advertised from each page’s `<head>` with `<link rel="alternate" type="text/markdown">`
- [`objects.inv`](https://thorwhalen.github.io/kodokan/objects.inv): the Sphinx inventory: a symbol-to-URL index (`sphobjinv convert plain objects.inv -`)


# api.html.md

# API reference

| [`kodokan`](_autosummary/kodokan.html.md#module-kodokan)   | kodokan — study Kodokan Judo throws from video via body-pose analysis.   |
|---------------------------------------------------------------------------|--------------------------------------------------------------------------|


