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.

22.2 KB
Raw Blame
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createParakeetReader, createTranscriber, PARAKEET_LOCK_MS } from '../src/main/asr/transcribe'
import type { Chunk } from '../src/main/asr/chunker'
import type { ParakeetToken } from '../src/main/asr/parakeet'

const servers: Server[] = []
afterEach(async () => { await Promise.all(servers.splice(0).map((s) => new Promise<void>((r) => s.close(() => r())))) })

/** a stand-in server: counts requests, remembers their form fields and audio length, answers what `reply` says */
async function stub(reply: (n: number, fields: Record<string, string>) => unknown) {
  const seen: Array<{ fields: Record<string, string>; samples: number }> = []
  const server = createServer((req, res) => {
    const parts: Buffer[] = []
    req.on('data', (d: Buffer) => parts.push(d))
    req.on('end', () => {
      const body = Buffer.concat(parts)
      const fields: Record<string, string> = {}
      for (const m of body.toString('latin1').matchAll(/name="([^"]+)"(?!; filename)\r\n\r\n([^\r]*)\r\n/g)) fields[m[1]] = m[2]
      const riff = body.indexOf('RIFF')
      seen.push({ fields, samples: body.readUInt32LE(riff + 40) / 2 })
      res.setHeader('content-type', 'application/json')
      const answer = reply(seen.length - 1, fields) as { __status?: number }
      if (answer?.__status) res.statusCode = answer.__status
      res.end(JSON.stringify(answer))
    })
  })
  servers.push(server)
  await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
  return { url: async () => `http://127.0.0.1:${(server.address() as AddressInfo).port}`, seen }
}

/** whisper's answer: what it heard, in which language, how sure */
const whisperSays = (text: string, language = 'english', prob = 0.99) => ({ language, detected_language: language, detected_language_probability: prob, segments: text ? [{ start: 0.2, end: 2, text: ` ${text}`, avg_logprob: -0.1, no_speech_prob: 0.01 }] : [] })
/** Parakeet's answer: the words as sure tokens at a talking pace, or as the unsure ones of a language it doesn't know */
const parakeetSays = (text: string, logprob = -0.01) => {
  // pieces of two letters, the first of a word with its space
  const tokens: ParakeetToken[] = text.split(' ').filter(Boolean).flatMap((w) => (w.match(/.{1,2}/gu) ?? []).map((piece, i) => (i ? piece : `▁${piece}`)))
    .map((piece, i) => ({ text: piece, start: i * 0.1, end: i * 0.1 + 0.08, logprob }))
  return { duration: tokens.length * 0.1, text, tokens }
}
const GIBBERISH = 'Intannetodektaj tik kankjok sen citi Kensak Suratok u sorakka Gen Xiu no Ze detik show intannet odek tajtik kank jok sen citi'
/** a chunk with this much clear speech in it */
const chunk = (track: 'me' | 'them', startMs: number, sec = 10, clearMs = sec * 800): Chunk => ({ track, startMs, samples: new Float32Array(16000 * sec), clearMs })

