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.

9.1 KB
Raw Blame
import { chmodSync, existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { createServer } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createRequire } from 'node:module'
import { afterEach, describe, expect, it } from 'vitest'
import { createWhisperServer, killStale } from '../src/main/asr/server'
import { fakeParakeetMeasure, fakeParakeetTry, measureParakeet } from '../src/main/asr/speedCheck'
import { wavBytes } from '../src/main/asr/transcribe'
import type { WhisperServer } from '../src/main/asr/server'
import { helperFile } from '../src/shared/platform'
import bundled from '../../catalog/catalog.json'
import licenses from '../../catalog/licenses.json'

const dir = () => mkdtempSync(join(tmpdir(), 'yogurt-pk-'))

/** a stand-in for the parakeet-server program: writes down its arguments and answers GET / */
function fakeBinary() {
  const d = dir(), js = join(d, 'pk.js')
  writeFileSync(js, `
    const fs = require('fs'), a = process.argv
    fs.writeFileSync(${JSON.stringify(join(d, 'args'))}, JSON.stringify(a.slice(2)))
    process.stderr.write('parakeet_backend_init_gpu: using MTL0 backend\\n')
    require('http').createServer((q, r) => { if (q.method === 'POST') { q.resume(); r.statusCode = 500; return r.end('{}') } r.end('ok') }).listen(Number(a[a.indexOf('--port') + 1]), a[a.indexOf('--host') + 1])
  `)
  const bin = join(d, 'parakeet-server')
  writeFileSync(bin, `#!/bin/sh\nexec "${process.execPath}" "${js}" "$@"\n`)
  chmodSync(bin, 0o755)
  return { bin, args: () => JSON.parse(readFileSync(join(d, 'args'), 'utf8')) as string[] }
}

describe('parakeet-server', () => {
  it('is a helper next to whisper-server on every system', () => {
    expect(helperFile('parakeet', 'darwin')).toBe('parakeet-server')
    expect(helperFile('parakeet', 'linux')).toBe('parakeet-server')
    expect(helperFile('parakeet', 'win32')).toBe('parakeet-server.exe')
  })
  // the stand-in is a shell script, which Windows can't start
  it.skipIf(process.platform === 'win32')('is started with the model, the address and the threads: no beam and no VAD, which it does not have; -ng keeps it on the processor', async () => {
    const f = fakeBinary()
    const s = createWhisperServer({ binary: f.bin, engine: 'parakeet', model: '/m/pk.bin', vadModel: '/vad.bin', cpuOnly: true, pidFile: join(dir(), 'parakeet-server.pid') })
    try {
      expect(await s.url()).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/)
      const a = f.args()
      expect(a.slice(0, 4)).toEqual(['-m', '/m/pk.bin', '--host', '127.0.0.1'])
      expect(a).toContain('-t')
      expect(a).toContain('-ng')
      for (const no of ['-bs', '--vad', '-vm']) expect(a).not.toContain(no)
    } finally { await s.stop() }
  })
  it('one left over from a Yogurt that was killed is cleaned up like a whisper-server; another program with that pid is left alone', () => {
    const killed: number[] = []
    const run = (name: string) => { const f = join(dir(), 'x.pid'); writeFileSync(f, '4242'); killStale(f, { name: () => name, kill: (pid) => killed.push(pid) }); return existsSync(f) }
    expect(run('/Applications/Yogurt.app/Contents/Resources/bin/parakeet-server')).toBe(false)
    expect(run('parakeet-server.exe')).toBe(false)
    expect(killed).toEqual([4242, 4242])
    run('Safari')
    expect(killed).toHaveLength(2)
  })
  it('is signed like whisper-server: with no entitlements of its own', () => {
    const { helperEntitlements } = createRequire(import.meta.url)('../scripts/sign.cjs') as { helperEntitlements(file: string, buildDir: string): string | null }
    expect(helperEntitlements('/x/Yogurt.app/Contents/Resources/bin/parakeet-server', '/build')).toBe(join('/build', 'entitlements.none.plist'))
  })
})

