create-pmos 0.77.0 → 0.79.0

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.
@@ -720,6 +720,8 @@ function computeWorkflowDerived(id, opts) {
720
720
  return Number.isFinite(t) ? t : null;
721
721
  })();
722
722
  const steps = [];
723
+ // Steps the PM cut or made optional on 2026-10-07 (planning/initiatives/sdlc-step-cuts.md).
724
+ const CUT_NOTE = 'cut by the PM 2026-10-07 (sdlc-step-cuts)';
723
725
 
724
726
  // ── route ─ the lane is chosen and the two intake questions are answered ─────────────────────
725
727
  const sRoute = specimenRoute(fm.specimen_test);
@@ -731,6 +733,9 @@ function computeWorkflowDerived(id, opts) {
731
733
  if (!missing.length) {
732
734
  steps.push(step('route', 'route', 'done',
733
735
  `${lane} lane · specimen test ${sRoute} · surface ${fRoute}`));
736
+ } else if (effLane !== 'feature') {
737
+ // The routing questions are asked of feature work only.
738
+ steps.push(step('route', 'route', 'done', `${lane} lane — routing questions are for features only (${CUT_NOTE})`));
734
739
  } else if (legacy) {
735
740
  steps.push(step('route', 'route', 'unknown',
736
741
  `${lane} lane · ${missing.join(' + ')} not declared (record predates ${ENFORCED_FROM})`));
@@ -875,41 +880,21 @@ function computeWorkflowDerived(id, opts) {
875
880
  }
876
881
  }
877
882
 
878
- // ── understand ─ O4: an existing surface is explained BEFORE it is specified ─────────────────
883
+ // ── understand ─ O4, made optional (sdlc-step-cuts) ───────────────────────────────────────
884
+ // An explain-surface pass that exists is shown; a missing one never blocks.
879
885
  {
880
886
  const expl = String(fm.explainer_path || '').trim();
881
- if (fRoute !== 'existing') {
882
- steps.push(step('understand', 'understand', 'na',
883
- fRoute === 'greenfield' ? 'greenfield — nothing existing to explain first' : 'surface check not declared'));
884
- } else if (!expl) {
885
- steps.push(step('understand', 'understand', legacy ? 'unknown' : 'blocked',
886
- 'surface_check says existing but no explainer_path is set',
887
- 'run build-skills/explain-surface.skill in a FRESH context (not the agent that will write the spec), then set explainer_path:',
888
- { blocking: !legacy, rule: 'O4' }));
889
- } else if (!fs.existsSync(path.join(root, expl))) {
890
- steps.push(step('understand', 'understand', legacy ? 'unknown' : 'blocked',
891
- `explainer_path '${expl}' does not exist in the repo`,
892
- 'set explainer_path to a real explain-surface output',
893
- { blocking: !legacy, rule: 'O4' }));
887
+ if (expl && fs.existsSync(path.join(root, expl))) {
888
+ steps.push(step('understand', 'understand', 'done', `${expl} — optional surface explainer`));
894
889
  } else {
895
- const eIdx = firstAppearance(root, range, expl);
896
- const ok = ordered(eIdx, prdIdx);
897
- if (ok === null) {
898
- steps.push(step('understand', 'understand', 'unknown',
899
- `${expl} present; order undecidable (${range.ok ? 'no spec artifact to order against' : range.reason})`));
900
- } else if (ok) {
901
- steps.push(step('understand', 'understand', 'done', `${expl} — first-appeared before ${prd}`));
902
- } else {
903
- steps.push(step('understand', 'understand', legacy ? 'unknown' : 'blocked',
904
- `ORDER VIOLATION — the spec (${prd}) first-appeared BEFORE the explainer (${expl})`,
905
- 'without the pass first, the AGENT acquires the understanding and the PM approves a spec built on facts they never saw',
906
- { blocking: !legacy, rule: 'O4' }));
907
- }
890
+ steps.push(step('understand', 'understand', 'na', `the surface explainer is optional — ${CUT_NOTE}`));
908
891
  }
909
892
  }
910
893
 
911
894
  // ── spec ─ the lane's artifacts, and O1/O2: they precede the build ───────────────────────────
912
- const needsRubric = effLane === 'feature';
895
+ // A feature PRD's done-criteria section can serve as its rubric (sdlc-step-cuts), so a separate
896
+ // rubric file is optional in every lane. One that is declared must still exist.
897
+ const needsRubric = false;
913
898
  {
914
899
  const wants = {
915
900
  feature: 'a PRD', discovery: 'a spike brief', incident: 'an incident record',
@@ -925,7 +910,7 @@ function computeWorkflowDerived(id, opts) {
925
910
  } else if (!prd) {
926
911
  steps.push(step('spec', 'spec', 'blocked', `no prd_path — the ${effLane} lane needs ${wants}`,
927
912
  effLane === 'feature'
928
- ? 'author the PRD (skills/core/prd.skill) and the rubric alongside it (D13), then set prd_path + rubric_path'
913
+ ? 'author the PRD (skills/core/prd.skill) with its done-criteria (D13), then set prd_path'
929
914
  : `author ${wants} and set prd_path in ${recRel}`,
930
915
  { blocking: true, rule: 'R2' }));
931
916
  } else if (prdIdx === null) {
@@ -970,88 +955,24 @@ function computeWorkflowDerived(id, opts) {
970
955
  const runs = cachedJsonl(path.join(L.runsDir, L.runsFile)).filter((r) => r && r.initiative_id === id);
971
956
  const runsRel = path.relative(root, path.join(L.runsDir, L.runsFile));
972
957
 
973
- // ── priors ─ O7: the episodic read is CITED, and the citation is checked ─────────────────────
974
- // AGENTS.md step 3 mandates reading this initiative's earlier runs BEFORE acting — the one kernel
975
- // invariant that was still asserted only in prose. Nothing can derive that a file was READ, and
976
- // this rule does not pretend to: what it derives is the three things that ARE decidable from the
977
- // record, and together they are what separates it from a checkbox.
978
- // 1. whether earlier runs existed at all — the rule is vacuous on a first run, and says so
979
- // 2. whether the run declared what it consulted
980
- // 3. whether the ids it named are REAL and actually EARLIER
981
- // (3) is the part that matters. O5's `PM_approved: true` is a bare boolean, satisfiable by typing
982
- // it; a fabricated `priors` list fails against the corpus it claims to have read. The rule is
983
- // NON-BLOCKING for the same reason O5/O6 are: it cannot be true before a run exists, and a rule
984
- // enforced at a moment it cannot be satisfied only teaches people to reach for the escape hatch.
985
- {
986
- const latest = runs.length ? runs[runs.length - 1] : null;
987
- const earlier = runs.slice(0, -1);
988
- const cite = priorsCitation(latest);
989
- const how = `consult this initiative's earlier runs BEFORE acting (AGENTS.md step 3) and cite them as \`priors\` on the run in ${runsRel}`;
990
- if (!latest) {
991
- steps.push(step('priors', 'priors', 'pending', 'no run logged for this initiative yet', how, { rule: 'O7' }));
992
- } else if (!earlier.length) {
993
- // Not a pass — there was nothing to pass. A tick here would be the watermelon this engine exists to prevent.
994
- steps.push(step('priors', 'priors', 'na',
995
- `${latest.run_id} is the first run on this initiative — no priors to consult`));
996
- } else if (cite.malformed) {
997
- steps.push(step('priors', 'priors', legacy ? 'pending' : 'blocked',
998
- `${latest.run_id} has a malformed priors citation — ${cite.malformed}`,
999
- `use \`priors: ["<run_id>", …]\` or \`priors: {consulted: [...], note: "…"}\` in ${runsRel}`,
1000
- { rule: 'O7' }));
1001
- } else if (!cite.declared) {
1002
- steps.push(step('priors', 'priors', legacy ? 'pending' : 'blocked',
1003
- `${latest.run_id} follows ${earlier.length} earlier run(s) on this initiative and cites no priors`,
1004
- how, { rule: 'O7' }));
1005
- } else {
1006
- const byId = new Map(runs.map((r) => [String(r.run_id), r]));
1007
- const earlierIds = new Set(earlier.map((r) => String(r.run_id)));
1008
- const missing = cite.consulted.filter((x) => !byId.has(x));
1009
- const notEarlier = cite.consulted.filter((x) => byId.has(x) && !earlierIds.has(x));
1010
- if (missing.length) {
1011
- // The check a declared field would otherwise never get. A citation naming a run that does not
1012
- // exist reports a read that cannot have happened — worse than an absent citation, because it
1013
- // reads as compliance on the board.
1014
- steps.push(step('priors', 'priors', legacy ? 'pending' : 'blocked',
1015
- `${latest.run_id} cites prior run(s) that do not exist on this initiative: ${missing.join(', ')}`,
1016
- `cite run_ids that are actually in ${runsRel} — a citation naming nothing reports a read that cannot have happened`,
1017
- { rule: 'O7' }));
1018
- } else if (notEarlier.length) {
1019
- steps.push(step('priors', 'priors', legacy ? 'pending' : 'blocked',
1020
- `${latest.run_id} cites ${notEarlier.join(', ')}, which ${notEarlier.length > 1 ? 'are' : 'is'} not EARLIER than it`,
1021
- 'a run cannot consult itself or a run that came after it — cite only runs logged before this one',
1022
- { rule: 'O7' }));
1023
- } else if (!cite.consulted.length && !cite.note) {
1024
- steps.push(step('priors', 'priors', legacy ? 'pending' : 'blocked',
1025
- `${latest.run_id} declares an empty priors list with no note, over ${earlier.length} earlier run(s)`,
1026
- 'an empty list with no reason is indistinguishable from not looking — say which priors were read, or say in `note` why none applied',
1027
- { rule: 'O7' }));
1028
- } else if (!cite.consulted.length) {
1029
- // Allowed, and deliberately not silent: the machine cannot judge whether the priors were
1030
- // genuinely irrelevant, so it surfaces the claim verbatim for the PM instead of ticking.
1031
- steps.push(step('priors', 'priors', 'done',
1032
- `${latest.run_id} consulted none of ${earlier.length} earlier run(s) — declared irrelevant: ${cite.note}`));
1033
- } else {
1034
- steps.push(step('priors', 'priors', 'done',
1035
- `${latest.run_id} cites ${cite.consulted.length} prior run(s): ${cite.consulted.join(', ')}${cite.note ? ` — ${cite.note}` : ''}`));
1036
- }
1037
- }
1038
- }
958
+ // ── priors ─ O7, cut (sdlc-step-cuts) ───────────────────────────────────────────────────────
959
+ // Reading earlier runs is still good practice; citing them is no longer checked.
960
+ steps.push(step('priors', 'priors', 'na', `prior-run citation is not required — ${CUT_NOTE}`));
1039
961
 
1040
- // ── contract ─ O5: PM-approved done-criteria before the build. Reported, never CI-blocking ────
962
+ // ── contract ─ O5: PM-approved done-criteria. Reported, never blocking ─────────────────────
963
+ // Since sdlc-step-cuts only the feature lane asks for it, and a missing sign-off is pending, not
964
+ // blocked: the PM's approval of the PRD and the acceptance at the end are the sign-offs that count.
1041
965
  const approved = runs.find((r) => r.pre_run_contract && r.pre_run_contract.PM_approved === true);
1042
966
  {
1043
967
  if (approved) {
1044
968
  steps.push(step('contract', 'contract', 'done',
1045
969
  `PM-approved pre_run_contract on run ${approved.run_id}${approved.pre_run_contract.approved_by ? ` (by ${approved.pre_run_contract.approved_by})` : ''}`));
1046
- } else if (runs.length) {
1047
- steps.push(step('contract', 'contract', legacy ? 'pending' : 'blocked',
1048
- `${runs.length} run(s) logged, none with pre_run_contract.PM_approved: true`,
1049
- `agree numbered done_criteria + test_method with the PM and record the approval in ${runsRel}`,
1050
- { rule: 'O5' }));
970
+ } else if (effLane !== 'feature') {
971
+ steps.push(step('contract', 'contract', 'na', `${effLane} lane — the PM's acceptance stands in for a contract sign-off (${CUT_NOTE})`));
1051
972
  } else {
1052
973
  steps.push(step('contract', 'contract', 'pending',
1053
- 'no run logged for this initiative yet',
1054
- `agree done_criteria + test_method BEFORE building and append the run to ${runsRel} with PM_approved: true`,
974
+ runs.length ? `${runs.length} run(s) logged, none with pre_run_contract.PM_approved: true` : 'no run logged for this initiative yet',
975
+ `agree done_criteria + test_method with the PM (approving the PRD counts) and record it in ${runsRel}`,
1055
976
  { rule: 'O5' }));
1056
977
  }
1057
978
  }
@@ -1143,41 +1064,32 @@ function computeWorkflowDerived(id, opts) {
1143
1064
  * fix that made a chore's gate visible ADDED one. The module's own rule, repeated in three
1144
1065
  * files — "a skip is an honest RECORD that verification did not happen; it is not
1145
1066
  * verification" — now applies to the surface that reports it. */
1067
+ // The Review Gate runs on request since sdlc-step-cuts: a skip is n/a, and a FAIL is reported
1068
+ // for the PM to weigh at acceptance rather than holding the gate shut.
1146
1069
  if (verdict === 'SKIPPED') {
1147
- steps.push(step('review', 'review', 'pending', label,
1148
- 'the gate was skipped, so it is still owed — commission an independent evaluator and record a real verdict',
1149
- { rule: 'R3' }));
1070
+ steps.push(step('review', 'review', 'na', `${label} — skipped; the Review Gate runs on request (${CUT_NOTE})`));
1150
1071
  } else if (verdict === 'FAIL') {
1151
- steps.push(step('review', 'review', 'blocked', label,
1152
- 'the Review Gate FAILED — remediate the findings and record a new verdict', { rule: 'R3' }));
1072
+ steps.push(step('review', 'review', 'pending', label,
1073
+ 'the Review Gate FAILED — weigh the findings at acceptance, or remediate and record a new verdict', { rule: 'R3' }));
1153
1074
  } else {
1154
1075
  steps.push(step('review', 'review', 'done', label));
1155
1076
  }
1156
1077
  } else {
1157
- steps.push(step('review', 'review', 'pending', 'no Review-Gate verdict recorded',
1158
- 'score the build against the rubric (build-skills/evaluator.skill), then append to evals.jsonl',
1159
- { rule: 'R3' }));
1078
+ steps.push(step('review', 'review', 'na', `no Review-Gate verdict — it runs on request (${CUT_NOTE})`));
1160
1079
  }
1161
1080
  }
1162
1081
 
1163
- // ── explain ─ O6: the run is explained AFTER the build and BEFORE acceptance ─────────────────
1082
+ // ── explain ─ O6, made optional (sdlc-step-cuts) ────────────────────────────────────────────
1083
+ // A run explainer that exists is shown; a missing one never blocks acceptance.
1164
1084
  {
1165
1085
  let found = null;
1166
1086
  for (const r of runs) {
1167
1087
  const p = path.join(L.explainers, `${r.run_id}-explainer.md`);
1168
1088
  if (fs.existsSync(p)) { found = path.relative(root, p); break; }
1169
1089
  }
1170
- if (found) {
1171
- steps.push(step('explain', 'explain', 'done', found));
1172
- } else if (!runs.length) {
1173
- steps.push(step('explain', 'explain', 'pending', 'no run to explain yet',
1174
- 'log the run first, then run build-skills/explain-run.skill against its diff', { rule: 'O6' }));
1175
- } else {
1176
- steps.push(step('explain', 'explain', legacy ? 'pending' : 'blocked',
1177
- `no explainer at ${path.relative(root, L.explainers)}/${runs[runs.length - 1].run_id}-explainer.md`,
1178
- 'run build-skills/explain-run.skill — raw-transcript vigilance degrades within ~30 min, so the explainer is what the PM actually reviews',
1179
- { rule: 'O6' }));
1180
- }
1090
+ steps.push(found
1091
+ ? step('explain', 'explain', 'done', found)
1092
+ : step('explain', 'explain', 'na', `the run explainer is optional — ${CUT_NOTE}`));
1181
1093
  }
1182
1094
 
1183
1095
  // ── accept ─ the human PM, final and non-delegable (D12) ─────────────────────────────────────
@@ -4,6 +4,7 @@
4
4
  * write(runtimeDir, { id, source, pcm, t }) add one chunk of 16 kHz mono 16-bit samples at meeting time t (ms)
5
5
  * info(runtimeDir, id) → { bytes, ms } | null
6
6
  * remove(runtimeDir, id) delete the note's audio
7
+ * sources(runtimeDir, id) → [{ source, file, bytes, ms }] each source's own samples (Run 9)
7
8
  * serve(req, res, runtimeDir, id) the audio as a WAV file, with byte ranges so the page can seek
8
9
  * getKeep(runtimeDir) · setKeep(runtimeDir, bool) "Keep the audio for replay", on by default, for this machine
9
10
  *
@@ -13,6 +14,10 @@
13
14
  * arrives on time or early, so the small jitter of the page's timer leaves no clicks; a chunk that arrives much later (Listen again)
14
15
  * is placed at its own time, and the gap stays silent.
15
16
  *
17
+ * EACH SOURCE APART (Run 9). Each source is also written to its own file, `<id>.mic.pcm` and `<id>.meeting.pcm`, at the same
18
+ * place and with nothing added, so the final pass after Stop (lib/notes-final.js) can tell the PM's microphone from the
19
+ * meeting. remove deletes all three.
20
+ *
16
21
  * WHAT IT NEVER DOES. It sends nothing and opens no network module. The routes (lib/routes-notes.js) write nothing for a
17
22
  * private note, delete the file when a note is made private or deleted, and write nothing when the PM switches keeping off.
18
23
  */
@@ -27,6 +32,8 @@ const ID_RE = /^n-[0-9a-z]{4,16}-[0-9a-f]{4}$/;
27
32
 
28
33
  const dirOf = (runtimeDir) => path.join(runtimeDir, 'notes', 'recordings');
29
34
  const fileOf = (runtimeDir, id) => path.join(dirOf(runtimeDir), id + '.pcm');
35
+ const SOURCES = ['mic', 'meeting'];
36
+ const sourceFileOf = (runtimeDir, id, source) => path.join(dirOf(runtimeDir), id + '.' + source + '.pcm');
30
37
  const settingsFile = (runtimeDir) => path.join(runtimeDir, 'notes', 'audio-settings.json');
31
38
  const next = new Map(); // `${file}|${source}` → the byte offset where that source's last chunk ended
32
39
 
@@ -43,8 +50,9 @@ function setKeep(runtimeDir, keep) {
43
50
  return { ok: true, keep };
44
51
  }
45
52
 
46
- /** Add one chunk at meeting time `t`. Samples already there (the other source) are added to, and clipped. */
47
- function write(runtimeDir, { id, source, pcm, t }) {
53
+ /** Add one chunk at meeting time `t`. Samples already there (the other source) are added to, and clipped. With `mixed:
54
+ * false` only the source's own file is written: the PM keeps no audio for replay, and the final pass deletes it when done. */
55
+ function write(runtimeDir, { id, source, pcm, t, mixed = true }) {
48
56
  if (!ID_RE.test(String(id || '')) || !pcm || !pcm.length || pcm.length % 2) return { ok: false, error: 'nothing to keep' };
49
57
  const f = fileOf(runtimeDir, id);
50
58
  const key = f + '|' + source;
@@ -55,14 +63,21 @@ function write(runtimeDir, { id, source, pcm, t }) {
55
63
  if (at >= MAX_BYTES) return { ok: true, kept: false };
56
64
  const len = Math.min(pcm.length, MAX_BYTES - at);
57
65
  fs.mkdirSync(dirOf(runtimeDir), { recursive: true });
58
- const fd = fs.openSync(f, fs.existsSync(f) ? 'r+' : 'w+', 0o600);
59
- try {
60
- const old = Buffer.alloc(len);
61
- fs.readSync(fd, old, 0, len, at);
62
- const out = Buffer.alloc(len);
63
- for (let i = 0; i < len; i += 2) out.writeInt16LE(Math.max(-32768, Math.min(32767, old.readInt16LE(i) + pcm.readInt16LE(i))), i);
64
- fs.writeSync(fd, out, 0, len, at);
65
- } finally { fs.closeSync(fd); }
66
+ if (mixed) {
67
+ const fd = fs.openSync(f, fs.existsSync(f) ? 'r+' : 'w+', 0o600);
68
+ try {
69
+ const old = Buffer.alloc(len);
70
+ fs.readSync(fd, old, 0, len, at);
71
+ const out = Buffer.alloc(len);
72
+ for (let i = 0; i < len; i += 2) out.writeInt16LE(Math.max(-32768, Math.min(32767, old.readInt16LE(i) + pcm.readInt16LE(i))), i);
73
+ fs.writeSync(fd, out, 0, len, at);
74
+ } finally { fs.closeSync(fd); }
75
+ }
76
+ if (SOURCES.includes(source)) {
77
+ const sf = sourceFileOf(runtimeDir, id, source);
78
+ const sd = fs.openSync(sf, fs.existsSync(sf) ? 'r+' : 'w+', 0o600);
79
+ try { fs.writeSync(sd, pcm, 0, len, at); } finally { fs.closeSync(sd); }
80
+ }
66
81
  next.set(key, at + len);
67
82
  return { ok: true, kept: true, at_ms: at / BYTES_PER_MS };
68
83
  }
@@ -71,11 +86,26 @@ function info(runtimeDir, id) {
71
86
  if (!ID_RE.test(String(id || ''))) return null;
72
87
  try { const st = fs.statSync(fileOf(runtimeDir, id)); return st.size ? { bytes: st.size, ms: Math.round(st.size / BYTES_PER_MS) } : null; } catch { return null; }
73
88
  }
89
+ function removeSources(runtimeDir, id) {
90
+ if (!ID_RE.test(String(id || ''))) return;
91
+ for (const src of SOURCES) { try { fs.unlinkSync(sourceFileOf(runtimeDir, id, src)); } catch { /* none */ } }
92
+ }
74
93
  function remove(runtimeDir, id) {
75
94
  if (!ID_RE.test(String(id || ''))) return false;
76
95
  for (const k of [...next.keys()]) if (k.startsWith(fileOf(runtimeDir, id) + '|')) next.delete(k);
96
+ for (const src of SOURCES) { try { fs.unlinkSync(sourceFileOf(runtimeDir, id, src)); } catch { /* none */ } }
77
97
  try { fs.unlinkSync(fileOf(runtimeDir, id)); return true; } catch { return false; }
78
98
  }
99
+ /** The note's audio, one file per source: [{ source, file, bytes, ms }], the sources that were heard. */
100
+ function sources(runtimeDir, id) {
101
+ if (!ID_RE.test(String(id || ''))) return [];
102
+ const out = [];
103
+ for (const source of SOURCES) {
104
+ const file = sourceFileOf(runtimeDir, id, source);
105
+ try { const st = fs.statSync(file); if (st.size) out.push({ source, file, bytes: st.size, ms: Math.round(st.size / BYTES_PER_MS) }); } catch { /* not heard */ }
106
+ }
107
+ return out;
108
+ }
79
109
 
80
110
  function wavHeader(dataBytes) {
81
111
  const h = Buffer.alloc(44);
@@ -108,4 +138,4 @@ function serve(req, res, runtimeDir, id) {
108
138
  fs.createReadStream(fileOf(runtimeDir, id), { start: from, end: to }).on('error', () => res.end()).pipe(res);
109
139
  }
110
140
 
111
- module.exports = { write, info, remove, serve, getKeep, setKeep, wavHeader, RATE, BYTES_PER_MS, MAX_BYTES };
141
+ module.exports = { write, info, remove, removeSources, sources, serve, getKeep, setKeep, wavHeader, RATE, BYTES_PER_MS, MAX_BYTES };
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env python3
2
+ """notes-diarize.py: who spoke when in one audio file, on this machine (meeting-notes Run 9).
3
+
4
+ python3 notes-diarize.py --segmentation <model.onnx> --embedding <model.onnx> --wav <file.wav> [--speakers N]
5
+
6
+ The WAV is 16 kHz mono 16-bit. Prints one JSON object to stdout:
7
+ {"ok": true, "segments": [{"start": 0.5, "end": 3.2, "speaker": 0}, ...]}
8
+ or {"ok": false, "error": "..."} with exit code 1.
9
+
10
+ It uses sherpa-onnx's offline speaker diarization (a pyannote segmentation model and a speaker embedding model,
11
+ clustered). It reads no network and writes no file. lib/notes-final.js runs it after Stop, one file at a time.
12
+ """
13
+ import argparse
14
+ import json
15
+ import sys
16
+ import wave
17
+
18
+
19
+ def fail(msg):
20
+ print(json.dumps({"ok": False, "error": msg}))
21
+ sys.exit(1)
22
+
23
+
24
+ def main():
25
+ ap = argparse.ArgumentParser()
26
+ ap.add_argument("--segmentation", required=True)
27
+ ap.add_argument("--embedding", required=True)
28
+ ap.add_argument("--wav", required=True)
29
+ ap.add_argument("--speakers", type=int, default=0, help="the number of speakers when known, else 0")
30
+ ap.add_argument("--threshold", type=float, default=0.5, help="clustering threshold when the number is not known")
31
+ a = ap.parse_args()
32
+ try:
33
+ import numpy as np
34
+ import sherpa_onnx
35
+ except Exception as e: # noqa: BLE001
36
+ fail("sherpa-onnx is not installed: " + str(e))
37
+ try:
38
+ with wave.open(a.wav, "rb") as w:
39
+ if w.getframerate() != 16000 or w.getnchannels() != 1 or w.getsampwidth() != 2:
40
+ fail("the audio must be 16 kHz mono 16-bit")
41
+ samples = np.frombuffer(w.readframes(w.getnframes()), dtype=np.int16).astype(np.float32) / 32768.0
42
+ except wave.Error as e:
43
+ fail("cannot read the audio: " + str(e))
44
+ config = sherpa_onnx.OfflineSpeakerDiarizationConfig(
45
+ segmentation=sherpa_onnx.OfflineSpeakerSegmentationModelConfig(
46
+ pyannote=sherpa_onnx.OfflineSpeakerSegmentationPyannoteModelConfig(model=a.segmentation)),
47
+ embedding=sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=a.embedding),
48
+ clustering=sherpa_onnx.FastClusteringConfig(num_clusters=a.speakers if a.speakers > 0 else -1, threshold=a.threshold),
49
+ min_duration_on=0.3,
50
+ min_duration_off=0.5,
51
+ )
52
+ if not config.validate():
53
+ fail("the diarization models are missing or do not load")
54
+ sd = sherpa_onnx.OfflineSpeakerDiarization(config)
55
+ result = sd.process(samples).sort_by_start_time()
56
+ segs = [{"start": round(r.start, 2), "end": round(r.end, 2), "speaker": int(r.speaker)} for r in result]
57
+ print(json.dumps({"ok": True, "segments": segs}))
58
+
59
+
60
+ if __name__ == "__main__":
61
+ main()