paces 0.0.27__tar.gz → 0.0.29__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.
- {paces-0.0.27 → paces-0.0.29}/PKG-INFO +3 -1
- {paces-0.0.27 → paces-0.0.29}/paces/__init__.py +1 -0
- {paces-0.0.27 → paces-0.0.29}/paces/edits.py +202 -1
- paces-0.0.29/paces/known_k.py +158 -0
- {paces-0.0.27 → paces-0.0.29}/paces/segmenters.py +53 -27
- {paces-0.0.27 → paces-0.0.29}/pyproject.toml +6 -2
- {paces-0.0.27 → paces-0.0.29}/tests/test_edits.py +110 -0
- paces-0.0.29/tests/test_known_k.py +71 -0
- {paces-0.0.27 → paces-0.0.29}/.gitignore +0 -0
- {paces-0.0.27 → paces-0.0.29}/LICENSE +0 -0
- {paces-0.0.27 → paces-0.0.29}/README.md +0 -0
- {paces-0.0.27 → paces-0.0.29}/docs/README.md +0 -0
- {paces-0.0.27 → paces-0.0.29}/docs/alignment/README.md +0 -0
- {paces-0.0.27 → paces-0.0.29}/docs/poc-reference/README.md +0 -0
- {paces-0.0.27 → paces-0.0.29}/docs/poc-reference/artifacts/clips.json +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/__main__.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/ask.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/ask_contract.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/bodies/__init__.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/bodies/_base.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/bodies/derivation.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/bodies/document.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/bodies/signal.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/bodies/step.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/corrections.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/cues.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/data/ask/ask.css +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/data/ask/ask.html +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/data/ask/ask.js +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/derivation.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/evidence.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/excerpts.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/measure.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/model.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/pose.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/projection.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/render.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/segmentation.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/timed_text.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/paces/tools.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/audio_synth.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/data/body_schemas.json +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/data/routine.json +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/poc_fixture.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_ask.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_chapters.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_cli_surface.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_corrections.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_cues.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_derivation.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_edit_protection_residuals.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_evidence.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_evidence_schemas.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_excerpts.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_measure.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_pose.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_render_media.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_roundtrip_poc.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_segment.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_smoke.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/test_vertical_slice.py +0 -0
- {paces-0.0.27 → paces-0.0.29}/tests/video_synth.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: paces
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.29
|
|
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)
|
|
@@ -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])
|
|
@@ -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
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
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=
|
|
712
|
-
source=
|
|
725
|
+
confidence=confidence,
|
|
726
|
+
source=source,
|
|
713
727
|
)
|
|
714
728
|
for row, span in zip(step_rows, spans)
|
|
715
729
|
)
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
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.
|
|
9
|
+
version = "0.0.29"
|
|
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"]
|
|
@@ -453,3 +453,113 @@ def test_scalar_list_edits_do_not_survive_but_keep_their_record():
|
|
|
453
453
|
merged = merge_regenerated(committed, fresh)
|
|
454
454
|
assert merged.steps[0].tags == ["wrong-tag"] # not protected, by design
|
|
455
455
|
assert merged.steps[0].locks # but the record survives
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _repeats(names_and_starts) -> StepDocument:
|
|
459
|
+
"""A document of steps named and timed as given, with the generated ids
|
|
460
|
+
a segmenter makes for repeats (``turn``, ``turn-2``, ...)."""
|
|
461
|
+
from paces.segmenters import unique_slug_ids
|
|
462
|
+
|
|
463
|
+
names = [n for n, _ in names_and_starts]
|
|
464
|
+
return _doc(
|
|
465
|
+
steps=[
|
|
466
|
+
Step(
|
|
467
|
+
id=sid,
|
|
468
|
+
name=name,
|
|
469
|
+
duration=Measure(value="1", unit="eight"),
|
|
470
|
+
spans=[SourceSpan(source="vid", start=str(start), end=str(start + 4))],
|
|
471
|
+
origin=Origin(generated_by="segmenter:grid-placed"),
|
|
472
|
+
)
|
|
473
|
+
for sid, (name, start) in zip(unique_slug_ids(names), names_and_starts)
|
|
474
|
+
]
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def test_a_lock_on_a_repeat_stays_on_it_when_a_repeat_is_inserted_before_it():
|
|
479
|
+
"""paces#50: committed [Turn, Kick, Turn] (turn, kick, turn-2) with a lock
|
|
480
|
+
on turn-2; regeneration finds a new Turn at 5 s, so its ids shift to turn,
|
|
481
|
+
turn-2, kick, turn-3. The lock stays on the Turn at 20 s, and the new one
|
|
482
|
+
gets an id no committed step holds."""
|
|
483
|
+
committed = apply_edits(
|
|
484
|
+
_repeats([("Turn", 0), ("Kick", 10), ("Turn", 20)]),
|
|
485
|
+
[{"op": "set", "path": "/steps/turn-2/name", "value": "Turn (left)"}],
|
|
486
|
+
by="user:thor",
|
|
487
|
+
)
|
|
488
|
+
fresh = _repeats([("Turn", 0), ("Turn", 5), ("Kick", 10), ("Turn", 20)])
|
|
489
|
+
merged = merge_regenerated(committed, fresh)
|
|
490
|
+
by_start = {str(s.spans[0].start): s for s in merged.steps}
|
|
491
|
+
assert by_start["20"].name == "Turn (left)" and by_start["20"].id == "turn-2"
|
|
492
|
+
assert by_start["5"].name == "Turn" and by_start["5"].id not in {"turn", "turn-2", "kick"}
|
|
493
|
+
assert by_start["0"].id == "turn"
|
|
494
|
+
assert len({s.id for s in merged.steps}) == 4
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def test_repeats_without_times_keep_their_positional_ids():
|
|
498
|
+
"""With no span to tell occurrences apart, the merge matches by id as before."""
|
|
499
|
+
committed = _repeats([("Turn", 0), ("Turn", 20)])
|
|
500
|
+
for step in committed.steps:
|
|
501
|
+
step.spans = []
|
|
502
|
+
fresh = committed.model_copy(deep=True)
|
|
503
|
+
assert [s.id for s in merge_regenerated(committed, fresh).steps] == ["turn", "turn-2"]
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _ids(doc) -> list[str]:
|
|
507
|
+
out = []
|
|
508
|
+
|
|
509
|
+
def walk(steps):
|
|
510
|
+
for s in steps:
|
|
511
|
+
out.append(s.id)
|
|
512
|
+
walk(s.steps)
|
|
513
|
+
|
|
514
|
+
walk(doc.steps)
|
|
515
|
+
return out
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def test_repeat_identity_never_makes_two_steps_one_id():
|
|
519
|
+
"""paces#58 review: a step named "Turn 2" holds the id a second Turn would
|
|
520
|
+
take; a nested repeat must not take its parent's id; and ids stay unique."""
|
|
521
|
+
committed = _repeats([("Turn", 0), ("Turn", 20)]) # turn, turn-2
|
|
522
|
+
fresh = _repeats([("Turn 2", 10), ("Turn", 0), ("Turn", 20)]) # turn-2, turn, turn-3
|
|
523
|
+
merged = merge_regenerated(committed, fresh)
|
|
524
|
+
ids = _ids(merged)
|
|
525
|
+
assert len(ids) == len(set(ids)), ids
|
|
526
|
+
assert {str(s.spans[0].start): s.id for s in merged.steps}["20"] == "turn-2"
|
|
527
|
+
|
|
528
|
+
parent = _repeats([("Turn", 0)])
|
|
529
|
+
nested = _repeats([("Turn", 0)])
|
|
530
|
+
nested.steps[0].steps = _repeats([("Turn", 1), ("Turn", 2)]).steps # ids turn, turn-2
|
|
531
|
+
nested.steps[0].steps[0].id, nested.steps[0].steps[1].id = "turn-2", "turn-3"
|
|
532
|
+
ids = _ids(merge_regenerated(parent, nested))
|
|
533
|
+
assert len(ids) == len(set(ids)), ids
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def test_repeat_identity_reads_time_order_not_list_order():
|
|
537
|
+
committed = _repeats([("Turn", 0), ("Turn", 20)])
|
|
538
|
+
committed.steps.reverse() # [turn-2 @20, turn @0]
|
|
539
|
+
merged = merge_regenerated(committed, _repeats([("Turn", 0), ("Turn", 20)]))
|
|
540
|
+
assert {str(s.spans[0].start): s.id for s in merged.steps} == {"0": "turn", "20": "turn-2"}
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def test_a_renamed_repeat_and_a_cue_on_it_stay_with_their_occurrence():
|
|
544
|
+
"""An ``/id`` rename (``turn-2`` -> ``my-turn``) keeps to the Turn at 20 s
|
|
545
|
+
when a Turn is inserted earlier, and a fresh cue anchored to the fresh id
|
|
546
|
+
of that Turn is re-anchored with it."""
|
|
547
|
+
from paces.model import Anchor, Cue
|
|
548
|
+
|
|
549
|
+
committed = apply_edits(
|
|
550
|
+
_repeats([("Turn", 0), ("Kick", 10), ("Turn", 20)]),
|
|
551
|
+
[{"op": "set", "path": "/steps/turn-2/id", "value": "my-turn"}],
|
|
552
|
+
by="user:thor",
|
|
553
|
+
)
|
|
554
|
+
fresh = _repeats([("Turn", 0), ("Turn", 5), ("Kick", 10), ("Turn", 20)])
|
|
555
|
+
fresh.cues = [Cue(id="clap", kind="count", text="clap", anchor=Anchor(step="turn-3"))]
|
|
556
|
+
merged = merge_regenerated(committed, fresh)
|
|
557
|
+
by_start = {str(s.spans[0].start): s.id for s in merged.steps}
|
|
558
|
+
assert by_start["20"] == "my-turn" and by_start["5"] not in {"my-turn", "turn"}
|
|
559
|
+
assert merged.cues[0].anchor.step == "my-turn"
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def test_unnamed_steps_keep_their_place_ids():
|
|
563
|
+
committed = _repeats([("", 0), ("", 10)])
|
|
564
|
+
fresh = _repeats([("", 0), ("", 5), ("", 10)])
|
|
565
|
+
assert _ids(merge_regenerated(committed, fresh)) == _ids(fresh)
|
|
@@ -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
|
|
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
|