paces 0.0.29__tar.gz → 0.0.30__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. {paces-0.0.29 → paces-0.0.30}/PKG-INFO +1 -1
  2. {paces-0.0.29 → paces-0.0.30}/paces/__init__.py +2 -0
  3. {paces-0.0.29 → paces-0.0.30}/paces/ask.py +1 -1
  4. {paces-0.0.29 → paces-0.0.30}/paces/bodies/__init__.py +10 -0
  5. paces-0.0.30/paces/bodies/correction.py +77 -0
  6. {paces-0.0.29 → paces-0.0.30}/paces/corrections.py +205 -6
  7. {paces-0.0.29 → paces-0.0.30}/paces/evidence.py +190 -1
  8. {paces-0.0.29 → paces-0.0.30}/paces/pose.py +1 -0
  9. {paces-0.0.29 → paces-0.0.30}/paces/segmenters.py +9 -1
  10. {paces-0.0.29 → paces-0.0.30}/paces/tools.py +7 -1
  11. {paces-0.0.29 → paces-0.0.30}/pyproject.toml +1 -1
  12. {paces-0.0.29 → paces-0.0.30}/tests/data/body_schemas.json +109 -0
  13. paces-0.0.30/tests/test_corrections_log.py +310 -0
  14. {paces-0.0.29 → paces-0.0.30}/tests/test_evidence.py +4 -1
  15. {paces-0.0.29 → paces-0.0.30}/.gitignore +0 -0
  16. {paces-0.0.29 → paces-0.0.30}/LICENSE +0 -0
  17. {paces-0.0.29 → paces-0.0.30}/README.md +0 -0
  18. {paces-0.0.29 → paces-0.0.30}/docs/README.md +0 -0
  19. {paces-0.0.29 → paces-0.0.30}/docs/alignment/README.md +0 -0
  20. {paces-0.0.29 → paces-0.0.30}/docs/poc-reference/README.md +0 -0
  21. {paces-0.0.29 → paces-0.0.30}/docs/poc-reference/artifacts/clips.json +0 -0
  22. {paces-0.0.29 → paces-0.0.30}/paces/__main__.py +0 -0
  23. {paces-0.0.29 → paces-0.0.30}/paces/ask_contract.py +0 -0
  24. {paces-0.0.29 → paces-0.0.30}/paces/bodies/_base.py +0 -0
  25. {paces-0.0.29 → paces-0.0.30}/paces/bodies/derivation.py +0 -0
  26. {paces-0.0.29 → paces-0.0.30}/paces/bodies/document.py +0 -0
  27. {paces-0.0.29 → paces-0.0.30}/paces/bodies/signal.py +0 -0
  28. {paces-0.0.29 → paces-0.0.30}/paces/bodies/step.py +0 -0
  29. {paces-0.0.29 → paces-0.0.30}/paces/cues.py +0 -0
  30. {paces-0.0.29 → paces-0.0.30}/paces/data/ask/ask.css +0 -0
  31. {paces-0.0.29 → paces-0.0.30}/paces/data/ask/ask.html +0 -0
  32. {paces-0.0.29 → paces-0.0.30}/paces/data/ask/ask.js +0 -0
  33. {paces-0.0.29 → paces-0.0.30}/paces/derivation.py +0 -0
  34. {paces-0.0.29 → paces-0.0.30}/paces/edits.py +0 -0
  35. {paces-0.0.29 → paces-0.0.30}/paces/excerpts.py +0 -0
  36. {paces-0.0.29 → paces-0.0.30}/paces/known_k.py +0 -0
  37. {paces-0.0.29 → paces-0.0.30}/paces/measure.py +0 -0
  38. {paces-0.0.29 → paces-0.0.30}/paces/model.py +0 -0
  39. {paces-0.0.29 → paces-0.0.30}/paces/projection.py +0 -0
  40. {paces-0.0.29 → paces-0.0.30}/paces/render.py +0 -0
  41. {paces-0.0.29 → paces-0.0.30}/paces/segmentation.py +0 -0
  42. {paces-0.0.29 → paces-0.0.30}/paces/timed_text.py +0 -0
  43. {paces-0.0.29 → paces-0.0.30}/tests/audio_synth.py +0 -0
  44. {paces-0.0.29 → paces-0.0.30}/tests/data/routine.json +0 -0
  45. {paces-0.0.29 → paces-0.0.30}/tests/poc_fixture.py +0 -0
  46. {paces-0.0.29 → paces-0.0.30}/tests/test_ask.py +0 -0
  47. {paces-0.0.29 → paces-0.0.30}/tests/test_chapters.py +0 -0
  48. {paces-0.0.29 → paces-0.0.30}/tests/test_cli_surface.py +0 -0
  49. {paces-0.0.29 → paces-0.0.30}/tests/test_corrections.py +0 -0
  50. {paces-0.0.29 → paces-0.0.30}/tests/test_cues.py +0 -0
  51. {paces-0.0.29 → paces-0.0.30}/tests/test_derivation.py +0 -0
  52. {paces-0.0.29 → paces-0.0.30}/tests/test_edit_protection_residuals.py +0 -0
  53. {paces-0.0.29 → paces-0.0.30}/tests/test_edits.py +0 -0
  54. {paces-0.0.29 → paces-0.0.30}/tests/test_evidence_schemas.py +0 -0
  55. {paces-0.0.29 → paces-0.0.30}/tests/test_excerpts.py +0 -0
  56. {paces-0.0.29 → paces-0.0.30}/tests/test_known_k.py +0 -0
  57. {paces-0.0.29 → paces-0.0.30}/tests/test_measure.py +0 -0
  58. {paces-0.0.29 → paces-0.0.30}/tests/test_pose.py +0 -0
  59. {paces-0.0.29 → paces-0.0.30}/tests/test_render_media.py +0 -0
  60. {paces-0.0.29 → paces-0.0.30}/tests/test_roundtrip_poc.py +0 -0
  61. {paces-0.0.29 → paces-0.0.30}/tests/test_segment.py +0 -0
  62. {paces-0.0.29 → paces-0.0.30}/tests/test_smoke.py +0 -0
  63. {paces-0.0.29 → paces-0.0.30}/tests/test_vertical_slice.py +0 -0
  64. {paces-0.0.29 → paces-0.0.30}/tests/video_synth.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: paces