describe('timing Parakeet for the speed check', () => {
  let close: (() => void) | undefined
  afterEach(() => close?.())
  /** a stand-in parakeet-server: each reading after the first (the warm-up) takes delayMs and gives these words */
  async function standIn(delayMs: number, words = 'ask not what your country can do') {
    let asked = 0
    const http = createServer((req, res) => {
      req.resume()
      req.on('end', () => {
        const n = asked++
        const tokens = words.split(' ').filter(Boolean).map((w, i) => ({ text: `▁${w}`, start: i * 0.3, end: i * 0.3 + 0.2, logprob: -0.01 }))
        setTimeout(() => { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ duration: 1, text: words, tokens })) }, n === 0 ? 0 : delayMs)
      })
    })
    await new Promise<void>((r) => http.listen(0, '127.0.0.1', r))
    close = () => http.close()
    const url = `http://127.0.0.1:${(http.address() as { port: number }).port}`
    let stopped = false
    return { srv: { url: async () => url, stop: async () => { stopped = true }, cpuOnly: true } as unknown as WhisperServer, asked: () => asked, stopped: () => stopped }
  }
  const clip = (seconds: number) => { const f = join(dir(), 'clip.wav'); writeFileSync(f, wavBytes(new Float32Array(seconds * 16000))); return f }

  it('by the whisper models\' rules: one reading of the clip over its length, after a warm-up that is not counted; the server is stopped after', async () => {
    const s = await standIn(200)
    const rtf = await measureParakeet('/m/pk.bin', { binary: 'x', clip: clip(1), server: () => s.srv })
    expect(rtf).toBeGreaterThan(0.15)
    expect(rtf).toBeLessThan(0.5)
    expect(s.asked()).toBe(2)
    expect(s.stopped()).toBe(true)
  })
  it('longer than twice the clip is stopped: too slow', async () => {
    const s = await standIn(2500)
    expect(await measureParakeet('/m/pk.bin', { binary: 'x', clip: clip(1), server: () => s.srv })).toBeNull()
    expect(s.stopped()).toBe(true)
  })
  it('a Parakeet that hears no words in the clip is never picked, however fast', async () => {
    const s = await standIn(10, '')
    expect(await measureParakeet('/m/pk.bin', { binary: 'x', clip: clip(1), server: () => s.srv })).toBeNull()
  })
  // the stand-in is a shell script, which Windows can't start
  it.skipIf(process.platform === 'win32')('runs the way meetings will: on the processor where asked (Windows and Linux), with the graphics on a Mac; its pid is kept while it runs, so one left behind by a quit is cleaned up', async () => {
    const f = fakeBinary()
    const pidFile = join(dir(), 'speech-timing.pid')
    // one left by a Yogurt that quit while timing (the pid is nobody's now): cleared when the next one starts
    writeFileSync(pidFile, '999999')
    // the stand-in answers no readings: the try fails, after the program was started as asked
    await expect(measureParakeet('/m/pk.bin', { binary: f.bin, clip: clip(1), cpu: true, pidFile })).rejects.toThrow()
    expect(f.args()).toContain('-ng')
    expect(existsSync(pidFile)).toBe(false)
    await expect(measureParakeet('/m/pk.bin', { binary: f.bin, clip: clip(1), pidFile })).rejects.toThrow()
    expect(f.args()).not.toContain('-ng')
    expect(existsSync(pidFile)).toBe(false)
  })
  it('fake mode: Parakeet gets the time every model gets, or its own', async () => {
    const path = '/m/ggml-parakeet-tdt-0.6b-v3-q8_0.bin'
    expect(await fakeParakeetMeasure('')(path)).toBe(0.1)
    expect(await fakeParakeetMeasure('2')(path)).toBe(2)
    expect(await fakeParakeetMeasure('slow')(path)).toBeNull()
    expect(await fakeParakeetMeasure('parakeet-tdt-0.6b-v3-q8_0=0.8,whisper-small-q5_1=1.4')(path)).toBe(0.8)
    expect(await fakeParakeetMeasure('whisper-small-q5_1=1.4')(path)).toBe(0.1)
    // a Mac's try knows no times, and either can be told the helper is broken or hears nothing
    expect(await fakeParakeetTry()(path)).toBe(0.1)
    await expect(fakeParakeetMeasure('', 'broken')(path)).rejects.toThrow(/could not start/)
    await expect(fakeParakeetTry('broken')(path)).rejects.toThrow(/could not start/)
    expect(await fakeParakeetTry('deaf')(path)).toBeNull()
  })
})

describe('the credit Parakeet\'s licence asks for', () => {
  const root = join(__dirname, '../..')
  it('the catalog names NVIDIA, the licence (CC-BY-4.0, on the allowed list) and that the weights are converted', () => {
    const p = bundled.parakeet
    expect(p.license).toBe('CC-BY-4.0')
    expect(licenses).toContain('CC-BY-4.0')
    expect(p.attribution).toMatch(/NVIDIA/)
    expect(p.attribution).toMatch(/CC BY 4\.0/)
    expect(p.attribution).toMatch(/converted/i)
    expect(p.attribution).toContain('ggml-org/parakeet-GGUF')
  })
  it('the licences shipped with the app have its credit, the converted-weights note and the licence text', () => {
    const text = readFileSync(join(root, 'app/resources/licenses/parakeet-tdt-0.6b-v3-CC-BY-4.0.txt'), 'utf8')
    expect(text).toMatch(/Parakeet TDT 0\.6B v3 by NVIDIA/)
    expect(text).toMatch(/converted\s+weights/i)
    expect(text).toContain('35156454d1a39de06863303dd209fd2bed6ee079')
    expect(text).toContain('Creative Commons Attribution 4.0 International Public License')
  })
  it('the third-party notices list it with the other models', () => {
    const notices = readFileSync(join(root, 'THIRD_PARTY_NOTICES.md'), 'utf8')
    expect(notices).toMatch(/Parakeet TDT 0\.6B v3.*NVIDIA.*CC BY 4\.0/)
    expect(notices).toMatch(/converted weights/)
  })
})