Skip to content

AI, fully local on your computer.

5.4 KB
Raw Blame
import { existsSync } from 'node:fs'
import type { Transcriber } from './index'
import type { TranscriberMissing } from '../../../shared/types'
import { createWhisperCliTranscriber, resolveWhisperCliPath } from './cli'
import { resolveSidecarSelection } from '../select-sidecar-backed'
import type { BoundModelStartCheck } from '../models'

// Availability-aware transcriber selector, the reranker pattern verbatim:
// NO mock fallback. A real `WhisperCliTranscriber` is chosen only when BOTH the
// platform `whisper-cli` binary AND the transcriber weights are present; otherwise the
// selector returns NULL and an audio import fails per-file with friendly copy
// (graceful-fallback rule — a mock transcript would silently corrupt the corpus).

/** The transcriber model resolved from its manifest (id + GGML weight path). */
export interface TranscriberModelInfo {
  id: string
  /** Absolute path to the transcriber GGML weight file. */
  modelPath: string
  /**
   * Every file the manifest requires (the weight + its `files[]`, #310). The Silero VAD model
   * (#504) is found here by name; the selection ladder requires all of them to be present.
   */
  requiredPaths?: string[]
}

/**
 * The Silero VAD GGML file as the whisper.cpp project names it (`ggml-silero-<version>.bin`,
 * #504). Declared in the whisper manifest's `files[]`, so it is fetched, verified and required
 * together with the weight; recognised here by name so the manifest schema stays untouched.
 */
export const VAD_MODEL_FILE_RE = /^ggml-silero-.*\.bin$/i

/**
 * The VAD model among a resolved transcriber's required files, or null when none is declared.
 * Matches the last path segment on EITHER separator (a Windows path is judged the same on a
 * POSIX host — `node:path`'s basename would not split it there).
 */
export function vadModelPathOf(model: Pick<TranscriberModelInfo, 'requiredPaths'>): string | null {
  return model.requiredPaths?.find((p) => VAD_MODEL_FILE_RE.test(p.split(/[\\/]/).pop() ?? p)) ?? null
}

export interface TranscriberSelectionDeps {
  /** Drive root used to resolve `runtime/whisper.cpp/<os>/whisper-cli`. */
  rootPath: string
  /** The transcriber model from the manifest, or null when none is configured. */
  model: TranscriberModelInfo | null
  /** Dev build — gates the dev-only `HILBERTRAUM_WHISPER_BIN` override (M-5). Default false. */
  isDev?: boolean
  onSelect?: (kind: 'whisper' | 'none', reason: string) => void
  /** #913: the voice model's start check (`WhisperCliOptions.checkModel`). Absent ⇒ no check. */
  checkModel?: BoundModelStartCheck
}

/**
 * Build the active `Transcriber`, or null when unavailable. Construction is cheap
 * (the CLI is spawned per `transcribe()` call), so this returns synchronously.
 */
export function createSelectedTranscriber(deps: TranscriberSelectionDeps): Transcriber | null {
  const makeTranscriber = (model: TranscriberModelInfo, binPath: string): Transcriber =>
    createWhisperCliTranscriber({
      id: model.id,
      binPath,
      modelPath: model.modelPath,
      vadModelPath: vadModelPathOf(model),
      checkModel: deps.checkModel
    })

  // Shared model→binary→weights ladder (L16). NO mock fallback — a mock transcript would
  // silently corrupt the corpus, so unavailable means null.
  const sel = resolveSidecarSelection<TranscriberModelInfo, Transcriber>({
    rootPath: deps.rootPath,
    model: deps.model,
    resolveBin: (root) => resolveWhisperCliPath(root, process.platform, process.env, { isDev: deps.isDev }),
    makeReal: makeTranscriber,
    binaryName: 'whisper-cli',
    modelNoun: 'transcriber model'
  })
  if (!sel.available) {
    deps.onSelect?.('none', sel.reason)
    return null
  }
  deps.onSelect?.('whisper', sel.reason)
  return makeTranscriber(sel.model, sel.binPath)
}

export interface TranscriberMissingDeps {
  rootPath: string
  model: TranscriberModelInfo | null
  isDev?: boolean
  /** The `whisper_cpp` engine family has a build for this host in runtime-sources.yaml. */
  engineFetchable: boolean
  resolveBin?: (rootPath: string) => string | null
  modelExists?: (modelPath: string) => boolean
}

/**
 * Which piece keeps the transcriber unavailable (#527), or null when both are present. The
 * selection ladder above stops at the FIRST missing rung (binary before weights), so it cannot
 * say "the engine is missing but the model is here" — the case a Linux drive hit with v1.8.6's
 * Windows-only engine, where every surface blamed the model the user had just downloaded. This
 * checks the binary and the weights independently; an engine with no host build is reported
 * whatever the weights' state, because downloading them cannot make the transcriber work.
 */
export function transcriberMissingReason(deps: TranscriberMissingDeps): TranscriberMissing | null {
  const resolveBin =
    deps.resolveBin ??
    ((root: string) => resolveWhisperCliPath(root, process.platform, process.env, { isDev: deps.isDev }))
  const modelExists = deps.modelExists ?? existsSync
  const binaryPresent = resolveBin(deps.rootPath) != null
  const required = deps.model
    ? deps.model.requiredPaths?.length
      ? deps.model.requiredPaths
      : [deps.model.modelPath]
    : null
  const weightsPresent = required != null && required.every((p) => modelExists(p))
  if (binaryPresent) return weightsPresent ? null : 'model'
  if (!deps.engineFetchable) return 'engine-unsupported'
  return weightsPresent ? 'engine' : 'model-and-engine'
}