describe("Parakeet's reader", () => {
  it('gives lines on meeting time with word times, like whisper\'s', async () => {
    const pk = await stub(() => ({ duration: 3, text: 'Hello there. Fine.', tokens: [
      { text: '▁Hel', start: 0.5, end: 0.7, logprob: -0.01 }, { text: 'lo', start: 0.7, end: 0.9, logprob: -0.01 }, { text: '▁there', start: 1.0, end: 1.3, logprob: -0.01 }, { text: '.', start: 1.3, end: 1.3, logprob: -0.01 },
      { text: '▁Fine', start: 2.0, end: 2.4, logprob: -0.01 }, { text: '.', start: 2.4, end: 2.4, logprob: -0.01 }] }))
    const r = await createParakeetReader(pk)(chunk('them', 60_000, 3))
    expect(r.lines).toEqual([
      { track: 'them', startMs: 60_500, endMs: 61_300, text: 'Hello there.', words: [{ text: ' Hello', startMs: 60_500, endMs: 60_900 }, { text: ' there.', startMs: 61_000, endMs: 61_300 }] },
      { track: 'them', startMs: 62_000, endMs: 62_400, text: 'Fine.', words: [{ text: ' Fine.', startMs: 62_000, endMs: 62_400 }] },
    ])
    expect(r.flagged).toBe(false)
    expect(pk.seen[0].fields.prompt).toBeUndefined()
  })
  it('never sends more than 15 s in one pass, and puts the passes back on one clock', async () => {
    const pk = await stub((n) => ({ duration: 15, text: n ? 'two' : 'one', tokens: [{ text: n ? '▁two.' : '▁one.', start: 1, end: 1.5, logprob: -0.01 }] }))
    const r = await createParakeetReader(pk)(chunk('them', 0, 28))
    expect(pk.seen).toHaveLength(2)
    for (const s of pk.seen) expect(s.samples / 16000).toBeLessThanOrEqual(15)
    expect(r.lines.map((l) => l.text)).toEqual(['one.', 'two.'])
    expect(r.lines[1].startMs).toBe(Math.round((pk.seen[0].samples / 16 + 1000)))
  })
})

describe('English only', () => {
  it('goes straight to Parakeet: whisper is never asked', async () => {
    const w = await stub(() => whisperSays('whisper heard this'))
    const pk = await stub(() => parakeetSays('Thanks for joining everyone.'))
    const engines: string[] = [], heard: string[] = []
    const tr = createTranscriber({ url: w.url, language: () => 'en', onLanguage: (_t, l) => heard.push(l), parakeet: { url: pk.url, onEngine: (t, e, why) => engines.push(`${t} ${e}: ${why}`) } })
    expect((await tr(chunk('me', 0))).map((l) => l.text)).toEqual(['Thanks for joining everyone.'])
    await tr(chunk('me', 12_000), { partial: true })
    expect(w.seen).toHaveLength(0)
    expect(pk.seen).toHaveLength(2)
    expect(engines).toEqual(['me parakeet: Parakeet knows en'])
    expect(heard).toEqual(['english'])
  })
  it('a pinned language Parakeet does not cover stays with whisper', async () => {
    const w = await stub(() => whisperSays('こんにちは', 'japanese'))
    const pk = await stub(() => parakeetSays(GIBBERISH, -0.8))
    const tr = createTranscriber({ url: w.url, language: () => 'ja', parakeet: { url: pk.url } })
    expect((await tr(chunk('them', 0))).map((l) => l.text)).toEqual(['こんにちは'])
    expect(pk.seen).toHaveLength(0)
    expect(w.seen[0].fields.language).toBe('ja')
  })
  it('gibberish on several chunks in a row, where whisper hears a language Parakeet does not cover, sends the track back to whisper for good; the other track stays', async () => {
    const w = await stub(() => whisperSays('what whisper makes of it', 'japanese', 0.97))
    const pk = await stub(() => parakeetSays(GIBBERISH, -0.76))
    const engines: string[] = []
    const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`) } })
    // each flagged chunk is read by whisper instead, so no gibberish is saved even before the track moves
    for (let i = 0; i < 3; i++) expect((await tr(chunk('them', i * 12_000))).map((l) => l.text)).toEqual(['what whisper makes of it'])
    expect(pk.seen).toHaveLength(3)
    await tr(chunk('them', 40_000))
    await tr(chunk('them', 52_000), { partial: true })
    expect(pk.seen).toHaveLength(3)
    expect(w.seen).toHaveLength(5)
    expect(engines).toEqual(['them parakeet', 'them whisper'])
    await tr(chunk('me', 60_000))
    expect(pk.seen).toHaveLength(4)
  })
  it('a noisy room: Parakeet unsure of chunk after chunk, but whisper hears English in them, so the track stays with Parakeet', async () => {
    const w = await stub(() => whisperSays('whisper reads the unsure ones', 'english', 0.9))
    let unsure = true
    const pk = await stub(() => (unsure ? parakeetSays('We can uh use uh the total topic for the music hyper scale that', -0.28) : parakeetSays('Now it is clear again, thanks for waiting everyone.')))
    const engines: string[] = []
    const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`) } })
    for (let i = 0; i < 5; i++) expect((await tr(chunk('them', i * 12_000))).map((l) => l.text)).toEqual(['whisper reads the unsure ones'])
    unsure = false
    expect((await tr(chunk('them', 70_000))).map((l) => l.text)).toEqual(['Now it is clear again, thanks for waiting everyone.'])
    expect(engines).toEqual(['them parakeet'])
    expect(pk.seen).toHaveLength(6)
  })
  it('short flagged chunks change nothing: Parakeet keeps the track and its words', async () => {
    const w = await stub(() => whisperSays('whisper'))
    const pk = await stub(() => parakeetSays('Yeah sure', -0.5))
    // 2 s chunks: too short to judge
    const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url } })
    for (let i = 0; i < 6; i++) expect((await tr(chunk('them', i * 3000, 2))).map((l) => l.text)).toEqual(['Yeah sure'])
    expect(w.seen).toHaveLength(0)
  })
})

