Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

fix(voice): cap speech segments at the transcription batch limit

Luis Ortiz65a23b7404e0
diff --git a/src/core/capture/voice/__tests__/batching.test.ts b/src/core/capture/voice/__tests__/batching.test.ts
index 65b24d1..78487ed 100644
--- a/src/core/capture/voice/__tests__/batching.test.ts
+++ b/src/core/capture/voice/__tests__/batching.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import { buildBatches, MAX_BATCH_S, mergeGaps } from '../batching';
+import { detectSpeechByEnergy } from '../energy-gate';
import { absoluteSeconds, type SpeechSegment } from '../types';
const seg = (start: number, end: number): SpeechSegment => ({
@@ -59,3 +60,55 @@ describe('buildBatches', () => {
expect(buildBatches([seg(0, 5)]).dropped).toBe(0);
});
});
+
+describe('mergeGaps against the cap', () => {
+ it('refuses a merge that would push the span over the cap', () => {
+ expect(mergeGaps([seg(0, 24), seg(24.2, 30)])).toHaveLength(2);
+ });
+
+ it('still absorbs a contained segment when the container is over the cap', () => {
+ expect(mergeGaps([seg(0, 40), seg(5, 10)])).toEqual([seg(0, 40)]);
+ });
+});
+
+describe('buildBatches with an over-long segment', () => {
+ it('emits only batches that fit the cap', () => {
+ const { batches } = buildBatches([seg(0, 60)]);
+ expect(batches.length).toBeGreaterThan(1);
+ for (const b of batches) expect(b.end - b.start).toBeLessThanOrEqual(MAX_BATCH_S);
+ });
+
+ it('counts every forced split', () => {
+ expect(buildBatches([seg(0, 60)]).forcedSplits).toBe(2);
+ });
+
+ it('reports no forced splits for conforming segments', () => {
+ expect(buildBatches([seg(0, 5), seg(6, 10)]).forcedSplits).toBe(0);
+ });
+
+ it('keeps the forced pieces ordered, contiguous and inside the original span', () => {
+ const pieces = buildBatches([seg(0, 60)]).batches.flatMap((b) => b.segments);
+ expect(pieces[0].start).toBe(0);
+ expect(pieces[pieces.length - 1].end).toBe(60);
+ for (let i = 1; i < pieces.length; i += 1) expect(pieces[i].start).toBe(pieces[i - 1].end);
+ });
+});
+
+describe('energy gate to batches', () => {
+ it('keeps continuous narration under the cap without a forced split', async () => {
+ const rate = 16000;
+ const pcm = new Int16Array(rate * 60);
+ for (let burst = 0, at = 0.5; at < 59; burst += 1) {
+ const length = 4 + (burst % 4);
+ const to = Math.min(pcm.length, Math.round((at + length) * rate));
+ for (let i = Math.round(at * rate); i < to; i += 1) {
+ pcm[i] = Math.round(Math.sin((2 * Math.PI * 220 * i) / rate) * 0.4 * 32767);
+ }
+ at += length + 0.2 + (burst % 3) * 0.1;
+ }
+ const { batches, forcedSplits } = buildBatches(mergeGaps(await detectSpeechByEnergy(pcm, rate)));
+ expect(batches.length).toBeGreaterThan(1);
+ expect(forcedSplits).toBe(0);
+ for (const b of batches) expect(b.end - b.start).toBeLessThanOrEqual(MAX_BATCH_S);
+ });
+});
diff --git a/src/core/capture/voice/__tests__/energy-gate.test.ts b/src/core/capture/voice/__tests__/energy-gate.test.ts
index 3858c16..d891668 100644
--- a/src/core/capture/voice/__tests__/energy-gate.test.ts
+++ b/src/core/capture/voice/__tests__/energy-gate.test.ts
@@ -1,5 +1,12 @@
import { describe, expect, it } from 'vitest';
-import { detectSpeechByEnergy, FRAME_MS, SEGMENT_PAD_MS, SPEECH_RMS_THRESHOLD } from '../energy-gate';
+import {
+ detectSpeechByEnergy,
+ FRAME_MS,
+ MAX_SEGMENT_S,
+ SEGMENT_PAD_MS,
+ SPEECH_RMS_THRESHOLD,
+ SPLIT_SEARCH_S,
+} from '../energy-gate';
const SAMPLE_RATE = 16000;
const PAD_S = SEGMENT_PAD_MS / 1000;
@@ -97,3 +104,44 @@ describe('detectSpeechByEnergy', () => {
expect(Math.abs(segment.end - (2 + PAD_S))).toBeLessThanOrEqual(FRAME_MS / 1000);
});
});
+
+describe('detectSpeechByEnergy segment cap', () => {
+ it('never emits a segment longer than the cap', async () => {
+ const segments = await detectSpeechByEnergy(loud(silence(60), 0.5, 59.5), SAMPLE_RATE);
+ expect(segments.length).toBeGreaterThan(1);
+ for (const segment of segments) expect(segment.end - segment.start).toBeLessThanOrEqual(MAX_SEGMENT_S);
+ });
+
+ it('leaves a run under the cap as a single segment', async () => {
+ const segments = await detectSpeechByEnergy(loud(silence(30), 1, 21), SAMPLE_RATE);
+ expect(segments).toHaveLength(1);
+ expect(segments[0].end - segments[0].start).toBeCloseTo(20 + 2 * PAD_S, 1);
+ });
+
+ it('cuts at the quietest frame inside the tail of the allowed window', async () => {
+ const dip = MAX_SEGMENT_S - SPLIT_SEARCH_S + 1;
+ const pcm = loud(loud(silence(40), 0, 40), dip, dip + 0.4, 0.02);
+ const [first] = await detectSpeechByEnergy(pcm, SAMPLE_RATE);
+ expect(first.end).toBeGreaterThanOrEqual(dip - FRAME_MS / 1000);
+ expect(first.end).toBeLessThanOrEqual(dip + 0.4);
+ expect(MAX_SEGMENT_S - first.end).toBeGreaterThan(1);
+ });
+
+ it('keeps split segments ordered, contiguous and inside the recording', async () => {
+ const segments = await detectSpeechByEnergy(loud(silence(60), 0.5, 59.5), SAMPLE_RATE);
+ for (const segment of segments) {
+ expect(segment.start).toBeGreaterThanOrEqual(0);
+ expect(segment.end).toBeLessThanOrEqual(60);
+ expect(segment.end).toBeGreaterThan(segment.start);
+ }
+ for (let i = 1; i < segments.length; i += 1) {
+ expect(segments[i].start).toBeGreaterThanOrEqual(segments[i - 1].end);
+ }
+ });
+
+ it('caps a segment grown past the cap by overlapping padding', async () => {
+ const segments = await detectSpeechByEnergy(loud(loud(silence(50), 1, 21), 21.2, 45), SAMPLE_RATE);
+ expect(segments.length).toBeGreaterThan(1);
+ for (const segment of segments) expect(segment.end - segment.start).toBeLessThanOrEqual(MAX_SEGMENT_S);
+ });
+});
diff --git a/src/core/capture/voice/__tests__/narration-updates.test.ts b/src/core/capture/voice/__tests__/narration-updates.test.ts
index 4cf3f9a..4fa094c 100644
--- a/src/core/capture/voice/__tests__/narration-updates.test.ts
+++ b/src/core/capture/voice/__tests__/narration-updates.test.ts
@@ -6,6 +6,7 @@ const STATS: NarrationStats = {
batches: 0,
failedBatches: 0,
droppedBatches: 0,
+ forcedSplits: 0,
verbatimSegments: 0,
splitSegments: 0,
rejectedSegments: 0,
diff --git a/src/core/capture/voice/batching.ts b/src/core/capture/voice/batching.ts
index 4f3335d..824e393 100644
--- a/src/core/capture/voice/batching.ts
+++ b/src/core/capture/voice/batching.ts
@@ -4,11 +4,16 @@ export const MERGE_GAP_S = 0.5;
export const MAX_BATCH_S = 25;
export const MIN_SPEECH_S = 1;
+function joinable(last: SpeechSegment, next: SpeechSegment, gap: number): boolean {
+ if (next.start - last.end > gap) return false;
+ return next.end <= last.end || next.end - last.start <= MAX_BATCH_S;
+}
+
export function mergeGaps(segments: SpeechSegment[], gap = MERGE_GAP_S): SpeechSegment[] {
const out: SpeechSegment[] = [];
for (const s of [...segments].sort((a, b) => a.start - b.start)) {
const last = out[out.length - 1];
- if (last && s.start - last.end <= gap) {
+ if (last && joinable(last, s, gap)) {
last.end = absoluteSeconds(Math.max(last.end, s.end));
} else {
out.push({ ...s });
@@ -20,14 +25,34 @@ export function mergeGaps(segments: SpeechSegment[], gap = MERGE_GAP_S): SpeechS
export interface BatchPlan {
batches: Batch[];
dropped: number;
+ forcedSplits: number;
}
const speechSeconds = (segments: SpeechSegment[]): number =>
segments.reduce((total, s) => total + (s.end - s.start), 0);
+function capSegment(s: SpeechSegment): SpeechSegment[] {
+ const span = s.end - s.start;
+ if (span <= MAX_BATCH_S) return [s];
+ const parts = Math.ceil(span / MAX_BATCH_S);
+ const size = span / parts;
+ return Array.from({ length: parts }, (_, i) => ({
+ start: absoluteSeconds(s.start + i * size),
+ end: absoluteSeconds(i === parts - 1 ? s.end : s.start + (i + 1) * size),
+ }));
+}
+
export function buildBatches(segments: SpeechSegment[]): BatchPlan {
- const grouped: Batch[] = [];
+ const capped: SpeechSegment[] = [];
+ let forcedSplits = 0;
for (const s of segments) {
+ const parts = capSegment(s);
+ forcedSplits += parts.length - 1;
+ capped.push(...parts);
+ }
+
+ const grouped: Batch[] = [];
+ for (const s of capped) {
const last = grouped[grouped.length - 1];
if (last && s.end - last.start <= MAX_BATCH_S) {
last.end = s.end;
@@ -37,5 +62,5 @@ export function buildBatches(segments: SpeechSegment[]): BatchPlan {
}
}
const batches = grouped.filter((b) => speechSeconds(b.segments) >= MIN_SPEECH_S);
- return { batches, dropped: grouped.length - batches.length };
+ return { batches, dropped: grouped.length - batches.length, forcedSplits };
}
diff --git a/src/core/capture/voice/energy-gate.ts b/src/core/capture/voice/energy-gate.ts
index 8cf650e..4d96017 100644
--- a/src/core/capture/voice/energy-gate.ts
+++ b/src/core/capture/voice/energy-gate.ts
@@ -1,8 +1,11 @@
+import { MAX_BATCH_S } from './batching';
import { absoluteSeconds, type SpeechSegment } from './types';
export const FRAME_MS = 30;
export const SEGMENT_PAD_MS = 300;
export const SPEECH_RMS_THRESHOLD = 10 ** (-45 / 20);
+export const MAX_SEGMENT_S = MAX_BATCH_S;
+export const SPLIT_SEARCH_S = 3;
const MS_PER_S = 1000;
const INT16_SCALE = 32768;
@@ -21,25 +24,31 @@ export async function detectSpeechByEnergy(pcm: Int16Array, sampleRate: number):
if (pcm.length === 0 || sampleRate <= 0) return [];
const frameSize = Math.max(1, Math.round((sampleRate * FRAME_MS) / MS_PER_S));
+ const frameSeconds = frameSize / sampleRate;
const duration = pcm.length / sampleRate;
const pad = SEGMENT_PAD_MS / MS_PER_S;
- const segments: SpeechSegment[] = [];
+ const rms: number[] = [];
+ for (let frameStart = 0; frameStart < pcm.length; frameStart += frameSize) {
+ rms.push(frameRms(pcm, frameStart, Math.min(frameStart + frameSize, pcm.length)));
+ }
+
+ const runs: { start: number; end: number }[] = [];
const push = (fromSample: number, toSample: number) => {
const start = Math.max(0, fromSample / sampleRate - pad);
const end = Math.min(duration, toSample / sampleRate + pad);
- const last = segments[segments.length - 1];
+ const last = runs[runs.length - 1];
if (last && start <= last.end) {
- last.end = absoluteSeconds(Math.max(last.end, end));
+ last.end = Math.max(last.end, end);
return;
}
- segments.push({ start: absoluteSeconds(start), end: absoluteSeconds(end) });
+ runs.push({ start, end });
};
let voicedFrom = -1;
- for (let frameStart = 0; frameStart < pcm.length; frameStart += frameSize) {
- const frameEnd = Math.min(frameStart + frameSize, pcm.length);
- const voiced = frameRms(pcm, frameStart, frameEnd) > SPEECH_RMS_THRESHOLD;
+ for (let frame = 0; frame < rms.length; frame += 1) {
+ const frameStart = frame * frameSize;
+ const voiced = rms[frame] > SPEECH_RMS_THRESHOLD;
if (voiced && voicedFrom < 0) voicedFrom = frameStart;
if (!voiced && voicedFrom >= 0) {
push(voicedFrom, frameStart);
@@ -48,5 +57,29 @@ export async function detectSpeechByEnergy(pcm: Int16Array, sampleRate: number):
}
if (voicedFrom >= 0) push(voicedFrom, pcm.length);
+ const quietestCut = (start: number, limit: number): number => {
+ const firstFrame = Math.max(1, Math.ceil((limit - SPLIT_SEARCH_S) / frameSeconds));
+ const lastFrame = Math.min(rms.length - 1, Math.floor(limit / frameSeconds));
+ let cut = limit;
+ let quietest = Number.POSITIVE_INFINITY;
+ for (let frame = firstFrame; frame <= lastFrame; frame += 1) {
+ if (rms[frame] >= quietest) continue;
+ quietest = rms[frame];
+ cut = frame * frameSeconds;
+ }
+ return cut > start ? cut : limit;
+ };
+
+ const segments: SpeechSegment[] = [];
+ for (const run of runs) {
+ let start = run.start;
+ while (run.end - start > MAX_SEGMENT_S) {
+ const cut = quietestCut(start, start + MAX_SEGMENT_S);
+ segments.push({ start: absoluteSeconds(start), end: absoluteSeconds(cut) });
+ start = cut;
+ }
+ segments.push({ start: absoluteSeconds(start), end: absoluteSeconds(run.end) });
+ }
+
return segments;
}
diff --git a/src/core/capture/voice/pipeline.ts b/src/core/capture/voice/pipeline.ts
index caa2928..4d31835 100644
--- a/src/core/capture/voice/pipeline.ts
+++ b/src/core/capture/voice/pipeline.ts
@@ -26,13 +26,14 @@ function sliceSpeech(pcm: Int16Array, segments: SpeechSegment[], sampleRate: num
export async function runNarrationPipeline(input: PipelineInput): Promise<NarrationResult> {
const { pcm, sampleRate, steps, detectSpeech, transcribe } = input;
- const { batches, dropped } = buildBatches(mergeGaps(await detectSpeech(pcm, sampleRate)));
+ const { batches, dropped, forcedSplits } = buildBatches(mergeGaps(await detectSpeech(pcm, sampleRate)));
const collected = new Map<string, string[]>();
const stats = {
batches: batches.length,
failedBatches: 0,
droppedBatches: dropped,
+ forcedSplits,
verbatimSegments: 0,
splitSegments: 0,
rejectedSegments: 0,
diff --git a/src/core/capture/voice/types.ts b/src/core/capture/voice/types.ts
index 5d7a790..e7e60cf 100644
--- a/src/core/capture/voice/types.ts
+++ b/src/core/capture/voice/types.ts
@@ -61,6 +61,7 @@ export interface NarrationStats {
batches: number;
failedBatches: number;
droppedBatches: number;
+ forcedSplits: number;
verbatimSegments: number;
splitSegments: number;
rejectedSegments: number;
diff --git a/src/lib/voice-narration.ts b/src/lib/voice-narration.ts
index 4d55f85..31e341f 100644
--- a/src/lib/voice-narration.ts
+++ b/src/lib/voice-narration.ts
@@ -28,6 +28,7 @@ export const EMPTY_NARRATION: NarrationResult = {
batches: 0,
failedBatches: 0,
droppedBatches: 0,
+ forcedSplits: 0,
verbatimSegments: 0,
splitSegments: 0,
rejectedSegments: 0,