paces 0.0.28__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.28 → paces-0.0.30}/PKG-INFO +1 -1
  2. {paces-0.0.28 → paces-0.0.30}/paces/__init__.py +2 -0
  3. {paces-0.0.28 → paces-0.0.30}/paces/ask.py +1 -1
  4. {paces-0.0.28 → 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.28 → paces-0.0.30}/paces/corrections.py +205 -6
  7. {paces-0.0.28 → paces-0.0.30}/paces/edits.py +202 -1
  8. {paces-0.0.28 → paces-0.0.30}/paces/evidence.py +190 -1
  9. {paces-0.0.28 → paces-0.0.30}/paces/pose.py +1 -0
  10. {paces-0.0.28 → paces-0.0.30}/paces/segmenters.py +9 -1
  11. {paces-0.0.28 → paces-0.0.30}/paces/tools.py +7 -1
  12. {paces-0.0.28 → paces-0.0.30}/pyproject.toml +1 -1
  13. {paces-0.0.28 → paces-0.0.30}/tests/data/body_schemas.json +109 -0
  14. paces-0.0.30/tests/test_corrections_log.py +310 -0
  15. {paces-0.0.28 → paces-0.0.30}/tests/test_edits.py +110 -0
  16. {paces-0.0.28 → paces-0.0.30}/tests/test_evidence.py +4 -1
  17. {paces-0.0.28 → paces-0.0.30}/.gitignore +0 -0
  18. {paces-0.0.28 → paces-0.0.30}/LICENSE +0 -0
  19. {paces-0.0.28 → paces-0.0.30}/README.md +0 -0
  20. {paces-0.0.28 → paces-0.0.30}/docs/README.md +0 -0
  21. {paces-0.0.28 → paces-0.0.30}/docs/alignment/README.md +0 -0
  22. {paces-0.0.28 → paces-0.0.30}/docs/poc-reference/README.md +0 -0
  23. {paces-0.0.28 → paces-0.0.30}/docs/poc-reference/artifacts/clips.json +0 -0
  24. {paces-0.0.28 → paces-0.0.30}/paces/__main__.py +0 -0
  25. {paces-0.0.28 → paces-0.0.30}/paces/ask_contract.py +0 -0
  26. {paces-0.0.28 → paces-0.0.30}/paces/bodies/_base.py +0 -0
  27. {paces-0.0.28 → paces-0.0.30}/paces/bodies/derivation.py +0 -0
  28. {paces-0.0.28 → paces-0.0.30}/paces/bodies/document.py +0 -0
  29. {paces-0.0.28 → paces-0.0.30}/paces/bodies/signal.py +0 -0
  30. {paces-0.0.28 → paces-0.0.30}/paces/bodies/step.py +0 -0
  31. {paces-0.0.28 → paces-0.0.30}/paces/cues.py +0 -0
  32. {paces-0.0.28 → paces-0.0.30}/paces/data/ask/ask.css +0 -0
  33. {paces-0.0.28 → paces-0.0.30}/paces/data/ask/ask.html +0 -0
  34. {paces-0.0.28 → paces-0.0.30}/paces/data/ask/ask.js +0 -0
  35. {paces-0.0.28 → paces-0.0.30}/paces/derivation.py +0 -0
  36. {paces-0.0.28 → paces-0.0.30}/paces/excerpts.py +0 -0
  37. {paces-0.0.28 → paces-0.0.30}/paces/known_k.py +0 -0
  38. {paces-0.0.28 → paces-0.0.30}/paces/measure.py +0 -0
  39. {paces-0.0.28 → paces-0.0.30}/paces/model.py +0 -0
  40. {paces-0.0.28 → paces-0.0.30}/paces/projection.py +0 -0
  41. {paces-0.0.28 → paces-0.0.30}/paces/render.py +0 -0
  42. {paces-0.0.28 → paces-0.0.30}/paces/segmentation.py +0 -0
  43. {paces-0.0.28 → paces-0.0.30}/paces/timed_text.py +0 -0
  44. {paces-0.0.28 → paces-0.0.30}/tests/audio_synth.py +0 -0
  45. {paces-0.0.28 → paces-0.0.30}/tests/data/routine.json +0 -0
  46. {paces-0.0.28 → paces-0.0.30}/tests/poc_fixture.py +0 -0
  47. {paces-0.0.28 → paces-0.0.30}/tests/test_ask.py +0 -0
  48. {paces-0.0.28 → paces-0.0.30}/tests/test_chapters.py +0 -0
  49. {paces-0.0.28 → paces-0.0.30}/tests/test_cli_surface.py +0 -0
  50. {paces-0.0.28 → paces-0.0.30}/tests/test_corrections.py +0 -0
  51. {paces-0.0.28 → paces-0.0.30}/tests/test_cues.py +0 -0
  52. {paces-0.0.28 → paces-0.0.30}/tests/test_derivation.py +0 -0
  53. {paces-0.0.28 → paces-0.0.30}/tests/test_edit_protection_residuals.py +0 -0
  54. {paces-0.0.28 → paces-0.0.30}/tests/test_evidence_schemas.py +0 -0
  55. {paces-0.0.28 → paces-0.0.30}/tests/test_excerpts.py +0 -0
  56. {paces-0.0.28 → paces-0.0.30}/tests/test_known_k.py +0 -0
  57. {paces-0.0.28 → paces-0.0.30}/tests/test_measure.py +0 -0
  58. {paces-0.0.28 → paces-0.0.30}/tests/test_pose.py +0 -0
  59. {paces-0.0.28 → paces-0.0.30}/tests/test_render_media.py +0 -0
  60. {paces-0.0.28 → paces-0.0.30}/tests/test_roundtrip_poc.py +0 -0
  61. {paces-0.0.28 → paces-0.0.30}/tests/test_segment.py +0 -0
  62. {paces-0.0.28 → paces-0.0.30}/tests/test_smoke.py +0 -0
  63. {paces-0.0.28 → paces-0.0.30}/tests/test_vertical_slice.py +0 -0
  64. {paces-0.0.28 → 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.28
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,
@@ -56,7 +56,7 @@ from __future__ import annotations
56
56
 
57
57
  import copy
58
58
  import re
59
- from collections.abc import Mapping, Sequence
59
+ from collections.abc import Iterator, Mapping, Sequence
60
60
  from datetime import datetime, timezone
61
61
  from typing import Any
62
62
 
@@ -435,6 +435,198 @@ def _renamed_from(committed: list[dict]) -> dict[str, dict]:
435
435
  return out
436
436
 
437
437
 
438
+ def _occurrence_start(step: Mapping) -> float | None:
439
+ """Where a step first starts in its media (its first span's start), if anywhere."""
440
+ spans = step.get("spans") or []
441
+ return float(spans[0]["start"]) if spans else None
442
+
443
+
444
+ def _walk(steps: list[dict]) -> Iterator[dict]:
445
+ """Every step of a tree, parents before children."""
446
+ for step in steps:
447
+ yield step
448
+ yield from _walk(step.get("steps", []))
449
+
450
+
451
+ def _renamed_was(step: Mapping) -> str | None:
452
+ """The id a step had before an ``/id`` lock renamed it, if one did."""
453
+ for lock in step.get("locks", []):
454
+ if lock.get("path") == "/id" and lock.get("was") is not None:
455
+ return str(lock["was"])
456
+ return None
457
+
458
+
459
+ def _generated_family(name: str, sid: str) -> str | None:
460
+ """The family of a generated id: the slug of ``name`` when ``sid`` is that
461
+ slug or it with a ``-N`` repeat suffix (:func:`paces.segmenters.unique_slug_ids`);
462
+ ``None`` for an unnamed step or an id the name did not generate.
463
+
464
+ >>> _generated_family("Turn", "turn-3"), _generated_family("Turn", "spin"), _generated_family("", "seg-1")
465
+ ('turn', None, None)
466
+ """
467
+ from paces.segmenters import _slugify
468
+
469
+ if not name:
470
+ return None # unnamed (``seg-1``): its id is its place
471
+ base = _slugify(name)
472
+ if sid == base or re.fullmatch(rf"{re.escape(base)}-\d+", sid):
473
+ return base
474
+ return None
475
+
476
+
477
+ def _time_matching(a: list[float], b: list[float]) -> list[tuple[int, int]]:
478
+ """The order-preserving pairing of times ``a`` with times ``b`` (each sorted;
479
+ each used at most once, as many pairs as the shorter list) of least total
480
+ distance.
481
+
482
+ >>> _time_matching([0.0, 20.0], [0.0, 5.0, 20.0])
483
+ [(0, 0), (1, 2)]
484
+ >>> _time_matching([0.0, 5.0, 20.0], [0.0, 20.0])
485
+ [(0, 0), (2, 1)]
486
+ """
487
+ if len(a) > len(b):
488
+ return [(i, j) for j, i in _time_matching(b, a)]
489
+ n, m = len(a), len(b)
490
+ inf = float("inf")
491
+ # cost[i][j]: best pairing of a[:i] into b[:j] with every a used (i <= j)
492
+ cost = [[inf] * (m + 1) for _ in range(n + 1)]
493
+ cost[0] = [0.0] * (m + 1)
494
+ for i in range(1, n + 1):
495
+ for j in range(i, m + 1):
496
+ cost[i][j] = min(
497
+ cost[i][j - 1], cost[i - 1][j - 1] + abs(a[i - 1] - b[j - 1])
498
+ )
499
+ pairs, i, j = [], n, m
500
+ while i > 0:
501
+ if j > i and cost[i][j] == cost[i][j - 1]:
502
+ j -= 1
503
+ else:
504
+ pairs.append((i - 1, j - 1))
505
+ i, j = i - 1, j - 1
506
+ return pairs[::-1]
507
+
508
+
509
+ def _repeat_ids(committed: list[dict], fresh: list[dict]) -> dict[str, str]:
510
+ """``{fresh id: id to use}`` that keeps repeated steps' identity by name and
511
+ time rather than by the place a generated ``-N`` suffix encodes (paces#50).
512
+
513
+ Generated ids of repeats are numbered by position (``turn``, ``turn-2``), so
514
+ a repeat inserted earlier shifts every later one's suffix, and a lock on the
515
+ committed ``turn-2`` would land on the new second Turn. Over the WHOLE tree
516
+ (ids are unique document-wide), each family of generated ids (a name's slug
517
+ and its repeats) on both sides, with a repeat or a moved id, is paired by
518
+ start time (:func:`_time_matching`, each side in time order). A fresh
519
+ occurrence takes its committed partner's id (the id an ``/id`` lock renamed
520
+ away from, for a renamed one, so the rename rule finds it); an unpaired one
521
+ the first id of its family that no committed or other fresh step holds
522
+ (or held, before a rename); and a fresh step outside these families whose id
523
+ an assignment takes is re-identified the same way. Families without times
524
+ on every occurrence are left as they are.
525
+ """
526
+ c_steps, f_steps = list(_walk(committed)), list(_walk(fresh))
527
+ families: dict[str, tuple[list[tuple[dict, str]], list[dict]]] = {}
528
+ for step in c_steps:
529
+ was = _renamed_was(step)
530
+ key = was or step["id"]
531
+ family = _generated_family(step.get("name", ""), key)
532
+ if family is None and step.get("name"):
533
+ # a name (or id) a human edited: the id it was generated with says the
534
+ # family; it pairs only with a family analysis generates from a name
535
+ family = re.sub(r"-\d+$", "", key)
536
+ if family is not None:
537
+ families.setdefault(family, ([], []))[0].append((step, key))
538
+ for step in f_steps:
539
+ family = _generated_family(step.get("name", ""), step["id"])
540
+ if family is not None:
541
+ families.setdefault(family, ([], []))[1].append(step)
542
+
543
+ mapping: dict[str, str] = {}
544
+ unpaired: list[tuple[str, str]] = [] # (fresh id, family)
545
+ for family, (cs, fs) in families.items():
546
+ if not cs or not fs:
547
+ continue
548
+ if len(cs) == 1 and len(fs) == 1 and cs[0][1] == fs[0]["id"]:
549
+ continue # one each, same id: nothing to re-identify
550
+ if any(_occurrence_start(s) is None for s, _ in cs) or any(
551
+ _occurrence_start(s) is None for s in fs
552
+ ):
553
+ continue # no clock to tell occurrences apart: keep the positional ids
554
+ cs = sorted(cs, key=lambda c: _occurrence_start(c[0]))
555
+ fs = sorted(fs, key=_occurrence_start)
556
+ pairs = _time_matching(
557
+ [_occurrence_start(s) for s, _ in cs], [_occurrence_start(s) for s in fs]
558
+ )
559
+ paired = {j for _, j in pairs}
560
+ for i, j in pairs:
561
+ mapping[fs[j]["id"]] = cs[i][1]
562
+ unpaired += [(fs[j]["id"], family) for j in range(len(fs)) if j not in paired]
563
+
564
+ used = {s["id"] for s in c_steps} | {w for s in c_steps if (w := _renamed_was(s))}
565
+ used |= set(mapping.values())
566
+ used |= {s["id"] for s in f_steps if s["id"] not in mapping}
567
+
568
+ def free(base: str) -> str:
569
+ candidate, n = base, 1
570
+ while candidate in used:
571
+ n += 1
572
+ candidate = f"{base}-{n}"
573
+ used.add(candidate)
574
+ return candidate
575
+
576
+ held = {s["id"] for s in c_steps} | {w for s in c_steps if (w := _renamed_was(s))}
577
+ held |= set(mapping.values())
578
+ for sid, family in unpaired:
579
+ if sid in held: # its positional id is a committed occurrence's: move it
580
+ mapping[sid] = free(family)
581
+ # a fresh step the mapping does not move, whose id an assignment now takes
582
+ taken = {new for old, new in mapping.items() if old != new}
583
+ for step in f_steps:
584
+ sid = step["id"]
585
+ if sid not in mapping and sid in taken:
586
+ family = _generated_family(step.get("name", ""), sid) or re.sub(
587
+ r"-\d+$", "", sid
588
+ )
589
+ mapping[sid] = free(family)
590
+ return {old: new for old, new in mapping.items() if old != new}
591
+
592
+
593
+ def _renumbered(
594
+ doc: dict, ids: Mapping[str, str], *, renamed: Mapping[str, str] | None = None
595
+ ) -> dict:
596
+ """``doc`` (a fresh dump) with its step ids, and every reference to one (a
597
+ cue's anchor, a step's ``variant_of``), replaced through ``ids``. A
598
+ reference that lands on an id an ``/id`` lock renamed (``renamed``: was ->
599
+ now) follows the rename, as the step itself will in the merge."""
600
+ if not ids:
601
+ return doc
602
+ renamed = renamed or {}
603
+ ref = {old: renamed.get(new, new) for old, new in ids.items()}
604
+
605
+ def steps(rows: list[dict]) -> list[dict]:
606
+ out = []
607
+ for step in rows:
608
+ step = dict(step)
609
+ step["id"] = ids.get(step["id"], step["id"])
610
+ if step.get("variant_of") is not None:
611
+ step["variant_of"] = ref.get(step["variant_of"], step["variant_of"])
612
+ step["steps"] = steps(step.get("steps", []))
613
+ out.append(step)
614
+ return out
615
+
616
+ doc = dict(doc)
617
+ doc["steps"] = steps(doc["steps"])
618
+ cues = []
619
+ for cue in doc.get("cues", []):
620
+ cue = dict(cue)
621
+ anchor = dict(cue.get("anchor") or {})
622
+ if anchor.get("step") is not None:
623
+ anchor["step"] = ref.get(anchor["step"], anchor["step"])
624
+ cue["anchor"] = anchor
625
+ cues.append(cue)
626
+ doc["cues"] = cues
627
+ return doc
628
+
629
+
438
630
  def _merge_steps(committed: list[dict], fresh: list[dict]) -> list[dict]:
439
631
  committed_by_id: dict[str, dict] = {}
440
632
  for step in committed: # first occurrence wins, matching apply_edits
@@ -540,6 +732,9 @@ def merge_regenerated(committed: StepDocument, fresh: StepDocument) -> StepDocum
540
732
  4. Cues, questions and sources are unioned by id (fresh wins on shared
541
733
  ids) — analysis rarely regenerates them, and dropping committed
542
734
  content silently is the failure this module exists to prevent.
735
+ 5. Repeated steps are matched by name and time, not by their generated
736
+ ``-N`` suffix (:func:`_repeat_ids`): a repeat inserted earlier
737
+ does not move a lock onto the wrong occurrence (paces#50).
543
738
 
544
739
  Edits made through :func:`apply_edits` are always locked, so "hand edit"
545
740
  and "protected" coincide by construction; edits made by hand-editing the
@@ -547,6 +742,12 @@ def merge_regenerated(committed: StepDocument, fresh: StepDocument) -> StepDocum
547
742
  """
548
743
  committed_dump = committed.model_dump(mode="python", by_alias=False)
549
744
  out = fresh.model_dump(mode="python", by_alias=False)
745
+ renamed = {
746
+ was: s["id"] for s in _walk(committed_dump["steps"]) if (was := _renamed_was(s))
747
+ }
748
+ out = _renumbered(
749
+ out, _repeat_ids(committed_dump["steps"], out["steps"]), renamed=renamed
750
+ )
550
751
  out["steps"] = _merge_steps(committed_dump["steps"], out["steps"])
551
752
  for key in ("cues", "questions", "sources"):
552
753
  out[key] = _union_by_id(committed_dump[key], out[key])