Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(parakeet): cut long offline audio at a pause instead of a fixed offset (#2478)
matthias-veraceb91744c03b
diff --git a/src/helpers/parakeetSegmentation.js b/src/helpers/parakeetSegmentation.jsnew file mode 100644index 000000000..f52d6c3a6--- /dev/null+++ b/src/helpers/parakeetSegmentation.js@@ -0,0 +1,93 @@+// Splits float32 PCM for offline models that cap the clip length. A cut at a+// fixed offset lands mid-word, and each segment decodes independently: the+// word at the cut comes back garbled, and a short tail can decode to nothing+// (#2476). So each cut moves to the quietest stretch shortly before the limit.++const BYTES_PER_SAMPLE = 4; // float32+const FRAME_SECONDS = 0.01;+// Long enough that a stop-consonant closure inside a word doesn't pass for a pause.+const PAUSE_FRAMES = 10;+const SEARCH_SECONDS = 4;+// Without a stretch clearly quieter than the audio at the limit there is no+// pause to find, so the cut stays at the limit.+const PAUSE_ENERGY_RATIO = 0.5;+// A remainder this short decodes to nothing and flags the transcript as+// partial. None of the limits is the model's own maximum, so the last segment+// absorbs it instead.+const TAIL_ALLOWANCE_SECONDS = 0.5;++function frameEnergy(samples, offset, frameBytes) {+ let sum = 0;+ for (let i = offset; i < offset + frameBytes; i += BYTES_PER_SAMPLE) {+ const value = samples.readFloatLE(i);+ sum += value * value;+ }+ return sum;+}++function windowEnergy(energies, start) {+ let sum = 0;+ for (let i = start; i < start + PAUSE_FRAMES; i++) sum += energies[i];+ return sum;+}++// Returns the byte offset to cut at within [from, to]; `to` is the hard limit.+function findPauseCut(samples, from, to, frameBytes) {+ const frameCount = Math.floor((to - from) / frameBytes);+ if (frameCount < PAUSE_FRAMES) return to;+ const energies = [];+ for (let frame = 0; frame < frameCount; frame++) {+ energies.push(frameEnergy(samples, from + frame * frameBytes, frameBytes));+ }++ // Windows are summed afresh rather than slid, so equal stretches of digital+ // silence compare equal. A run of them is cut in its middle, away from the+ // words on either side.+ let quietestEnergy = Infinity;+ let runStart = 0;+ let runEnd = 0;+ for (let start = 0; start + PAUSE_FRAMES <= frameCount; start++) {+ const energy = windowEnergy(energies, start);+ if (energy < quietestEnergy) {+ quietestEnergy = energy;+ runStart = start;+ runEnd = start;+ } else if (energy === quietestEnergy && runEnd === start - 1) {+ runEnd = start;+ }+ }+ const limitEnergy = windowEnergy(energies, frameCount - PAUSE_FRAMES);+ if (quietestEnergy >= limitEnergy * PAUSE_ENERGY_RATIO) return to;+ return from + Math.floor((runStart + runEnd + PAUSE_FRAMES) / 2) * frameBytes;+}++// samples: Buffer of float32 PCM. Returns subarrays that together cover the+// input in order; each is at most maxSegmentSeconds, the last up to+// TAIL_ALLOWANCE_SECONDS longer.+function splitAtPauses(samples, { sampleRate, maxSegmentSeconds }) {+ const maxSegmentBytes = maxSegmentSeconds * sampleRate * BYTES_PER_SAMPLE;+ const searchBytes = SEARCH_SECONDS * sampleRate * BYTES_PER_SAMPLE;+ const frameBytes = Math.round(FRAME_SECONDS * sampleRate) * BYTES_PER_SAMPLE;+ const tailAllowanceBytes = TAIL_ALLOWANCE_SECONDS * sampleRate * BYTES_PER_SAMPLE;+ // An earlier cut must not cost an extra segment: that would leave a short+ // tail, which is what decodes to nothing.+ const segmentCount = Math.ceil((samples.length - tailAllowanceBytes) / maxSegmentBytes);++ const segments = [];+ let start = 0;+ while (samples.length - start > maxSegmentBytes + tailAllowanceBytes) {+ const limit = start + maxSegmentBytes;+ const segmentsAfterCut = segmentCount - segments.length - 1;+ const earliest = Math.max(+ limit - searchBytes,+ samples.length - segmentsAfterCut * maxSegmentBytes - tailAllowanceBytes+ );+ const cut = findPauseCut(samples, earliest, limit, frameBytes);+ segments.push(samples.subarray(start, cut));+ start = cut;+ }+ segments.push(samples.subarray(start));+ return segments;+}++module.exports = { splitAtPauses };diff --git a/src/helpers/parakeetServer.js b/src/helpers/parakeetServer.jsindex 230dbf77d..e8d613c79 100644--- a/src/helpers/parakeetServer.js+++ b/src/helpers/parakeetServer.js@@ -14,6 +14,7 @@ const {const { getSafeTempDir } = require("./safeTempDir");const { createAbortError } = require("./abortError");const ParakeetWsServer = require("./parakeetWsServer");+const { splitAtPauses } = require("./parakeetSegmentation");const {getModelRuntime,getModelType,@@ -158,9 +159,9 @@ class ParakeetServerManager {: getModelType(modelName) === "cohere-transcribe"? COHERE_MAX_SEGMENT_SECONDS: MAX_SEGMENT_SECONDS;- const maxSegmentBytes = maxSegmentSeconds * SAMPLE_RATE * BYTES_PER_SAMPLE;+ const segments = splitAtPauses(samples, { sampleRate: SAMPLE_RATE, maxSegmentSeconds });- if (samples.length <= maxSegmentBytes) {+ if (segments.length === 1) {const result = await this.wsServer.transcribe(samples, SAMPLE_RATE, { signal });if (result.text?.trim()) return result;throwIfAborted();@@ -175,16 +176,13 @@ class ParakeetServerManager {return { ...retry, elapsed: (result.elapsed || 0) + (retry.elapsed || 0) };}+ const shortestSegmentBytes = Math.min(...segments.map((segment) => segment.length));debugLogger.debug("Parakeet segmenting long audio", {durationSeconds,- segmentCount: Math.ceil(samples.length / maxSegmentBytes),+ segmentCount: segments.length,+ shortestSegmentSeconds: shortestSegmentBytes / BYTES_PER_SAMPLE / SAMPLE_RATE,});- const segments = [];- for (let offset = 0; offset < samples.length; offset += maxSegmentBytes) {- segments.push(samples.subarray(offset, offset + maxSegmentBytes));- }-const decodeSegment = async (segment, segmentIndex) => {throwIfAborted();const first = await this.wsServer.transcribe(segment, SAMPLE_RATE, { signal });diff --git a/test/helpers/parakeetSegmentation.test.js b/test/helpers/parakeetSegmentation.test.jsnew file mode 100644index 000000000..566d91418--- /dev/null+++ b/test/helpers/parakeetSegmentation.test.js@@ -0,0 +1,182 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const { splitAtPauses } = require("../../src/helpers/parakeetSegmentation");++const SAMPLE_RATE = 16000;+const OPTIONS = { sampleRate: SAMPLE_RATE, maxSegmentSeconds: 15 };++// Float32 PCM from spans of a 200 Hz tone; `amplitude: 0` is a pause.+function pcm(spans) {+ const total = spans.reduce((sum, span) => sum + Math.round(span.seconds * SAMPLE_RATE), 0);+ const buf = Buffer.alloc(total * 4);+ let index = 0;+ for (const { seconds, amplitude = 0.5 } of spans) {+ for (let i = 0; i < Math.round(seconds * SAMPLE_RATE); i++, index++) {+ buf.writeFloatLE(amplitude * Math.sin((2 * Math.PI * 200 * index) / SAMPLE_RATE), index * 4);+ }+ }+ return buf;+}++const seconds = (segment) => segment.length / 4 / SAMPLE_RATE;++test("audio within the limit stays one segment", () => {+ const samples = pcm([{ seconds: 15 }]);+ const segments = splitAtPauses(samples, OPTIONS);+ assert.equal(segments.length, 1);+ assert.equal(segments[0].length, samples.length);+});++test("without a pause the cut stays at the limit", () => {+ const segments = splitAtPauses(pcm([{ seconds: 31 }]), OPTIONS);+ assert.deepEqual(segments.map(seconds), [15, 15, 1]);+});++test("the cut moves into a pause shortly before the limit", () => {+ const segments = splitAtPauses(+ pcm([{ seconds: 13 }, { seconds: 0.3, amplitude: 0 }, { seconds: 3.7 }]),+ OPTIONS+ );+ assert.deepEqual(segments.map(seconds), [13.15, 3.85]);+});++test("a long silence is cut in its middle, away from the words on either side", () => {+ const segments = splitAtPauses(+ pcm([{ seconds: 11.5 }, { seconds: 3.4, amplitude: 0 }, { seconds: 1.1 }]),+ OPTIONS+ );+ assert.equal(seconds(segments[0]), 13.2);+});++test("a pause just inside the search window moves the cut", () => {+ const segments = splitAtPauses(+ pcm([{ seconds: 11.3 }, { seconds: 0.5, amplitude: 0 }, { seconds: 4.2 }]),+ OPTIONS+ );+ assert.equal(seconds(segments[0]), 11.55);+});++test("a pause just before the search window leaves the cut at the limit", () => {+ const segments = splitAtPauses(+ pcm([{ seconds: 10.5 }, { seconds: 0.45, amplitude: 0 }, { seconds: 5.05 }]),+ OPTIONS+ );+ assert.equal(seconds(segments[0]), 15);+});++test("a stretch under half the energy at the limit moves the cut, one above it does not", () => {+ // Energy scales with amplitude squared: 0.3 is 0.36 of the 0.5 tone, 0.4 is 0.64.+ const withStretch = (amplitude) =>+ seconds(+ splitAtPauses(+ pcm([{ seconds: 12 }, { seconds: 0.5, amplitude }, { seconds: 3.5 }]),+ OPTIONS+ )[0]+ );+ const quieter = withStretch(0.3);+ assert.ok(quieter > 12 && quieter < 12.5, `cut at ${quieter}s, expected inside the stretch`);+ assert.equal(withStretch(0.4), 15);+});++test("the stretch is compared with the audio at the limit, not the start of the search", () => {+ const segments = splitAtPauses(+ pcm([{ seconds: 11 }, { seconds: 0.5, amplitude: 0.05 }, { seconds: 4.5 }]),+ OPTIONS+ );+ const cut = seconds(segments[0]);+ assert.ok(cut > 11 && cut < 11.5, `cut at ${cut}s, expected inside the soft stretch`);+});++test("a cut moves earlier only when that does not add a segment", () => {+ // Cutting at 12 s would leave 16 s, so a third, 1 s segment.+ const twoSegments = splitAtPauses(+ pcm([{ seconds: 12 }, { seconds: 0.3, amplitude: 0 }, { seconds: 15.7 }]),+ OPTIONS+ );+ assert.deepEqual(twoSegments.map(seconds), [15, 13]);++ const threeSegments = splitAtPauses(+ pcm([{ seconds: 13 }, { seconds: 0.3, amplitude: 0 }, { seconds: 26.7 }]),+ OPTIONS+ );+ assert.deepEqual(threeSegments.map(seconds), [13.15, 15, 11.85]);+});++test("a softer stretch counts as a pause, not only digital silence", () => {+ const segments = splitAtPauses(+ pcm([{ seconds: 12 }, { seconds: 0.2, amplitude: 0.02 }, { seconds: 5 }]),+ OPTIONS+ );+ const cut = seconds(segments[0]);+ assert.ok(cut > 12 && cut < 12.2, `cut at ${cut}s, expected inside the soft stretch`);+});++test("a pause too early for the search window leaves the cut at the limit", () => {+ const segments = splitAtPauses(+ pcm([{ seconds: 5 }, { seconds: 0.5, amplitude: 0 }, { seconds: 11.5 }]),+ OPTIONS+ );+ assert.deepEqual(segments.map(seconds), [15, 2]);+});++test("a dip shorter than a pause window does not move the cut", () => {+ const segments = splitAtPauses(+ pcm([{ seconds: 13 }, { seconds: 0.03, amplitude: 0 }, { seconds: 4 }]),+ OPTIONS+ );+ assert.equal(seconds(segments[0]), 15);+});++test("a soft stretch of 110 ms is long enough to count as a pause", () => {+ const segments = splitAtPauses(+ pcm([{ seconds: 13 }, { seconds: 0.11, amplitude: 0.25 }, { seconds: 3.89 }]),+ OPTIONS+ );+ const cut = seconds(segments[0]);+ assert.ok(cut > 13 && cut < 13.11, `cut at ${cut}s, expected inside the stretch`);+});++test("a cut with no room left to move stays at the limit", () => {+ // Any earlier cut would push the 15.47 s remainder past the last segment's allowance.+ const segments = splitAtPauses(+ pcm([{ seconds: 14.97 }, { seconds: 0.03, amplitude: 0 }, { seconds: 15.47 }]),+ OPTIONS+ );+ assert.deepEqual(segments.map(seconds), [15, 15.47]);+});++test("the last segment's allowance neither adds a segment nor stops a cut moving into a pause", () => {+ const noExtraSegment = splitAtPauses(+ pcm([{ seconds: 12 }, { seconds: 0.3, amplitude: 0 }, { seconds: 17.95 }]),+ OPTIONS+ );+ assert.deepEqual(noExtraSegment.map(seconds), [15, 15.25]);++ const intoPause = splitAtPauses(+ pcm([{ seconds: 14.6 }, { seconds: 0.3, amplitude: 0 }, { seconds: 15.4 }]),+ OPTIONS+ );+ assert.deepEqual(intoPause.map(seconds), [14.85, 15.45]);+});++test("a remainder under half a second joins the last segment instead of decoding alone", () => {+ assert.deepEqual(splitAtPauses(pcm([{ seconds: 15.25 }]), OPTIONS).map(seconds), [15.25]);+ assert.deepEqual(splitAtPauses(pcm([{ seconds: 30.25 }]), OPTIONS).map(seconds), [15, 15.25]);+ assert.deepEqual(splitAtPauses(pcm([{ seconds: 15.75 }]), OPTIONS).map(seconds), [15, 0.75]);+});++test("segments cover the input in order without gaps or overlap", () => {+ const samples = pcm([+ { seconds: 14 },+ { seconds: 0.4, amplitude: 0 },+ { seconds: 13.6 },+ { seconds: 0.4, amplitude: 0 },+ { seconds: 6 },+ ]);+ const segments = splitAtPauses(samples, OPTIONS);+ assert.equal(segments.length, 3);+ assert.ok(segments.every((segment) => seconds(segment) <= 15));+ assert.ok(segments.every((segment) => segment.length % 4 === 0));+ assert.ok(Buffer.concat(segments).equals(samples));+});diff --git a/test/helpers/parakeetServer.test.js b/test/helpers/parakeetServer.test.jsindex bbb9a5a4c..fbded2a5c 100644--- a/test/helpers/parakeetServer.test.js+++ b/test/helpers/parakeetServer.test.js@@ -132,6 +132,41 @@ test("a silent segment decoding to empty is not retried or flagged", async () =>assert.equal(fake.calls.length, 3);});+test("long audio is cut in a pause before the limit, not mid-word at it", async () => {+ const fake = fakeWsServer([{ text: "one" }, { text: "two" }]);+ const manager = managerWith(fake);++ const result = await manager.transcribe(+ wavFromSeconds([{ seconds: 13 }, { seconds: 0.5, silent: true }, { seconds: 2.5 }])+ );++ assert.equal(result.text, "one two");+ assert.deepEqual(fake.calls, [13.25 * SAMPLE_RATE * 4, 2.75 * SAMPLE_RATE * 4]);+});++test("a pause-aligned cut never adds a short extra segment", async () => {+ const fake = fakeWsServer([{ text: "one" }, { text: "two" }]);+ const manager = managerWith(fake);++ const result = await manager.transcribe(+ wavFromSeconds([{ seconds: 12 }, { seconds: 0.5, silent: true }, { seconds: 15.5 }])+ );++ assert.equal(result.text, "one two");+ assert.deepEqual(fake.calls, [SEGMENT_BYTES, 13 * SAMPLE_RATE * 4]);+});++test("a remainder under half a second past the cap stays in the one request", async () => {+ const fake = fakeWsServer([{ text: "" }, { text: "hello" }]);+ const manager = managerWith(fake);++ const result = await manager.transcribe(wavFromSeconds([{ seconds: 15.25 }]));++ assert.equal(result.text, "hello");+ assert.ok(!result.truncated, "nothing was split off to lose");+ assert.deepEqual(fake.calls, [15.25 * SAMPLE_RATE * 4, 15.25 * SAMPLE_RATE * 4]);+});+test("a pre-aborted signal rejects before any decode is issued", async () => {const fake = fakeWsServer([]);const manager = managerWith(fake);