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 πŸ“–

feat(capture): keep every transcribed line, attributed or not

davbio4be5afbbe7e2
diff --git a/src/core/capture/voice/__tests__/narration-updates.test.ts b/src/core/capture/voice/__tests__/narration-updates.test.ts
index 4fa094c..29c974d 100644
--- a/src/core/capture/voice/__tests__/narration-updates.test.ts
+++ b/src/core/capture/voice/__tests__/narration-updates.test.ts
@@ -13,7 +13,7 @@ const STATS: NarrationStats = {
};
function result(descriptions: NarrationResult['descriptions']): NarrationResult {
- return { descriptions, stats: STATS };
+ return { descriptions, transcript: { epochMs: 0, lines: [] }, stats: STATS };
}
describe('narrationUpdates', () => {
diff --git a/src/core/capture/voice/__tests__/transcript-lines.test.ts b/src/core/capture/voice/__tests__/transcript-lines.test.ts
new file mode 100644
index 0000000..06459c8
--- /dev/null
+++ b/src/core/capture/voice/__tests__/transcript-lines.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from 'vitest';
+import { runNarrationPipeline } from '../pipeline';
+import { absoluteSeconds, type StepWindow } from '../types';
+
+const steps: StepWindow[] = [
+ { stepId: 's1', from: absoluteSeconds(0), to: absoluteSeconds(10) },
+ { stepId: 's2', from: absoluteSeconds(10), to: absoluteSeconds(20) },
+];
+const pcm = new Int16Array(16000 * 20);
+const scores = { no_speech_prob: 0.01, avg_logprob: -0.2, compression_ratio: 1.4 };
+const speech = (start: number, end: number) => [{ start: absoluteSeconds(start), end: absoluteSeconds(end) }];
+
+const run = (segments: unknown[], words?: unknown[], detected = speech(1, 18)) =>
+ runNarrationPipeline({
+ pcm,
+ sampleRate: 16000,
+ steps,
+ audioEpochMs: 1_700_000_000_000,
+ detectSpeech: async () => detected,
+ transcribe: async () => ({ segments, words }) as never,
+ });
+
+describe('the transcript the pipeline keeps', () => {
+ it('keeps a line a filter threw away, with the reason it was thrown away', async () => {
+ const result = await run([
+ { start: 0, end: 3, text: 'Open the settings menu.', ...scores },
+ { start: 3, end: 5, text: 'Thanks for watching', ...scores },
+ ]);
+
+ expect(result.descriptions).toEqual([{ stepId: 's1', text: 'Open the settings menu.' }]);
+ expect(result.transcript.lines).toContainEqual(
+ expect.objectContaining({ text: 'Open the settings menu.', stepId: 's1', rejectReason: null }),
+ );
+ const rejected = result.transcript.lines.find((line) => line.text === 'Thanks for watching');
+ expect(rejected?.rejectReason).toBe('blocklist:thanks for watching');
+ expect(rejected?.stepId).toBeNull();
+ });
+
+ it('keeps a line no step claimed', async () => {
+ const result = await run(
+ [{ start: 0, end: 2, text: 'Let me find my notes.', ...scores }],
+ undefined,
+ speech(25, 28),
+ );
+
+ expect(result.descriptions).toEqual([]);
+ expect(result.transcript.lines).toEqual([
+ expect.objectContaining({ text: 'Let me find my notes.', stepId: null, rejectReason: null }),
+ ]);
+ });
+
+ it('carries the step onto an ordinary attributed line', async () => {
+ const result = await run([
+ { start: 0, end: 3, text: 'Open the settings menu.', ...scores },
+ { start: 11, end: 14, text: 'Then save it.', ...scores },
+ ]);
+
+ expect(result.transcript.lines.map((line) => [line.stepId, line.text])).toEqual([
+ ['s1', 'Open the settings menu.'],
+ ['s2', 'Then save it.'],
+ ]);
+ });
+
+ it('stamps the audio epoch so slices can be ordered later', async () => {
+ const result = await run([{ start: 0, end: 3, text: 'Open the settings menu.', ...scores }]);
+ expect(result.transcript.epochMs).toBe(1_700_000_000_000);
+ });
+
+ it('records each side of a segment split across two steps', async () => {
+ const result = await run(
+ [{ start: 8, end: 12, text: 'Open settings then save it', ...scores }],
+ [
+ { word: 'Open', start: 8, end: 8.4 },
+ { word: 'settings', start: 8.5, end: 9 },
+ { word: 'then', start: 10.5, end: 10.8 },
+ { word: 'save', start: 11, end: 11.3 },
+ { word: 'it', start: 11.4, end: 11.6 },
+ ],
+ speech(0, 20),
+ );
+
+ expect(result.transcript.lines.map((line) => [line.stepId, line.text])).toEqual([
+ ['s1', 'Open settings'],
+ ['s2', 'then save it'],
+ ]);
+ });
+
+ it('keeps a split segment whole and unattributed when there are no word timings', async () => {
+ const result = await run([{ start: 8, end: 12, text: 'Open settings then save it', ...scores }], [], speech(0, 20));
+
+ expect(result.descriptions).toEqual([]);
+ expect(result.transcript.lines).toEqual([
+ expect.objectContaining({ text: 'Open settings then save it', stepId: null }),
+ ]);
+ });
+
+ it('has nothing to keep when there was no speech to transcribe', async () => {
+ const result = await run([], undefined, []);
+ expect(result.transcript.lines).toEqual([]);
+ });
+});
diff --git a/src/core/capture/voice/attribute.ts b/src/core/capture/voice/attribute.ts
index de8ca6b..52c1080 100644
--- a/src/core/capture/voice/attribute.ts
+++ b/src/core/capture/voice/attribute.ts
@@ -5,6 +5,7 @@ import {
type Batch,
type StepWindow,
type TranscriptionResponse,
+ type TranscriptLine,
} from './types';
export function makeToAbsolute(batch: Batch): (batchTime: number) => AbsoluteSeconds {
@@ -27,55 +28,92 @@ export function makeToAbsolute(batch: Batch): (batchTime: number) => AbsoluteSec
export interface AssignResult {
byStep: Map<string, string[]>;
+ lines: TranscriptLine[];
verbatim: number;
split: number;
rejected: number;
}
+interface WordGroup {
+ stepId: string;
+ words: string[];
+ start: number;
+ end: number;
+}
+
export function assignSegments(response: TranscriptionResponse, batch: Batch, steps: StepWindow[]): AssignResult {
const toAbsolute = makeToAbsolute(batch);
const byStep = new Map<string, string[]>();
+ const lines: TranscriptLine[] = [];
const add = (stepId: string, text: string) => {
if (!text) return;
const existing = byStep.get(stepId);
if (existing) existing.push(text);
else byStep.set(stepId, [text]);
};
+ const record = (line: TranscriptLine) => {
+ if (line.text) lines.push(line);
+ };
let verbatim = 0;
let split = 0;
let rejected = 0;
for (const segment of response.segments ?? []) {
- if (rejectReason(segment)) {
+ const start = toAbsolute(segment.start);
+ const end = toAbsolute(segment.end);
+ const text = (segment.text ?? '').trim();
+ const reason = rejectReason(segment);
+
+ if (reason) {
rejected += 1;
+ record({ start, end, text, stepId: null, rejectReason: reason });
continue;
}
- const start = toAbsolute(segment.start);
- const end = toAbsolute(segment.end);
+
const spanned = steps.filter((s) => start < s.to && end > s.from);
if (spanned.length <= 1) {
const step = spanned[0] ?? steps.find((s) => start >= s.from && start <= s.to);
if (step) {
- add(step.stepId, segment.text.trim());
+ add(step.stepId, text);
verbatim += 1;
}
+ record({ start, end, text, stepId: step?.stepId ?? null, rejectReason: null });
continue;
}
split += 1;
- const grouped = new Map<string, string[]>();
+ const grouped = new Map<string, WordGroup>();
for (const word of response.words ?? []) {
if (word.start < segment.start || word.start > segment.end) continue;
const at = toAbsolute(word.start);
const step = steps.find((s) => at >= s.from && at <= s.to) ?? spanned[spanned.length - 1];
const existing = grouped.get(step.stepId);
- if (existing) existing.push(word.word.trim());
- else grouped.set(step.stepId, [word.word.trim()]);
+ if (existing) {
+ existing.words.push(word.word.trim());
+ existing.end = Math.max(existing.end, toAbsolute(word.end));
+ } else {
+ grouped.set(step.stepId, {
+ stepId: step.stepId,
+ words: [word.word.trim()],
+ start: at,
+ end: toAbsolute(word.end),
+ });
+ }
+ }
+
+ if (grouped.size === 0) {
+ record({ start, end, text, stepId: null, rejectReason: null });
+ continue;
+ }
+
+ for (const group of [...grouped.values()].sort((a, b) => a.start - b.start)) {
+ const joined = group.words.join(' ').trim();
+ add(group.stepId, joined);
+ record({ start: group.start, end: group.end, text: joined, stepId: group.stepId, rejectReason: null });
}
- for (const [stepId, words] of grouped) add(stepId, words.join(' ').trim());
}
- return { byStep, verbatim, split, rejected };
+ return { byStep, lines, verbatim, split, rejected };
}
diff --git a/src/core/capture/voice/pipeline.ts b/src/core/capture/voice/pipeline.ts
index 4d31835..dfcffe8 100644
--- a/src/core/capture/voice/pipeline.ts
+++ b/src/core/capture/voice/pipeline.ts
@@ -1,12 +1,13 @@
import { assignSegments } from './attribute';
import { buildBatches, mergeGaps } from './batching';
-import type { NarrationResult, SpeechSegment, StepWindow, TranscriptionResponse } from './types';
+import type { NarrationResult, SpeechSegment, StepWindow, TranscriptionResponse, TranscriptLine } from './types';
import { encodeWav } from './wav';
export interface PipelineInput {
pcm: Int16Array;
sampleRate: number;
steps: StepWindow[];
+ audioEpochMs?: number;
detectSpeech: (pcm: Int16Array, sampleRate: number) => Promise<SpeechSegment[]>;
transcribe: (wav: Blob) => Promise<TranscriptionResponse>;
}
@@ -25,10 +26,11 @@ function sliceSpeech(pcm: Int16Array, segments: SpeechSegment[], sampleRate: num
}
export async function runNarrationPipeline(input: PipelineInput): Promise<NarrationResult> {
- const { pcm, sampleRate, steps, detectSpeech, transcribe } = input;
+ const { pcm, sampleRate, steps, audioEpochMs, detectSpeech, transcribe } = input;
const { batches, dropped, forcedSplits } = buildBatches(mergeGaps(await detectSpeech(pcm, sampleRate)));
const collected = new Map<string, string[]>();
+ const lines: TranscriptLine[] = [];
const stats = {
batches: batches.length,
failedBatches: 0,
@@ -48,6 +50,7 @@ export async function runNarrationPipeline(input: PipelineInput): Promise<Narrat
continue;
}
const assigned = assignSegments(response, batch, steps);
+ lines.push(...assigned.lines);
stats.verbatimSegments += assigned.verbatim;
stats.splitSegments += assigned.split;
stats.rejectedSegments += assigned.rejected;
@@ -64,5 +67,7 @@ export async function runNarrationPipeline(input: PipelineInput): Promise<Narrat
if (text) descriptions.push({ stepId, text });
}
- return { descriptions, stats };
+ lines.sort((a, b) => a.start - b.start);
+
+ return { descriptions, transcript: { epochMs: audioEpochMs ?? 0, lines }, stats };
}
diff --git a/src/core/capture/voice/types.ts b/src/core/capture/voice/types.ts
index e7e60cf..dc70a77 100644
--- a/src/core/capture/voice/types.ts
+++ b/src/core/capture/voice/types.ts
@@ -67,7 +67,22 @@ export interface NarrationStats {
rejectedSegments: number;
}
+export interface TranscriptLine {
+ start: number;
+ end: number;
+ text: string;
+ stepId: string | null;
+ rejectReason: string | null;
+ addedByHand?: boolean;
+}
+
+export interface NarrationTranscript {
+ epochMs: number;
+ lines: TranscriptLine[];
+}
+
export interface NarrationResult {
descriptions: Array<{ stepId: string; text: string }>;
+ transcript: NarrationTranscript;
stats: NarrationStats;
}
diff --git a/src/lib/voice-host.ts b/src/lib/voice-host.ts
index 1b17bd3..8d52234 100644
--- a/src/lib/voice-host.ts
+++ b/src/lib/voice-host.ts
@@ -180,8 +180,9 @@ export function createVoiceHost(): VoiceHost {
pending += 1;
try {
const result = await narrateRecording(slice, [request.step], request.settings);
- if (result.descriptions.length > 0) deliver(request.guideId, result);
- return { ok: true, flushed: result.descriptions.length > 0 };
+ const attributed = result.descriptions.length > 0;
+ if (attributed || result.transcript.lines.length > 0) deliver(request.guideId, result);
+ return { ok: true, flushed: attributed };
} finally {
pending -= 1;
}
diff --git a/src/lib/voice-narration.ts b/src/lib/voice-narration.ts
index c8babf3..7192e4f 100644
--- a/src/lib/voice-narration.ts
+++ b/src/lib/voice-narration.ts
@@ -23,6 +23,7 @@ export interface VoiceRecording {
export const EMPTY_NARRATION: NarrationResult = {
descriptions: [],
+ transcript: { epochMs: 0, lines: [] },
stats: {
batches: 0,
failedBatches: 0,
@@ -55,6 +56,7 @@ export async function narrateRecording(
pcm: recording.pcm,
sampleRate: recording.sampleRate,
steps: buildStepWindows(steps, recording.audioEpochMs, recording.durationSeconds),
+ audioEpochMs: recording.audioEpochMs,
detectSpeech: detectSpeechByEnergy,
transcribe: createTranscriber(settings),
});