Skip to content

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.

11.5 KB
Raw Blame
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { forgetParakeetTrouble, hookTranscription, releaseIdleSpeech, settleTranscription, stopTranscriptionServer, transcribeRecorded } from '../src/main/asr'
import type { WhisperServer } from '../src/main/asr/server'
import type { Spoken } from '../src/shared/spoken'
import { openStore, type Meeting, type Store } from '../src/main/store'

// the session around the pipeline; the echo canceller is tested on its own
vi.mock('../src/main/asr/aec3', () => ({ loadAec3: async () => {}, aec3: vi.fn(() => null) }))

let store: Store
beforeEach(() => { store = openStore(':memory:') })
const meeting = (): Meeting => store.createMeeting({ title: 't', startedAt: 1, endedAt: null, eventId: null, app: null, attendees: [], state: 'recording' })
const disposers: Array<() => void> = []
afterEach(async () => { disposers.splice(0).forEach((d) => d()); await settleTranscription(2000); stopTranscriptionServer() })

/** stand-in speech servers, remembered by the model they were started for */
function fakeServers() {
  const made: Array<{ model: string; pidFile?: string; urls: number; stops: number }> = []
  const make = (model: string, pidFile?: string) => {
    const rec = { model, pidFile, urls: 0, stops: 0 }
    made.push(rec)
    return { url: async () => { rec.urls++; return 'http://127.0.0.1:1' }, resetBudget: () => {}, gpuAgain: () => false, timeoutMs: () => 30_000, timed: () => {}, tooSlow: false, cpuRtf: null, cpuOnly: false, wedged: async () => 'http://127.0.0.1:1', alive: async () => true, kill: () => {}, stop: async () => { rec.stops++ } } as unknown as WhisperServer
  }
  return { made, make, of: (model: string) => made.filter((m) => m.model === model) }
}

function hooks(o: { whisper: string; parakeet?: { model: string; lid: string }; spoken?: Spoken; off?: string | null; afterMeeting?: boolean }) {
  const s = fakeServers()
  const starts: Array<(m: Meeting) => void> = [], stops: Array<(m: Meeting) => void> = []
  const warns: string[] = []
  disposers.push(hookTranscription({
    store, modelPath: () => o.whisper, send: () => {}, warn: (c) => warns.push(c), server: s.make, serverIdleMs: 60_000, pidFile: join('/profile', 'whisper-server.pid'),
    parakeet: () => o.parakeet, parakeetOff: () => o.off ?? null, spoken: () => o.spoken ?? 'en', afterMeeting: () => !!o.afterMeeting,
    onStart: (fn) => { starts.push(fn) }, onStop: (fn) => { stops.push(fn) },
  }))
  return { s, warns, begin: (m: Meeting) => starts.forEach((f) => f(m)), end: async (m: Meeting) => { stops.forEach((f) => f(m)); await settleTranscription(2000) } }
}

/** what the log said under the ASR tag */
function asrLog() {
  const spy = vi.spyOn(console, 'info').mockImplementation(() => {})
  return { lines: () => spy.mock.calls.filter((a) => a[0] === 'ASR').map((a) => String(a[1])), restore: () => spy.mockRestore() }
}

