paces 0.0.26__tar.gz → 0.0.28__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 (62) hide show
  1. {paces-0.0.26 → paces-0.0.28}/PKG-INFO +3 -1
  2. {paces-0.0.26 → paces-0.0.28}/paces/__init__.py +1 -0
  3. {paces-0.0.26 → paces-0.0.28}/paces/ask_contract.py +4 -0
  4. {paces-0.0.26 → paces-0.0.28}/paces/data/ask/ask.js +201 -146
  5. paces-0.0.28/paces/known_k.py +158 -0
  6. {paces-0.0.26 → paces-0.0.28}/paces/segmenters.py +53 -27
  7. {paces-0.0.26 → paces-0.0.28}/pyproject.toml +6 -2
  8. {paces-0.0.26 → paces-0.0.28}/tests/test_ask.py +29 -0
  9. paces-0.0.28/tests/test_known_k.py +71 -0
  10. {paces-0.0.26 → paces-0.0.28}/.gitignore +0 -0
  11. {paces-0.0.26 → paces-0.0.28}/LICENSE +0 -0
  12. {paces-0.0.26 → paces-0.0.28}/README.md +0 -0
  13. {paces-0.0.26 → paces-0.0.28}/docs/README.md +0 -0
  14. {paces-0.0.26 → paces-0.0.28}/docs/alignment/README.md +0 -0
  15. {paces-0.0.26 → paces-0.0.28}/docs/poc-reference/README.md +0 -0
  16. {paces-0.0.26 → paces-0.0.28}/docs/poc-reference/artifacts/clips.json +0 -0
  17. {paces-0.0.26 → paces-0.0.28}/paces/__main__.py +0 -0
  18. {paces-0.0.26 → paces-0.0.28}/paces/ask.py +0 -0
  19. {paces-0.0.26 → paces-0.0.28}/paces/bodies/__init__.py +0 -0
  20. {paces-0.0.26 → paces-0.0.28}/paces/bodies/_base.py +0 -0
  21. {paces-0.0.26 → paces-0.0.28}/paces/bodies/derivation.py +0 -0
  22. {paces-0.0.26 → paces-0.0.28}/paces/bodies/document.py +0 -0
  23. {paces-0.0.26 → paces-0.0.28}/paces/bodies/signal.py +0 -0
  24. {paces-0.0.26 → paces-0.0.28}/paces/bodies/step.py +0 -0
  25. {paces-0.0.26 → paces-0.0.28}/paces/corrections.py +0 -0
  26. {paces-0.0.26 → paces-0.0.28}/paces/cues.py +0 -0
  27. {paces-0.0.26 → paces-0.0.28}/paces/data/ask/ask.css +0 -0
  28. {paces-0.0.26 → paces-0.0.28}/paces/data/ask/ask.html +0 -0
  29. {paces-0.0.26 → paces-0.0.28}/paces/derivation.py +0 -0
  30. {paces-0.0.26 → paces-0.0.28}/paces/edits.py +0 -0
  31. {paces-0.0.26 → paces-0.0.28}/paces/evidence.py +0 -0
  32. {paces-0.0.26 → paces-0.0.28}/paces/excerpts.py +0 -0
  33. {paces-0.0.26 → paces-0.0.28}/paces/measure.py +0 -0
  34. {paces-0.0.26 → paces-0.0.28}/paces/model.py +0 -0
  35. {paces-0.0.26 → paces-0.0.28}/paces/pose.py +0 -0
  36. {paces-0.0.26 → paces-0.0.28}/paces/projection.py +0 -0
  37. {paces-0.0.26 → paces-0.0.28}/paces/render.py +0 -0
  38. {paces-0.0.26 → paces-0.0.28}/paces/segmentation.py +0 -0
  39. {paces-0.0.26 → paces-0.0.28}/paces/timed_text.py +0 -0
  40. {paces-0.0.26 → paces-0.0.28}/paces/tools.py +0 -0
  41. {paces-0.0.26 → paces-0.0.28}/tests/audio_synth.py +0 -0
  42. {paces-0.0.26 → paces-0.0.28}/tests/data/body_schemas.json +0 -0
  43. {paces-0.0.26 → paces-0.0.28}/tests/data/routine.json +0 -0
  44. {paces-0.0.26 → paces-0.0.28}/tests/poc_fixture.py +0 -0
  45. {paces-0.0.26 → paces-0.0.28}/tests/test_chapters.py +0 -0
  46. {paces-0.0.26 → paces-0.0.28}/tests/test_cli_surface.py +0 -0
  47. {paces-0.0.26 → paces-0.0.28}/tests/test_corrections.py +0 -0
  48. {paces-0.0.26 → paces-0.0.28}/tests/test_cues.py +0 -0
  49. {paces-0.0.26 → paces-0.0.28}/tests/test_derivation.py +0 -0
  50. {paces-0.0.26 → paces-0.0.28}/tests/test_edit_protection_residuals.py +0 -0
  51. {paces-0.0.26 → paces-0.0.28}/tests/test_edits.py +0 -0
  52. {paces-0.0.26 → paces-0.0.28}/tests/test_evidence.py +0 -0
  53. {paces-0.0.26 → paces-0.0.28}/tests/test_evidence_schemas.py +0 -0
  54. {paces-0.0.26 → paces-0.0.28}/tests/test_excerpts.py +0 -0
  55. {paces-0.0.26 → paces-0.0.28}/tests/test_measure.py +0 -0
  56. {paces-0.0.26 → paces-0.0.28}/tests/test_pose.py +0 -0
  57. {paces-0.0.26 → paces-0.0.28}/tests/test_render_media.py +0 -0
  58. {paces-0.0.26 → paces-0.0.28}/tests/test_roundtrip_poc.py +0 -0
  59. {paces-0.0.26 → paces-0.0.28}/tests/test_segment.py +0 -0
  60. {paces-0.0.26 → paces-0.0.28}/tests/test_smoke.py +0 -0
  61. {paces-0.0.26 → paces-0.0.28}/tests/test_vertical_slice.py +0 -0
  62. {paces-0.0.26 → paces-0.0.28}/tests/video_synth.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: paces
3
- Version: 0.0.26
3
+ Version: 0.0.28
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
@@ -18,6 +18,8 @@ Requires-Dist: numba>=0.59; extra == 'audio'
18
18
  Provides-Extra: cli
19
19
  Requires-Dist: argcomplete>=3; extra == 'cli'
20
20
  Requires-Dist: cw<0.2,>=0.1.1; extra == 'cli'
21
+ Provides-Extra: cpd
22
+ Requires-Dist: ruptures>=1.1; extra == 'cpd'
21
23
  Provides-Extra: dev
22
24
  Requires-Dist: cw<0.2,>=0.1.1; extra == 'dev'
