Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

5.6 KB
Raw Blame
import type { ParakeetVersion } from '../../../modules/parakeet-asr/src';
import type { LocalModelKey } from '@/lib/localModelCatalog';

/**
 * Pure routing policy for on-device transcription: which local engine handles the user's
 * selected languages. No I/O — availability is passed in — so the full matrix is unit-testable.
 */

export interface LocalEngineAvailability {
  /** Native module linked (iOS dev/prod build; false on Android and Expo Go). */
  parakeetSupported: boolean;
  parakeetV2Downloaded: boolean;
  parakeetV3Downloaded: boolean;
  whisperDownloaded: boolean;
}

export type LocalEngineChoice =
  | { engine: 'parakeet'; version: ParakeetVersion }
  | { engine: 'whisper' }
  | { engine: 'none'; preferred: 'parakeet-v2' | 'parakeet-v3' | 'whisper' };

/**
 * The 25 languages of NVIDIA parakeet-tdt-0.6b-v3 (per the official model card). FluidAudio
 * 0.15.4's `Language` enum (Sources/FluidAudio/Shared/TokenLanguageFilter.swift) is a superset —
 * every code here has an enum case, so the per-language decoder hint works for all of them.
 */
export const PARAKEET_V3_LANGUAGES: ReadonlySet<string> = new Set([
  'bg',
  'hr',
  'cs',
  'da',
  'nl',
  'en',
  'et',
  'fi',
  'fr',
  'de',
  'el',
  'hu',
  'it',
  'lv',
  'lt',
  'mt',
  'pl',
  'pt',
  'ro',
  'ru',
  'sk',
  'sl',
  'es',
  'sv',
  'uk',
]);

/** Region-stripped, deduped base ISO codes with 'auto'/empties removed. */
function normalizeLanguages(languages: readonly string[]): string[] {
  const normalized = languages
    .map((code) => code.trim().toLowerCase().split('-')[0])
    .filter((code) => code.length > 0 && code !== 'auto');
  return [...new Set(normalized)];
}

/**
 * The engine the user's language selection *should* use, ignoring what's downloaded:
 * - exactly English → Parakeet v2 (fastest and most accurate for English)
 * - one or more languages, all inside v3's set → Parakeet v3 (auto language ID across them)
 * - empty ('auto') or anything outside v3's coverage → Whisper (attempts all ~99 languages)
 *
 * Per-recording engine routing is impossible — the spoken language isn't known before
 * transcription — so a mixed selection like en+he must go to Whisper for everything.
 */
export function preferredEngineForLanguages(
  languages: readonly string[],
): { engine: 'parakeet'; version: ParakeetVersion } | { engine: 'whisper' } {
  const normalized = normalizeLanguages(languages);
  if (normalized.length === 0) {
    return { engine: 'whisper' };
  }
  if (normalized.length === 1 && normalized[0] === 'en') {
    return { engine: 'parakeet', version: 'v2' };
  }
  if (normalized.every((code) => PARAKEET_V3_LANGUAGES.has(code))) {
    return { engine: 'parakeet', version: 'v3' };
  }
  return { engine: 'whisper' };
}

/** Whether a model can transcribe every selected language. Auto-detect needs Whisper. */
export function localModelCoversLanguages(
  model: LocalModelKey,
  languages: readonly string[],
): boolean {
  if (model === 'whisper-base') return true;
  const normalized = normalizeLanguages(languages);
  if (normalized.length === 0) return false;
  if (model === 'parakeet-v2') return normalized.every((code) => code === 'en');
  return normalized.every((code) => PARAKEET_V3_LANGUAGES.has(code));
}

function isInstalled(model: LocalModelKey, availability: LocalEngineAvailability): boolean {
  if (model === 'whisper-base') return availability.whisperDownloaded;
  if (!availability.parakeetSupported) return false;
  return model === 'parakeet-v2'
    ? availability.parakeetV2Downloaded
    : availability.parakeetV3Downloaded;
}

// Automatic takes the first downloaded model here that covers every selected language. Each
// Parakeet is the most accurate for what it covers (v2 for English, v3 for its 25 languages), and
// Whisper base covers the rest.
const AUTOMATIC_ORDER: readonly LocalModelKey[] = ['parakeet-v2', 'parakeet-v3', 'whisper-base'];
// With nothing downloaded that covers the languages, a model that misses some still beats no
// transcription; v3 covers more of them than v2. Whisper base never gets here, it covers all.
const UNCOVERED_FALLBACK_ORDER: readonly LocalModelKey[] = ['parakeet-v3', 'parakeet-v2'];

function choiceFor(model: LocalModelKey): Exclude<LocalEngineChoice, { engine: 'none' }> {
  return model === 'whisper-base'
    ? { engine: 'whisper' }
    : { engine: 'parakeet', version: model === 'parakeet-v2' ? 'v2' : 'v3' };
}

/**
 * Resolve the engine against what's actually installed: the picked model, else the first entry
 * of AUTOMATIC_ORDER that is downloaded and covers the languages, else any downloaded model.
 * 'none' (caller surfaces a download prompt) only when nothing is downloaded.
 */
export function selectLocalEngine(
  languages: readonly string[],
  availability: LocalEngineAvailability,
  // The model the user picked for this workflow. A missing or unsuitable pick falls back to the
  // automatic choice, so a deleted model or a language change never breaks transcription.
  picked?: LocalModelKey,
): LocalEngineChoice {
  const installed = (model: LocalModelKey): boolean => isInstalled(model, availability);
  const usable = (model: LocalModelKey): boolean =>
    installed(model) && localModelCoversLanguages(model, languages);

  if (picked && usable(picked)) return choiceFor(picked);
  const model = AUTOMATIC_ORDER.find(usable) ?? UNCOVERED_FALLBACK_ORDER.find(installed);
  if (model) return choiceFor(model);

  const preferred = preferredEngineForLanguages(languages);
  return {
    engine: 'none',
    preferred:
      preferred.engine === 'parakeet' && availability.parakeetSupported
        ? `parakeet-${preferred.version}`
        : 'whisper',
  };
}