3
- Version: 0.0.29
3
+ Version: 0.0.30
4
4
  Summary: Turn instructional media into structured, interactive learning material
5
5
  Project-URL: Homepage, https://github.com/thorwhalen/paces
6
6
  Project-URL: Repository, https://github.com/thorwhalen/paces
@@ -139,6 +139,8 @@ _LAZY = {
139
139
  "from_store": "paces.evidence",
140
140
  "StoreWrite": "paces.evidence",
141
141
  "recipes_from_store": "paces.evidence",
142
+ "corrections_to_store": "paces.evidence",
143
+ "corrections_from_store": "paces.evidence",
142
144
  }
143
145
 
144
146
 
@@ -238,7 +238,7 @@ def load_answers(answers: Mapping) -> Answers:
238
238
 
239
239
  >>> load_answers({"kind": "PacesAskAnswers", "version": 1, "k": 4,
240
240
  ... "corrections": [{"verb": "split", "anchorT": "15"}]})
241
- Answers(k=4, corrections=(Correction(verb='split', anchor_t=15.0, span=None, step_id=None, author='', at='', media_key=None, reason=''),), boundaries=None)
241
+ Answers(k=4, corrections=(Correction(verb='split', anchor_t=15.0, span=None, step_id=None, author='', at='', media_key=None, reason='', migrated_from=None),), boundaries=None)
242
242
  """
243
243
  if not isinstance(answers, Mapping):
244
244
  raise ValueError(
@@ -24,6 +24,11 @@ Two rules hold across every body here:
24
24
  document itself already makes.
25
25
  """
26
26
 