describe('a meeting with Parakeet', () => {
  it('English only: parakeet-server is warmed up, whisper is not started at all, and the log says who reads and why', async () => {
    const log = asrLog()
    try {
      const h = hooks({ whisper: '/m/ggml-base-q5_1.bin', parakeet: { model: '/m/ggml-parakeet-tdt-0.6b-v3-q8_0.bin', lid: '/m/ggml-base-q5_1.bin' } })
      const m = meeting()
      h.begin(m)
      expect(h.s.of('/m/ggml-parakeet-tdt-0.6b-v3-q8_0.bin')[0]).toMatchObject({ urls: 1, pidFile: join('/profile', 'parakeet-server.pid') })
      expect(h.s.of('/m/ggml-base-q5_1.bin').reduce((n, x) => n + x.urls, 0)).toBe(0)
      expect(log.lines().find((l) => l.startsWith('meeting start'))).toMatch(/Parakeet \(ggml-parakeet-tdt-0\.6b-v3-q8_0\.bin\) reads both tracks, the language is given as en; whisper \(ggml-base-q5_1\.bin\) stands by/)
      await h.end(m)
    } finally { log.restore() }
  })
  it('Multi-language: Parakeet and the small whisper that hears languages are warmed up; the bigger whisper waits until a track needs it', async () => {
    const log = asrLog()
    try {
      const h = hooks({ whisper: '/m/ggml-large-v3-turbo-q5_0.bin', parakeet: { model: '/m/pk.bin', lid: '/m/ggml-base-q5_1.bin' }, spoken: 'multi' })
      const m = meeting()
      h.begin(m)
      expect(h.s.of('/m/pk.bin')[0].urls).toBe(1)
      expect(h.s.of('/m/ggml-base-q5_1.bin')[0]).toMatchObject({ urls: 1, pidFile: join('/profile', 'whisper-server-lid.pid') })
      expect(h.s.of('/m/ggml-large-v3-turbo-q5_0.bin')[0].urls).toBe(0)
      expect(log.lines().find((l) => l.startsWith('meeting start'))).toMatch(/Multi-language: whisper \(ggml-base-q5_1\.bin\) hears each track's language first, then Parakeet \(pk\.bin\) reads the languages it covers and whisper \(ggml-large-v3-turbo-q5_0\.bin\) the rest/)
      await h.end(m)
    } finally { log.restore() }
  })
  it('Multi-language with only the small whisper: it hears the languages itself, and no third server is made', async () => {
    const h = hooks({ whisper: '/m/ggml-base-q5_1.bin', parakeet: { model: '/m/pk.bin', lid: '/m/ggml-base-q5_1.bin' }, spoken: 'multi' })
    const m = meeting()
    h.begin(m)
    expect(h.s.made.map((x) => x.model).sort()).toEqual(['/m/ggml-base-q5_1.bin', '/m/pk.bin'])
    expect(h.s.of('/m/ggml-base-q5_1.bin')[0].urls).toBe(1)
    await h.end(m)
  })
  it('a computer whose whisper only transcribes after the meeting is live with Parakeet', async () => {
    const h = hooks({ whisper: '/m/ggml-small-q5_1.bin', parakeet: { model: '/m/pk.bin', lid: '/m/ggml-base-q5_1.bin' }, afterMeeting: true })
    const m = meeting()
    h.begin(m)
    await new Promise((r) => setTimeout(r, 450))
    expect(h.warns).not.toContain('live-paused')
    await h.end(m)
  })
  it('every speech server goes when they are let go, and the next meeting starts new ones', async () => {
    const h = hooks({ whisper: '/m/turbo.bin', parakeet: { model: '/m/pk.bin', lid: '/m/base.bin' }, spoken: 'multi' })
    const a = meeting()
    h.begin(a); await h.end(a)
    await releaseIdleSpeech()
    expect(h.s.made.map((x) => x.stops)).toEqual([1, 1, 1])
    const b = meeting()
    h.begin(b)
    expect(h.s.made).toHaveLength(6)
    await h.end(b)
  })
})

describe('a meeting without Parakeet', () => {
  it('the kill switch: whisper reads every language as before, and the log says the switch is why', async () => {
    const log = asrLog()
    try {
      const h = hooks({ whisper: '/m/ggml-large-v3-turbo-q5_0.bin', off: 'YOGURT_ASR=whisper' })
      const m = meeting()
      h.begin(m)
      expect(h.s.made.map((x) => x.model)).toEqual(['/m/ggml-large-v3-turbo-q5_0.bin'])
      expect(h.s.made[0].urls).toBe(1)
      expect(log.lines().find((l) => l.startsWith('meeting start'))).toMatch(/whisper \(ggml-large-v3-turbo-q5_0\.bin\) reads every language: YOGURT_ASR=whisper/)
      await h.end(m)
    } finally { log.restore() }
  })
  it('not downloaded yet (an install from before it): whisper as before, and the log says so', async () => {
    const log = asrLog()
    try {
      const h = hooks({ whisper: '/m/ggml-large-v3-turbo-q5_0.bin' })
      const m = meeting()
      h.begin(m)
      expect(h.s.made).toHaveLength(1)
      expect(log.lines().find((l) => l.startsWith('meeting start'))).toMatch(/reads every language: Parakeet is not in use on this computer/)
      await h.end(m)
    } finally { log.restore() }
  })
  it('a computer that transcribes after the meeting still does', async () => {
    const h = hooks({ whisper: '/m/ggml-small-q5_1.bin', afterMeeting: true })
    const m = meeting()
    h.begin(m)
    await vi.waitFor(() => expect(h.warns).toContain('live-paused'))
    await h.end(m)
  })
})

describe('parakeet-server will not start', () => {
  const RATE = 16000
  /** n phrases of 1 s of tone with 1 s of quiet after each, as a saved recording's track */
  async function* track(n: number) { for (let i = 0; i < n; i++) { yield Float32Array.from({ length: RATE }, (_, k) => 0.3 * Math.sin(k / 10)); yield new Float32Array(RATE) } }
  const http: Array<import('node:http').Server> = []
  afterEach(async () => { await Promise.all(http.splice(0).map((s) => new Promise<void>((r) => s.close(() => r())))); forgetParakeetTrouble() })
  /** a whisper that answers every chunk in English */
  async function whisper() {
    const { createServer } = await import('node:http')
    const s = createServer((req, res) => { req.resume(); req.on('end', () => { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ detected_language: 'english', detected_language_probability: 0.99, segments: [{ start: 0, end: 1, text: ' Whisper read this' }] })) }) })
    http.push(s)
    await new Promise<void>((r) => s.listen(0, '127.0.0.1', r))
    return `http://127.0.0.1:${(s.address() as import('node:net').AddressInfo).port}`
  }

  it('the saved-recording pass (and Transcribe again) falls back to whisper, finishes whole, and the next meeting starts on whisper', async () => {
    const url = await whisper()
    const made: Array<{ model: string; urls: number }> = []
    const make = (model: string) => {
      const rec = { model, urls: 0 }
      made.push(rec)
      const dead = model.includes('parakeet')
      return { url: async () => { rec.urls++; if (dead) throw new Error('parakeet-server could not start: spawn ENOENT'); return url }, resetBudget: () => {}, gpuAgain: () => false, timeoutMs: () => 30_000, timed: () => {}, tooSlow: false, cpuRtf: null, cpuOnly: false, wedged: async () => { if (dead) throw new Error('parakeet-server stopped and will not be started again this meeting'); return url }, alive: async () => !dead, kill: () => {}, stop: async () => {} } as unknown as WhisperServer
    }
    const wanted: number[] = [], warns: string[] = []
    const info = vi.spyOn(console, 'info').mockImplementation(() => {}), warn = vi.spyOn(console, 'warn').mockImplementation(() => {}), err = vi.spyOn(console, 'error').mockImplementation(() => {})
    try {
      disposers.push(hookTranscription({
        store, modelPath: () => '/m/ggml-base-q5_1.bin', send: () => {}, warn: (c) => warns.push(c), server: make, serverIdleMs: 60_000, holdMs: 0,
        parakeet: () => ({ model: '/m/ggml-parakeet.bin', lid: '/m/ggml-base-q5_1.bin' }), parakeetOff: () => null, spoken: () => 'en', wantWhisper: () => wanted.push(1),
        onStart: () => {}, onStop: () => {},
      }))
      const m = store.createMeeting({ title: 't', startedAt: 1, endedAt: 2, eventId: null, app: null, attendees: [], state: 'done' })
      expect(await transcribeRecorded(m.id, { them: track(4) })).toBe(true)
      // every chunk was read, by whisper, and nothing is left waiting or in error
      expect(store.segments(m.id).map((l) => l.text)).toEqual(Array(4).fill('Whisper read this'))
      expect(store.meeting(m.id)?.transcriptionPending).toBeFalsy()
      expect(warns).toEqual([])
      expect(warn.mock.calls.map((a) => a.join(' ')).join('\n')).toMatch(/ASR them: parakeet-server failed \(.*could not start.*\): whisper reads this chunk/)
      expect(wanted.length).toBeGreaterThan(0)
      // it never answered: the next meeting does not try it
      const before = made.filter((x) => x.model.includes('parakeet')).reduce((n, x) => n + x.urls, 0)
      const next = store.createMeeting({ title: 'n', startedAt: 3, endedAt: 4, eventId: null, app: null, attendees: [], state: 'done' })
      expect(await transcribeRecorded(next.id, { them: track(2) })).toBe(true)
      expect(made.filter((x) => x.model.includes('parakeet')).reduce((n, x) => n + x.urls, 0)).toBe(before)
      expect(info.mock.calls.filter((a) => a[0] === 'ASR').map((a) => String(a[1])).at(-1)).toMatch(/whisper \(ggml-base-q5_1\.bin\) reads every language: parakeet-server failed earlier/)
    } finally { info.mockRestore(); warn.mockRestore(); err.mockRestore() }
  })
})