Skip to content

Build your personal knowledge base with Trilium Notes

feat(transcription): split an utterance where the speaker changes

Elian Doran04310df6a4ce
diff --git a/.claude/skills/working-with-transcription/SKILL.md b/.claude/skills/working-with-transcription/SKILL.md
index f4b6ca3183..a33e281d21 100644
--- a/.claude/skills/working-with-transcription/SKILL.md
+++ b/.claude/skills/working-with-transcription/SKILL.md
@@ -19,7 +19,8 @@ capture window (hidden, offscreen) transcription process (Electron
per source: SourcePipeline → VadSegmenter (Silero, 512-sample windows)
│ utterances
one queue: recognizer.transcribe() (Parakeet TDT 0.6B v3, fp32 or int8, libuv pool)
- │ speaker: EmbeddingSpeakerTracker (TitaNet, synchronous)
+ │ speakers: EmbeddingSpeakerTracker (TitaNet, synchronous),
+ │ splits an utterance at a change of speaker
sinks: posted to the main process, dev: TranscriptFileSink
│ parentPort: ready / pending / utterance / log / stopped
main process: TranscriptionWorker → AttachmentSink (transcript attachment)
@@ -125,7 +126,11 @@ The export has errors of its own (it wrote "MicroEdge" and "SortMap", and split
## Speaker detection
-The app labels the system source's utterances live when `speaker/nemo_en_titanet_small.onnx` is installed: `EmbeddingSpeakerTracker` in `engine.ts` embeds each transcribed utterance and `SpeakerClusterer` (`speakers.ts`, settings `SPEAKER_SETTINGS`) assigns it, giving the utterance a `speaker` number that `TranscriptView` shows as "Speaker n". The microphone is never labelled. It runs synchronously in the transcription process, ~15–100 ms per utterance, holding back the next chunks but nothing else. `replay.mjs` does not label speakers; use `diarize.mjs`.
+The app labels the system source's utterances live when `speaker/nemo_en_titanet_small.onnx` is installed: `EmbeddingSpeakerTracker` in `engine.ts` embeds each transcribed utterance and `SpeakerClusterer` (`speakers.ts`, settings `SPEAKER_SETTINGS`) assigns it, giving the utterance a `speaker` number that `TranscriptView` shows as "Speaker n". The microphone is never labelled. It runs synchronously in the transcription process, holding back the next chunks but nothing else. `replay.mjs` does not label speakers; use `diarize.mjs`.
+
+**Turns within an utterance** (`TURN_SETTINGS`): a VAD segment holds both sides of a quick exchange, since a reply needs no 0.75 s pause. Once a speaker is known, an utterance of 4 s or more is embedded again in 2 s windows 1 s apart, each matched against the known speakers (`SpeakerClusterer.match()`, which moves no centroid); where another label holds for two windows (`findSpeakerChanges()`), the utterance is cut half a second into the new run, moved to the nearest word start within 1 s, preferring one after a sentence end (`snapToWordBoundary()`, on the token times Parakeet returns with `transcribe()`). `RecordingSession` writes each turn as an utterance of its own, its text the words starting in it. That costs one embedding per second of a long utterance, ~0.1–0.3 s for a 20 s one.
+
+On the 67-minute meeting of 2026-10-15 (two people on the system track), scored per second against voice prints of the two named speakers: 7.3% of the speech had the wrong or no speaker before turns, 2.7% after (two speakers, 502 → 560 utterances). The reference was built with the same model and similar windows, so the gain is likely overstated; the cuts read right in the text ("…for us? | Yes, but…", "Have a nice day. | Thank you. Have a nice day. Bye.").
`diarize.mjs` labels one source's utterances by speaker in two ways and times both:
@@ -215,7 +220,7 @@ node $S/worker-test.mjs latest # 120 s of system.wav at
node $S/worker-test.mjs latest --source microphone --seconds 60 --speed 8
```
-`worker-test.mjs` runs the real `TranscriptionWorker` in Electron: it starts the transcription process on `apps/desktop/data/transcription-model`, and a hidden page posts a recording's WAV through a `MessageChannelMain` port as the capture page does. It prints the engine's load time, the utterances (with speakers), how long `stop` took and whether the process exited, and the main process's event-loop lag throughout. On two minutes of a meeting's system track: ready after 1.3 s, lag p50 0.1 ms, p99 1.1 ms, max 25 ms. Before the split, speaker labelling alone held the main thread 15–100 ms per utterance.
+`worker-test.mjs` runs the real `TranscriptionWorker` in Electron: it starts the transcription process on `apps/desktop/data/transcription-model` (or `--model`, writing the utterances to `--out`), and a hidden page posts a recording's WAV through a `MessageChannelMain` port as the capture page does. It prints the engine's load time, the utterances (with speakers), how long `stop` took and whether the process exited, and the main process's event-loop lag throughout. On two minutes of a meeting's system track: ready after 1.3 s, lag p50 0.1 ms, p99 1.1 ms, max 25 ms. Before the split, speaker labelling alone held the main thread 15–100 ms per utterance. On Windows, Electron launched by it prints nothing and runs into the timeout (unresolved); there, `RecordingSession` and `loadSherpaEngine()` can be driven in plain Node with `node --import tsx` instead, feeding the WAV in 4096-sample chunks, which tests everything but the process boundary.
In development the process loads `transcription_worker.ts` through the `NODE_OPTIONS="--import tsx"` it inherits from `scripts/electron-start.mts`; built, `worker_client.ts` finds `transcription_worker.cjs` beside `main.mjs`. Packaged builds do not ship `sherpa-onnx-node` yet (it is external to every bundle, but not copied or unpacked from the asar).
diff --git a/.claude/skills/working-with-transcription/worker-test.mjs b/.claude/skills/working-with-transcription/worker-test.mjs
index db7721b9ac..7a1ff357b4 100644
--- a/.claude/skills/working-with-transcription/worker-test.mjs
+++ b/.claude/skills/working-with-transcription/worker-test.mjs
@@ -10,15 +10,18 @@
// --source <name> which WAV of the recording to play, default system
// --seconds <n> how much of it, default 120
// --speed <n> how much faster than real time to post it, default 4
+// --model <dir> the model directory, default apps/desktop/data/transcription-model
+// --out <file> writes the utterances there, in the transcript format
//
-// The model directory is apps/desktop/data/transcription-model. Like `pnpm desktop:start`, it
-// loads the TypeScript through NODE_OPTIONS="--import tsx", which the utility process inherits.
+// Like `pnpm desktop:start`, it loads the TypeScript through NODE_OPTIONS="--import tsx", which
+// the utility process inherits.
import { execFileSync } from "node:child_process";
import fs from "node:fs";
+import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
-import { fileURLToPath } from "node:url";
+import { fileURLToPath, pathToFileURL } from "node:url";
import { parseArgs, resolveRecording } from "./recordings.mjs";
@@ -50,9 +53,11 @@ async function launch() {
wav: path.join(recording.directory, file),
source,
seconds: Number(options.seconds ?? 120),
- speed: Number(options.speed ?? 4)
+ speed: Number(options.speed ?? 4),
+ model: path.resolve(options.model ?? MODEL_DIR),
+ out: options.out ? path.resolve(options.out) : null
};
- const { getElectronPath, getNixLdLibraryPath, isNixOS } = await import(path.join(REPO, "scripts/utils.mts"));
+ const { getElectronPath, getNixLdLibraryPath, isNixOS } = await import(pathToFileURL(path.join(REPO, "scripts/utils.mts")).href);
const env = {
...process.env,
LD_LIBRARY_PATH: isNixOS() ? getNixLdLibraryPath() : process.env.LD_LIBRARY_PATH,
@@ -62,7 +67,12 @@ async function launch() {
delete env.ELECTRON_RUN_AS_NODE;
console.log(`${config.seconds} s of ${config.wav}, ${config.speed}× real time\n`);
- const output = execFileSync(getElectronPath(), [ SELF, "--no-sandbox" ], {
+ // Off NixOS, getElectronPath() returns the bare `electron` command, which only a shell
+ // resolves; the package itself exports the binary's path.
+ const electron = isNixOS()
+ ? getElectronPath()
+ : createRequire(path.join(DESKTOP, "package.json"))("electron");
+ const output = execFileSync(electron, [ SELF, "--no-sandbox" ], {
cwd: DESKTOP,
env,
encoding: "utf8",
@@ -92,7 +102,7 @@ async function launch() {
async function runInElectron(config) {
const { app, BrowserWindow, MessageChannelMain } = await import("electron");
const { TranscriptionWorker } = await import(
- path.join(DESKTOP, "src/services/transcription/worker_client.ts"));
+ pathToFileURL(path.join(DESKTOP, "src/services/transcription/worker_client.ts")).href);
await app.whenReady();
const utterances = [];
@@ -115,9 +125,9 @@ async function runInElectron(config) {
});
const startedAt = performance.now();
const models = {
- recognizer: MODEL_DIR,
- vad: path.join(MODEL_DIR, "silero_vad.onnx"),
- speaker: path.join(MODEL_DIR, "speaker", "nemo_en_titanet_small.onnx")
+ recognizer: config.model,
+ vad: path.join(config.model, "silero_vad.onnx"),
+ speaker: path.join(config.model, "speaker", "nemo_en_titanet_small.onnx")
};
await worker.start({ noteId: "worker-test", models, recordingDirectory: null });
const readyMs = Math.round(performance.now() - startedAt);
@@ -146,6 +156,9 @@ async function runInElectron(config) {
const stopMs = Math.round(performance.now() - stopAt);
exited = true;
fs.rmSync(pagePath, { force: true });
+ if (config.out) {
+ fs.writeFileSync(config.out, JSON.stringify({ version: 1, startedAt: Date.now(), utterances }));
+ }
finish({
readyMs,
chunks,
diff --git a/apps/desktop/src/services/transcription/engine.spec.ts b/apps/desktop/src/services/transcription/engine.spec.ts
index 6bf3b4c7f6..c280479222 100644
--- a/apps/desktop/src/services/transcription/engine.spec.ts
+++ b/apps/desktop/src/services/transcription/engine.spec.ts
@@ -11,7 +11,9 @@ const h = vi.hoisted(() => ({
extractorConfig: null as Record<string, unknown> | null,
decoded: [] as Float32Array[],
isEmbeddingReady: true,
- embeddings: [] as number[][]
+ embeddings: [] as number[][],
+ /** The length of each stretch of samples a speaker embedding was computed from. */
+ embedded: [] as number[]
}));
/** Silero as the segmenter sees it: windows in, then whatever segments the spec queues. */
@@ -63,7 +65,11 @@ vi.mock("sherpa-onnx-node", () => ({
}),
decodeAsync: async (stream: { samples: Float32Array }) => {
h.decoded.push(stream.samples);
- return { text: " Hello there. " };
+ return {
+ text: " Hello there. ",
+ tokens: [ " Hel", "lo", " there", "." ],
+ timestamps: [ 0, 0.16, 0.4, 0.72 ]
+ };
}
};
}
@@ -74,7 +80,12 @@ vi.mock("sherpa-onnx-node", () => ({
h.extractorConfig = config;
}
createStream() {
- return { acceptWaveform: vi.fn(), inputFinished: vi.fn() };
+ return {
+ acceptWaveform: ({ samples }: { samples: Float32Array }) => {
+ h.embedded.push(samples.length);
+ },
+ inputFinished: vi.fn()
+ };
}
isReady() {
return h.isEmbeddingReady;
@@ -102,6 +113,7 @@ beforeEach(() => {
h.isEmbeddingReady = true;
h.decoded.length = 0;
h.embeddings.length = 0;
+ h.embedded.length = 0;
vads.length = 0;
});
@@ -133,7 +145,10 @@ describe("loadSherpaEngine", () => {
});
const samples = new Float32Array(1600);
- expect(await engine.recognizer.transcribe(samples)).toBe("Hello there.");
+ expect(await engine.recognizer.transcribe(samples)).toEqual({
+ text: "Hello there.",
+ words: [ { text: "Hello", startSeconds: 0 }, { text: "there.", startSeconds: 0.4 } ]
+ });
expect(h.decoded).toEqual([ samples ]);
});
@@ -185,16 +200,41 @@ describe("loadSherpaEngine", () => {
expect(h.extractorConfig?.model).toBe(MODELS.speaker);
expect(engine.settings.speakers).toMatchObject({
model: "nemo_en_titanet_small.onnx", threshold: 0.5, minDurationSeconds: 1.5,
- newSpeakerMinDurationSeconds: 5, shortThreshold: 0.3
+ newSpeakerMinDurationSeconds: 5, shortThreshold: 0.3,
+ turns: { windowSeconds: 2, hopSeconds: 1, minSegmentSeconds: 4, minTurnSeconds: 1 }
});
const tracker = engine.createSpeakerTracker?.();
- const long = new Float32Array(16000 * 6);
- h.embeddings.push([ 1, 0 ], [ 0, 1 ], [ 0.9, 0.1 ]);
- expect([ 1, 2, 3 ].map(() => tracker?.identify(long))).toEqual([ 1, 2, 1 ]);
+ // No speaker is known yet, so the utterance is not searched for a change.
+ h.embeddings.push([ 1, 0 ]);
+ expect(tracker?.identify(new Float32Array(16000 * 6), []))
+ .toEqual([ { startSeconds: 0, endSeconds: 6, speaker: 1 } ]);
+ expect(h.embedded).toEqual([ 16000 * 6 ]);
+
+ // Nine 2 s windows: speaker 1 for two, then an unknown voice; the cut at 2.5 s moves to
+ // the sentence starting at 2.2 s, and each turn is identified on its own.
+ h.embedded.length = 0;
+ h.embeddings.push([ 1, 0 ], [ 1, 0 ], ...Array(7).fill([ 0, 1 ]), [ 1, 0 ], [ 0, 1 ]);
+ const words = [
+ { text: "Is it?", startSeconds: 0 },
+ { text: "Yes", startSeconds: 2.2 },
+ { text: "indeed.", startSeconds: 2.9 }
+ ];
+ expect(tracker?.identify(new Float32Array(16000 * 10), words)).toEqual([
+ { startSeconds: 0, endSeconds: 2.2, speaker: 1 },
+ { startSeconds: 2.2, endSeconds: 10, speaker: 2 }
+ ]);
+ expect(h.embedded).toEqual([ ...Array(9).fill(32000), 35200, 124800 ]);
+
+ // Shorter than 4 s: one turn, without windows.
+ h.embeddings.push([ 0.9, 0.1 ]);
+ expect(tracker?.identify(new Float32Array(16000 * 3), []))
+ .toEqual([ { startSeconds: 0, endSeconds: 3, speaker: 1 } ]);
+ expect(h.embeddings).toEqual([]);
h.isEmbeddingReady = false;
- expect(tracker?.identify(new Float32Array(100))).toBeNull();
+ expect(tracker?.identify(new Float32Array(1600), []))
+ .toEqual([ { startSeconds: 0, endSeconds: 0.1, speaker: null } ]);
const withoutSpeakers = await loadSherpaEngine({ ...MODELS, speaker: null });
expect(withoutSpeakers.createSpeakerTracker).toBeUndefined();
diff --git a/apps/desktop/src/services/transcription/engine.ts b/apps/desktop/src/services/transcription/engine.ts
index f56fc20fab..ece89b9857 100644
--- a/apps/desktop/src/services/transcription/engine.ts
+++ b/apps/desktop/src/services/transcription/engine.ts
@@ -3,11 +3,20 @@ import path from "path";
import type { SpeakerEmbeddingExtractor, Vad } from "sherpa-onnx-node";
import { type ModelPaths, SAMPLE_RATE } from "./protocol";
-import { SpeakerClusterer, type SpeakerClustererOptions } from "./speakers";
+import {
+ findSpeakerChanges, SpeakerClusterer, type SpeakerClustererOptions, type SpeakerTurn,
+ snapToWordBoundary, type TimedWord
+} from "./speakers";
+
+/** The text of an utterance and when each of its words starts. */
+export interface Recognition {
+ text: string;
+ words: TimedWord[];
+}
/** Turns one utterance into text. */
export interface SpeechRecognizer {
- transcribe(samples: Float32Array): Promise<string>;
+ transcribe(samples: Float32Array): Promise<Recognition>;
}
/** A stretch of speech found in a source, `start` counted in samples from the source's start. */
@@ -29,10 +38,10 @@ export interface SpeechSegmenter {
/** Tells the speakers of one source apart. Each source needs its own. */
export interface SpeakerTracker {
/**
- * Returns the speaker of an utterance, numbered from 1 in the order they were first heard, or
- * `null` when the utterance is too short to tell.
+ * Returns the turns of an utterance in order, covering it whole, each with its speaker
+ * numbered from 1 in the order they were first heard. `words` places the cuts between turns.
*/
- identify(samples: Float32Array): number | null;
+ identify(samples: Float32Array, words: TimedWord[]): SpeakerTurn[];
}
export interface SpeechEngine {
@@ -73,6 +82,17 @@ const SPEAKER_SETTINGS: SpeakerClustererOptions = {
shortThreshold: 0.3
};
+/**
+ * An utterance of `minSegmentSeconds` or more is searched for a change of speaker in windows of
+ * `windowSeconds`, `hopSeconds` apart; a turn shorter than `minTurnSeconds` is not split off.
+ */
+const TURN_SETTINGS = {
+ windowSeconds: 2,
+ hopSeconds: 1,
+ minSegmentSeconds: 4,
+ minTurnSeconds: 1
+};
+
const VAD_SETTINGS = {
threshold: 0.5,
minSilenceDuration: 0.75,
@@ -125,7 +145,8 @@ export async function loadSherpaEngine(models: ModelPaths): Promise<SpeechEngine
async transcribe(samples) {
const stream = recognizer.createStream();
stream.acceptWaveform({ samples, sampleRate: SAMPLE_RATE });
- return (await recognizer.decodeAsync(stream)).text.trim();
+ const result = await recognizer.decodeAsync(stream);
+ return { text: result.text.trim(), words: toWords(result.tokens, result.timestamps) };
}
},
createSegmenter: () => new VadSegmenter(new sherpa.Vad({
@@ -146,7 +167,7 @@ export async function loadSherpaEngine(models: ModelPaths): Promise<SpeechEngine
recognizer: { ...RECOGNIZER_SETTINGS, ...decodingSettings },
vad: VAD_SETTINGS,
speakers: speakerModel
- ? { model: path.basename(speakerModel), ...SPEAKER_SETTINGS }
+ ? { model: path.basename(speakerModel), ...SPEAKER_SETTINGS, turns: TURN_SETTINGS }
: null
}
};
@@ -183,8 +204,9 @@ class VadSegmenter implements SpeechSegmenter {
}
/**
- * Identifies speakers by clustering TitaNet embeddings. The embedding is computed synchronously,
- * about 100 ms per utterance on one thread.
+ * Identifies speakers by clustering TitaNet embeddings, and splits an utterance where the speaker
+ * changes within it. Embeddings are computed synchronously, about 10–100 ms each on one thread:
+ * one per turn, plus one per window of an utterance searched for a change.
*/
class EmbeddingSpeakerTracker implements SpeakerTracker {
private readonly clusterer: SpeakerClusterer;
@@ -196,15 +218,70 @@ class EmbeddingSpeakerTracker implements SpeakerTracker {
this.clusterer = new SpeakerClusterer(options);
}
- identify(samples: Float32Array) {
+ identify(samples: Float32Array, words: TimedWord[]) {
+ const durationSeconds = samples.length / SAMPLE_RATE;
+ const bounds = [ 0, ...this.findTurnChanges(samples, words), durationSeconds ];
+ return bounds.slice(1).map((endSeconds, index) => {
+ const startSeconds = bounds[index];
+ const embedding = this.embed(samples, startSeconds, endSeconds);
+ const speaker = embedding
+ ? this.clusterer.assign(embedding, endSeconds - startSeconds)
+ : null;
+ return { startSeconds, endSeconds, speaker };
+ });
+ }
+
+ /** Returns the times, in seconds, at which another known or unknown speaker takes over. */
+ private findTurnChanges(samples: Float32Array, words: TimedWord[]) {
+ const { windowSeconds, hopSeconds, minSegmentSeconds, minTurnSeconds } = TURN_SETTINGS;
+ const durationSeconds = samples.length / SAMPLE_RATE;
+ if (durationSeconds < minSegmentSeconds || !this.clusterer.hasSpeakers) {
+ return [];
+ }
+
+ const labels: (number | null)[] = [];
+ for (let start = 0; start + windowSeconds <= durationSeconds; start += hopSeconds) {
+ const embedding = this.embed(samples, start, start + windowSeconds);
+ labels.push(embedding ? this.clusterer.match(embedding) : null);
+ }
+ const cuts: number[] = [];
+ for (const window of findSpeakerChanges(labels)) {
+ // The first window of the new run is mostly the new speaker, the one before it mostly
+ // the previous one, so the change falls in the first hop of the new run's window.
+ const cut = snapToWordBoundary(window * hopSeconds + hopSeconds / 2, words);
+ if (cut - (cuts.at(-1) ?? 0) >= minTurnSeconds && durationSeconds - cut >= minTurnSeconds) {
+ cuts.push(cut);
+ }
+ }
+ return cuts;
+ }
+
+ private embed(samples: Float32Array, startSeconds: number, endSeconds: number) {
const stream = this.extractor.createStream();
- stream.acceptWaveform({ samples, sampleRate: SAMPLE_RATE });
+ stream.acceptWaveform({
+ samples: samples.subarray(
+ Math.round(startSeconds * SAMPLE_RATE), Math.round(endSeconds * SAMPLE_RATE)),
+ sampleRate: SAMPLE_RATE
+ });
stream.inputFinished();
if (!this.extractor.isReady(stream)) {
return null;
}
// Electron's V8 memory cage rejects the external buffers sherpa-onnx uses by default.
- const embedding = this.extractor.compute(stream, false);
- return this.clusterer.assign(embedding, samples.length / SAMPLE_RATE);
+ return this.extractor.compute(stream, false);
+ }
+}
+
+/** Joins Parakeet's tokens into words; a token that starts with a space starts a word. */
+function toWords(tokens: string[], timestamps: number[]): TimedWord[] {
+ const words: TimedWord[] = [];
+ for (const [ index, token ] of tokens.entries()) {
+ const last = words.at(-1);
+ if (token.startsWith(" ") || !last) {
+ words.push({ text: token.trim(), startSeconds: timestamps[index] });
+ } else {
+ last.text += token;
+ }
}
+ return words.filter(({ text }) => text);
}
diff --git a/apps/desktop/src/services/transcription/session.spec.ts b/apps/desktop/src/services/transcription/session.spec.ts
index dde412a779..4f8efe7b99 100644
--- a/apps/desktop/src/services/transcription/session.spec.ts
+++ b/apps/desktop/src/services/transcription/session.spec.ts
@@ -43,8 +43,15 @@ function createHarness(extraSinks: TranscriptSink[] = [], taps: AudioTap[] = [])
const engine = {
settings: {},
recognizer: {
- transcribe: vi.fn(async (samples: Float32Array) =>
- samples[0] ? `utterance ${samples[0]}` : "")
+ transcribe: vi.fn(async (samples: Float32Array) => samples[0]
+ ? {
+ text: `utterance ${samples[0]}`,
+ words: [
+ { text: "utterance", startSeconds: 0 },
+ { text: String(samples[0]), startSeconds: 0.6 }
+ ]
+ }
+ : { text: "", words: [] })
},
createSpeakerTracker: undefined as (() => SpeakerTracker) | undefined,
createSegmenter: vi.fn(() => {
@@ -170,7 +177,7 @@ describe("RecordingSession", () => {
const { session, engine, sink, deliver, onPendingChanged } = createHarness();
let finishTranscribing = () => {};
engine.recognizer.transcribe.mockImplementationOnce(() => new Promise((resolve) => {
- finishTranscribing = () => resolve("utterance 1");
+ finishTranscribing = () => resolve({ text: "utterance 1", words: [] });
}));
await session.start();
@@ -208,7 +215,7 @@ describe("RecordingSession", () => {
it("labels the system source's utterances by speaker, never the microphone's", async () => {
const { session, engine, deliver, written } = createHarness();
const identify = vi.fn()
- .mockReturnValueOnce(2)
+ .mockReturnValueOnce([ { startSeconds: 0, endSeconds: 1, speaker: 2 } ])
.mockImplementationOnce(() => {
throw new Error("model crashed");
});
@@ -235,6 +242,30 @@ describe("RecordingSession", () => {
"Transcription: identifying the speaker on system failed: Error: model crashed");
});
+ it("writes each speaker's turn within an utterance as an utterance of its own", async () => {
+ const { session, engine, deliver, written } = createHarness();
+ const identify = vi.fn(() => [
+ { startSeconds: 0, endSeconds: 0.5, speaker: 1 },
+ { startSeconds: 0.5, endSeconds: 0.55, speaker: null },
+ { startSeconds: 0.55, endSeconds: 1, speaker: 2 }
+ ]);
+ engine.createSpeakerTracker = () => ({ identify });
+ await session.start();
+
+ deliver("system", utteranceChunk(7, 16000), 3000);
+ await session.stop();
+
+ expect(identify).toHaveBeenCalledExactlyOnceWith(expect.any(Float32Array), [
+ { text: "utterance", startSeconds: 0 },
+ { text: "7", startSeconds: 0.6 }
+ ]);
+ // The middle turn holds no word, so it is left out.
+ expect(written).toEqual([
+ { source: "system", offsetMs: 2000, durationMs: 500, text: "utterance", speaker: 1 },
+ { source: "system", offsetMs: 2550, durationMs: 450, text: "7", speaker: 2 }
+ ]);
+ });
+
it("logs each source's peak level every 5 s, to spot a silent source", async () => {
const { session, deliver } = createHarness();
await session.start();
diff --git a/apps/desktop/src/services/transcription/session.ts b/apps/desktop/src/services/transcription/session.ts
index ac436ae5a8..22b8c6a3ca 100644
--- a/apps/desktop/src/services/transcription/session.ts
+++ b/apps/desktop/src/services/transcription/session.ts
@@ -3,6 +3,7 @@ import type { MessagePortMain } from "electron";
import type { SpeakerTracker, SpeechEngine, SpeechSegment, SpeechSegmenter } from "./engine";
import { type CaptureMessage, type Logger, SAMPLE_RATE } from "./protocol";
+import type { TimedWord } from "./speakers";
/** The sources whose speakers are told apart; the microphone carries only the local speaker. */
const DIARIZED_SOURCES: readonly TranscriptSource[] = [ "system" ];
@@ -155,21 +156,36 @@ export class RecordingSession {
private enqueue(source: TranscriptSource, offsetMs: number, samples: Float32Array) {
this.queued.set(source, (this.queued.get(source) ?? 0) + 1);
this.queue = this.queue.then(async () => {
- const text = await this.options.engine.recognizer.transcribe(samples);
+ const { text, words } = await this.options.engine.recognizer.transcribe(samples);
if (!text) {
return;
}
const durationMs = samples.length / SAMPLE_RATE * 1000;
- const speaker = this.identifySpeaker(source, samples);
- const utterance = {
- source, offsetMs, durationMs, text, ...(speaker === null ? {} : { speaker })
- };
- for (const sink of this.options.sinks) {
- try {
- await sink.write(utterance);
- } catch (e) {
- this.log.error(`Transcription: a sink failed: ${e}`);
+ const turns = this.identifySpeakers(source, samples, words);
+ const utterances: TranscriptUtterance[] = turns && turns.length > 1
+ ? turns.map((turn) => ({
+ source,
+ offsetMs: offsetMs + Math.round(turn.startSeconds * 1000),
+ durationMs: Math.round((turn.endSeconds - turn.startSeconds) * 1000),
+ text: words
+ .filter(({ startSeconds }) =>
+ startSeconds >= turn.startSeconds && startSeconds < turn.endSeconds)
+ .map((word) => word.text)
+ .join(" "),
+ ...(turn.speaker === null ? {} : { speaker: turn.speaker })
+ })).filter((utterance) => utterance.text)
+ : [ {
+ source, offsetMs, durationMs, text,
+ ...(turns?.[0]?.speaker == null ? {} : { speaker: turns[0].speaker })
+ } ];
+ for (const utterance of utterances) {
+ for (const sink of this.options.sinks) {
+ try {
+ await sink.write(utterance);
+ } catch (e) {
+ this.log.error(`Transcription: a sink failed: ${e}`);
+ }
}
}
}).catch((e) => this.log.error(`Transcription failed: ${e}`)).finally(() => {
@@ -178,10 +194,13 @@ export class RecordingSession {
});
}
- /** Runs synchronously, about 100 ms per utterance, so the next chunks wait meanwhile. */
- private identifySpeaker(source: TranscriptSource, samples: Float32Array) {
+ /**
+ * Returns the speakers' turns of an utterance, or `null` for a source without speakers. Runs
+ * synchronously, 0.1–0.3 s per utterance, so the next chunks wait meanwhile.
+ */
+ private identifySpeakers(source: TranscriptSource, samples: Float32Array, words: TimedWord[]) {
try {
- return this.speakerTrackers.get(source)?.identify(samples) ?? null;
+ return this.speakerTrackers.get(source)?.identify(samples, words) ?? null;
} catch (e) {
this.log.error(`Transcription: identifying the speaker on ${source} failed: ${e}`);
return null;
diff --git a/apps/desktop/src/services/transcription/speakers.spec.ts b/apps/desktop/src/services/transcription/speakers.spec.ts
index 474985353e..791fae3156 100644
--- a/apps/desktop/src/services/transcription/speakers.spec.ts
+++ b/apps/desktop/src/services/transcription/speakers.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { SpeakerClusterer } from "./speakers";
+import { findSpeakerChanges, SpeakerClusterer, snapToWordBoundary } from "./speakers";
const options = {
threshold: 0.5,
@@ -63,4 +63,58 @@ describe("SpeakerClusterer", () => {
// Cosine 0.28 with [1, 0] alone; 0.68 with the moved centroid.
expect(clusterer.assign(new Float32Array([ 0.28, 0.96 ]), 6)).toBe(1);
});
+
+ it("matches an embedding to a known speaker without changing any", () => {
+ const clusterer = new SpeakerClusterer(options);
+ expect(clusterer.match(new Float32Array([ 1, 0 ]))).toBeNull();
+ clusterer.assign(new Float32Array([ 1, 0 ]), 6);
+
+ expect(clusterer.match(new Float32Array([ 0.6, 0.8 ]))).toBe(1);
+ expect(clusterer.match(new Float32Array([ 0.28, 0.96 ]))).toBeNull();
+ // The match above left the centroid at [1, 0], so a new speaker starts here.
+ expect(clusterer.assign(new Float32Array([ 0.28, 0.96 ]), 6)).toBe(2);
+ });
+});
+
+describe("findSpeakerChanges", () => {
+ it("returns where a different label starts a run of at least two windows", () => {
+ expect(findSpeakerChanges([ 1, 1, 1, 1 ])).toEqual([]);
+ expect(findSpeakerChanges([ 1, 1, 2, 2, 2 ])).toEqual([ 2 ]);
+ expect(findSpeakerChanges([ 1, 2, 2, 1, 1 ])).toEqual([ 1, 3 ]);
+ expect(findSpeakerChanges([ 1, null, null, 1 ])).toEqual([ 1 ]);
+ });
+
+ it("ignores a different label that holds for one window only", () => {
+ expect(findSpeakerChanges([ 1, 2, 1, 1, null, 1 ])).toEqual([]);
+ expect(findSpeakerChanges([ 1, 1, 2, 1, 2, 2 ])).toEqual([ 4 ]);
+ });
+});
+
+describe("snapToWordBoundary", () => {
+ const words = [
+ { text: "Yeah,", startSeconds: 0 },
+ { text: "for", startSeconds: 1.44 },
+ { text: "us?", startSeconds: 1.6 },
+ { text: "Yes,", startSeconds: 1.84 },
+ { text: "but", startSeconds: 2.16 },
+ { text: "in", startSeconds: 2.32 },
+ { text: "the", startSeconds: 2.48 },
+ { text: "test", startSeconds: 2.8 },
+ { text: "what", startSeconds: 5 }
+ ];
+
+ it("prefers the start of a sentence within reach to a nearer word", () => {
+ expect(snapToWordBoundary(2.5, words)).toBe(1.84);
+ });
+
+ it("takes the nearest word start when no sentence starts within reach", () => {
+ expect(snapToWordBoundary(4.2, words)).toBe(5);
+ expect(snapToWordBoundary(3.7, words)).toBe(2.8);
+ });
+
+ it("keeps the cut where no word starts within reach", () => {
+ expect(snapToWordBoundary(10, words)).toBe(10);
+ // The first word's start is no boundary: nothing precedes it.
+ expect(snapToWordBoundary(0.3, words)).toBe(0.3);
+ });
});
diff --git a/apps/desktop/src/services/transcription/speakers.ts b/apps/desktop/src/services/transcription/speakers.ts
index f4b2d5e393..39629c8934 100644
--- a/apps/desktop/src/services/transcription/speakers.ts
+++ b/apps/desktop/src/services/transcription/speakers.ts
@@ -24,17 +24,19 @@ export class SpeakerClusterer {
constructor(private readonly options: SpeakerClustererOptions) {}
+ get hasSpeakers() {
+ return this.centroids.length > 0;
+ }
+
+ /** Returns the speaker an embedding reaches the threshold with, changing no speaker. */
+ match(embedding: Float32Array): number | null {
+ const { best, bestSimilarity } = this.nearest(normalize(embedding));
+ return best >= 0 && bestSimilarity >= this.options.threshold ? best + 1 : null;
+ }
+
assign(embedding: Float32Array, durationSeconds: number): number | null {
const normalized = normalize(embedding);
- let best = -1;
- let bestSimilarity = -Infinity;
- for (const [ index, centroid ] of this.centroids.entries()) {
- const similarity = dot(normalize(centroid), normalized);
- if (similarity > bestSimilarity) {
- best = index;
- bestSimilarity = similarity;
- }
- }
+ const { best, bestSimilarity } = this.nearest(normalized);
const isLongEnough = durationSeconds >= this.options.minDurationSeconds;
if (best >= 0 && bestSimilarity >= this.options.threshold) {
@@ -52,6 +54,74 @@ export class SpeakerClusterer {
}
return null;
}
+
+ private nearest(normalized: Float32Array) {
+ let best = -1;
+ let bestSimilarity = -Infinity;
+ for (const [ index, centroid ] of this.centroids.entries()) {
+ const similarity = dot(normalize(centroid), normalized);
+ if (similarity > bestSimilarity) {
+ best = index;
+ bestSimilarity = similarity;
+ }
+ }
+ return { best, bestSimilarity };
+ }
+}
+
+/** A word of a transcribed utterance, `startSeconds` counted from the utterance's start. */
+export interface TimedWord {
+ text: string;
+ startSeconds: number;
+}
+
+/** A stretch of an utterance spoken by one speaker, `null` when it is too short to tell. */
+export interface SpeakerTurn {
+ startSeconds: number;
+ endSeconds: number;
+ speaker: number | null;
+}
+
+/**
+ * Returns the indexes of the windows at which another label starts a run of `minRun` windows or
+ * more. `null` labels a window that matches no known speaker and counts as a label of its own.
+ */
+export function findSpeakerChanges(labels: (number | null)[], minRun = 2) {
+ const changes: number[] = [];
+ let current = labels[0];
+ let runStart = 0;
+ for (const [ index, label ] of labels.entries()) {
+ if (label !== labels[runStart]) {
+ runStart = index;
+ }
+ if (index - runStart + 1 === minRun && label !== current) {
+ changes.push(runStart);
+ current = label;
+ }
+ }
+ return changes;
+}
+
+/**
+ * Moves a cut to the start of a word within `reachSeconds`: the nearest one that follows a
+ * sentence end, else the nearest one. Keeps the cut where no word starts within reach.
+ */
+export function snapToWordBoundary(cutSeconds: number, words: TimedWord[], reachSeconds = 1) {
+ const boundaries = words.slice(1)
+ .map((word, index) => ({
+ seconds: word.startSeconds,
+ followsSentence: /[.?!]$/.test(words[index].text)
+ }))
+ .filter(({ seconds }) => Math.abs(seconds - cutSeconds) <= reachSeconds);
+ const sentenceStarts = boundaries.filter(({ followsSentence }) => followsSentence);
+ const candidates = sentenceStarts.length ? sentenceStarts : boundaries;
+ let best = cutSeconds;
+ for (const { seconds } of candidates) {
+ if (best === cutSeconds || Math.abs(seconds - cutSeconds) < Math.abs(best - cutSeconds)) {
+ best = seconds;
+ }
+ }
+ return best;
}
function normalize(vector: Float32Array) {
diff --git a/apps/desktop/src/services/transcription/transcription_worker.spec.ts b/apps/desktop/src/services/transcription/transcription_worker.spec.ts
index 03d6dc704b..ae95ffb834 100644
--- a/apps/desktop/src/services/transcription/transcription_worker.spec.ts
+++ b/apps/desktop/src/services/transcription/transcription_worker.spec.ts
@@ -47,7 +47,9 @@ class FakeParentPort extends EventEmitter {
/** An engine whose segmenter completes an utterance per chunk, transcribed as "Chunk <n>". */
const engine = {
settings: { recognizer: { decodingMethod: "greedy_search" } },
- recognizer: { transcribe: async (samples: Float32Array) => `Chunk ${samples[0]}` },
+ recognizer: {
+ transcribe: async (samples: Float32Array) => ({ text: `Chunk ${samples[0]}`, words: [] })
+ },
createSegmenter: () => ({
accept: (samples: Float32Array) => [ { start: 0, samples } ],
flush: () => [],
diff --git a/apps/desktop/src/sherpa-onnx-node.d.ts b/apps/desktop/src/sherpa-onnx-node.d.ts
index 4cf8ce2841..b660693379 100644
--- a/apps/desktop/src/sherpa-onnx-node.d.ts
+++ b/apps/desktop/src/sherpa-onnx-node.d.ts
@@ -6,7 +6,12 @@ declare module "sherpa-onnx-node" {
export class OfflineRecognizer {
static createAsync(config: object): Promise<OfflineRecognizer>;
createStream(): OfflineStream;
- decodeAsync(stream: OfflineStream): Promise<{ text: string }>;
+ /** `timestamps` holds each token's start in seconds from the start of the stream. */
+ decodeAsync(stream: OfflineStream): Promise<{
+ text: string;
+ tokens: string[];
+ timestamps: number[];
+ }>;
}
export interface SpeakerEmbeddingStream {