27
+ from paces.bodies.correction import (
28
+ CORRECTION_BODY_SCHEMA_URI,
29
+ CORRECTION_TIER,
30
+ GuideCorrectionBodyV1,
31
+ )
27
32
  from paces.bodies.derivation import (
28
33
  RECIPE_BODY_SCHEMA_URI,
29
34
  RECIPE_TIER,
@@ -73,10 +78,15 @@ PACES_BODY_SCHEMA_URIS = (
73
78
  GRID_BODY_SCHEMA_URI,
74
79
  BEAT_BODY_SCHEMA_URI,
75
80
  RECIPE_BODY_SCHEMA_URI,
81
+ CORRECTION_BODY_SCHEMA_URI,
76
82
  )
77
83
 
78
84
  __all__ = [
79
85
  "PACES_BODY_SCHEMA_URIS",
86
+ # the correction log (paces#34)
87
+ "CORRECTION_TIER",
88
+ "CORRECTION_BODY_SCHEMA_URI",
89
+ "GuideCorrectionBodyV1",
80
90
  # document envelope
81
91
  "DOC_TIER",
82
92
  "DOC_BODY_SCHEMA_URI",
@@ -0,0 +1,77 @@
1
+ """Body schema for a human correction — the log of ``docs/alignment/07 §7.5``, stored.
2
+
3
+ ``annot://schema/guide-correction/v1``, tier ``correction``: one row per entry
4
+ of a guide's correction log (:mod:`paces.corrections`), in log order
5
+ (``ordinal``). The log is kept **separately from the result**: it is human input
6
+ with provenance, not analysis, so :func:`paces.evidence.to_store`'s
7
+ re-derivation never prunes it, and only
8
+ :func:`paces.evidence.corrections_to_store` rewrites it.
9
+
10
+ The annotation's reference is the stretch of media the correction is about:
11
+ a ``pin``'s or ``forbid``'s ``span`` (where the step is, or is not), so an
12
+ interval query finds it, and a point at ``anchor_t`` for the other verbs. A
13
+ ``pin``'s or ``forbid``'s ``anchor_t`` is then not the reference's start (a
14
+ forbid's anchor lies outside its span), so it travels in the body as a
15
+ decimal string: the *key* naming which step is meant, not an interval.
16
+
17
+ ``author`` and ``at`` are required here, though optional on
18
+ :class:`~paces.corrections.Correction`: a hand-written log stays easy to type,
19
+ and a stored log is where provenance pays (paces#34).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Literal
25
+
26
+ from lacing.schema import register_body_schema
27
+ from pydantic import Field
28
+
29
+ from paces.bodies._base import BodyBase, Decimal
30
+
31
+ CORRECTION_TIER = "correction"
32
+ CORRECTION_BODY_SCHEMA_URI = "annot://schema/guide-correction/v1"
33
+
34
+
35
+ class GuideCorrectionBodyV1(BodyBase):
36
+ """One entry of a guide's correction log."""
37
+
38
+ doc_id: str = Field(..., description="Which guide this correction belongs to.")
39
+ ordinal: int = Field(
40
+ ...,
41
+ ge=0,
42
+ description=(
43
+ "The entry's position in the log. Replay applies corrections in "
44
+ "this order, each to the result of the ones before it."
45
+ ),
46
+ )
47
+ verb: Literal["pin", "forbid", "absent", "split", "merge"] = Field(
48
+ ..., description="What the human said (paces.corrections.VERBS)."
49
+ )
50
+ anchor_t: Decimal | None = Field(
51
+ None,
52
+ description=(
53
+ "For pin and forbid, whose reference is their span: the time naming "
54
+ "the step meant, in seconds. None for the other verbs, whose "
55
+ "reference is a point at it."
56
+ ),
57
+ )
58
+ step_id: str | None = Field(
59
+ None, description="The step id shown when it was made; display only."
60
+ )
61
+ author: str = Field(..., min_length=1, description="Who made the correction.")
62
+ at: str = Field(..., min_length=1, description="When (ISO-8601).")
63
+ media_key: str | None = Field(
64
+ None,
65
+ description=(
66
+ "Which rendering of the media the correction was true of. A replay "
67
+ "told another key skips it as stale until it is migrated."
68
+ ),
69
+ )
70
+ migrated_from: str | None = Field(
71
+ None,
72
+ description="The media key it was migrated from, when a re-cut moved it.",
73
+ )
74
+ reason: str = Field("", description="Why, in the human's words.")
75
+
76
+
77
+ register_body_schema(CORRECTION_BODY_SCHEMA_URI, GuideCorrectionBodyV1)
@@ -85,7 +85,9 @@ class Correction:
85
85
 
86
86
  ``step_id`` is for display only and is NEVER the join key: replay finds
87
87
  its target by ``anchor_t``. ``media_key`` records which rendering of the
88
- media the correction was true of, so a later re-cut can migrate the log.
88
+ media the correction was true of, so a later re-cut can migrate the log
89
+ (:func:`migrate_corrections`, which sets ``migrated_from``), and a replay
90
+ told another key skips it as stale (:func:`stale_corrections`).
89
91
  Times are kept to the millisecond (:data:`TIME_PLACES`), so the wire form
90
92
  round-trips exactly.
91
93
 
@@ -101,6 +103,7 @@ class Correction:
101
103
  at: str = "" # ISO-8601 timestamp
102
104
  media_key: str | None = None
103
105
  reason: str = ""
106
+ migrated_from: str | None = None # the media key a re-cut moved it from
104
107
 
105
108
  def __post_init__(self):
106
109
  for name in ("author", "at", "reason"):
@@ -108,7 +111,7 @@ class Correction:
108
111
  raise ValueError(
109
112
  f"{name} must be a string, got {getattr(self, name)!r}"
110
113
  )
111
- for name in ("step_id", "media_key"):
114
+ for name in ("step_id", "media_key", "migrated_from"):
112
115
  if getattr(self, name) is not None and not isinstance(
113
116
  getattr(self, name), str
114
117
  ):
@@ -118,6 +121,8 @@ class Correction:
118
121
  if self.verb not in VERBS:
119
122
  raise ValueError(f"unknown verb {self.verb!r}; expected one of {VERBS}")
120
123
  object.__setattr__(self, "anchor_t", _to_ms(self.anchor_t, what="anchor_t"))
124
+ if self.anchor_t < 0:
125
+ raise ValueError(f"anchor_t is a time on the media, got {self.anchor_t}")
121
126
  needs_span = self.verb in ("pin", "forbid")
122
127
  if needs_span != (self.span is not None):
123
128
  raise ValueError(
@@ -127,7 +132,7 @@ class Correction:
127
132
  if not isinstance(self.span, (tuple, list)) or len(self.span) != 2:
128
133
  raise ValueError(f"span must be (start, end), got {self.span!r}")
129
134
  start, end = (_to_ms(t, what="span") for t in self.span)
130
- if not start < end:
135
+ if not 0 <= start < end:
131
136
  raise ValueError(
132
137
  f"span must be (start, end) with start < end: {self.span}"
133
138
  )
@@ -186,6 +191,7 @@ _WIRE_KEYS = {
186
191
  "at": "at",
187
192
  "media_key": "mediaKey",
188
193
  "reason": "reason",
194
+ "migrated_from": "migratedFrom",
189
195
  }
190
196
  _REQUIRED_WIRE_KEYS = ("verb", "anchorT")
191
197
 
@@ -195,7 +201,14 @@ def to_wire(correction: Correction) -> dict:
195
201
  wire: dict = {"verb": correction.verb, "anchorT": time_str(correction.anchor_t)}
196
202
  if correction.span is not None:
197
203
  wire["span"] = [time_str(t) for t in correction.span]
198
- for field_name in ("step_id", "author", "at", "media_key", "reason"):
204
+ for field_name in (
205
+ "step_id",
206
+ "author",
207
+ "at",
208
+ "media_key",
209
+ "reason",
210
+ "migrated_from",
211
+ ):
199
212
  value = getattr(correction, field_name)
200
213
  if value:
201
214
  wire[_WIRE_KEYS[field_name]] = value
@@ -255,6 +268,186 @@ def normalize_corrections(
255
268
  return tuple(c if isinstance(c, Correction) else from_wire(c) for c in corrections)
256
269
 
257
270
 
271
+ # ── renderings: stale corrections and migrating a log across a re-cut ───────
272
+
273
+
274
+ def stale_corrections(
275
+ corrections: Iterable[Correction | Mapping], media_key: str | None
276
+ ) -> tuple[tuple[Correction, ...], tuple[str, ...]]:
277
+ """``(current, flags)``: the log without the corrections made against
278
+ another rendering of the media, and a ``correction-stale`` flag for each.
279
+
280
+ A correction recorded against another ``media_key`` is about different
281
+ times (a re-cut moved everything after its cut), so replaying it would act
282
+ on the wrong moment. It is skipped and said, never dropped silently; once
283
+ :func:`migrate_corrections` moves it to this rendering it applies again. A
284
+ correction with no ``media_key`` (a hand-written log), or a call with
285
+ ``media_key=None`` (the rendering is not known), is current.
286
+
287
+ >>> log = [split(5, media_key="cut-a"), split(9, media_key="cut-b"), merge(20)]
288
+ >>> current, flags = stale_corrections(log, "cut-b")
289
+ >>> [c.label for c in current]
290
+ ['split@9', 'merge@20']
291
+ >>> flags
292
+ ("correction-stale: split@5 (made against media 'cut-a', not 'cut-b'; migrate it with migrate_corrections)",)
293
+ """
294
+ log = normalize_corrections(corrections)
295
+ if media_key is None:
296
+ return log, ()
297
+ current, flags = [], []
298
+ for c in log:
299
+ if c.media_key is not None and c.media_key != media_key:
300
+ flags.append(
301
+ f"correction-stale: {c.label} (made against media {c.media_key!r}, "
302
+ f"not {media_key!r}; migrate it with migrate_corrections)"
303
+ )
304
+ else:
305
+ current.append(c)
306
+ return tuple(current), tuple(flags)
307
+
308
+
309
+ @dataclass(frozen=True, slots=True)
310
+ class CorrectionMigration:
311
+ """What :func:`migrate_corrections` did: the new log, and what it could not move."""
312
+
313
+ corrections: tuple[Correction, ...]
314
+ dropped: tuple[tuple[Correction, str], ...] = ()
315
+ moved: int = 0 # how many were made against the old rendering and moved
316
+ untagged: int = 0 # corrections with no media_key: left as they were
317
+
318
+ @property
319
+ def flags(self) -> tuple[str, ...]:
320
+ """One ``correction-unmigrated`` line per dropped correction, saying why;
321
+ and ``correction-migration-empty`` when nothing was made against the old
322
+ rendering, so a no-op is never mistaken for a migration."""
323
+ flags = tuple(
324
+ f"correction-unmigrated: {c.label} ({why})" for c, why in self.dropped
325
+ )
326
+ if not self.moved and not self.dropped:
327
+ note = (
328
+ f"; {self.untagged} correction(s) carry no media key and replay "
329
+ "unchanged on every rendering: tag them with media_key= first"
330
+ if self.untagged
331
+ else ""
332
+ )
333
+ flags += (
334
+ "correction-migration-empty: no correction was made against the "
335
+ f"old rendering{note}",
336
+ )
337
+ return flags
338
+
339
+
340
+ def _remap_after_cuts():
341
+ """The fleet's one rule for moving a time across cuts (``mixing``'s)."""
342
+ try:
343
+ from mixing.transcript.formats import remap_time_after_cuts
344
+ except ImportError as error: # pragma: no cover - the message is the point
345
+ raise ImportError(
346
+ "migrating corrections across a re-cut uses mixing's "
347
+ "remap_time_after_cuts, which the [audio] extra installs; or pass remap="
348
+ ) from error
349
+ return remap_time_after_cuts
350
+
351
+
352
+ def _cut_dicts(cuts) -> list[dict]:
353
+ """The cuts as sorted, merged ``{"start", "end"}`` spans: the remap sums cut
354
+ lengths, so an overlap (or a duplicate) would be removed twice.
355
+
356
+ >>> _cut_dicts([(15, 25), (10, 20), (30, 40), (30, 40)])
357
+ [{'start': 10.0, 'end': 25.0}, {'start': 30.0, 'end': 40.0}]
358
+ """
359
+ spans = []
360
+ for cut in cuts:
361
+ start, end = (cut["start"], cut["end"]) if isinstance(cut, Mapping) else cut
362
+ start = _to_ms(start, what="a cut's start")
363
+ end = _to_ms(end, what="a cut's end")
364
+ if not 0 <= start < end:
365
+ raise ValueError(
366
+ f"a cut must be (start, end) with 0 <= start < end, got {cut!r}"
367
+ )
368
+ spans.append([start, end])
369
+ merged: list[list[float]] = []
370
+ for start, end in sorted(spans):
371
+ if merged and start <= merged[-1][1]:
372
+ merged[-1][1] = max(merged[-1][1], end)
373
+ else:
374
+ merged.append([start, end])
375
+ return [{"start": start, "end": end} for start, end in merged]
376
+
377
+
378
+ def migrate_corrections(
379
+ corrections: Iterable[Correction | Mapping],
380
+ *,
381
+ cuts,
382
+ from_media_key: str,
383
+ to_media_key: str,
384
+ remap=None,
385
+ ) -> CorrectionMigration:
386
+ """Move the corrections made against ``from_media_key`` onto the rendering
387
+ ``to_media_key``, which is that media with ``cuts`` removed.
388
+
389
+ ``cuts`` are ``(start, end)`` pairs or ``{"start", "end"}`` mappings on the
390
+ old timeline (``mixing``'s cut list). Each moved correction's times go
391
+ through ``remap`` (default: ``mixing.transcript.formats.remap_time_after_cuts``,
392
+ the fleet's one rule), its ``media_key`` becomes ``to_media_key`` and
393
+ ``migrated_from`` records the old one. A correction whose anchor was cut
394
+ out, or whose span the cuts remove or collapse, has nothing left to say
395
+ about the new rendering: it is returned in ``dropped`` with the reason,
396
+ never silently lost. Corrections made against any other rendering, or with
397
+ no ``media_key``, are kept unchanged, in log order.
398
+
399
+ >>> remap = lambda t, cuts: t - sum(c["end"] - c["start"] for c in cuts if c["end"] <= t)
400
+ >>> moved = migrate_corrections([split(30, media_key="v1"), merge(5, media_key="v1")],
401
+ ... cuts=[(10, 20)], from_media_key="v1", to_media_key="v2",
402
+ ... remap=remap)
403
+ >>> [(c.label, c.media_key, c.migrated_from) for c in moved.corrections]
404
+ [('split@20', 'v2', 'v1'), ('merge@5', 'v2', 'v1')]
405
+ """
406
+ remap = remap or _remap_after_cuts()
407
+ cut_list = _cut_dicts(cuts)
408
+
409
+ def inside_a_cut(t: float) -> bool:
410
+ return any(c["start"] <= t < c["end"] for c in cut_list)
411
+
412
+ kept: list[Correction] = []
413
+ dropped: list[tuple[Correction, str]] = []
414
+ moved_count = untagged = 0
415
+ for c in normalize_corrections(corrections):
416
+ if c.media_key != from_media_key:
417
+ untagged += c.media_key is None
418
+ kept.append(c)
419
+ continue
420
+ if inside_a_cut(c.anchor_t):
421
+ dropped.append((c, "its time was cut out"))
422
+ continue
423
+ span = None
424
+ if c.span is not None:
425
+ start, end = c.span
426
+ span = (remap(start, cut_list), remap(end, cut_list))
427
+ if not span[0] < span[1]:
428
+ dropped.append((c, "the cuts remove its span"))
429
+ continue
430
+ try:
431
+ moved = dataclasses.replace(
432
+ c,
433
+ anchor_t=remap(c.anchor_t, cut_list),
434
+ span=span,
435
+ media_key=to_media_key,
436
+ migrated_from=from_media_key,
437
+ )
438
+ except ValueError as error:
439
+ dropped.append((c, f"it no longer holds after the cuts: {error}"))
440
+ continue
441
+ kept.append(moved)
442
+ moved_count += 1
443
+ return CorrectionMigration(
444
+ corrections=tuple(kept),
445
+ dropped=tuple(dropped),
446
+ moved=moved_count,
447
+ untagged=untagged,
448
+ )
449
+
450
+
258
451
  # ── replay: the fallback for segmenters that do not read the log ────────────
259
452
 
260
453
 
@@ -288,9 +481,14 @@ def replay(
288
481
  *,
289
482
  merge_tolerance_s: float = DFLT_MERGE_TOLERANCE_S,
290
483
  min_step_s: float = DFLT_MIN_STEP_S,
484
+ media_key: str | None = None,
291
485
  ) -> Segmentation:
292
486
  """Apply a correction log to a segmentation, in log order.
293
487
 
488
+ ``media_key`` names the rendering ``seg`` was made from: a correction made
489
+ against another one is skipped and flagged ``correction-stale``
490
+ (:func:`stale_corrections`). ``None`` (default) applies every correction.
491
+
294
492
  Each correction acts on the result of the ones before it, as the human
295
493
  made them. Applied ones are flagged ``corrected: <verb>@<t>``; one that
296
494
  finds nothing to act on is flagged ``correction-unmatched``, one that
@@ -322,12 +520,13 @@ def replay(
322
520
  )
323
521
  outcomes: list = []
324
522
  cuts_touched = False # once a correction edits the cut set, it is rebuilt
325
- for correction in normalize_corrections(corrections):
523
+ current, stale = stale_corrections(corrections, media_key)
524
+ for correction in current:
326
525
  before = state.boundaries
327
526
  state, outcome = _APPLY[correction.verb](state, correction, options)
328
527
  cuts_touched = cuts_touched or state.boundaries != before
329
528
  outcomes.append(outcome)
330
- flags = tuple(_final_flags(state.steps, outcomes))
529
+ flags = stale + tuple(_final_flags(state.steps, outcomes))
331
530
  unchanged = not cuts_touched
332
531
  return dataclasses.replace(
333
532
  seg,
@@ -103,6 +103,9 @@ except ImportError as error: # pragma: no cover
103
103
  ) from error
104
104
 
105
105
  from paces.bodies import (
106
+ CORRECTION_BODY_SCHEMA_URI,
107
+ CORRECTION_TIER,
108
+ GuideCorrectionBodyV1,
106
109
  BEAT_BODY_SCHEMA_URI,
107
110
  BEAT_TIER,
108
111
  CUE_BODY_SCHEMA_URI,
@@ -177,6 +180,7 @@ TIERS: tuple[Tier, ...] = (
177
180
  stereotype=TierStereotype.SYMBOLIC_ASSOCIATION,
178
181
  parent=STEP_TIER,
179
182
  ),
183
+ Tier(CORRECTION_TIER),
180
184
  )
181
185
 
182
186
  _HEX64 = re.compile(r"^[0-9a-f]{64}$")
@@ -273,6 +277,7 @@ class StoreWrite:
273
277
 
274
278
  @property
275
279
  def total(self) -> int:
280
+ """All records handled: written, updated, unchanged and relinked."""
276
281
  return self.written + self.updated + self.unchanged + self.relinked
277
282
 
278
283
 
@@ -325,6 +330,7 @@ class _Writer:
325
330
  generated_by: str = DFLT_GENERATED_BY,
326
331
  derived_from: Iterable[Any] = (),
327
332
  confidence: float | None = None,
333
+ activity: str = "derive",
328
334
  ) -> tuple[UUID, str]:
329
335
  """Upsert one annotation; return its ``(id, value_digest)``."""
330
336
  annotation_id = uuid5(PACES_NAMESPACE, f"{tier}\n{key}")
@@ -347,7 +353,7 @@ class _Writer:
347
353
  was_attributed_to=self._attributed_to,
348
354
  was_derived_from=list(derived_from),
349
355
  generated_at_time=self._generated_at,
350
- activity="derive",
356
+ activity=activity,
351
357
  ),
352
358
  confidence=confidence,
353
359
  )
@@ -388,6 +394,10 @@ class _Writer:
388
394
  self._record(annotation_id)
389
395
  return annotation_id, digest
390
396
 
397
+ def existing(self, tier: str, key: str) -> Annotation | None:
398
+ """The row already stored under this evidence key, if any."""
399
+ return self._index.get(uuid5(PACES_NAMESPACE, f"{tier}\n{key}"))
400
+
391
401
  def _record(self, annotation_id: UUID) -> None:
392
402
  self.ids.append(str(annotation_id))
393
403
  self.touched.add(annotation_id)
@@ -645,6 +655,12 @@ DOC_SCOPED_TIERS = frozenset(
645
655
  {DOC_TIER, SOURCE_TIER, GRID_TIER, STEP_TIER, SUB_STEP_TIER, CUE_TIER, RECIPE_TIER}
646
656
  )
647
657
 
658
+ #: Tiers whose rows belong to one guide (each carries a ``doc_id``) but hold
659
+ #: human input, not analysis: the correction log (paces#34). A re-derivation is
660
+ #: NOT authoritative over them, so :func:`to_store` never prunes them; only
661
+ #: :func:`corrections_to_store`, which holds the whole log, rewrites them.
662
+ LOG_TIERS = frozenset({CORRECTION_TIER})
663
+
648
664
  #: The doc-scoped tiers every ``to_store`` writes, because they are projected
649
665
  #: from the ``Segmentation`` itself.
650
666
  _ALWAYS_WRITTEN_TIERS = frozenset(
@@ -1300,3 +1316,176 @@ def recipes_from_store(store, *, asset_id: str, doc_id: str | None = None) -> di
1300
1316
  }
1301
1317
  for row in rows
1302
1318
  }
1319
+
1320
+
1321
+ # ── the correction log (paces#34) ───────────────────────────────────────────
1322
+
1323
+ #: What wrote a stored correction row: the human's log, put in by this call.
1324
+ CORRECTIONS_GENERATED_BY = "processor:paces.corrections_to_store"
1325
+
1326
+
1327
+ @dataclass(frozen=True)
1328
+ class CorrectionsWrite:
1329
+ """What :func:`corrections_to_store` did."""
1330
+
1331
+ written: int
1332
+ updated: int
1333
+ unchanged: int
1334
+ removed: int # rows of a longer, earlier log this one replaced
1335
+ annotation_ids: tuple[str, ...]
1336
+
1337
+
1338
+ def corrections_to_store(
1339
+ corrections,
1340
+ *,
1341
+ store,
1342
+ asset_id: str,
1343
+ doc_id: str = "guide",
1344
+ author: str = "",
1345
+ at: str | None = None,
1346
+ attributed_to: str = DFLT_ATTRIBUTED_TO,
1347
+ generated_at: RationalTime | None = None,
1348
+ rate: int = DEFAULT_RATE,
1349
+ ) -> CorrectionsWrite:
1350
+ """Store a guide's correction log in *store*, one row per entry, in order.
1351
+
1352
+ The log is kept **separately from the result** (``docs/alignment/07
1353
+ §7.5``): its rows are on the ``correction`` tier, which :func:`to_store`'s
1354
+ re-derivation never prunes, and this call is the only writer. A call holds
1355
+ the guide's whole log, so rows of corrections it no longer has are removed.
1356
+
1357
+ **A row's id is the correction's identity**, not its position: the asset,
1358
+ the guide, the verb, its times and its rendering (``uuid5``, like every
1359
+ paces row). Inserting or deleting an entry leaves every other row (and
1360
+ anything derived from it) alone; ``ordinal`` in the body is the order.
1361
+ Rows are digest-gated: storing the same log again writes nothing.
1362
+
1363
+ Provenance pays here, so a stored correction must name its ``author``
1364
+ (its own, else ``author=``; ``ValueError`` when neither) and gets ``at``
1365
+ filled: its own, else the one already stored for the same correction (a
1366
+ log reloaded from the wire has none, and re-storing it must not restamp
1367
+ it), else ``at=``, else now. Each row's activity is ``create`` (a human
1368
+ made it), or ``migrate`` for one a re-cut moved
1369
+ (:func:`paces.corrections.migrate_corrections`).
1370
+
1371
+ Args:
1372
+ corrections: :class:`~paces.corrections.Correction` objects or their
1373
+ wire mappings, in log order.
1374
+ store: Any ``lacing.IntervalAnnotationStore``.
1375
+ asset_id: The media the corrections are about.
1376
+ doc_id: Which guide's log this is.
1377
+ rate: Ticks per second. Correction times are kept to the millisecond,
1378
+ so it must be a multiple of 1000.
1379
+ """
1380
+ from paces.corrections import normalize_corrections
1381
+ from paces.edits import _now_iso
1382
+ from paces.segmentation import time_str
1383
+
1384
+ if rate % 1000:
1385
+ raise ValueError(
1386
+ f"rate={rate}: correction times are kept to the millisecond, so the "
1387
+ "tick rate must be a multiple of 1000"
1388
+ )
1389
+ log = normalize_corrections(corrections)
1390
+ unnamed = [c.label for c in log if not (c.author or author)]
1391
+ if unnamed:
1392
+ raise ValueError(
1393
+ f"a stored correction names its author; {unnamed} have none: pass "
1394
+ "author= or set Correction.author"
1395
+ )
1396
+ stamp = at or _now_iso()
1397
+ register_tiers(store)
1398
+ writer = _Writer(
1399
+ store,
1400
+ attributed_to=attributed_to,
1401
+ generated_at=generated_at or RationalTime.now(),
1402
+ )
1403
+ seen: dict[str, int] = {}
1404
+ for ordinal, c in enumerate(log):
1405
+ identity = "\n".join(
1406
+ [
1407
+ asset_id,
1408
+ doc_id,
1409
+ c.verb,
1410
+ time_str(c.anchor_t),
1411
+ "" if c.span is None else "/".join(map(time_str, c.span)),
1412
+ c.media_key or "",
1413
+ ]
1414
+ )
1415
+ seen[identity] = seen.get(identity, 0) + 1 # the same correction twice
1416
+ key = f"correction:{identity}\n{seen[identity]}"
1417
+ stored = writer.existing(CORRECTION_TIER, key)
1418
+ spanned = c.span is not None
1419
+ writer.put(
1420
+ tier=CORRECTION_TIER,
1421
+ key=key,
1422
+ interval=(
1423
+ _interval(*(time_str(t) for t in c.span), rate=rate)
1424
+ if spanned
1425
+ else _point(time_str(c.anchor_t), rate=rate)
1426
+ ),
1427
+ asset_id=asset_id,
1428
+ body=GuideCorrectionBodyV1(
1429
+ doc_id=doc_id,
1430
+ ordinal=ordinal,
1431
+ verb=c.verb,
1432
+ anchor_t=time_str(c.anchor_t) if spanned else None,
1433
+ step_id=c.step_id,
1434
+ author=c.author or author,
1435
+ at=c.at or (stored.body.get("at") if stored else None) or stamp,
1436
+ media_key=c.media_key,
1437
+ migrated_from=c.migrated_from,
1438
+ reason=c.reason,
1439
+ ).model_dump(mode="json"),
1440
+ schema_uri=CORRECTION_BODY_SCHEMA_URI,
1441
+ generated_by=CORRECTIONS_GENERATED_BY,
1442
+ activity="create" if c.migrated_from is None else "migrate",
1443
+ )
1444
+ writer.prune(asset_id=asset_id, doc_id=doc_id, tiers={CORRECTION_TIER})
1445
+ return CorrectionsWrite(
1446
+ written=writer.written,
1447
+ updated=writer.updated + writer.relinked,
1448
+ unchanged=writer.unchanged,
1449
+ removed=writer.removed,
1450
+ annotation_ids=tuple(writer.ids),
1451
+ )
1452
+
1453
+
1454
+ def corrections_from_store(store, *, asset_id: str, doc_id: str = "guide") -> tuple:
1455
+ """The correction log held for one guide, in log order: the inverse of
1456
+ :func:`corrections_to_store` (the ``author`` and ``at`` it filled come back
1457
+ filled)."""
1458
+ from paces.corrections import Correction
1459
+
1460
+ rows = sorted(
1461
+ (
1462
+ row
1463
+ for row in store.all()
1464
+ if row.tier == CORRECTION_TIER
1465
+ and getattr(row.reference, "asset_id", None) == asset_id
1466
+ and row.body.get("doc_id") == doc_id
1467
+ ),
1468
+ key=lambda row: row.body["ordinal"],
1469
+ )
1470
+
1471
+ def times(row):
1472
+ interval = row.reference.interval
1473
+ start = float(_decimal(interval.start))
1474
+ if row.body.get("anchor_t") is None: # a point at the anchor
1475
+ return start, None
1476
+ return float(row.body["anchor_t"]), (start, float(_decimal(interval.end)))
1477
+
1478
+ return tuple(
1479
+ Correction(
1480
+ verb=row.body["verb"],
1481
+ anchor_t=times(row)[0],
1482
+ span=times(row)[1],
1483
+ step_id=row.body["step_id"],
1484
+ author=row.body["author"],
1485
+ at=row.body["at"],
1486
+ media_key=row.body["media_key"],
1487
+ migrated_from=row.body["migrated_from"],
1488
+ reason=row.body["reason"],
1489
+ )
1490
+ for row in rows
1491
+ )
@@ -359,6 +359,7 @@ class RtmlibPoseLocator:
359
359
  return ";".join([f"{LOCATOR_STEM}@{engine}", *terms])
360
360
 
361
361
  def __call__(self, query: LocateQuery) -> SubjectObservation | None:
362
+ """Locate the subject in the media of ``query``; ``None`` when no pose is found."""
362
363
  estimate = self.pose_estimator or _body_estimator(self.mode, self.device)
363
364
  read_frame = _frame_reader(query.media_path)
364
365
  frame_size = (query.frame_width, query.frame_height)