describe('Multi-language', () => {
  it('whisper hears the language of the first 10 s of speech; a covered one moves the track to Parakeet', async () => {
    const lid = await stub(() => whisperSays('hallo zusammen wir fangen an', 'german', 0.97))
    const big = await stub(() => whisperSays('never asked'))
    const pk = await stub(() => parakeetSays('Hallo zusammen, wir fangen an.'))
    const engines: string[] = [], heard: Array<[string, boolean]> = []
    const tr = createTranscriber({ url: big.url, onLanguage: (_t, l, _n, locked) => heard.push([l, locked]), parakeet: { url: pk.url, lid, onEngine: (t, e, why) => engines.push(`${t} ${e}: ${why}`) } })
    expect(PARAKEET_LOCK_MS).toBe(10_000)
    // 6 s heard: not locked yet, but the line is Parakeet's already (whisper is sure it is German)
    expect((await tr(chunk('them', 0, 6))).map((l) => l.text)).toEqual(['Hallo zusammen, wir fangen an.'])
    expect(engines).toEqual([])
    expect((await tr(chunk('them', 7000, 6))).map((l) => l.text)).toEqual(['Hallo zusammen, wir fangen an.'])
    expect(engines).toEqual(['them parakeet: Parakeet knows german'])
    expect(lid.seen).toHaveLength(2)
    expect(lid.seen[0].fields.language).toBe('auto')
    // locked: whisper is done with this track
    await tr(chunk('them', 14_000, 6))
    await tr(chunk('them', 21_000, 6), { partial: true })
    expect(lid.seen).toHaveLength(2)
    expect(big.seen).toHaveLength(0)
    expect(pk.seen).toHaveLength(4)
    expect(heard).toEqual([['german', false], ['german', false], ['german', true]])
  })
  it('a language Parakeet does not cover stays with whisper: the bigger model reads it, and a fetch of one is asked for', async () => {
    const lid = await stub(() => whisperSays('konnichiwa', 'japanese', 0.98))
    const big = await stub(() => whisperSays('こんにちは、始めましょう', 'japanese', 0.98))
    const pk = await stub(() => parakeetSays(GIBBERISH, -0.8))
    const engines: string[] = [], uncovered: string[] = []
    const tr = createTranscriber({ url: big.url, parakeet: { url: pk.url, lid, onEngine: (t, e, why) => engines.push(`${t} ${e}: ${why}`), onUncovered: (l) => uncovered.push(l) } })
    expect((await tr(chunk('them', 0, 12))).map((l) => l.text)).toEqual(['こんにちは、始めましょう'])
    expect(engines).toEqual(['them whisper: Parakeet does not know japanese'])
    expect(uncovered).toEqual(['japanese'])
    await tr(chunk('them', 13_000, 8))
    expect(pk.seen).toHaveLength(0)
    expect(lid.seen).toHaveLength(1)
    expect(big.seen.map((s) => s.fields.language)).toEqual(['japanese', 'japanese'])
  })
  it('with one whisper only (no bigger one on disk), it hears the language and reads what Parakeet cannot', async () => {
    const w = await stub(() => whisperSays('こんにちは', 'japanese', 0.98))
    const pk = await stub(() => parakeetSays(GIBBERISH, -0.8))
    const tr = createTranscriber({ url: w.url, parakeet: { url: pk.url } })
    expect((await tr(chunk('them', 0, 12))).map((l) => l.text)).toEqual(['こんにちは'])
    await tr(chunk('them', 13_000, 8))
    expect(w.seen.map((s) => s.fields.language)).toEqual(['auto', 'japanese'])
    expect(pk.seen).toHaveLength(0)
  })
  it('whisper unsure of the language, or Parakeet unsure of its own reading, keeps whisper\'s line before the lock', async () => {
    const lid = await stub((n) => (n === 0 ? whisperSays('maybe english', 'english', 0.55) : whisperSays('sure english now', 'english', 0.95)))
    const pk = await stub(() => parakeetSays('Mumble jumble', -0.6))
    const tr = createTranscriber({ url: lid.url, parakeet: { url: pk.url } })
    expect((await tr(chunk('me', 0, 3))).map((l) => l.text)).toEqual(['maybe english'])
    expect(pk.seen).toHaveLength(0)
    expect((await tr(chunk('me', 4000, 3))).map((l) => l.text)).toEqual(['sure english now'])
    expect(pk.seen).toHaveLength(1)
  })
  it('a track on Parakeet that turns to gibberish is heard again by whisper, and follows the language it is in now', async () => {
    let japanese = false
    const lid = await stub(() => (japanese ? whisperSays('nihongo', 'japanese', 0.98) : whisperSays('good morning all', 'english', 0.98)))
    const big = await stub(() => whisperSays('日本語で話します', 'japanese', 0.98))
    const pk = await stub(() => (japanese ? parakeetSays(GIBBERISH, -0.8) : parakeetSays('Good morning all, shall we start now?')))
    const engines: string[] = []
    const tr = createTranscriber({ url: big.url, parakeet: { url: pk.url, lid, onEngine: (t, e) => engines.push(`${t} ${e}`) } })
    await tr(chunk('them', 0, 12))
    expect(engines).toEqual(['them parakeet'])
    japanese = true
    // each gibberish chunk is read by whisper instead; the third in a row gives the track up
    for (let i = 1; i <= 3; i++) expect((await tr(chunk('them', i * 13_000, 12))).map((l) => l.text)).toEqual(['日本語で話します'])
    expect(engines).toEqual(['them parakeet', 'them whisper'])
    const asked = pk.seen.length
    await tr(chunk('them', 60_000, 12))
    expect(pk.seen).toHaveLength(asked)
  })
  it('one good chunk between flagged ones keeps the track on Parakeet', async () => {
    let bad = false
    const lid = await stub(() => whisperSays('good morning all', 'english', 0.98))
    const pk = await stub(() => (bad ? parakeetSays(GIBBERISH, -0.8) : parakeetSays('Good morning all, shall we start now?')))
    const engines: string[] = []
    const tr = createTranscriber({ url: lid.url, parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`) } })
    await tr(chunk('them', 0, 12))
    for (const flags of [true, true, false, true, true]) { bad = flags; await tr(chunk('them', 20_000, 12)) }
    expect(engines).toEqual(['them parakeet'])
  })
  it('each track has its own language and its own reader', async () => {
    const lid = await stub((_n, f) => whisperSays('x y z', f.language === 'auto' ? 'english' : f.language))
    const pk = await stub(() => parakeetSays('Fine by me, go ahead.'))
    const tr = createTranscriber({ url: lid.url, parakeet: { url: pk.url } })
    await tr(chunk('me', 0, 12))
    expect(pk.seen).toHaveLength(1)
    // the other track is not locked by that
    await tr(chunk('them', 0, 2), { partial: true })
    expect(lid.seen.at(-1)!.fields.language).toBe('auto')
  })
})

describe('without Parakeet (not downloaded yet, too slow here, or switched off)', () => {
  it('whisper reads everything and locks on the first clear chunk, as before', async () => {
    const w = await stub(() => whisperSays('hola a todos empezamos', 'spanish', 0.95))
    const tr = createTranscriber({ url: w.url })
    await tr(chunk('them', 0, 2))
    await tr(chunk('them', 3000, 2))
    expect(w.seen.map((s) => s.fields.language)).toEqual(['auto', 'spanish'])
  })
})

describe('parakeet-server fails while a meeting runs (it will not start, crashes, or answers with an error)', () => {
  const down = { __status: 500 }
  const quiet = () => { const w = vi.spyOn(console, 'warn').mockImplementation(() => {}); return () => w.mockRestore() }
  it('English only: whisper reads the chunk instead, and after two failures in a row the track stays with whisper', async () => {
    const restore = quiet()
    try {
      const w = await stub(() => whisperSays('whisper reads it'))
      const pk = await stub(() => down)
      const engines: string[] = [], failed: Array<{ never: boolean }> = []
      const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`), onFailed: (f) => failed.push({ never: f.never }) } })
      expect((await tr(chunk('them', 0))).map((l) => l.text)).toEqual(['whisper reads it'])
      expect((await tr(chunk('them', 12_000))).map((l) => l.text)).toEqual(['whisper reads it'])
      expect(engines).toEqual(['them parakeet', 'them whisper'])
      const asked = pk.seen.length
      expect((await tr(chunk('them', 24_000))).map((l) => l.text)).toEqual(['whisper reads it'])
      await tr(chunk('them', 36_000), { partial: true })
      expect(pk.seen).toHaveLength(asked)
      // Parakeet never answered once: the caller is told, so the next meetings start on whisper
      expect(failed).toEqual([{ never: true }])
    } finally { restore() }
  })
  it('one failure between good readings changes nothing', async () => {
    const restore = quiet()
    try {
      let broken = false
      const w = await stub(() => whisperSays('whisper covers the gap'))
      const pk = await stub(() => (broken ? down : parakeetSays('Parakeet reads this one fine, thanks.')))
      const engines: string[] = [], failed: unknown[] = []
      const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`), onFailed: (f) => failed.push(f) } })
      for (const b of [false, true, false, true, false]) { broken = b; expect((await tr(chunk('them', 0))).map((l) => l.text)).toEqual([b ? 'whisper covers the gap' : 'Parakeet reads this one fine, thanks.']) }
      expect(engines).toEqual(['them parakeet'])
      expect(failed).toEqual([])
    } finally { restore() }
  })
  it('Multi-language, a track locked on Parakeet: whisper reads in the locked language, and takes the track after two failures', async () => {
    const restore = quiet()
    try {
      let broken = false
      const lid = await stub(() => whisperSays('guten morgen zusammen', 'german', 0.97))
      const big = await stub(() => whisperSays('Guten Morgen zusammen (whisper)', 'german', 0.97))
      const pk = await stub(() => (broken ? down : parakeetSays('Guten Morgen zusammen, wir fangen an.')))
      const engines: string[] = [], failed: Array<{ never: boolean }> = []
      const tr = createTranscriber({ url: big.url, parakeet: { url: pk.url, lid, onEngine: (t, e) => engines.push(`${t} ${e}`), onFailed: (f) => failed.push({ never: f.never }) } })
      await tr(chunk('them', 0, 12))
      expect(engines).toEqual(['them parakeet'])
      broken = true
      expect((await tr(chunk('them', 13_000, 8))).map((l) => l.text)).toEqual(['Guten Morgen zusammen (whisper)'])
      expect((await tr(chunk('them', 22_000, 8))).map((l) => l.text)).toEqual(['Guten Morgen zusammen (whisper)'])
      expect(big.seen.map((x) => x.fields.language)).toEqual(['german', 'german'])
      expect(engines).toEqual(['them parakeet', 'them whisper'])
      const asked = pk.seen.length
      await tr(chunk('them', 31_000, 8))
      expect(pk.seen).toHaveLength(asked)
      // it had answered before: only this meeting's track leaves it
      expect(failed).toEqual([{ never: false }])
    } finally { restore() }
  })
  it('before the lock, whisper\'s finished reading is kept when Parakeet fails', async () => {
    const restore = quiet()
    try {
      const lid = await stub(() => whisperSays('good morning everyone', 'english', 0.97))
      const pk = await stub(() => down)
      const tr = createTranscriber({ url: lid.url, parakeet: { url: pk.url } })
      expect((await tr(chunk('me', 0, 4))).map((l) => l.text)).toEqual(['good morning everyone'])
    } finally { restore() }
  })
  it('a stopped transcription is not taken for a failing Parakeet', async () => {
    const w = await stub(() => whisperSays('never'))
    const pk = await stub(() => parakeetSays('never either'))
    const abort = new AbortController()
    abort.abort()
    const tr = createTranscriber({ url: w.url, language: () => 'en', signal: abort.signal, parakeet: { url: pk.url } })
    await expect(tr(chunk('them', 0))).rejects.toThrow()
    expect(w.seen).toHaveLength(0)
  })
})

describe('leaving Parakeet needs whisper to be sure of what it hears', () => {
  it('hold music or noise: Parakeet unsure and whisper only guessing at a language keeps an English only track on Parakeet', async () => {
    const restore = vi.spyOn(console, 'warn').mockImplementation(() => {})
    try {
      const w = await stub(() => whisperSays('la la la', 'japanese', 0.41))
      let music = true
      const pk = await stub(() => (music ? parakeetSays(GIBBERISH, -0.6) : parakeetSays('Sorry about the wait, shall we begin now?')))
      const engines: string[] = []
      const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`) } })
      for (let i = 0; i < 6; i++) await tr(chunk('them', i * 12_000))
      music = false
      expect((await tr(chunk('them', 90_000))).map((l) => l.text)).toEqual(['Sorry about the wait, shall we begin now?'])
      expect(engines).toEqual(['them parakeet'])
    } finally { restore.mockRestore() }
  })
})