23
25
  Requires-Dist: lacing>=0.0.54; extra == 'dev'
@@ -75,6 +75,7 @@ from paces.segmenters import (
75
75
  # Segmenters in their own modules register on import (ADR-0003); importing
76
76
  # them here is what puts them in the catalog for every ``paces.*`` import.
77
77
  from paces import cues # noqa: F401
78
+ from paces import known_k # noqa: F401 (paces#39: the known-k segmenter)
78
79
 
79
80
  __all__ = [
80
81
  # the document (the contract)
@@ -21,6 +21,8 @@ from typing import Any, Literal
21
21
  from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
22
22
  from pydantic.alias_generators import to_camel
23
23
 
24
+ from paces.segmentation import TIME_PLACES
25
+
24
26
  PROPOSAL_KIND = "PacesAskProposal"
25
27
  ANSWERS_KIND = "PacesAskAnswers"
26
28
  #: The proposal/answers contract version. Both documents carry it; a reader
@@ -72,6 +74,8 @@ class Proposal(_Wire):
72
74
  cut_meets: list[bool] = []
73
75
  steps: list[ProposedStep]
74
76
  min_step_s: str
77
+ #: The decimal places every time here keeps (the page writes its own the same way).
78
+ time_places: int = Field(TIME_PLACES, ge=1)
75
79
  snap: Snap
76
80
 
77
81
 
@@ -5,22 +5,28 @@
5
5
 
6
6
  // ── pure core ─────────────────────────────────────────────────────────────
7
7
 
8
- const TIME_PLACES = 3;
8
+ /** The places a time keeps when the proposal does not say (one written before it carried timePlaces). */
9
+ const DFLT_TIME_PLACES = 3;
10
+
11
+ /** The places the proposal's times keep: Python's paces.segmentation.TIME_PLACES when it wrote it. */
12
+ const timePlaces = (proposal) => proposal.timePlaces ?? DFLT_TIME_PLACES;
9
13
 
10
14
  /**
11
15
  * Seconds as paces' wire decimal, exactly as Python's
12
- * decimal_str(t, places=3) writes it for t >= 0: 3 places, trailing zeros
16
+ * decimal_str(t, places=places) writes it for t >= 0: trailing zeros
13
17
  * dropped ("95.8"). toFixed breaks an exact binary tie (10.0625) upward;
14
18
  * Python's format rounds it to even ("10.062"), so a tie is corrected here.
15
19
  * toFixed(20) tells a tie apart: a double >= 0.0005 is never within 5e-21
16
- * of a tie without being on it.
20
+ * of a tie without being on it. `places` is an option, not a second
21
+ * argument, so times.map(timeStr) is not handed the index as places.
17
22
  */
18
- function timeStr(t) {
23
+ function timeStr(t, { places = DFLT_TIME_PLACES } = {}) {
19
24
  const x = Number(t);
20
- let text = x.toFixed(TIME_PLACES);
21
- if (x >= 0 && /\.\d{3}50*$/.test(x.toFixed(20)) && /[13579]$/.test(text)) {
22
- const digits = (BigInt(text.replace(".", "")) - 1n).toString().padStart(TIME_PLACES + 1, "0");
23
- text = `${digits.slice(0, -TIME_PLACES)}.${digits.slice(-TIME_PLACES)}`;
25
+ let text = x.toFixed(places);
26
+ const tie = new RegExp(`\\.\\d{${places}}50*$`);
27
+ if (x >= 0 && tie.test(x.toFixed(20)) && /[13579]$/.test(text)) {
28
+ const digits = (BigInt(text.replace(".", "")) - 1n).toString().padStart(places + 1, "0");
29
+ text = `${digits.slice(0, -places)}.${digits.slice(-places)}`;
24
30
  }
25
31
  text = text.replace(/0+$/, "").replace(/\.$/, "");
26
32
  return text === "-0" || text === "" ? "0" : text;
@@ -98,7 +104,7 @@ const RULES = {
98
104
  // M1: a struck cut is not a snap target, so strike + tap = move it.
99
105
  const targets = p.snap.targets.filter((c) => !s.struck.includes(c)).map(Number);
100
106
  const { t: snappedT, snapped } = snap(Number(raw), targets, Number(p.snap.windowS));
101
- const key = timeStr(snappedT);
107
+ const key = timeStr(snappedT, { places: timePlaces(p) });
102
108
  const t = Number(key);
103
109
  const at = mmss(key);
104
110
  if (p.cuts.includes(key)) {
@@ -188,12 +194,12 @@ const RULES = {
188
194
 
189
195
  duration(p, s, { seconds }) {
190
196
  const d = Number(seconds);
191
- if (!Number.isFinite(d) || d <= 0 || timeStr(d) === s.duration) return same(s);
197
+ if (!Number.isFinite(d) || d <= 0 || timeStr(d, { places: timePlaces(p) }) === s.duration) return same(s);
192
198
  const past = s.added.filter((t) => Number(t) >= d);
193
199
  const message = past.length
194
200
  ? `${past.length} of your cuts lie past the end of this media (${mmss(d)}) and will not be sent.`
195
201
  : "";
196
- return { state: { ...s, duration: timeStr(d) }, message };
202
+ return { state: { ...s, duration: timeStr(d, { places: timePlaces(p) }) }, message };
197
203
  },
198
204
  };
199
205
 
@@ -243,7 +249,7 @@ function buildAnswers(proposal, state) {
243
249
  for (const [i, step] of proposal.steps.entries()) {
244
250
  if (!isAbsent(state, i) || !step.spans.length) continue;
245
251
  const [a, b] = step.spans[0].map(Number);
246
- corrections.push({ verb: "absent", anchorT: timeStr((a + b) / 2), stepId: step.id, ...meta });
252
+ corrections.push({ verb: "absent", anchorT: timeStr((a + b) / 2, { places: timePlaces(proposal) }), stepId: step.id, ...meta });
247
253
  }
248
254
  for (const cut of proposal.cuts) {
249
255
  if (state.struck.includes(cut)) corrections.push({ verb: "merge", anchorT: cut, ...meta });
@@ -287,30 +293,42 @@ function draftKey(proposal) {
287
293
  /** How long the status line offers to undo a Start over. */
288
294
  const UNDO_MS = 15000;
289
295
 
290
- function startPage(doc) {
296
+ // ── DOM layer ─────────────────────────────────────────────────────────────
297
+ // startPage builds one page context and hands it to small wiring and render
298
+ // functions, each reading on its own: the header (k, restore, start over),
299
+ // the media, the keyboard, the lists, and the answers. Every state decision
300
+ // stays in reduce(); these only dispatch actions and draw.
301
+
302
+ /** The page's shared context: its elements, proposal, state and the two verbs, dispatch and render. */
303
+ function pageContext(doc) {
291
304
  const $ = (id) => doc.getElementById(id);
292
305
  const proposal = JSON.parse($("proposal").textContent);
293
306
  const store = draftStore(draftKey(proposal));
294
307
  const saved = store.load();
295
- let state = Object.assign(freshState(proposal), saved || {});
296
- let fresh = null; // the cut just added: highlighted on the next render only
297
- let undoOpen = false;
298
- let undoTimer = null;
299
- const video = $("video");
300
- const tapButton = $("tap");
301
-
302
- const say = (text) => { $("status-text").textContent = text; };
303
- const syncK = () => { $("k").value = state.k ?? ""; };
304
- function dispatch(action) {
305
- const out = reduce(proposal, state, { ...action, at: new Date().toISOString() });
306
- if (out.message) say(out.message);
307
- if (out.state !== state) { state = out.state; store.save(state); }
308
- fresh = out.fresh;
309
- render(); // also after a refusal: a checkbox the reducer refused flips back
308
+ const ctx = {
309
+ doc, $, proposal, store, saved,
310
+ state: Object.assign(freshState(proposal), saved || {}),
311
+ fresh: null, // the cut just added: highlighted on the next render only
312
+ undo: { open: false, timer: null },
313
+ video: $("video"),
314
+ tapButton: $("tap"),
315
+ };
316
+ ctx.say = (text) => { $("status-text").textContent = text; };
317
+ ctx.syncK = () => { $("k").value = ctx.state.k ?? ""; };
318
+ ctx.render = () => render(ctx);
319
+ ctx.dispatch = (action) => {
320
+ const out = reduce(proposal, ctx.state, { ...action, at: new Date().toISOString() });
321
+ if (out.message) ctx.say(out.message);
322
+ if (out.state !== ctx.state) { ctx.state = out.state; store.save(ctx.state); }
323
+ ctx.fresh = out.fresh;
324
+ ctx.render(); // also after a refusal: a checkbox the reducer refused flips back
310
325
  return out;
311
- }
326
+ };
327
+ return ctx;
328
+ }
312
329
 
313
- // Pressed feedback in the same frame as the press (the feedback principle).
330
+ /** Pressed feedback in the same frame as the press (the feedback principle). */
331
+ function wirePressedFeedback(doc) {
314
332
  doc.addEventListener("pointerdown", (e) => {
315
333
  const b = e.target.closest && e.target.closest("button");
316
334
  if (b) b.setAttribute("data-pressed", "");
@@ -318,36 +336,44 @@ function startPage(doc) {
318
336
  for (const type of ["pointerup", "pointercancel", "pointerleave"]) {
319
337
  doc.addEventListener(type, () => doc.querySelectorAll("button[data-pressed]").forEach((b) => b.removeAttribute("data-pressed")), true);
320
338
  }
339
+ }
321
340
 
341
+ /** The method line, the step count, a restored draft, Start over and its Undo. */
342
+ function wireHeader(ctx) {
343
+ const { $, proposal } = ctx;
322
344
  const methodBits = [proposal.method && `proposed by ${proposal.method}`, ...proposal.flags.filter((f) => !f.startsWith("try:"))];
323
345
  $("method").textContent = methodBits.filter(Boolean).join(" · ");
324
346
  $("k-evidence").textContent = proposal.kEvidence;
325
- if (saved) {
347
+ if (ctx.saved) {
326
348
  $("restored").hidden = false;
327
- $("restored-text").textContent = `Picked up where you left off${state.at ? ` (${new Date(state.at).toLocaleString()})` : ""}.`;
349
+ $("restored-text").textContent = `Picked up where you left off${ctx.state.at ? ` (${new Date(ctx.state.at).toLocaleString()})` : ""}.`;
328
350
  }
329
351
  $("start-over").addEventListener("click", () => {
330
- dispatch({ type: "startOver" });
352
+ ctx.dispatch({ type: "startOver" });
331
353
  $("restored").hidden = true;
332
- syncK();
333
- undoOpen = true;
334
- clearTimeout(undoTimer);
335
- undoTimer = setTimeout(() => { undoOpen = false; render(); }, UNDO_MS);
336
- render();
354
+ ctx.syncK();
355
+ ctx.undo.open = true;
356
+ clearTimeout(ctx.undo.timer);
357
+ ctx.undo.timer = setTimeout(() => { ctx.undo.open = false; ctx.render(); }, UNDO_MS);
358
+ ctx.render();
337
359
  });
338
360
  $("undo").addEventListener("click", () => {
339
- undoOpen = false;
340
- clearTimeout(undoTimer);
341
- dispatch({ type: "undoStartOver" });
342
- syncK();
361
+ ctx.undo.open = false;
362
+ clearTimeout(ctx.undo.timer);
363
+ ctx.dispatch({ type: "undoStartOver" });
364
+ ctx.syncK();
343
365
  });
366
+ ctx.syncK();
367
+ $("k").addEventListener("input", (e) => ctx.dispatch({ type: "setK", value: e.target.value }));
368
+ }
344
369
 
345
- syncK();
346
- $("k").addEventListener("input", (e) => dispatch({ type: "setK", value: e.target.value }));
347
-
348
- // Media: the proposal's own, or a file from this device. Loading and
349
- // failure each say so (the heavy-media principle); Cut here waits for the
350
- // media's metadata, so a tap always has a real clock under it.
370
+ /**
371
+ * Media: the proposal's own, or a file from this device. Loading and failure
372
+ * each say so (the heavy-media principle); Cut here waits for the media's
373
+ * metadata, so a tap always has a real clock under it.
374
+ */
375
+ function wireMedia(ctx) {
376
+ const { $, proposal, video, tapButton } = ctx;
351
377
  const mediaNote = (text) => { $("no-media-text").textContent = text; };
352
378
  const showMedia = (src, name) => {
353
379
  tapButton.disabled = true;
@@ -360,13 +386,13 @@ function startPage(doc) {
360
386
  video.addEventListener("loadedmetadata", () => {
361
387
  $("media-state").hidden = true;
362
388
  tapButton.disabled = false;
363
- dispatch({ type: "duration", seconds: video.duration });
389
+ ctx.dispatch({ type: "duration", seconds: video.duration });
364
390
  });
365
391
  video.addEventListener("error", () => {
366
392
  $("player").hidden = true;
367
393
  tapButton.disabled = true;
368
394
  mediaNote("This browser could not play that media (moved, missing, or a format it does not read). Open a copy from this device:");
369
- say("Could not play the media here.");
395
+ ctx.say("Could not play the media here.");
370
396
  });
371
397
  if (proposal.media && /youtu\.?be/.test(proposal.media)) {
372
398
  mediaNote("This page plays files, not YouTube links. Open a downloaded copy from this device:");
@@ -375,13 +401,19 @@ function startPage(doc) {
375
401
  }
376
402
  $("file").addEventListener("change", (e) => {
377
403
  const file = e.target.files && e.target.files[0];
378
- if (file) { showMedia(URL.createObjectURL(file), file.name); say(`Opened ${file.name}.`); }
404
+ if (file) { showMedia(URL.createObjectURL(file), file.name); ctx.say(`Opened ${file.name}.`); }
379
405
  });
406
+ }
380
407
 
381
- const tap = () => { if (!tapButton.disabled) dispatch({ type: "tap", t: video.currentTime }); };
408
+ /**
409
+ * Cut here, by button or Space. Space taps only from the page itself, the
410
+ * video or Cut here; every other button, link and summary keeps its native
411
+ * Space. A held key taps once.
412
+ */
413
+ function wireKeyboard(ctx) {
414
+ const { doc, $, video, tapButton } = ctx;
415
+ const tap = () => { if (!tapButton.disabled) ctx.dispatch({ type: "tap", t: video.currentTime }); };
382
416
  tapButton.addEventListener("click", tap);
383
- // Space taps only from the page itself, the video or Cut here; every other
384
- // button, link and summary keeps its native Space. A held key taps once.
385
417
  const spaceTargets = [doc.body, doc.documentElement, video, tapButton];
386
418
  doc.addEventListener("keydown", (e) => {
387
419
  if (e.code !== "Space" || !spaceTargets.includes(e.target) || $("player").hidden) return;
@@ -392,115 +424,138 @@ function startPage(doc) {
392
424
  // Cut here's own Space-click would tap a second time.
393
425
  if (e.code === "Space" && e.target === tapButton) e.preventDefault();
394
426
  });
427
+ }
395
428
 
396
- const button = (label, onClick, extra = {}) => {
397
- const b = doc.createElement("button");
398
- b.type = "button"; b.textContent = label;
399
- Object.assign(b, extra);
400
- b.addEventListener("click", onClick);
401
- return b;
402
- };
403
- const seek = (t) => () => { if (!$("player").hidden) { video.currentTime = Number(t); video.play(); } };
404
-
405
- function renderCuts() {
406
- const list = $("cuts");
407
- list.replaceChildren();
408
- for (const row of cutRows(proposal, state)) {
409
- const li = doc.createElement("li");
410
- li.className = row.kind + (row.t === fresh ? " fresh" : "");
411
- li.append(button(mmss(row.t), seek(row.t), { className: "time link", title: "Play from here"}));
412
- li.lastChild.dataset.focusKey = `time:${row.t}`;
413
- const label = doc.createElement("span");
414
- label.className = "grow muted small";
415
- label.textContent = { proposed: "proposed", struck: "not a cut", added: "added by you" }[row.kind];
416
- li.append(label);
417
- if (row.kind === "added") {
418
- li.append(button("Remove", () => dispatch({ type: "remove", cut: row.t })));
419
- li.lastChild.dataset.focusKey = `act:${row.t}`;
420
- } else if (!row.meets) {
421
- label.textContent = "edge of a gap";
422
- } else {
423
- const struck = row.kind === "struck";
424
- li.append(button(struck ? "Keep it" : "Not a cut", () => dispatch({ type: struck ? "keep" : "strike", cut: row.t })));
425
- li.lastChild.setAttribute("aria-pressed", String(struck));
426
- li.lastChild.dataset.focusKey = `act:${row.t}`;
427
- }
428
- list.append(li);
429
- }
430
- if (!list.children.length) {
431
- const li = doc.createElement("li");
432
- li.className = "muted"; li.textContent = "No cuts yet. Tap along with the video to add them.";
433
- list.append(li);
429
+ function makeButton(doc, label, onClick, extra = {}) {
430
+ const b = doc.createElement("button");
431
+ b.type = "button"; b.textContent = label;
432
+ Object.assign(b, extra);
433
+ b.addEventListener("click", onClick);
434
+ return b;
435
+ }
436
+
437
+ /** Play the media from t, when it is showing. */
438
+ const seekTo = (ctx, t) => () => {
439
+ if (!ctx.$("player").hidden) { ctx.video.currentTime = Number(t); ctx.video.play(); }
440
+ };
441
+
442
+ /** An empty list says why it is empty. */
443
+ function emptyRow(doc, list, text) {
444
+ if (list.children.length) return;
445
+ const li = doc.createElement("li");
446
+ li.className = "muted"; li.textContent = text;
447
+ list.append(li);
448
+ }
449
+
450
+ function renderCuts(ctx) {
451
+ const { doc, $, proposal, state } = ctx;
452
+ const list = $("cuts");
453
+ list.replaceChildren();
454
+ for (const row of cutRows(proposal, state)) {
455
+ const li = doc.createElement("li");
456
+ li.className = row.kind + (row.t === ctx.fresh ? " fresh" : "");
457
+ li.append(makeButton(doc, mmss(row.t), seekTo(ctx, row.t), { className: "time link", title: "Play from here" }));
458
+ li.lastChild.dataset.focusKey = `time:${row.t}`;
459
+ const label = doc.createElement("span");
460
+ label.className = "grow muted small";
461
+ label.textContent = { proposed: "proposed", struck: "not a cut", added: "added by you" }[row.kind];
462
+ li.append(label);
463
+ if (row.kind === "added") {
464
+ li.append(makeButton(doc, "Remove", () => ctx.dispatch({ type: "remove", cut: row.t })));
465
+ li.lastChild.dataset.focusKey = `act:${row.t}`;
466
+ } else if (!row.meets) {
467
+ label.textContent = "edge of a gap";
468
+ } else {
469
+ const struck = row.kind === "struck";
470
+ li.append(makeButton(doc, struck ? "Keep it" : "Not a cut", () => ctx.dispatch({ type: struck ? "keep" : "strike", cut: row.t })));
471
+ li.lastChild.setAttribute("aria-pressed", String(struck));
472
+ li.lastChild.dataset.focusKey = `act:${row.t}`;
434
473
  }
474
+ list.append(li);
435
475
  }
476
+ emptyRow(doc, list, "No cuts yet. Tap along with the video to add them.");
477
+ }
436
478
 
437
- function renderSteps() {
438
- const list = $("steps");
439
- list.replaceChildren();
440
- for (const [i, step] of proposal.steps.entries()) {
441
- const li = doc.createElement("li");
442
- const label = doc.createElement("label");
443
- label.className = "grow";
444
- const box = doc.createElement("input");
445
- box.type = "checkbox";
446
- box.checked = isAbsent(state, i);
447
- box.disabled = !step.spans.length;
448
- box.dataset.focusKey = `step:${i}`;
449
- box.addEventListener("change", () => dispatch({ type: "absent", index: i, on: box.checked }));
450
- const span = step.spans[0];
451
- label.append(box, ` ${step.name || "(unnamed)"} `);
452
- const when = doc.createElement("span");
453
- when.className = "muted small";
454
- when.textContent = span ? `${mmss(span[0])}–${mmss(span[1])} · not in this video` : "has no time in this video to mark";
455
- label.append(when);
456
- li.append(label);
457
- list.append(li);
458
- }
459
- if (!proposal.steps.length) {
460
- const li = doc.createElement("li");
461
- li.className = "muted"; li.textContent = "No steps were proposed.";
462
- list.append(li);
463
- }
479
+ function renderSteps(ctx) {
480
+ const { doc, $, proposal, state } = ctx;
481
+ const list = $("steps");
482
+ list.replaceChildren();
483
+ for (const [i, step] of proposal.steps.entries()) {
484
+ const li = doc.createElement("li");
485
+ const label = doc.createElement("label");
486
+ label.className = "grow";
487
+ const box = doc.createElement("input");
488
+ box.type = "checkbox";
489
+ box.checked = isAbsent(state, i);
490
+ box.disabled = !step.spans.length;
491
+ box.dataset.focusKey = `step:${i}`;
492
+ box.addEventListener("change", () => ctx.dispatch({ type: "absent", index: i, on: box.checked }));
493
+ const span = step.spans[0];
494
+ label.append(box, ` ${step.name || "(unnamed)"} `);
495
+ const when = doc.createElement("span");
496
+ when.className = "muted small";
497
+ when.textContent = span ? `${mmss(span[0])}–${mmss(span[1])} · not in this video` : "has no time in this video to mark";
498
+ label.append(when);
499
+ li.append(label);
500
+ list.append(li);
464
501
  }
502
+ emptyRow(doc, list, "No steps were proposed.");
503
+ }
465
504
 
466
- const answersText = () => JSON.stringify(buildAnswers(proposal, state), null, 2);
467
- // Rows are rebuilt on every change; keep keyboard focus on the same control
468
- // (or on its list, never on <body>, where Space would add a cut).
469
- function render() {
470
- const focused = doc.activeElement;
471
- const focusKey = focused && focused.dataset ? focused.dataset.focusKey : undefined;
472
- const focusList = focused && focused.closest ? focused.closest("#cuts, #steps") : null;
473
- renderCuts();
474
- fresh = null; // the highlight plays once, for the row just added
475
- renderSteps();
476
- if (focusKey) {
477
- const again = doc.querySelector(`[data-focus-key="${focusKey}"]`);
478
- if (again) again.focus();
479
- else if (focusList) focusList.focus();
480
- }
481
- $("k-state").textContent = !state.kTouched
482
- ? "Edit the number to confirm it. Until you do, it is not sent."
483
- : state.k === null
484
- ? "That is not a step count, so none is sent."
485
- : "Saved with your answers for segmenters that use a known step count.";
486
- $("undo").hidden = !(undoOpen && state.previous);
487
- $("answers").value = answersText();
505
+ const answersText = (ctx) => JSON.stringify(buildAnswers(ctx.proposal, ctx.state), null, 2);
506
+
507
+ /**
508
+ * Draw the page from the state. Rows are rebuilt on every change; keyboard
509
+ * focus stays on the same control (or on its list, never on <body>, where
510
+ * Space would add a cut).
511
+ */
512
+ function render(ctx) {
513
+ const { doc, $, state } = ctx;
514
+ const focused = doc.activeElement;
515
+ const focusKey = focused && focused.dataset ? focused.dataset.focusKey : undefined;
516
+ const focusList = focused && focused.closest ? focused.closest("#cuts, #steps") : null;
517
+ renderCuts(ctx);
518
+ ctx.fresh = null; // the highlight plays once, for the row just added
519
+ renderSteps(ctx);
520
+ if (focusKey) {
521
+ const again = doc.querySelector(`[data-focus-key="${focusKey}"]`);
522
+ if (again) again.focus();
523
+ else if (focusList) focusList.focus();
488
524
  }
525
+ $("k-state").textContent = !state.kTouched
526
+ ? "Edit the number to confirm it. Until you do, it is not sent."
527
+ : state.k === null
528
+ ? "That is not a step count, so none is sent."
529
+ : "Saved with your answers for segmenters that use a known step count.";
530
+ $("undo").hidden = !(ctx.undo.open && state.previous);
531
+ $("answers").value = answersText(ctx);
532
+ }
489
533
 
534
+ /** Download or copy the answers; a refused clipboard selects them instead. */
535
+ function wireAnswers(ctx) {
536
+ const { doc, $ } = ctx;
490
537
  $("download").addEventListener("click", () => {
491
- const url = URL.createObjectURL(new Blob([answersText() + "\n"], { type: "application/json" }));
538
+ const url = URL.createObjectURL(new Blob([answersText(ctx) + "\n"], { type: "application/json" }));
492
539
  const a = doc.createElement("a");
493
540
  a.href = url; a.download = "answers.json";
494
541
  doc.body.append(a); a.click(); a.remove();
495
542
  setTimeout(() => URL.revokeObjectURL(url), 1000);
496
- say("Downloaded answers.json.");
543
+ ctx.say("Downloaded answers.json.");
497
544
  });
498
545
  $("copy").addEventListener("click", async () => {
499
- try { await navigator.clipboard.writeText(answersText()); say("Copied the answers."); }
500
- catch { $("answers").closest("details").open = true; $("answers").select(); say("The answers are selected: copy them with your keyboard."); }
546
+ try { await navigator.clipboard.writeText(answersText(ctx)); ctx.say("Copied the answers."); }
547
+ catch { $("answers").closest("details").open = true; $("answers").select(); ctx.say("The answers are selected: copy them with your keyboard."); }
501
548
  });
549
+ }
502
550
 
503
- render();
551
+ function startPage(doc) {
552
+ const ctx = pageContext(doc);
553
+ wirePressedFeedback(doc);
554
+ wireHeader(ctx);
555
+ wireMedia(ctx);
556
+ wireKeyboard(ctx);
557
+ wireAnswers(ctx);
558
+ ctx.render();
504
559
  }
505
560
 
506
561
  if (typeof module !== "undefined" && module.exports) {
@@ -0,0 +1,158 @@
1
+ """Known-K change points: the step count a human gave turns peak-picking into exact change-point detection (paces#39).
2
+
3
+ The ask page asks for the number of steps first (``docs/alignment/07 §7.3``
4
+ step 1): one integer turns "find the peaks of a novelty curve" into "find the
5
+ K-1 change points that best split this signal", which kernel change-point
6
+ detection solves exactly (``docs/alignment/05 §7``, ``07 §2.16``). The
7
+ ``known-k`` capability is that consumer of ``k``:
8
+
9
+ - **features**: a frame-wise description of the media's audio
10
+ (:func:`audio_features`: MFCCs and their spectral contrast, each dimension
11
+ standardised), through paces' own audio decode (the ``[audio]`` extra);
12
+ - **cuts**: :func:`known_k_cuts`, ``ruptures.KernelCPD(...).predict(n_bkps=K-1)``
13
+ over those frames, no cut closer than ``min_step_s`` to another or to an end
14
+ (the ``[cpd]`` extra; ``ruptures`` is BSD-2-Clause);
15
+ - **names**: zipped on when a step list of exactly K was given, else honestly
16
+ unnamed (the ``explicit`` segmenter's rule, :func:`paces.segmenters.steps_on_boundaries`).
17
+
18
+ The boundaries are a proposal: the confidence is low
19
+ (:data:`DFLT_KNOWN_K_CONFIDENCE`) and the result is flagged
20
+ ``boundaries-proposed`` for the ask page to confirm. A K the media is too
21
+ short to hold (fewer than ``min_step_s`` per step) is refused, with a reason,
22
+ never a made-up split.
23
+
24
+ The pure core, :func:`known_k_cuts`, runs on any feature matrix:
25
+
26
+ >>> import numpy as np
27
+ >>> x = np.repeat([[0.0], [5.0], [0.0]], 50, axis=0) # three flat steps (needs ruptures)
28
+ >>> known_k_cuts(x, 3, frame_s=0.1, min_step_s=1.0) # doctest: +SKIP
29
+ [5.0, 10.0]
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import math
35
+ from collections.abc import Mapping
36
+ from typing import Any
37
+
38
+ from paces.segmentation import TIME_PLACES, Segmentation
39
+ from paces.segmenters import Capability, register, steps_on_boundaries
40
+
41
+ #: Seconds between two feature frames: fine enough for a step boundary, coarse
42
+ #: enough that kernel change-point detection stays fast on a long video.
43
+ DFLT_HOP_S: float = 0.1
44
+ #: MFCC coefficients per frame.
45
+ DFLT_N_MFCC: int = 13
46
+ #: The narrowest step a cut may make (s), from a cut or an end.
47
+ DFLT_KNOWN_K_MIN_STEP_S: float = 2.0
48
+ #: A proposal from the signal alone: the human confirms it on the ask page.
49
+ DFLT_KNOWN_K_CONFIDENCE: float = 0.35
50
+ #: The ruptures kernel: rbf compares feature distributions, not just means.
51
+ DFLT_KERNEL: str = "rbf"
52
+ #: The sample rate audio is decoded at for the features.
53
+ DFLT_SAMPLE_RATE: int = 22050
54
+
55
+
56
+ def known_k_cuts(
57
+ features: Any,
58
+ k: int,
59
+ *,
60
+ frame_s: float,
61
+ min_step_s: float = DFLT_KNOWN_K_MIN_STEP_S,
62
+ kernel: str = DFLT_KERNEL,
63
+ ) -> list[float] | None:
64
+ """The ``k - 1`` interior cut times (s) that best split ``features`` (one
65
+ row per frame, ``frame_s`` apart) into ``k`` steps, by kernel
66
+ change-point detection; ``[]`` for one step, ``None`` when ``k`` steps of
67
+ at least ``min_step_s`` do not fit in the frames."""
68
+ import numpy as np
69
+ import ruptures
70
+
71
+ x = np.asarray(features, dtype=float)
72
+ if x.ndim == 1:
73
+ x = x[:, None]
74
+ if k < 1:
75
+ raise ValueError(f"k must be a positive step count, got {k}")
76
+ if k == 1:
77
+ return []
78
+ min_size = max(2, math.ceil(min_step_s / frame_s))
79
+ if len(x) < k * min_size:
80
+ return None
81
+ bkps = (
82
+ ruptures.KernelCPD(kernel=kernel, min_size=min_size)
83
+ .fit(x)
84
+ .predict(n_bkps=k - 1)
85
+ )
86
+ return [round(b * frame_s, TIME_PLACES) for b in bkps[:-1]]
87
+
88
+
89
+ def audio_features(
90
+ path: Any,
91
+ *,
92
+ hop_s: float = DFLT_HOP_S,
93
+ n_mfcc: int = DFLT_N_MFCC,
94
+ sample_rate: int = DFLT_SAMPLE_RATE,
95
+ ) -> tuple[Any, float, float]:
96
+ """``(features, frame_s, duration_s)`` of the audio of ``path``: per frame,
97
+ its MFCCs and spectral contrast, each dimension standardised over the
98
+ media (so no one dimension's scale decides the cuts)."""
99
+ import librosa
100
+ import numpy as np
101
+
102
+ from paces.measure import _load_audio # the one decode path, wav or not
103
+
104
+ y, sr = _load_audio(path, sample_rate=sample_rate)
105
+ hop = max(1, int(round(hop_s * sr)))
106
+ mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=n_mfcc, hop_length=hop)
107
+ contrast = librosa.feature.spectral_contrast(y=y, sr=sr, hop_length=hop)
108
+ x = np.vstack([mfcc, contrast]).T
109
+ spread = x.std(axis=0)
110
+ x = (x - x.mean(axis=0)) / np.where(spread > 0, spread, 1.0)
111
+ return x, hop / sr, len(y) / sr
112
+
113
+
114
+ def _segment_known_k(inputs: Mapping[str, Any]) -> Segmentation:
115
+ """The ``known-k`` capability: K steps cut where the media's audio changes most."""
116
+ k = int(inputs["k"])
117
+ features, frame_s, duration = audio_features(inputs["media"])
118
+ cuts = known_k_cuts(features, k, frame_s=frame_s)
119
+ if cuts is None:
120
+ return Segmentation(
121
+ confidence=0.0,
122
+ flags=(
123
+ f"k-too-large: {k} steps of at least {DFLT_KNOWN_K_MIN_STEP_S} s "
124
+ f"do not fit in {duration:.1f} s of media",
125
+ ),
126
+ )
127
+ boundaries = (0.0, *cuts, round(duration, TIME_PLACES))
128
+ steps, flags = steps_on_boundaries(
129
+ boundaries,
130
+ inputs["steps"],
131
+ confidence=DFLT_KNOWN_K_CONFIDENCE,
132
+ source="known-k",
133
+ )
134
+ return Segmentation(
135
+ steps=steps,
136
+ boundaries=boundaries,
137
+ confidence=DFLT_KNOWN_K_CONFIDENCE,
138
+ flags=flags + ("boundaries-proposed",),
139
+ )
140
+
141
+
142
+ KNOWN_K = register(
143
+ Capability(
144
+ name="known-k",
145
+ gives="segmentation",
146
+ summary=(
147
+ "K steps where the media's audio changes most: kernel change-point "
148
+ "detection over MFCC frames, the step count from the ask page"
149
+ ),
150
+ target="paces.known_k:_segment_known_k",
151
+ needs=frozenset({"media.local", "k"}),
152
+ reads=frozenset({"steps"}),
153
+ requires=("ruptures", "librosa"),
154
+ licence="BSD-2-Clause (ruptures)",
155
+ base=0.3, # below every segmenter that is told where the steps are
156
+ resolution_s=DFLT_HOP_S,
157
+ )
158
+ )
@@ -28,6 +28,11 @@ spans. Like ``grid-measured`` (``paces/measure.py``) they register when
28
28
  ``paces`` is imported — the package ``__init__`` imports their module, so
29
29
  ``from paces.segmenters import segment`` sees them too.
30
30
 
31
+ Plus ``known-k`` (``paces/known_k.py``, the ``[cpd]`` extra): media and the
32
+ step count the ask page asked for, cut by kernel change-point detection over
33
+ the audio. Whatever runs, an answered ``k`` the result disagrees with is
34
+ flagged ``k-mismatch``.
35
+
31
36
  Honesty rules (``docs/alignment/07 §9.5``): a segmenter may never return a
32
37
  step count it has no evidence for. Four legitimate return states — confident /
33
38
  found-unnamed / proposed-uncertain / refused — all expressed by the type, none
@@ -572,6 +577,10 @@ def segment(
572
577
  )
573
578
  extra_flags = (f"ignored: {', '.join(ignored)}",) if ignored else ()
574
579
  extra_flags += problem_flags
580
+ found = len(result.steps) if result.steps else max(0, len(result.boundaries) - 1)
581
+ if k is not None and found and found != k:
582
+ # an answered step count the result disagrees with is said, not dropped
583
+ extra_flags += (f"k-mismatch: k={k}, found {found} steps",)
575
584
 
576
585
  # A grid describes the media's own clock; any segmentation over that
577
586
  # media may carry it (and its unit) even when placement didn't use it —
@@ -690,45 +699,62 @@ def _cumulative(rows: list[dict]) -> list[float]:
690
699
  return offsets
691
700
 
692
701
 
693
- def _segment_explicit(inputs: Mapping[str, Any]) -> Segmentation:
694
- """Adopt boundaries supplied explicitly (by a human or a prior run).
695
-
696
- N boundaries make N-1 spans. Names zip on when a step list of the right
697
- length was supplied; otherwise the result is honestly unnamed
698
- (``naming-abstained``), never invented.
702
+ def steps_on_boundaries(
703
+ boundaries: Sequence[float],
704
+ step_rows: Sequence[Mapping],
705
+ *,
706
+ confidence: float,
707
+ source: str,
708
+ ) -> tuple[tuple[SegStep, ...], tuple[str, ...]]:
709
+ """``(steps, flags)`` for the spans between ``boundaries``: the names of
710
+ ``step_rows`` zipped on when there is one per span, else honestly unnamed
711
+ (``seg-1``, ...) and flagged ``naming-abstained`` or, when the count
712
+ disagrees, ``step-count-mismatch``. Never invented.
713
+
714
+ >>> steps, flags = steps_on_boundaries([0, 5, 9], [], confidence=0.5, source="x")
715
+ >>> [s.id for s in steps], flags
716
+ (['seg-1', 'seg-2'], ('naming-abstained',))
699
717
  """
700
- boundaries = tuple(sorted(inputs["boundaries"]))
701
718
  spans = list(zip(boundaries, boundaries[1:]))
702
- step_rows = inputs["steps"]
703
- flags: tuple[str, ...] = ()
704
- steps: tuple[SegStep, ...] = ()
705
719
  if step_rows and len(step_rows) == len(spans):
706
720
  steps = tuple(
707
721
  SegStep(
708
722
  id=row["id"],
709
723
  name=row["name"],
710
724
  spans=(span,),
711
- confidence=DFLT_EXPLICIT_CONFIDENCE,
712
- source="explicit",
725
+ confidence=confidence,
726
+ source=source,
713
727
  )
714
728
  for row, span in zip(step_rows, spans)
715
729
  )
716
- else:
717
- if step_rows:
718
- flags = (
719
- f"step-count-mismatch: {len(step_rows)} steps vs {len(spans)} spans",
720
- )
721
- else:
722
- flags = ("naming-abstained",)
723
- steps = tuple(
724
- SegStep(
725
- id=f"seg-{i + 1}",
726
- spans=(span,),
727
- confidence=DFLT_EXPLICIT_CONFIDENCE,
728
- source="explicit",
729
- )
730
- for i, span in enumerate(spans)
730
+ return steps, ()
731
+ if step_rows:
732
+ flags: tuple[str, ...] = (
733
+ f"step-count-mismatch: {len(step_rows)} steps vs {len(spans)} spans",
731
734
  )
735
+ else:
736
+ flags = ("naming-abstained",)
737
+ steps = tuple(
738
+ SegStep(id=f"seg-{i + 1}", spans=(span,), confidence=confidence, source=source)
739
+ for i, span in enumerate(spans)
740
+ )
741
+ return steps, flags
742
+
743
+
744
+ def _segment_explicit(inputs: Mapping[str, Any]) -> Segmentation:
745
+ """Adopt boundaries supplied explicitly (by a human or a prior run).
746
+
747
+ N boundaries make N-1 spans. Names zip on when a step list of the right
748
+ length was supplied; otherwise the result is honestly unnamed
749
+ (``naming-abstained``), never invented.
750
+ """
751
+ boundaries = tuple(sorted(inputs["boundaries"]))
752
+ steps, flags = steps_on_boundaries(
753
+ boundaries,
754
+ inputs["steps"],
755
+ confidence=DFLT_EXPLICIT_CONFIDENCE,
756
+ source="explicit",
757
+ )
732
758
  return Segmentation(
733
759
  steps=steps,
734
760
  boundaries=boundaries,
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
 
7
7
  [project]
8
8
  name = "paces"
9
- version = "0.0.26"
9
+ version = "0.0.28"
10
10
  description = "Turn instructional media into structured, interactive learning material"
11
11
  readme = "README.md"
12
12
  license = "MIT"
@@ -37,6 +37,10 @@ paces = "paces.__main__:main"
37
37
 
38
38
  [project.optional-dependencies]
39
39
  cli = ["cw>=0.1.1,<0.2", "argcomplete>=3"]
40
+ # The known-k segmenter (paces#39): kernel change-point detection over the
41
+ # media's audio features, for a step count the ask page asked for. ruptures
42
+ # is BSD-2-Clause; the features need the [audio] extra too.
43
+ cpd = ["ruptures>=1.1"]
40
44
  audio = [
41
45
  # Grid measurement (issue #2): the fleet's `mixing` owns speech/music
42
46
  # segmentation and beat tracking; [beats] pulls librosa, [audio] pulls
@@ -179,7 +183,7 @@ install.windows = "choco install ffmpeg -y --no-progress"
179
183
  # --------------------------------------------------------------------------
180
184
  [tool.wads.licence]
181
185
  enabled = false
182
- include-extras = ["cli", "audio", "media", "pose", "lacing"]
186
+ include-extras = ["cli", "audio", "media", "pose", "lacing", "cpd"]
183
187
 
184
188
  [tool.hatch.build.targets.wheel]
185
189
  packages = ["paces"]
@@ -590,3 +590,32 @@ def test_js_refuses_striking_a_gap_edge_and_tapping_a_gap():
590
590
  assert out[0] == [] and "nothing to merge" in out[1]
591
591
  assert out[2] == [] and "gap between steps" in out[3]
592
592
  assert out[4] == ["25"]
593
+
594
+
595
+ @needs_node
596
+ def test_the_proposal_says_how_many_places_its_times_keep_and_the_page_keeps_them():
597
+ """paces#41 (3): the places travel in the proposal (``timePlaces``, Python's
598
+ ``TIME_PLACES``) instead of being a second constant in the page, and the
599
+ page writes every time it makes at that many places; a proposal written
600
+ before the field reads as 3."""
601
+ from paces.segmentation import TIME_PLACES
602
+
603
+ proposal = propose(segment("video.mp4"))
604
+ assert proposal["timePlaces"] == TIME_PLACES
605
+ actions = [{"type": "duration", "seconds": 30.0}, {"type": "tap", "t": 10.123456}]
606
+ for places, expected in ((TIME_PLACES, "10.123"), (2, "10.12"), (None, "10.123")):
607
+ p = {**proposal, "timePlaces": places}
608
+ if places is None:
609
+ del p["timePlaces"]
610
+ (_, tapped) = _reduce(p, actions)
611
+ assert tapped["state"]["added"] == [expected], places
612
+
613
+
614
+ @needs_node
615
+ def test_the_page_script_still_loads_as_a_module_with_only_its_pure_core():
616
+ """paces#41 (2): the DOM layer is split into functions (media, keyboard,
617
+ render, header, answers); requiring the script runs none of them and
618
+ exports the same pure core."""
619
+ assert _run_js("Object.keys(core).sort()") == sorted(
620
+ ["timeStr", "mmss", "snap", "freshState", "reduce", "buildAnswers", "cutRows"]
621
+ )
@@ -0,0 +1,71 @@
1
+ """The known-k segmenter and the k-mismatch flag (paces#39)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+
7
+ from paces import segment
8
+
9
+
10
+ def test_an_answered_k_the_result_disagrees_with_is_flagged():
11
+ """The ask page's step count is said when the result has another count,
12
+ whichever segmenter ran, instead of being dropped silently."""
13
+ seg = segment(boundaries=[0, 10, 20, 30], k=4)
14
+ assert "k-mismatch: k=4, found 3 steps" in seg.flags
15
+ assert not any(f.startswith("k-mismatch") for f in segment(boundaries=[0, 10, 20, 30], k=3).flags)
16
+
17
+
18
+ def test_known_k_cuts_finds_the_k_minus_1_change_points():
19
+ np = pytest.importorskip("numpy")
20
+ pytest.importorskip("ruptures")
21
+ from paces.known_k import known_k_cuts
22
+
23
+ x = np.repeat([[0.0, 1.0], [5.0, 1.0], [0.0, 3.0]], 50, axis=0)
24
+ assert known_k_cuts(x, 3, frame_s=0.1, min_step_s=1.0) == [5.0, 10.0]
25
+ assert known_k_cuts(x, 1, frame_s=0.1) == []
26
+ assert known_k_cuts(x, 20, frame_s=0.1, min_step_s=1.0) is None # 20 x 1 s > 15 s
27
+
28
+
29
+ def _three_sounds(path, seconds=(6.0, 5.0, 7.0), rate=22050):
30
+ """A wav of a low tone, noise, then a high tone: three steps whose audio differs."""
31
+ np = pytest.importorskip("numpy")
32
+ sf = pytest.importorskip("soundfile")
33
+ rng = np.random.default_rng(0)
34
+ parts = []
35
+ for i, s in enumerate(seconds):
36
+ t = np.arange(int(s * rate)) / rate
37
+ if i == 0:
38
+ parts.append(0.4 * np.sin(2 * np.pi * 220 * t))
39
+ elif i == 1:
40
+ parts.append(0.3 * rng.standard_normal(len(t)))
41
+ else:
42
+ parts.append(0.4 * np.sin(2 * np.pi * 1760 * t))
43
+ sf.write(str(path), np.concatenate(parts), rate)
44
+ return [seconds[0], seconds[0] + seconds[1]]
45
+
46
+
47
+ def test_the_known_k_segmenter_cuts_the_media_where_its_audio_changes(tmp_path):
48
+ """Media plus the human's k, nothing else: known-k is chosen, and its
49
+ K-1 cuts land on the changes; named when a step list of K was given."""
50
+ pytest.importorskip("ruptures")
51
+ pytest.importorskip("librosa")
52
+ wav = tmp_path / "three.wav"
53
+ truth = _three_sounds(wav)
54
+ seg = segment(str(wav), k=3)
55
+ assert seg.method == "known-k"
56
+ assert len(seg.boundaries) == 4
57
+ for got, want in zip(seg.boundaries[1:-1], truth):
58
+ assert abs(got - want) <= 0.3, (seg.boundaries, truth)
59
+ assert "boundaries-proposed" in seg.flags and "naming-abstained" in seg.flags
60
+ assert not any(f.startswith(("ignored", "k-mismatch")) for f in seg.flags)
61
+ named = segment(str(wav), k=3, steps=["tone", "noise", "whistle"])
62
+ assert [s.name for s in named.steps] == ["tone", "noise", "whistle"]
63
+
64
+
65
+ def test_a_k_the_media_cannot_hold_is_refused_with_a_reason(tmp_path):
66
+ pytest.importorskip("ruptures")
67
+ pytest.importorskip("librosa")
68
+ wav = tmp_path / "three.wav"
69
+ _three_sounds(wav)
70
+ seg = segment(str(wav), k=50)
71
+ assert seg.steps == () and any(f.startswith("k-too-large") for f in seg.flags)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes