Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.
TypeScript ai-meeting-assistantai-notetakerelectrongranola-alternativelinuxllama-cpplocal-ailocal-firstmacosmcpmeeting-minutesmeeting-notesoffline-firstopen-sourceprivacyspeech-to-texttranscriptionwhisperwhisper-cppwindows
Transcripts: a meeting recorded before the speech model was in is transcribed from its saved recording once the model is, then gets its notes (#30)
christianmat68c5a1f9a54d
diff --git a/app/e2e/transcribeLater.spec.ts b/app/e2e/transcribeLater.spec.tsnew file mode 100644index 00000000..bbf24e29--- /dev/null+++ b/app/e2e/transcribeLater.spec.ts@@ -0,0 +1,43 @@+import { _electron as electron, expect, test, type ElectronApplication, type Page } from '@playwright/test'+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++const main = join(import.meta.dirname, '../out/main/index.js')+const zoom = { bundleId: 'us.zoom.xos', name: 'zoom.us' }+const fake = (app: ElectronApplication, fn: string, arg?: unknown) =>+ app.evaluate((_e, [fn, arg]) => (globalThis as unknown as Record<string, Record<string, (a?: unknown) => unknown>>).__fake__[fn as string](arg), [fn, arg] as const)+const windowOf = async (app: ElectronApplication, hash: string): Promise<Page> => {+ for (let i = 0; i < 100; i++) {+ const w = app.windows().find((p) => p.url().includes(hash))+ if (w) return w+ await new Promise((r) => setTimeout(r, 50))+ }+ throw new Error(`no ${hash} window`)+}++// #30: a meeting recorded before the speech model was in is transcribed from its saved recording once the model is+test('a meeting with audio and no transcript is transcribed from its recording', async () => {+ const userData = mkdtempSync(join(tmpdir(), 'yogurt-e2e-'))+ const app = await electron.launch({ args: [main], env: { ...process.env, YOGURT_FAKE: '1', YOGURT_USER_DATA: userData } })+ try {+ const page = await app.firstWindow()+ await expect(page.getByTestId('home')).toBeVisible()+ await fake(app, 'signals', { micApps: [zoom], events: [] })+ await (await windowOf(app, '#prompt')).getByTestId('prompt-take-notes').click()+ await expect(page.getByTestId('note-state')).toHaveAttribute('data-state', 'recording')+ // the fixture says its four lines in about 15 s+ await page.waitForTimeout(16_000)+ await page.getByTestId('note-stop').click()+ await expect(page.getByTestId('note-state')).not.toHaveAttribute('data-state', 'recording')+ await fake(app, 'untranscribe')+ await page.getByTestId('note-transcript-toggle').click()+ await page.reload()+ await expect(page.getByTestId('transcript-bubble')).toHaveCount(0)+ await fake(app, 'transcribeWaiting')+ await page.reload()+ await page.getByTestId('note-transcript-toggle').click().catch(() => {})+ await expect(page.getByTestId('transcript-text').first()).toBeVisible({ timeout: 20_000 })+ await expect(page.getByTestId('transcript-text').filter({ hasText: 'launch plan' })).toHaveCount(1)+ } finally { await app.close() }+})diff --git a/app/native/yogurt-audio-linux/src/main.rs b/app/native/yogurt-audio-linux/src/main.rsindex 7a4fd736..8912c418 100644--- a/app/native/yogurt-audio-linux/src/main.rs+++ b/app/native/yogurt-audio-linux/src/main.rs@@ -42,6 +42,21 @@ pub fn uuid() -> String {fn fail(msg: &str) -> ! { eprintln!("{msg}"); std::process::exit(1) }+/// A recording made before the speech model was in, transcribed later (#30): the file as 16 kHz mono f32+/// (little-endian) on stdout, nothing else+fn decode(path: &str) {+ let mut out = std::io::BufWriter::new(std::io::stdout().lock());+ let mut down = resample::Down3::new();+ let mut buf: Vec<f32> = Vec::new();+ let read = ogg_opus::decode(Path::new(path), |s| {+ buf.clear();+ down.process(s, &mut buf);+ let bytes: Vec<u8> = buf.iter().flat_map(|x| x.to_le_bytes()).collect();+ out.write_all(&bytes)+ });+ if let Err(e) = read.and_then(|_| out.flush()) { fail(&format!("can't decode {path}: {e}")) }+}+fn arg_value(args: &[String], name: &str) -> Option<String> {let i = args.iter().position(|a| a == name)?;args.get(i + 1).cloned()@@ -282,11 +297,12 @@ fn main() {"speech-locales" => { println!(r#"{{"available":false,"supported":[],"installed":[]}}"#); return }"speech-install" => { println!(r#"{{"installed":false}}"#); return }"mic-devices" => { mic_devices(); return }+ "decode" if args.len() >= 3 => { decode(&args[2]); return }_ => {}}let dir_arg = arg_value(&args, "--dir");if args.len() < 4 || !matches!(sub, "record" | "join" | "inspect" | "compact") || dir_arg.is_none() {- fail("usage: yogurt-audio record --dir DIR [--part N --start-ms X] [--mic UID] [--speech LOCALE] | join --dir DIR | inspect --dir DIR | compact --dir DIR --out STAGING | speech-locales | speech-install LOCALE | mic-devices");+ fail("usage: yogurt-audio record --dir DIR [--part N --start-ms X] [--mic UID] [--speech LOCALE] | join --dir DIR | inspect --dir DIR | compact --dir DIR --out STAGING | decode FILE | speech-locales | speech-install LOCALE | mic-devices");}let dir = PathBuf::from(dir_arg.unwrap());match sub {diff --git a/app/native/yogurt-audio-win/src/main.rs b/app/native/yogurt-audio-win/src/main.rsindex dba4a2e1..82218f00 100644--- a/app/native/yogurt-audio-win/src/main.rs+++ b/app/native/yogurt-audio-win/src/main.rs@@ -40,7 +40,7 @@ fn testing() -> bool {std::env::var("YOGURT_AUDIO_TEST").as_deref() == Ok("1")}-const USAGE: &str = "usage: yogurt-audio record --dir DIR [--part N --start-ms X] [--mic ID] [--speech LOCALE] | join --dir DIR | inspect --dir DIR | compact --dir DIR --out STAGING | mic-devices | speech-locales | speech-install LOCALE";+const USAGE: &str = "usage: yogurt-audio record --dir DIR [--part N --start-ms X] [--mic ID] [--speech LOCALE] | join --dir DIR | inspect --dir DIR | compact --dir DIR --out STAGING | decode FILE | mic-devices | speech-locales | speech-install LOCALE";fn main() {let args: Vec<String> = std::env::args().collect();@@ -51,6 +51,7 @@ fn main() {"speech-install" => println!("{{\"installed\":false}}"),"mic-devices" => mic_devices(),"writer-probe" => writer_probe(&args),+ "decode" if args.len() >= 3 => decode(&args[2]),"record" | "join" | "inspect" | "compact" if args.len() >= 4 => {let Some(dir) = arg_value(&args, "--dir") else { fail(USAGE) };let dir = PathBuf::from(dir);@@ -72,6 +73,26 @@ fn main() {}}+/// A recording made before the speech model was in, transcribed later (#30): the file as 16 kHz mono f32+/// (little-endian) on stdout, nothing else+fn decode(path: &str) {+ use std::io::Write;+ let mut out = std::io::BufWriter::new(std::io::stdout().lock());+ let mut down = resample::Down3::default();+ let mut buf: Vec<f32> = Vec::new();+ let mut ok = true;+ let read = oggopus::decode(Path::new(path), |s| {+ buf.clear();+ down.process(s, &mut buf);+ let bytes: Vec<u8> = buf.iter().flat_map(|x| x.to_le_bytes()).collect();+ ok = out.write_all(&bytes).is_ok();+ ok+ });+ if read.is_none() || !ok || out.flush().is_err() {+ fail(&format!("can't decode {path}"))+ }+}+fn record(args: &[String], dir: &Path) {let _ = std::fs::create_dir_all(dir);let part: u32 = arg_value(args, "--part").and_then(|v| v.parse().ok()).unwrap_or(0);diff --git a/app/native/yogurt-audio/main.swift b/app/native/yogurt-audio/main.swiftindex f2c628cd..a7ff8d4a 100644--- a/app/native/yogurt-audio/main.swift+++ b/app/native/yogurt-audio/main.swift@@ -1128,6 +1128,19 @@ if args.count >= 3, args[1] == "speech-clock", let rate = Double(args[2]) {exit(0)}// Local measurement only: a 16 kHz mono wav through Apple's speech in LOCALE, final lines as speech frames on stdout+// A recording made before the speech model was in, transcribed later (#30): the file as 16 kHz mono float32+// (little-endian) on stdout, nothing else. One converter for the whole file, so its filter carries across buffers.+if args.count >= 3, args[1] == "decode" {+ guard let f = try? AVAudioFile(forReading: URL(fileURLWithPath: args[2])), let conv = AVAudioConverter(from: f.processingFormat, to: mono16) else { fail("can't read \(args[2])") }+ let out = FileHandle.standardOutput+ while let b = AVAudioPCMBuffer(pcmFormat: f.processingFormat, frameCapacity: 48000), (try? f.read(into: b)) != nil, b.frameLength > 0 {+ autoreleasepool {+ // the reader gone (Yogurt quit or gave up): stop quietly+ if let m = convert(conv, b), m.frameLength > 0, (try? out.write(contentsOf: Data(bytes: m.floatChannelData![0], count: Int(m.frameLength) * MemoryLayout<Float>.size))) == nil { exit(0) }+ }+ }+ exit(0)+}if args.count >= 4, args[1] == "speech-file" {#if compiler(>=6.2)guard #available(macOS 26, *) else { fail("speech-file needs macOS 26") }diff --git a/app/src/main/asr/backfill.ts b/app/src/main/asr/backfill.tsnew file mode 100644index 00000000..c53dd12e--- /dev/null+++ b/app/src/main/asr/backfill.ts@@ -0,0 +1,78 @@+import { spawn } from 'node:child_process'+import type { Track } from '../capture'+import { readWav } from '../fakeCapture'++/**+ * A meeting recorded before the speech model was in keeps its audio; once the model arrives the saved recording is+ * transcribed (#30). The recorder decodes its own file to 16 kHz mono, and the audio goes through the same pipeline as+ * a live meeting: 100 ms pieces on meeting time (the files are on meeting time), both tracks side by side so the echo+ * check lines them up, never faster than whisper keeps up (the pipeline drops what waits past its limit).+ */+const PIECE = 1600+const MAX_BACKLOG_MS = 60_000++/** 100 ms pieces of a 16 kHz stream that comes in pieces of any size */+async function* pieces(src: AsyncIterable<Float32Array>): AsyncGenerator<Float32Array> {+ let rest = new Float32Array(0)+ for await (const x of src) {+ const all = new Float32Array(rest.length + x.length)+ all.set(rest); all.set(x, rest.length)+ let i = 0+ for (; i + PIECE <= all.length; i += PIECE) yield all.slice(i, i + PIECE)+ rest = all.slice(i)+ }+ if (rest.length) yield rest+}++/** Feeds the tracks to the pipeline; resolves with the ms of meeting time fed (the longer track) */+export async function feedRecording(p: {+ tracks: Partial<Record<Track, AsyncIterable<Float32Array>>>+ push: (track: Track, ms: number, samples: Float32Array) => void+ backlogMs: () => number+ maxBacklogMs?: number+ wait?: (ms: number) => Promise<void>+ /** a recording started: the rest waits for the next time */+ stopped?: () => boolean+}): Promise<number> {+ const max = p.maxBacklogMs ?? MAX_BACKLOG_MS+ const wait = p.wait ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))+ const feeds = (Object.entries(p.tracks) as Array<[Track, AsyncIterable<Float32Array>]>).map(([track, src]) => ({ track, it: pieces(src), ms: 0, done: false }))+ while (feeds.some((f) => !f.done)) {+ if (p.stopped?.()) break+ // the track that is furthest behind goes next+ const f = feeds.filter((x) => !x.done).reduce((a, b) => (b.ms < a.ms ? b : a))+ const r = await f.it.next()+ if (r.done) { f.done = true; continue }+ while (p.backlogMs() > max && !p.stopped?.()) await wait(250)+ if (p.stopped?.()) break+ p.push(f.track, f.ms, r.value)+ f.ms += r.value.length / 16+ }+ for (const f of feeds) await f.it.return(undefined)+ return Math.max(0, ...feeds.map((f) => f.ms))+}++/** The recorder's own decoder (decode FILE): 16 kHz mono float32 on its stdout */+export async function* helperDecode(binary: string, file: string): AsyncGenerator<Float32Array> {+ const child = spawn(binary, ['decode', file], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })+ let err = ''+ child.stderr.on('data', (d: Buffer) => { err = (err + d.toString()).slice(-500) })+ const closed = new Promise<number | null>((r) => child.on('close', (code) => r(code)))+ let rest: Buffer = Buffer.alloc(0)+ let finished = false+ try {+ for await (const d of child.stdout as AsyncIterable<Buffer>) {+ const b = rest.length ? Buffer.concat([rest, d]) : d+ const n = b.length - (b.length % 4)+ // copied into its own buffer: a Float32Array needs 4-byte alignment+ if (n) yield new Float32Array(b.buffer.slice(b.byteOffset, b.byteOffset + n))+ rest = b.subarray(n)+ }+ const code = await closed+ finished = true+ if (code !== 0) throw new Error(`decoding ${file} failed (${code}): ${err.trim()}`)+ } finally { if (!finished) child.kill() }+}++/** Fake mode records wav: read as it is */+export async function* wavDecode(file: string): AsyncGenerator<Float32Array> { yield readWav(file) }diff --git a/app/src/main/asr/index.ts b/app/src/main/asr/index.tsindex a2957b9c..c3b63b08 100644--- a/app/src/main/asr/index.ts+++ b/app/src/main/asr/index.ts@@ -1,6 +1,7 @@-import { onCaptureStart, recordingFinished, type TranscribeWarn } from '../capture'+import { onCaptureStart, recordingFinished, type TranscribeWarn, type Track } from '../capture'import { onMeetingStart, onMeetingStop } from '../meeting'import { isFake } from '../paths'+import { feedRecording } from './backfill'import type { Meeting, Segment, Store } from '../store'import { createPipeline, type Pipeline } from './pipeline'import { echoConfidence } from './echo'@@ -18,6 +19,8 @@ import type { Chunk } from './chunker'* "meeting started" and "capture started" comes first, so the order the hooks were registered in does not matter.*/type Session = { complete?: () => boolean; pipeline: Pipeline | null; priorLines: Set<number>; done?: Promise<void>; store?: SessionStore; refresh?: (id: string) => void+ /** a saved recording that could not be read to the end (transcribeRecorded): the meeting keeps waiting */+ failed?: boolean/** Apple's speech listens in this locale for the meeting (null: whisper only); off once whisper hears another language */speech?: string | null }@@ -82,6 +85,14 @@ type SessionStore = Pick<Store, 'updateMeeting'> & Partial<Pick<Store, 'segmentslet server: WhisperServer | undefinedlet serverKey: string | undefinedconst sessions = new Map<string, Session>()+type Recorded = (id: string, tracks: Partial<Record<Track, AsyncIterable<Float32Array>>>, stopped?: () => boolean) => Promise<boolean>+let recorded: Recorded = async () => false+/**+ * A meeting recorded before the speech model was in (#30): its saved tracks (16 kHz) go through the same pipeline as a+ * live meeting. true: all of it is transcribed (the meeting no longer waits); false: no model yet, already being+ * transcribed, or the recording couldn't be read to the end (it waits for the next try).+ */+export const transcribeRecorded: Recorded = (id, tracks, stopped) => recorded(id, tracks, stopped)/** how much was heard in each language, per meeting; kept after the transcript is done, for the notes */const heard = new Map<string, Map<string, number>>()@@ -165,11 +176,12 @@ export function hookTranscription(p: {speechDeps = { ui: sp.ui, last: sp.last, install: sp.install ?? ((l) => installSpeechLocale(sp.binary, l)) }void (sp.locales ?? (() => readSpeechLocales(sp.binary)))().then((l) => { speechLocales = l; if (l.available) console.log(`speech: Apple's on-device speech can listen in ${l.installed.length} of ${l.supported.length} locales`) })} else { speechDeps = undefined; speechLocales = { available: false, supported: [], installed: [] } }- const open = (id: string): Session => {+ /** later: the saved recording of a meeting that was waiting for the speech model (transcribeRecorded) */+ const open = (id: string, later = false): Session => {const have = sessions.get(id)if (have) return have- // A later live session cannot finish audio awaiting deferred transcription.- const pendingBefore = p.store.meeting?.(id)?.transcriptionPending+ // A later live session cannot finish audio awaiting deferred transcription; the recording itself can.+ const pendingBefore = later ? false : p.store.meeting?.(id)?.transcriptionPendingp.store.updateMeeting(id, { transcriptionPending: true })let saveFailed = falseconst warned = new Set<TranscribeWarn>()@@ -201,7 +213,7 @@ export function hookTranscription(p: {}}const s: Session = {- complete: () => !!transcribe && !pendingBefore && !saveFailed && !warned.has('transcribe-failed'),+ complete: () => !!transcribe && !pendingBefore && !saveFailed && !warned.has('transcribe-failed') && !s.failed,store: p.store, refresh: p.refresh, speech: speechLocaleFor(id), priorLines: new Set(p.store.segments?.(id).map((s) => s.id) ?? []),pipeline: transcribe ? createPipeline({ meetingId: id, transcribe, save: (segs) => {try { p.store.addSegments(segs) } catch (e) { saveFailed = true; throw e }@@ -216,6 +228,20 @@ export function hookTranscription(p: {}const offStart = (p.onStart ?? onMeetingStart)((m) => { open(m.id) })+ recorded = async (id, tracks, stopped) => {+ if (sessions.has(id) || !p.modelPath()) return false+ const s = open(id, true)+ if (!s.pipeline) { sessions.delete(id); return false }+ const pipe = s.pipeline+ // no live view to keep up with: only the saved lines+ pipe.setQuickReads(false)+ let ms = 0+ try { ms = await feedRecording({ tracks, push: (t, at, x) => pipe.push(t, at, x), backlogMs: () => pipe.backlogMs(), stopped }) } catch (e) { s.failed = true; console.error('reading a saved recording failed', id, e) }+ if (stopped?.()) s.failed = true+ await finishSession(id, s, undefined, p.store)+ console.log(`ASR transcribed ${Math.round(ms / 1000)} s of a saved recording${s.failed ? ', not all of it' : ''}`)+ return !s.failed+ }// each capture of a meeting (a restarted recorder is a new one) feeds that meeting's sessionconst offCapture = onCaptureStart((c, meetingId) => {const s = open(meetingId)diff --git a/app/src/main/fake.ts b/app/src/main/fake.tsindex 71af16f5..ca355fac 100644--- a/app/src/main/fake.ts+++ b/app/src/main/fake.ts@@ -157,7 +157,9 @@ export const fakeNow = () => Date.now() + skew* prompts() what whisper and the notes model were given so far*/export function installFakeHooks(h: { signals(r: Reading): Promise<void>; advance(ms: number): Promise<void>; widget(): unknown; main(): unknown; go(route: string): void; crashCapture(): void; warn(code: string): void; bigMeeting(n: number): string; manyMeetings(o: number | { n: number; clean?: boolean }): void; calendarChanged(): void; tray(): string[]; trayClick(id: string): void; trayAccelerators(): Record<string, string | undefined>; permissions(): Promise<unknown>; notice(): unknown; noticeClick(): void; chatMeetings(): Promise<string[]> }) {+ // kept: hooks other modules added before these;(globalThis as Record<string, unknown>).__fake__ = {+ ...((globalThis as Record<string, unknown>).__fake__ as object | undefined),audioMetadataRelease: () => { audioMetadataReleased = true; releaseAudioMetadata?.() },signals: h.signals,advance: async (ms: number) => { skew += ms; await h.advance(ms) },diff --git a/app/src/main/index.ts b/app/src/main/index.tsindex 070c75d0..fa39507d 100644--- a/app/src/main/index.ts+++ b/app/src/main/index.ts@@ -49,7 +49,7 @@ import { isId, text } from './ipcArgs'import { hookMics } from './mics'import { activeCapture, audioHelperPath, hookCapture, joinParts, onCaptureStart, onRecordingEvent, prepareAppend, recordingFinished, recordingPaused, recordingSettled, rejoinInterrupted, setRecordingPaused, settleRecording, tell, type WarnCode } from './capture'import { createWidget } from './widget'-import { hookTranscription, onWhisperGpuOff, meetingLanguage, settleTranscription, speechLocaleFor, spokenChanged, transcriptionBacklogMs, stopTranscriptionServer, transcriptFinished, transcriptPartials } from './asr'+import { hookTranscription, transcribeRecorded, onWhisperGpuOff, meetingLanguage, settleTranscription, speechLocaleFor, spokenChanged, transcriptionBacklogMs, stopTranscriptionServer, transcriptFinished, transcriptPartials } from './asr'import { hookCallNames, type Watch } from './callNames'import { helperWatch, killAllWatches } from './callNames/watch'import { macFullName } from './user'@@ -75,6 +75,7 @@ import { hookMcp } from './mcp'import { startedHidden } from './mcp/paths'import { deleteRecording } from './deleteRecording'import { AUDIO_SCHEME, audioExts, createAudioHandler, trackFile, type AudioExt } from './audio'+import { helperDecode, wavDecode } from './asr/backfill'import { finishQuit, hookUpdates, isPreviewBuild, updateOfferChanged, updatesOn } from './updates'import type { NoteSaveResult, StartResult } from '../shared/types'@@ -746,6 +747,40 @@ app.whenReady().then(() => {// and meetings not in the library yet (or changed since) are indexed, once nothing else is waitingconst catchUp = () => { if (!caughtUp && setup.state.phase === 'ready') { caughtUp = true; void rejoined.catch(e => console.warn('audio startup repair retained its files', e)).finally(() => { notes.recover(); folderSuggestions.refresh(); void indexer.schedule() }) } }setup.onState(catchUp)+ // meetings recorded before the speech model was in (#30): transcribed from their saved recording once it is, one at+ // a time and never while recording (a new recording pauses it; it carries on after)+ const ownAudio = isFake() ? '.wav' : process.platform === 'darwin' ? '.m4a' : '.ogg'+ let backfilling = false+ const transcribeWaiting = async () => {+ if (backfilling || !setup.installed()?.asr || activeMeeting()) return+ backfilling = true+ try {+ await rejoined.catch(() => {})+ for (const m of store.untranscribedMeetings()) {+ if (activeMeeting()) break+ // the recorder may still be closing its files (the model came in during this very meeting)+ await recordingSettled(m.id)+ const tracks: Partial<Record<'me' | 'them', AsyncIterable<Float32Array>>> = {}+ for (const t of ['me', 'them'] as const) {+ const file = trackFile(meetingDir(m.id), t, audioKinds)+ if (file?.endsWith(ownAudio)) tracks[t] = isFake() ? wavDecode(file) : helperDecode(audioHelperPath(), file)+ }+ if (!Object.keys(tracks).length) continue+ console.info('ASR', `transcribing ${m.id} from its recording: it was recorded before the speech model was in`)+ const done = await transcribeRecorded(m.id, tracks, () => !!activeMeeting())+ win?.webContents.send('meetings:changed'); win?.webContents.send('transcript:speakers', m.id)+ // notes that came out empty (no transcript then) are written now+ if (done && store.notes(m.id).enhanced == null) void notes.writeAgain(m.id)+ }+ } catch (e) { console.error('transcribing waiting meetings failed', e) } finally { backfilling = false }+ }+ setup.onState(() => void transcribeWaiting())+ // tests: a recorded meeting back to "recorded before the speech model was in", and the catch-up run now+ if (isFake()) Object.assign(((globalThis as Record<string, unknown>).__fake__ ??= {}) as object, {+ untranscribe: () => { const id = store.meetings({ limit: 1 })[0].id; store.deleteSegments(store.segments(id).map((x) => x.id)); store.updateMeeting(id, { transcriptionPending: true }); return id },+ transcribeWaiting: () => transcribeWaiting(),+ })+ onMeetingStopSaved(() => void transcribeWaiting())app.on('will-quit', killAllWatches)app.on('will-quit', killAllHelpers)let flushToken = 0diff --git a/app/src/main/store.ts b/app/src/main/store.tsindex 4f720f6f..fb4f3893 100644--- a/app/src/main/store.ts+++ b/app/src/main/store.ts@@ -473,6 +473,15 @@ export class Store {this.db.prepare('UPDATE notes SET written_with = ? WHERE meeting_id = ?').run(people, meetingId)}+ /**+ * Stopped meetings still waiting for their transcript with not one line of it: recorded before the speech model was in+ * (#30), oldest first. One with some lines (whisper fell over partway) is left alone, so no line is transcribed twice.+ */+ untranscribedMeetings(): Meeting[] {+ return (this.db.prepare(`SELECT * FROM meetings m WHERE state = 'stopped' AND trashed_at IS NULL AND transcription_pending = 1+ AND NOT EXISTS (SELECT 1 FROM segments s WHERE s.meeting_id = m.id) ORDER BY started_at`).all() as Row[]).map(r => this.readMeeting(r))+ }+/** Stopped meetings with no enhanced notes: a quit or crash came before they were written */unenhancedMeetings(): Meeting[] {return (this.db.prepare(`SELECT * FROM meetings m WHERE state = 'stopped' AND trashed_at IS NULLdiff --git a/app/test/backfill.test.ts b/app/test/backfill.test.tsnew file mode 100644index 00000000..d1034517--- /dev/null+++ b/app/test/backfill.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest'+import { feedRecording } from '../src/main/asr/backfill'++async function* from(...parts: number[][]): AsyncGenerator<Float32Array> { for (const p of parts) yield Float32Array.from(p) }+const ones = (n: number) => new Array(n).fill(1)++describe('a recording transcribed after the meeting (#30)', () => {+ it('feeds both tracks in 100 ms pieces on meeting time, side by side so echo detection lines them up', async () => {+ const pushed: Array<[string, number, number]> = []+ const ms = await feedRecording({+ tracks: { me: from(ones(2500), ones(700)), them: from(ones(3200)) },+ push: (t, at, s) => pushed.push([t, at, s.length]), backlogMs: () => 0,+ })+ expect(pushed).toEqual([['me', 0, 1600], ['them', 0, 1600], ['me', 100, 1600], ['them', 100, 1600]])+ expect(ms).toBe(200)+ })+ it('keeps the last short piece', async () => {+ const pushed: Array<[string, number, number]> = []+ await feedRecording({ tracks: { me: from(ones(1700)) }, push: (t, at, s) => pushed.push([t, at, s.length]), backlogMs: () => 0 })+ expect(pushed).toEqual([['me', 0, 1600], ['me', 100, 100]])+ })+ it('waits while whisper is behind, so the pipeline never drops audio it was given', async () => {+ let backlog = 90_000, waits = 0+ const pushed: number[] = []+ await feedRecording({+ tracks: { them: from(ones(1600)) }, push: (_t, at) => pushed.push(at), backlogMs: () => backlog, maxBacklogMs: 60_000,+ wait: async () => { waits++; if (waits === 3) backlog = 1000 },+ })+ expect(waits).toBe(3)+ expect(pushed).toEqual([0])+ })+ it('stops when told to (a new recording started)', async () => {+ const pushed: number[] = []+ let n = 0+ await feedRecording({ tracks: { me: from(ones(16000)) }, push: (_t, at) => { pushed.push(at); n++ }, backlogMs: () => 0, stopped: () => n >= 3 })+ expect(pushed).toEqual([0, 100, 200])+ })+})diff --git a/app/test/transcription.test.ts b/app/test/transcription.test.tsindex 5f16bff6..3b2ca633 100644--- a/app/test/transcription.test.ts+++ b/app/test/transcription.test.ts@@ -2,7 +2,7 @@ import { EventEmitter } from 'node:events'import { PassThrough } from 'node:stream'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { Capture, encodeFrame, hookCapture, recordingFinished, type CaptureProc } from '../src/main/capture'-import { hookTranscription, settleTranscription, speechLocaleFor, spokenChanged, stopTranscriptionServer, transcribing } from '../src/main/asr'+import { hookTranscription, transcribeRecorded, settleTranscription, speechLocaleFor, spokenChanged, stopTranscriptionServer, transcribing } from '../src/main/asr'import type { Spoken } from '../src/shared/spoken'import type { TranscriptPartial } from '../src/shared/types'import { openStore, type Meeting, type Store } from '../src/main/store'@@ -339,3 +339,44 @@ it('refreshes saved live echoes with their IDs before recording ends', async ()expect(store.segments(m.id).every(s => !s.hidden)).toBe(true)await r.stop(m)})++describe('a meeting recorded before the speech model was in (#30)', () => {+ async function* track(...phrases: number[]): AsyncGenerator<Float32Array> {+ // a phrase (1 s of tone, 1 s of quiet) at each given second+ let at = 0+ for (const sec of phrases) {+ yield new Float32Array(Math.round((sec - at) * RATE))+ yield Float32Array.from([...tone(1), ...new Float32Array(RATE)])+ at = sec + 2+ }+ }+ it('once the model is in, is transcribed from its saved recording and no longer waits', async () => {+ rig('transcription-first')+ // as a meeting recorded with no speech model ends up: stopped, waiting, not one line+ const m = meeting()+ store.updateMeeting(m.id, { state: 'stopped', transcriptionPending: true })+ expect(store.untranscribedMeetings().map((x) => x.id)).toEqual([m.id])+ expect(await transcribeRecorded(m.id, { them: track(1, 4), me: track(7) })).toBe(true)+ const lines = store.segments(m.id).map((x) => `${x.track}@${Math.round(x.startMs / 1000)}`)+ expect(lines).toEqual(expect.arrayContaining(['them@1', 'them@4', 'me@7']))+ expect(store.meeting(m.id)?.transcriptionPending).not.toBe(true)+ expect(store.untranscribedMeetings()).toEqual([])+ })+ it('a meeting with some transcript is never transcribed again (no lines twice)', async () => {+ const r = rig('transcription-first', { transcriber: async () => { throw new Error('whisper fell over') } })+ const m = meeting()+ r.begin(m); r.procs[0].say('them', 500)+ await r.stop(m)+ store.updateMeeting(m.id, { state: 'stopped' })+ store.addSegments([{ meetingId: m.id, track: 'them', startMs: 0, endMs: 900, text: 'one line made it', speaker: null }])+ expect(store.meeting(m.id)?.transcriptionPending).toBe(true)+ expect(store.untranscribedMeetings()).toEqual([])+ })+ it('without the model yet, nothing happens and the meeting keeps waiting', async () => {+ rig('transcription-first', { modelPath: () => undefined })+ const m = meeting()+ store.updateMeeting(m.id, { state: 'stopped', transcriptionPending: true })+ expect(await transcribeRecorded(m.id, { them: track(1) })).toBe(false)+ expect(store.meeting(m.id)?.transcriptionPending).toBe(true)+ })+})