describe('a language Parakeet does not cover is told at once, so the bigger whisper can be fetched', () => {
  it('Multi-language: on the first chunk clearly heard in it, before the track is locked', async () => {
    const w = await stub(() => whisperSays('こんにちは', 'japanese', 0.95))
    const pk = await stub(() => parakeetSays(GIBBERISH, -0.8))
    const uncovered: string[] = []
    const tr = createTranscriber({ url: w.url, parakeet: { url: pk.url, onUncovered: (l) => uncovered.push(l) } })
    await tr(chunk('them', 0, 3))
    expect(uncovered).toEqual(['japanese'])
    await tr(chunk('them', 4000, 3))
    await tr(chunk('them', 8000, 12))
    // once per language
    expect(uncovered).toEqual(['japanese'])
  })
  it('English only: when a track falls off Parakeet because whisper hears another language', async () => {
    const restore = vi.spyOn(console, 'warn').mockImplementation(() => {})
    try {
      const w = await stub(() => whisperSays('what whisper makes of it', 'hindi', 0.93))
      const pk = await stub(() => parakeetSays(GIBBERISH, -0.76))
      const uncovered: string[] = []
      const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onUncovered: (l) => uncovered.push(l) } })
      await tr(chunk('them', 0)); await tr(chunk('them', 12_000))
      expect(uncovered).toEqual([])
      await tr(chunk('them', 24_000))
      expect(uncovered).toEqual(['hindi'])
    } finally { restore.mockRestore() }
  })
})