---
title: "Transcription"
canonical: https://docs.qvac.tether.io/sdk/v0.23/ai-capabilities/transcription/
collection: "SDK"
package: "@qvac/sdk"
line: v0.23
current_line: false
---

# Transcription (/sdk/v0.23/ai-capabilities/transcription)



## Overview

Transcription uses your choice of either [`qvac-fabric-speech.cpp`](https://github.com/tetherto/qvac-fabric-speech.cpp) or [NVIDIA Parakeet](https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3) (via the GGML-based [`parakeet-cpp`](https://github.com/tetherto/qvac-fabric-speech.cpp/tree/master/engines/parakeet) engine) as inference engine. Load a model using `modelType: "whisper"` for `qvac-fabric-speech.cpp`, or `modelType: "parakeet-transcription"` for Parakeet. Parakeet supports multilingual transcription (TDT), English-only transcription (CTC), English transcription with a single model that supports both batch and duplex streaming (Unified), the small [TranscribePsy](https://huggingface.co/qvac/TranscribePsy-250M-EU-sub-gguf) distillation for eight European languages, Indic-language transcription (Indic Conformer CTC), speaker diarization (Sortformer and Nemotron 3), and end-of-utterance detection (EOU) for duplex streaming.

Provide audio input as `audioChunk`, either as a file path (string) or an in-memory audio buffer.

`transcribe()` returns the full transcription as a single `string`. Its returned promise also exposes `stats`: await it after transcription to read terminal engine statistics. For Parakeet offline ASR, `encoderOnCoreml` reports whether a Core ML sidecar loaded, while `encoderUsedCoreml` reports whether this run encoded on Core ML. The stats promise resolves to `undefined` when the engine does not report statistics. If you need partial results as they become available, use `transcribeStream()` to receive text chunks in real-time. Both whisper and parakeet expose duplex `transcribeStream()` sessions; see "Streaming with `transcribeStream()`" below.

## Functions

Use the following sequence of function calls:

1. [`loadModel()`](/sdk/v0.23/reference/api#loadmodel)
2. [`transcribe()`](/sdk/v0.23/reference/api#transcribe) or [`transcribeStream()`](/sdk/v0.23/reference/api#transcribestream)
3. [`unloadModel()`](/sdk/v0.23/reference/api#unloadmodel)

For how to use each function, see [SDK — API reference](/sdk/v0.23/reference/api/).

## Models

### `qvac-fabric-speech.cpp`

You should load two models:

* a [`whisper.cpp`](https://github.com/ggml-org/whisper.cpp)-compatible model for transcription. Model file format: `*.bin`; and
* a VAD model (e.g., Silero) converted to GGML. Model file format: `*.bin` *(optional, recommended)*.

### Parakeet

Parakeet uses a GGUF checkpoint per variant, and the addon detects TDT / CTC / Unified / Sortformer / EOU from its GGUF metadata (TranscribePsy loads as a TDT model). Supply the GGUF via the top-level `modelSrc`:

```ts
await loadModel({
  modelSrc: PARAKEET_TDT_0_6B_V3_Q8_0,    // multilingual, ~750MB
  modelType: "parakeet-transcription",
});

await loadModel({
  modelSrc: PARAKEET_CTC_0_6B_Q8_0,       // english-only, streaming-capable
  modelType: "parakeet-transcription",
});

await loadModel({
  modelSrc: PARAKEET_UNIFIED_0_6B_Q8_0,   // english; batch + streaming, ~740MB
  modelType: "parakeet-transcription",
});

await loadModel({
  modelSrc: PARAKEET_TRANSCRIBEPSY_250M_Q8_0,  // nl/en/fr/de/it/pl/pt/es, ~305MB
  modelType: "parakeet-transcription",
});

await loadModel({
  modelSrc: PARAKEET_SORTFORMER_4SPK_V2_1_Q8_0,  // 4-speaker diarization
  modelType: "parakeet-transcription",
});

await loadModel({
  modelSrc: PARAKEET_EOU_120M_V1_Q8_0,    // end-of-utterance detection
  modelType: "parakeet-transcription",
});

await loadModel({
  modelSrc: PARAKEET_INDIC_CONFORMER_600M_Q8_0,  // Indic languages
  modelType: "parakeet-transcription",
  modelConfig: { language: "hi" },              // required; e.g. "hi", "ta"
});
```

On macOS and iOS, loading a supported Parakeet registry constant also downloads its complete Core ML encoder bundle and stages the `.mlmodelc` directory beside the GGUF. This applies to TDT 0.6B v3, Unified English 0.6B, EOU 120M v1, and streaming Sortformer v2.1. The sidecar weights increase the first download and disk use. Other platforms download the GGUF alone; if a sidecar is unavailable or cannot load, the GGUF encoder is used.

TranscribePsy publishes a separate Core ML distribution. `PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0` is an encoder-less GGUF whose encoder and decoder bundles the SDK downloads and stages beside it, so both stages run on the Apple Neural Engine; `stats.encoderUsedCoreml` on the `transcribe()` call reports it. That constant loads on macOS and iOS only: elsewhere the load is refused up front, and `PARAKEET_TRANSCRIBEPSY_250M_Q8_0` is the one to use.

**Long recordings.** Parakeet encodes a long `transcribe()` input in overlapping windows, so memory stays flat however long the recording is and cancellation lands between windows. The defaults need nothing from you: TranscribePsy uses the 60 s windows with 25 % overlap it recommends, the other models the engine's automatic windows. To trade speed for a smaller footprint, for example on a phone with little memory, set `longFormWindowFrames` and `longFormContextFrames` in `modelConfig` (encoder frames of 80 ms: 375 is a 30 s window, and 47 frames of context on each side keeps the 25 % overlap); a negative window encodes the whole input in one pass.

For model artifacts available as constants, see [SDK — Models](/sdk/v0.23/#models).

<Callout type="info">
  **Migrating from pre-0.6 Parakeet (ONNX multi-file):** the legacy multi-file ONNX `modelConfig` shape (`parakeetEncoderSrc` / `parakeetDecoderSrc` / `parakeetVocabSrc` / `parakeetPreprocessorSrc`, plus `parakeetCtcModelSrc` / `parakeetTokenizerSrc` and `parakeetSortformerSrc` for the CTC/Sortformer variants) is no longer supported. Passing any of those fields raises a structured `LegacyParakeetModelDeprecatedError` with a migration message. The legacy ONNX constants (e.g. `PARAKEET_TDT_ENCODER_INT8`, `PARAKEET_CTC_FP32`, `PARAKEET_SORTFORMER_FP32`) remain exported for one minor cycle for codemod migrations only and will be removed in a future release.
</Callout>

<Callout type="info">
  **On VAD:** when using `qvac-fabric-speech.cpp`, you can optionally provide a separate model for voice activity detection (VAD); this is recommended. In turn, Parakeet handles VAD internally, so no additional model or configuration is required.
</Callout>

## Speaker-aware MOSS transcription

MOSS-Transcribe-Diarize performs batch transcription with timestamps and speaker labels.
Load `MOSS_TRANSCRIBE_DIARIZE_Q8_0` (or the F16/Q5\_0 variant) with the
`moss-transcribe` model type. Registry constants select the type automatically.

```ts
import { loadModel, transcribe, MOSS_TRANSCRIBE_DIARIZE_Q8_0 } from '@qvac/sdk'

const modelId = await loadModel({ modelSrc: MOSS_TRANSCRIBE_DIARIZE_Q8_0 })
const segments = await transcribe({
  modelId,
  audioChunk: 'meeting.wav',
  metadata: true,
  hotwords: ['QVAC'],
  maxNewTokens: 2048
})
```

Segments include `speaker` labels such as `S01`, zero-based `speakerId`, and
`startMs`/`endMs`. Hotwords are request-specific: up to 64 nonempty terms, each
at most 64 UTF-8 bytes. A custom `prompt` cannot be combined with hotwords.
`maxNewTokens: 0` uses the model default. MOSS supports whole-recording batch
inference; duplex streaming and configuration reload are unavailable.

`modelConfig.backend` selects the native backend explicitly: `auto` (the
default), `cpu`, `cuda`, `vulkan`, `metal`, or an exact ggml device name such as
`CUDA0`. An explicit selection overrides `useGPU`, and the load fails if that
backend is unavailable instead of falling back. The same selector reaches
`assessModelFit`, where it also overrides the GPU gate. MOSS `stats` report
`totalSegments`, the `audioTokens`, `promptTokens` and `generatedTokens` counts,
and the `encoderTime`, `prefillTime` and `decoderTime` stage timings in ms.

Before downloading weights, call `assessModelFit` with the longest recording
you plan to transcribe and matching decoding options:

```ts
import { assessModelFit, MOSS_TRANSCRIBE_DIARIZE_Q8_0 } from "@qvac/sdk";

const fit = await assessModelFit({
  models: [
    {
      modelSrc: MOSS_TRANSCRIBE_DIARIZE_Q8_0,
      modelConfig: { useGPU: false },
      transcriptionWorkload: {
        audioSeconds: 300,
        hotwords: ["QVAC"],
        maxNewTokens: 0,
      },
    },
  ],
});
```

`transcriptionWorkload` is fit-only and requires a positive duration in seconds.
It accepts the same prompt, hotwords, and token limit as MOSS transcription;
omit either prompt or hotwords. Without a declared workload or an available
registry description/local model, the assessment can remain `unknown`.
Assessment does not load the model, reserve memory, or block transcription.

## Nemotron 3 speaker diarization

Nemotron 3 Diarization runs through `parakeet-transcription` and identifies up to
eight speakers, including overlapping activity. It returns speaker turns rather
than recognized words. For local weights:

```ts
const modelId = await loadModel({
  modelSrc: './Nemotron-3-Diarization.q8_0.gguf',
  modelType: 'parakeet-transcription'
})
const segments = await transcribe({ modelId, audioChunk: 'meeting.wav', metadata: true })
const turns = segments.flatMap(segment => segment.speakerSegments ?? [])
```

Each turn has zero-based `speakerId` and `startMs`/`endMs`. Configure
`diarizationThreshold` (0–1) and `diarizationMinSegmentMs` (a nonnegative integer)
at load or per stream in `parakeetStreamingConfig`; omit them to retain native
model defaults. Load with `streaming: true` before calling `transcribeStream`.
Enable `streamingSpeakerVad` at load or `emitSpeakerVad` per stream to receive
speaker-activity events. Streaming diarization metadata retains speaker IDs.

The CLI accepts MOSS `hotwords` and `max_new_tokens` in transcription requests.
Its `verbose_json` response includes whisper `language`, `no_speech_prob`,
`speaker_turn_next` and `token_timestamps` per segment, MOSS speaker labels and Nemotron
`speaker_segments` with `speaker_id`, `start`, and `end` in seconds.

## Whisper segment metadata

With `metadata: true`, every whisper segment carries the fields the engine
reports for its decode window alongside `text`, `startMs`, `endMs`, `append`
and `id`:

* `language` — the ISO 639-1 code the window was decoded in. Under
  `language: "auto"` (or `detect_language: true`) this is the detected
  language.
* `noSpeechProb` — the probability (0–1) that the window holds no speech, the
  value `no_speech_thold` is compared against.
* `speakerTurnNext` — `true` when a speaker turn follows the segment. Needs
  `tdrz_enable: true` and a tinydiarize model.
* `tokens` — the decoded text tokens, each `{ text, startMs, endMs, probability }`
  (special tokens are left out). Needs `token_timestamps: true`.

```ts
const modelId = await loadModel({
  modelSrc: './ggml-small.bin',
  modelType: 'whisper',
  modelConfig: { language: 'auto', token_timestamps: true, tdrz_enable: true }
})
const segments = await transcribe({ modelId, audioChunk: 'meeting.wav', metadata: true })
for (const segment of segments) {
  console.log(segment.language, segment.noSpeechProb, segment.speakerTurnNext)
  for (const token of segment.tokens ?? []) {
    console.log(token.text, token.startMs, token.endMs, token.probability)
  }
}
```

Two more whisper `modelConfig` keys reach the engine: `carry_initial_prompt:
true` prepends `initial_prompt` to every decode window instead of only the
first, and `contextParams["main-gpu"]` picks the GPU once `use_gpu` is `true` —
a ggml device-registry index, `"dedicated"`, or `"integrated"`. Do not combine
it with the legacy `contextParams.gpu_device` ordinal. The Python client's
generated `context_params` model exposes the same key as its `main_gpu` field.

## Streaming with `transcribeStream()`

`transcribeStream()` opens a duplex session for both engines — write audio chunks via `session.write(...)`, iterate events with `for await (const event of session) { ... }`. Events are typed as a discriminated union `{ type }`:

* `{ type: "text", text }` — incremental transcript text.
* `{ type: "segment", segment }` — segment metadata when `metadata: true`, on both engines. Parakeet segments also carry `isEndOfTurn` and `startsWord`; whisper segments carry `language`, `noSpeechProb`, and, when enabled, `speakerTurnNext` and `tokens` (see "Whisper segment metadata").
* `{ type: "vad", speaking, probability, source }` — voice-activity-detection state. `source` is `"silero"` for whisper, `"energy"` for Parakeet's energy detector (`streamingEnergyVad` at load or `emitEnergyVad` per stream, on CTC, TDT, RNN-T, and Nemotron models), or `"sortformer"` for Parakeet speaker activity, which also carries `speakerId`.
* `{ type: "endOfTurn", source: "whisper", silenceDurationMs }` — turn boundary detected from a measured silence window (whisper).
* `{ type: "endOfTurn", source: "parakeet" }` — turn boundary detected from the EOU model's `<EOU>` token (parakeet; no silence window — the event is token-driven).

The `source` field on `endOfTurn` lets consumers narrow the union: whisper events always carry a numeric `silenceDurationMs`; parakeet events never do.

Parakeet `vad` events also carry `timestamp`, the event time in seconds from the start of the streaming session. Sortformer streaming sessions report `aoscActive` in their terminal `stats`: `1` when the v2.1 AOSC speaker cache was active.

After the iterator completes, await `session.stats` to read terminal engine statistics. The promise resolves to `undefined` when the engine does not report stats.

```ts
for await (const event of session) {
  // Handle text, segment, VAD, or end-of-turn events.
}

const stats = await session.stats;
console.log(stats?.audioDuration, stats?.realTimeFactor);
```

<Callout type="info">
  **Wire compatibility:** post-0.6 servers emit `source` on every `endOfTurn` frame. SDK parsers still accept the legacy whisper wire shape `{ silenceDurationMs }` (no `source`) and normalize it to `source: "whisper"`. Upgrade client and server together when using parakeet `source: "parakeet"` events — older servers never emit that branch.
</Callout>

### Parakeet duplex streaming

Pass `parakeetStreamingConfig` to `transcribeStream()` to override per-call streaming knobs (each falls back to its `parakeetConfig.streaming*` load-time counterpart):

```ts
const session = await transcribeStream({
  modelId,
  parakeetStreamingConfig: {
    chunkMs: 1000,            // encoder cadence
    historyMs: 30000,         // sortformer rolling-history window
    leftContextMs: 500,       // ASR encoder left-context window
    rightLookaheadMs: 200,    // ASR encoder right-lookahead window
    emitPartials: true,       // emit partial segments before chunk boundaries
    emitEnergyVad: true,      // emit { type: "vad", source: "energy" } events
    energyVadThresholdDb: -35, // speech threshold in dBFS RMS
    energyVadWindowMs: 30,    // RMS window in ms (the engine caps it at 1000)
    energyVadHangoverMs: 200, // silence before the detector leaves "speaking"
  },
});

for await (const event of session) {
  switch (event.type) {
    case "text":
      process.stdout.write(event.text);
      break;
    case "endOfTurn":
      // event.source: "whisper" | "parakeet"
      console.log("\n[endOfTurn] turn boundary detected\n");
      break;
  }
}
```

The synthetic `{ type: "endOfTurn", source: "parakeet" }` event surfaces whenever the EOU model emits an `<EOU>` token, and is the parakeet equivalent of whisper's silence-window EOU. Pair it with the `PARAKEET_EOU_120M_V1_Q8_0` checkpoint when you need explicit turn boundaries from parakeet.

The energy detector is tuned with the same three knobs at load time as `streamingEnergyVadThresholdDb`, `streamingEnergyVadWindowMs`, and `streamingEnergyVadHangoverMs` in `parakeetConfig`; the per-stream values above override them for one session. The threshold is a dBFS RMS level (default -35), the window is the RMS span in ms (default 30), and the hangover is how long the audio must stay below the threshold before the state returns to silence (default 200 ms). VAD events reach sessions opened with `parakeetStreamingConfig` or `emitVadEvents: true`.

### Parakeet prewarming

Set `prewarm: true` in `parakeetConfig` to run one synthetic encoder pass while the model loads, so the first `transcribe()` or stream does not pay the GPU shader or kernel compile. `prewarmAudioSeconds` sets the length of that pass in seconds of audio (default 1; it must be greater than 0). Nemotron 3 Diarization also runs one streaming chunk. Both options apply at load time only and have no per-stream counterpart.

```ts
const modelId = await loadModel({
  modelSrc: PARAKEET_TDT_0_6B_V3_Q8_0,
  modelType: "parakeet-transcription",
  modelConfig: { useGPU: true, prewarm: true, prewarmAudioSeconds: 2 },
});
```

## Examples

### `qvac-fabric-speech.cpp`

The following script shows an example of `qvac-fabric-speech.cpp` transcription with prompt-guided decoding, VAD, and GPU acceleration. Pass the path of a 16 kHz mono WAV file as the first argument:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/asr/whispercpp-prompt.js title="whispercpp-prompt.js" lineNumbers
      /**
       * Whisper transcription with prompt example.
       *
       * Usage:
       *   npx tsx examples/asr/whispercpp-prompt.ts <wav-file>
       *
       * Pass the path of a 16 kHz mono WAV file. A sample is available in the QVAC
       * source repository, but not included in the published npm package:
       *   https://github.com/tetherto/qvac/blob/main/packages/sdk/examples/audio/sample-16khz.wav
       */
      import { loadModel, unloadModel, transcribe, WHISPER_TINY } from '@qvac/sdk';
      const audioFilePath = process.argv[2];
      if (!audioFilePath) {
          console.error('Usage: npx tsx examples/asr/whispercpp-prompt.ts <wav-file>');
          process.exit(1);
      }
      try {
          console.log('▸ Starting Whisper transcription with prompt example...');
          // Load the Whisper model
          console.log('▸ Loading Whisper model...');
          const modelId = await loadModel({
              modelSrc: WHISPER_TINY,
              modelConfig: {
                  audio_format: 'f32le',
                  // Sampling strategy
                  strategy: 'greedy',
                  n_threads: 4,
                  // Transcription options
                  language: 'en',
                  translate: false,
                  no_timestamps: false,
                  single_segment: false,
                  print_timestamps: true,
                  token_timestamps: true,
                  // Quality settings
                  temperature: 0.0,
                  suppress_blank: true,
                  suppress_nst: true,
                  // Advanced tuning
                  entropy_thold: 2.4,
                  logprob_thold: -1.0,
                  // VAD configuration
                  vad_params: {
                      threshold: 0.35,
                      min_speech_duration_ms: 200,
                      min_silence_duration_ms: 150,
                      max_speech_duration_s: 30.0,
                      speech_pad_ms: 600,
                      samples_overlap: 0.3
                  },
                  // Context parameters for GPU
                  contextParams: {
                      use_gpu: true,
                      flash_attn: true,
                      gpu_device: 0
                  }
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Whisper model loaded with ID: ${modelId}`);
          // Perform transcription
          console.log('▸ Transcribing audio...');
          const text = await transcribe({
              modelId,
              audioChunk: audioFilePath,
              prompt: 'This is a test recording with clear speech and proper punctuation.'
          });
          console.log('▸ Transcription result:');
          console.log(text);
          // Unload the model when done
          console.log('▸ Unloading Whisper model...');
          await unloadModel({ modelId });
          console.log('▸ Whisper model unloaded successfully');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/asr/whispercpp-prompt.ts title="whispercpp-prompt.ts" lineNumbers
      /**
       * Whisper transcription with prompt example.
       *
       * Usage:
       *   npx tsx examples/asr/whispercpp-prompt.ts <wav-file>
       *
       * Pass the path of a 16 kHz mono WAV file. A sample is available in the QVAC
       * source repository, but not included in the published npm package:
       *   https://github.com/tetherto/qvac/blob/main/packages/sdk/examples/audio/sample-16khz.wav
       */
      import { loadModel, unloadModel, transcribe, WHISPER_TINY } from '@qvac/sdk'

      const audioFilePath = process.argv[2]

      if (!audioFilePath) {
        console.error('Usage: npx tsx examples/asr/whispercpp-prompt.ts <wav-file>')
        process.exit(1)
      }

      try {
        console.log('▸ Starting Whisper transcription with prompt example...')

        // Load the Whisper model
        console.log('▸ Loading Whisper model...')
        const modelId = await loadModel({
          modelSrc: WHISPER_TINY,
          modelConfig: {
            audio_format: 'f32le',
            // Sampling strategy
            strategy: 'greedy',
            n_threads: 4,
            // Transcription options
            language: 'en',
            translate: false,
            no_timestamps: false,
            single_segment: false,
            print_timestamps: true,
            token_timestamps: true,
            // Quality settings
            temperature: 0.0,
            suppress_blank: true,
            suppress_nst: true,
            // Advanced tuning
            entropy_thold: 2.4,
            logprob_thold: -1.0,
            // VAD configuration
            vad_params: {
              threshold: 0.35,
              min_speech_duration_ms: 200,
              min_silence_duration_ms: 150,
              max_speech_duration_s: 30.0,
              speech_pad_ms: 600,
              samples_overlap: 0.3
            },
            // Context parameters for GPU
            contextParams: {
              use_gpu: true,
              flash_attn: true,
              gpu_device: 0
            }
          },
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Whisper model loaded with ID: ${modelId}`)

        // Perform transcription
        console.log('▸ Transcribing audio...')
        const text = await transcribe({
          modelId,
          audioChunk: audioFilePath,
          prompt: 'This is a test recording with clear speech and proper punctuation.'
        })

        console.log('▸ Transcription result:')
        console.log(text)

        // Unload the model when done
        console.log('▸ Unloading Whisper model...')
        await unloadModel({ modelId })
        console.log('▸ Whisper model unloaded successfully')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/transcription.py title="transcription.py" lineNumbers
      """Python port of packages/sdk/examples/asr/whispercpp-filesystem.ts.

      Transcribe an audio file with per-segment metadata. `transcribe` is a
      server-stream: it yields `TranscribeResponse` frames; with `metadata=True`
      each carries a `segment` ({text, start_ms, end_ms, append, id}).

      Pass a 16 kHz mono WAV path, e.g. the SDK's own sample:
        python examples/transcription.py \
          ../sdk/examples/audio/sample-16khz.wav
      """

      from __future__ import annotations

      import asyncio
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TranscribeRequest,
          load_model,
          transcribe,
          unload_model,
      )
      from tetherto.qvac_sdk.models import WHISPER_TINY


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          if len(sys.argv) < 2:
              print(
                  "Usage: python examples/transcription.py <wav-file-path>", file=sys.stderr
              )
              return 1
          audio_path = sys.argv[1]

          async with Client() as client:
              t = client.transport
              try:
                  print("▸ Loading Whisper model...")
                  model_id = await load_model(
                      t,
                      model_src=WHISPER_TINY,
                      model_config={"audio_format": "f32le", "language": "en"},
                      on_progress=print_progress,
                  )
                  print(f"▸ Whisper model loaded with ID: {model_id}")

                  print("▸ Transcribing audio...")
                  # audioChunk is a typed chunk, not a bare path: JS's transcribe
                  # wrapper turns a string into {type:"filePath"} for you, but Python
                  # calls the generated stub directly, so build the chunk explicitly.
                  request = TranscribeRequest.model_validate(
                      {
                          "type": "transcribe",
                          "modelId": model_id,
                          "audioChunk": {"type": "filePath", "value": audio_path},
                          "metadata": True,
                      }
                  )

                  segments = []
                  async for response in transcribe(t, request):
                      if response.segment is not None:
                          segments.append(response.segment)

                  print("▸ Transcription result:")
                  for seg in segments:
                      start = seg.start_ms / 1000
                      end = seg.end_ms / 1000
                      print(
                          f"  [{start:.2f}s → {end:.2f}s] (id={seg.id}, append={seg.append}) {seg.text}"
                      )
                  print("\nFull transcript:", "".join(s.text for s in segments).strip())

                  print("▸ Unloading Whisper model...")
                  await unload_model(t, model_id)
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/Transcription.kt title="Transcription.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/asr/whispercpp-filesystem.ts.
      //
      // Transcribe an audio file with per-segment metadata. With `metadata = true`,
      // `client.speech.transcribe()` collects every segment ({text, startMs, endMs,
      // append, id}) into `QvacTranscriptionResult.segments`.
      //
      // As in JS, the audio source is a typed value: `QvacDataInput` is a sealed
      // interface (`FilePath` or `Base64`), so there is no hand-built
      // `{type: "filePath"}` chunk as in Python, and the frames are aggregated for you.
      //
      // Pass a 16 kHz mono WAV path, e.g. the SDK's own sample
      // packages/sdk/examples/audio/sample-16khz.wav.
      //
      // RUN: ./gradlew -p examples run -Pexample=Transcription --args="<wav-file-path>"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacDataInput
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.speech
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(args: Array<String>): Unit = runBlocking {
          if (args.isEmpty()) {
              System.err.println("Usage: ./gradlew -p examples run -Pexample=Transcription --args=\"<wav-file-path>\"")
              exitProcess(1)
          }
          val audioPath = args[0]

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ Loading Whisper model...")
              val modelId = client.loadWithProgress(
                  Models.WHISPER_TINY,
                  modelConfig = buildJsonObject {
                      put("audio_format", "f32le")
                      put("language", "en")
                  },
              )
              println("▸ Whisper model loaded with ID: $modelId")

              println("▸ Transcribing audio...")
              val result = client.speech.transcribe(
                  modelId = modelId,
                  audio = QvacDataInput.FilePath(audioPath),
                  metadata = true,
              )

              println("▸ Transcription result:")
              for (seg in result.segments) {
                  val start = seg.startMs / 1000
                  val end = seg.endMs / 1000
                  println("  [%.2fs → %.2fs]".format(start, end) + " (id=${seg.id}, append=${seg.append}) ${seg.text}")
              }
              println("\nFull transcript: " + result.segments.joinToString("") { it.text }.trim())

              println("▸ Unloading Whisper model...")
              client.models.unload(modelId)
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant, modelConfig: JsonObject? = null): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Parakeet TDT

The following script shows an example of multilingual transcription using the Parakeet TDT model from a WAV file. Pass the path of a 16 kHz mono WAV file as the first argument; an optional second argument overrides the default model:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/asr/parakeet-tdt-filesystem.js title="parakeet-tdt-filesystem.js" lineNumbers
      /**
       * Parakeet TDT transcription from a WAV file.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-tdt-filesystem.ts <wav-file> [parakeet-tdt-gguf]
       *
       * Loads a single GGUF checkpoint (`PARAKEET_TDT_0_6B_V3_Q8_0` by default) and
       * transcribes the file with the batch `transcribe` API. Omit the model
       * argument to use the registry constant.
       *
       * Audio should be 16 kHz mono PCM in a WAV container.
       */
      import { loadModel, unloadModel, transcribe, PARAKEET_TDT_0_6B_V3_Q8_0 } from '@qvac/sdk';
      const args = process.argv.slice(2);
      if (!args[0]) {
          console.error('Usage: npx tsx examples/asr/parakeet-tdt-filesystem.ts <wav-file-path> ' +
              '[parakeet-tdt-gguf]');
          console.error('\nIf the model path is omitted, defaults to the registry model.');
          process.exit(1);
      }
      const audioFilePath = args[0];
      const parakeetModelSrc = args[1] ?? PARAKEET_TDT_0_6B_V3_Q8_0;
      try {
          console.log('▸ Starting Parakeet transcription example...');
          console.log('▸ Loading Parakeet model...');
          const modelId = await loadModel({
              modelSrc: parakeetModelSrc,
              modelType: 'parakeet-transcription',
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Parakeet model loaded with ID: ${modelId}`);
          console.log('▸ Transcribing audio...');
          const text = await transcribe({ modelId, audioChunk: audioFilePath });
          console.log(text);
          console.log('▸ Unloading Parakeet model...');
          await unloadModel({ modelId });
          console.log('▸ Parakeet model unloaded successfully');
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/asr/parakeet-tdt-filesystem.ts title="parakeet-tdt-filesystem.ts" lineNumbers
      /**
       * Parakeet TDT transcription from a WAV file.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-tdt-filesystem.ts <wav-file> [parakeet-tdt-gguf]
       *
       * Loads a single GGUF checkpoint (`PARAKEET_TDT_0_6B_V3_Q8_0` by default) and
       * transcribes the file with the batch `transcribe` API. Omit the model
       * argument to use the registry constant.
       *
       * Audio should be 16 kHz mono PCM in a WAV container.
       */
      import { loadModel, unloadModel, transcribe, PARAKEET_TDT_0_6B_V3_Q8_0 } from '@qvac/sdk'

      const args = process.argv.slice(2)

      if (!args[0]) {
        console.error(
          'Usage: npx tsx examples/asr/parakeet-tdt-filesystem.ts <wav-file-path> ' +
            '[parakeet-tdt-gguf]'
        )
        console.error('\nIf the model path is omitted, defaults to the registry model.')
        process.exit(1)
      }

      const audioFilePath = args[0]
      const parakeetModelSrc = args[1] ?? PARAKEET_TDT_0_6B_V3_Q8_0

      try {
        console.log('▸ Starting Parakeet transcription example...')

        console.log('▸ Loading Parakeet model...')
        const modelId = await loadModel({
          modelSrc: parakeetModelSrc,
          modelType: 'parakeet-transcription',
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Parakeet model loaded with ID: ${modelId}`)

        console.log('▸ Transcribing audio...')
        const text = await transcribe({ modelId, audioChunk: audioFilePath })

        console.log(text)

        console.log('▸ Unloading Parakeet model...')
        await unloadModel({ modelId })
        console.log('▸ Parakeet model unloaded successfully')
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/transcription_parakeet_tdt.py title="transcription_parakeet_tdt.py" lineNumbers
      """Python port of packages/sdk/examples/asr/parakeet-tdt-filesystem.ts.

      Parakeet TDT transcription from a WAV file. Loads a single GGUF checkpoint
      (`PARAKEET_TDT_0_6B_V3_Q8_0` by default) and transcribes the file with the
      batch `transcribe` API. Omit the model argument to use the registry constant.

      TypeScript's `transcribe()` returns the joined text. Python calls the worker
      directly, so `transcribe` yields `TranscribeResponse` frames and the example
      joins their `text` itself.

      Audio should be 16 kHz mono PCM in a WAV container.

      RUN: python examples/transcription_parakeet_tdt.py <wav-file> [parakeet-tdt-gguf]
      """

      from __future__ import annotations

      import asyncio
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TranscribeRequest,
          load_model,
          transcribe,
          unload_model,
      )
      from tetherto.qvac_sdk.models import PARAKEET_TDT_0_6B_V3_Q8_0


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          if len(sys.argv) < 2:
              print(
                  "Usage: python examples/transcription_parakeet_tdt.py <wav-file-path> "
                  "[parakeet-tdt-gguf]",
                  file=sys.stderr,
              )
              print(
                  "\nIf the model path is omitted, defaults to the registry model.",
                  file=sys.stderr,
              )
              return 1
          audio_path = sys.argv[1]
          parakeet_model_src = sys.argv[2] if len(sys.argv) > 2 else PARAKEET_TDT_0_6B_V3_Q8_0

          async with Client() as client:
              t = client.transport
              try:
                  print("▸ Starting Parakeet transcription example...")

                  print("▸ Loading Parakeet model...")
                  model_id = await load_model(
                      t,
                      model_src=parakeet_model_src,
                      model_type="parakeet-transcription",
                      on_progress=print_progress,
                  )
                  print(f"▸ Parakeet model loaded with ID: {model_id}")

                  print("▸ Transcribing audio...")
                  # audioChunk is a typed chunk, not a bare path: JS's transcribe
                  # wrapper turns a string into {type:"filePath"} for you, but Python
                  # calls the generated stub directly, so build the chunk explicitly.
                  request = TranscribeRequest.model_validate(
                      {
                          "type": "transcribe",
                          "modelId": model_id,
                          "audioChunk": {"type": "filePath", "value": audio_path},
                      }
                  )

                  text = ""
                  async for response in transcribe(t, request):
                      if response.text:
                          text += response.text

                  print(text)

                  print("▸ Unloading Parakeet model...")
                  await unload_model(t, model_id)
                  print("▸ Parakeet model unloaded successfully")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TranscriptionParakeetTdt.kt title="TranscriptionParakeetTdt.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/asr/parakeet-tdt-filesystem.ts.
      //
      // Parakeet TDT transcription from a WAV file. Loads a single GGUF checkpoint
      // (`Models.PARAKEET_TDT_0_6B_V3_Q8_0` by default) and transcribes the file with
      // the batch `client.speech.transcribe()` API. Omit the model argument to use the
      // registry constant.
      //
      // As in TypeScript, `transcribe()` returns the joined text
      // (`QvacTranscriptionResult.text`), so there are no frames to join by hand.
      //
      // Audio should be 16 kHz mono PCM in a WAV container.
      //
      // RUN: ./gradlew -p examples run -Pexample=TranscriptionParakeetTdt --args="<wav-file> [parakeet-tdt-gguf]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacDataInput
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.speech
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject

      fun main(args: Array<String>): Unit = runBlocking {
          if (args.isEmpty()) {
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=TranscriptionParakeetTdt " +
                      "--args=\"<wav-file-path> [parakeet-tdt-gguf]\"",
              )
              System.err.println("\nIf the model path is omitted, defaults to the registry model.")
              exitProcess(1)
          }
          val audioPath = args[0]
          val parakeetModelSrc = args.getOrNull(1) ?: Models.PARAKEET_TDT_0_6B_V3_Q8_0.src

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ Starting Parakeet transcription example...")

              println("▸ Loading Parakeet model...")
              val modelId = client.loadWithProgress(parakeetModelSrc, "parakeet-transcription")
              println("▸ Parakeet model loaded with ID: $modelId")

              println("▸ Transcribing audio...")
              val result = client.speech.transcribe(modelId, QvacDataInput.FilePath(audioPath))

              println(result.text)

              println("▸ Unloading Parakeet model...")
              client.models.unload(modelId)
              println("▸ Parakeet model unloaded successfully")
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(
          source: String,
          modelType: String,
          modelConfig: JsonObject? = null,
      ): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Parakeet CTC

The following script shows an example of English-only transcription using the Parakeet CTC model from a WAV file. Pass the path of a 16 kHz mono WAV file as the first argument; an optional second argument overrides the default model:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/asr/parakeet-ctc-filesystem.js title="parakeet-ctc-filesystem.js" lineNumbers
      /**
       * Parakeet CTC transcription from a WAV file.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-ctc-filesystem.ts <wav-file> [parakeet-ctc-gguf]
       *
       * Loads a single GGUF checkpoint (`PARAKEET_CTC_0_6B_Q8_0` by default) and
       * transcribes the file with the batch `transcribe` API. Omit the model
       * argument to use the registry constant.
       *
       * Audio should be 16 kHz mono PCM in a WAV container.
       */
      import { loadModel, unloadModel, transcribe, PARAKEET_CTC_0_6B_Q8_0 } from '@qvac/sdk';
      const args = process.argv.slice(2);
      if (!args[0]) {
          console.error('Usage: npx tsx examples/asr/parakeet-ctc-filesystem.ts <wav-file> ' + '[parakeet-ctc-gguf]');
          console.error('\nIf the model path is omitted, defaults to the registry model.');
          process.exit(1);
      }
      const audioFilePath = args[0];
      const parakeetModelSrc = args[1] ?? PARAKEET_CTC_0_6B_Q8_0;
      try {
          console.log('▸ Loading Parakeet CTC model...');
          const modelId = await loadModel({
              modelSrc: parakeetModelSrc,
              modelType: 'parakeet-transcription',
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Parakeet CTC model loaded with ID: ${modelId}`);
          console.log('▸ Transcribing audio...');
          const text = await transcribe({ modelId, audioChunk: audioFilePath });
          console.log(text);
          console.log('▸ Unloading model...');
          await unloadModel({ modelId });
          console.log('▸ Done');
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/asr/parakeet-ctc-filesystem.ts title="parakeet-ctc-filesystem.ts" lineNumbers
      /**
       * Parakeet CTC transcription from a WAV file.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-ctc-filesystem.ts <wav-file> [parakeet-ctc-gguf]
       *
       * Loads a single GGUF checkpoint (`PARAKEET_CTC_0_6B_Q8_0` by default) and
       * transcribes the file with the batch `transcribe` API. Omit the model
       * argument to use the registry constant.
       *
       * Audio should be 16 kHz mono PCM in a WAV container.
       */
      import { loadModel, unloadModel, transcribe, PARAKEET_CTC_0_6B_Q8_0 } from '@qvac/sdk'

      const args = process.argv.slice(2)

      if (!args[0]) {
        console.error(
          'Usage: npx tsx examples/asr/parakeet-ctc-filesystem.ts <wav-file> ' + '[parakeet-ctc-gguf]'
        )
        console.error('\nIf the model path is omitted, defaults to the registry model.')
        process.exit(1)
      }

      const audioFilePath = args[0]
      const parakeetModelSrc = args[1] ?? PARAKEET_CTC_0_6B_Q8_0

      try {
        console.log('▸ Loading Parakeet CTC model...')
        const modelId = await loadModel({
          modelSrc: parakeetModelSrc,
          modelType: 'parakeet-transcription',
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Parakeet CTC model loaded with ID: ${modelId}`)

        console.log('▸ Transcribing audio...')
        const text = await transcribe({ modelId, audioChunk: audioFilePath })

        console.log(text)

        console.log('▸ Unloading model...')
        await unloadModel({ modelId })
        console.log('▸ Done')
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/transcription_parakeet_ctc.py title="transcription_parakeet_ctc.py" lineNumbers
      """Python port of packages/sdk/examples/asr/parakeet-ctc-filesystem.ts.

      Parakeet CTC transcription from a WAV file. Loads a single GGUF checkpoint
      (`PARAKEET_CTC_0_6B_Q8_0` by default) and transcribes the file with the
      batch `transcribe` API. Omit the model argument to use the registry constant.

      TypeScript's `transcribe()` returns the joined text. Python calls the worker
      directly, so `transcribe` yields `TranscribeResponse` frames and the example
      joins their `text` itself.

      Audio should be 16 kHz mono PCM in a WAV container.

      RUN: python examples/transcription_parakeet_ctc.py <wav-file> [parakeet-ctc-gguf]
      """

      from __future__ import annotations

      import asyncio
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TranscribeRequest,
          load_model,
          transcribe,
          unload_model,
      )
      from tetherto.qvac_sdk.models import PARAKEET_CTC_0_6B_Q8_0


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          if len(sys.argv) < 2:
              print(
                  "Usage: python examples/transcription_parakeet_ctc.py <wav-file> "
                  "[parakeet-ctc-gguf]",
                  file=sys.stderr,
              )
              print(
                  "\nIf the model path is omitted, defaults to the registry model.",
                  file=sys.stderr,
              )
              return 1
          audio_path = sys.argv[1]
          parakeet_model_src = sys.argv[2] if len(sys.argv) > 2 else PARAKEET_CTC_0_6B_Q8_0

          async with Client() as client:
              t = client.transport
              try:
                  print("▸ Loading Parakeet CTC model...")
                  model_id = await load_model(
                      t,
                      model_src=parakeet_model_src,
                      model_type="parakeet-transcription",
                      on_progress=print_progress,
                  )
                  print(f"▸ Parakeet CTC model loaded with ID: {model_id}")

                  print("▸ Transcribing audio...")
                  # audioChunk is a typed chunk, not a bare path: JS's transcribe
                  # wrapper turns a string into {type:"filePath"} for you, but Python
                  # calls the generated stub directly, so build the chunk explicitly.
                  request = TranscribeRequest.model_validate(
                      {
                          "type": "transcribe",
                          "modelId": model_id,
                          "audioChunk": {"type": "filePath", "value": audio_path},
                      }
                  )

                  text = ""
                  async for response in transcribe(t, request):
                      if response.text:
                          text += response.text

                  print(text)

                  print("▸ Unloading model...")
                  await unload_model(t, model_id)
                  print("▸ Done")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TranscriptionParakeetCtc.kt title="TranscriptionParakeetCtc.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/asr/parakeet-ctc-filesystem.ts.
      //
      // Parakeet CTC transcription from a WAV file. Loads a single GGUF checkpoint
      // (`Models.PARAKEET_CTC_0_6B_Q8_0` by default) and transcribes the file with the
      // batch `client.speech.transcribe()` API. Omit the model argument to use the
      // registry constant.
      //
      // As in TypeScript, `transcribe()` returns the joined text
      // (`QvacTranscriptionResult.text`), so there are no frames to join by hand.
      //
      // Audio should be 16 kHz mono PCM in a WAV container.
      //
      // RUN: ./gradlew -p examples run -Pexample=TranscriptionParakeetCtc --args="<wav-file> [parakeet-ctc-gguf]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacDataInput
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.speech
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject

      fun main(args: Array<String>): Unit = runBlocking {
          if (args.isEmpty()) {
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=TranscriptionParakeetCtc " +
                      "--args=\"<wav-file> [parakeet-ctc-gguf]\"",
              )
              System.err.println("\nIf the model path is omitted, defaults to the registry model.")
              exitProcess(1)
          }
          val audioPath = args[0]
          val parakeetModelSrc = args.getOrNull(1) ?: Models.PARAKEET_CTC_0_6B_Q8_0.src

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ Loading Parakeet CTC model...")
              val modelId = client.loadWithProgress(parakeetModelSrc, "parakeet-transcription")
              println("▸ Parakeet CTC model loaded with ID: $modelId")

              println("▸ Transcribing audio...")
              val result = client.speech.transcribe(modelId, QvacDataInput.FilePath(audioPath))

              println(result.text)

              println("▸ Unloading model...")
              client.models.unload(modelId)
              println("▸ Done")
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(
          source: String,
          modelType: String,
          modelConfig: JsonObject? = null,
      ): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Parakeet Unified

The following script shows an example of English transcription using the Parakeet Unified model from a WAV file. Load it once and use it with either `transcribe()` for batch or `transcribeStream()` for low-latency streaming. The script uses batch `transcribe()`. Pass the path of a 16 kHz mono WAV file as the first argument; an optional second argument overrides the default model:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/asr/parakeet-unified-filesystem.js title="parakeet-unified-filesystem.js" lineNumbers
      /**
       * Parakeet Unified transcription from a WAV file.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-unified-filesystem.ts <wav-file> [parakeet-unified-gguf]
       *
       * Loads a single GGUF checkpoint (`PARAKEET_UNIFIED_0_6B_Q8_0` by default) and
       * transcribes the file with the batch `transcribe` API. The Unified RNN-T
       * checkpoint is English-only and serves both batch and low-latency streaming
       * from the same GGUF; the engine auto-detects the model type from the GGUF
       * metadata. Omit the model argument to use the registry constant.
       *
       * Audio should be 16 kHz mono PCM in a WAV container.
       */
      import { loadModel, unloadModel, transcribe, PARAKEET_UNIFIED_0_6B_Q8_0 } from '@qvac/sdk';
      const args = process.argv.slice(2);
      if (!args[0]) {
          console.error('Usage: npx tsx examples/asr/parakeet-unified-filesystem.ts <wav-file-path> ' +
              '[parakeet-unified-gguf]');
          console.error('\nIf the model path is omitted, defaults to the registry model.');
          process.exit(1);
      }
      const audioFilePath = args[0];
      const parakeetModelSrc = args[1] ?? PARAKEET_UNIFIED_0_6B_Q8_0;
      try {
          console.log('▸ Starting Parakeet Unified transcription example...');
          console.log('▸ Loading Parakeet Unified model...');
          const modelId = await loadModel({
              modelSrc: parakeetModelSrc,
              modelType: 'parakeet-transcription',
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Parakeet Unified model loaded with ID: ${modelId}`);
          console.log('▸ Transcribing audio...');
          const text = await transcribe({ modelId, audioChunk: audioFilePath });
          console.log(text);
          console.log('▸ Unloading Parakeet Unified model...');
          await unloadModel({ modelId });
          console.log('▸ Parakeet Unified model unloaded successfully');
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/asr/parakeet-unified-filesystem.ts title="parakeet-unified-filesystem.ts" lineNumbers
      /**
       * Parakeet Unified transcription from a WAV file.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-unified-filesystem.ts <wav-file> [parakeet-unified-gguf]
       *
       * Loads a single GGUF checkpoint (`PARAKEET_UNIFIED_0_6B_Q8_0` by default) and
       * transcribes the file with the batch `transcribe` API. The Unified RNN-T
       * checkpoint is English-only and serves both batch and low-latency streaming
       * from the same GGUF; the engine auto-detects the model type from the GGUF
       * metadata. Omit the model argument to use the registry constant.
       *
       * Audio should be 16 kHz mono PCM in a WAV container.
       */
      import { loadModel, unloadModel, transcribe, PARAKEET_UNIFIED_0_6B_Q8_0 } from '@qvac/sdk'

      const args = process.argv.slice(2)

      if (!args[0]) {
        console.error(
          'Usage: npx tsx examples/asr/parakeet-unified-filesystem.ts <wav-file-path> ' +
            '[parakeet-unified-gguf]'
        )
        console.error('\nIf the model path is omitted, defaults to the registry model.')
        process.exit(1)
      }

      const audioFilePath = args[0]
      const parakeetModelSrc = args[1] ?? PARAKEET_UNIFIED_0_6B_Q8_0

      try {
        console.log('▸ Starting Parakeet Unified transcription example...')

        console.log('▸ Loading Parakeet Unified model...')
        const modelId = await loadModel({
          modelSrc: parakeetModelSrc,
          modelType: 'parakeet-transcription',
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Parakeet Unified model loaded with ID: ${modelId}`)

        console.log('▸ Transcribing audio...')
        const text = await transcribe({ modelId, audioChunk: audioFilePath })

        console.log(text)

        console.log('▸ Unloading Parakeet Unified model...')
        await unloadModel({ modelId })
        console.log('▸ Parakeet Unified model unloaded successfully')
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/transcription_parakeet_unified.py title="transcription_parakeet_unified.py" lineNumbers
      """Python port of packages/sdk/examples/asr/parakeet-unified-filesystem.ts.

      Parakeet Unified transcription from a WAV file. Loads a single GGUF checkpoint
      (`PARAKEET_UNIFIED_0_6B_Q8_0` by default) and transcribes the file with the
      batch `transcribe` API. The Unified RNN-T checkpoint is English-only and serves
      both batch and low-latency streaming from the same GGUF; the engine
      auto-detects the model type from the GGUF metadata. Omit the model argument to
      use the registry constant.

      TypeScript's `transcribe()` returns the joined text. Python calls the worker
      directly, so `transcribe` yields `TranscribeResponse` frames and the example
      joins their `text` itself.

      Audio should be 16 kHz mono PCM in a WAV container.

      RUN: python examples/transcription_parakeet_unified.py <wav-file> [parakeet-unified-gguf]
      """

      from __future__ import annotations

      import asyncio
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TranscribeRequest,
          load_model,
          transcribe,
          unload_model,
      )
      from tetherto.qvac_sdk.models import PARAKEET_UNIFIED_0_6B_Q8_0


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          if len(sys.argv) < 2:
              print(
                  "Usage: python examples/transcription_parakeet_unified.py <wav-file-path> "
                  "[parakeet-unified-gguf]",
                  file=sys.stderr,
              )
              print(
                  "\nIf the model path is omitted, defaults to the registry model.",
                  file=sys.stderr,
              )
              return 1
          audio_path = sys.argv[1]
          parakeet_model_src = (
              sys.argv[2] if len(sys.argv) > 2 else PARAKEET_UNIFIED_0_6B_Q8_0
          )

          async with Client() as client:
              t = client.transport
              try:
                  print("▸ Starting Parakeet Unified transcription example...")

                  print("▸ Loading Parakeet Unified model...")
                  model_id = await load_model(
                      t,
                      model_src=parakeet_model_src,
                      model_type="parakeet-transcription",
                      on_progress=print_progress,
                  )
                  print(f"▸ Parakeet Unified model loaded with ID: {model_id}")

                  print("▸ Transcribing audio...")
                  # audioChunk is a typed chunk, not a bare path: JS's transcribe
                  # wrapper turns a string into {type:"filePath"} for you, but Python
                  # calls the generated stub directly, so build the chunk explicitly.
                  request = TranscribeRequest.model_validate(
                      {
                          "type": "transcribe",
                          "modelId": model_id,
                          "audioChunk": {"type": "filePath", "value": audio_path},
                      }
                  )

                  text = ""
                  async for response in transcribe(t, request):
                      if response.text:
                          text += response.text

                  print(text)

                  print("▸ Unloading Parakeet Unified model...")
                  await unload_model(t, model_id)
                  print("▸ Parakeet Unified model unloaded successfully")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TranscriptionParakeetUnified.kt title="TranscriptionParakeetUnified.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/asr/parakeet-unified-filesystem.ts.
      //
      // Parakeet Unified transcription from a WAV file. Loads a single GGUF checkpoint
      // (`Models.PARAKEET_UNIFIED_0_6B_Q8_0` by default) and transcribes the file with
      // the batch `client.speech.transcribe()` API. The Unified RNN-T checkpoint is
      // English-only and serves both batch and low-latency streaming from the same
      // GGUF; the engine auto-detects the model type from the GGUF metadata. Omit the
      // model argument to use the registry constant.
      //
      // As in TypeScript, `transcribe()` returns the joined text
      // (`QvacTranscriptionResult.text`), so there are no frames to join by hand.
      //
      // Audio should be 16 kHz mono PCM in a WAV container.
      //
      // RUN: ./gradlew -p examples run -Pexample=TranscriptionParakeetUnified --args="<wav-file> [parakeet-unified-gguf]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacDataInput
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.speech
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject

      fun main(args: Array<String>): Unit = runBlocking {
          if (args.isEmpty()) {
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=TranscriptionParakeetUnified " +
                      "--args=\"<wav-file-path> [parakeet-unified-gguf]\"",
              )
              System.err.println("\nIf the model path is omitted, defaults to the registry model.")
              exitProcess(1)
          }
          val audioPath = args[0]
          val parakeetModelSrc = args.getOrNull(1) ?: Models.PARAKEET_UNIFIED_0_6B_Q8_0.src

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ Starting Parakeet Unified transcription example...")

              println("▸ Loading Parakeet Unified model...")
              val modelId = client.loadWithProgress(parakeetModelSrc, "parakeet-transcription")
              println("▸ Parakeet Unified model loaded with ID: $modelId")

              println("▸ Transcribing audio...")
              val result = client.speech.transcribe(modelId, QvacDataInput.FilePath(audioPath))

              println(result.text)

              println("▸ Unloading Parakeet Unified model...")
              client.models.unload(modelId)
              println("▸ Parakeet Unified model unloaded successfully")
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(
          source: String,
          modelType: String,
          modelConfig: JsonObject? = null,
      ): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Parakeet Unified with Core ML

The following macOS script loads a regenerated Unified GGUF from disk, downloads its five Core ML encoder files through the registry, and transcribes a WAV file. Pass the path of the regenerated GGUF (`parakeet-unified-en-0.6b.{f16,q4_0,q8_0}.gguf`) as the first argument and the path of a 16 kHz mono WAV file as the second:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/asr/parakeet-unified-coreml.js title="parakeet-unified-coreml.js" lineNumbers
      /**
       * Transcribe a WAV file with Parakeet Unified and its Core ML encoder sidecar.
       *
       * From packages/sdk:
       *   npx tsx examples/asr/parakeet-unified-coreml.ts \
       *     /path/to/parakeet-unified-en-0.6b.q4_0.gguf <16-kHz-wav-file>
       *
       * The GGUF must be a regenerated Unified artifact. The five compiled Core ML
       * files are downloaded through the SDK registry and staged beside the GGUF.
       */
      import { downloadAsset, getModelInfo, loadModel, transcribe, unloadModel } from '@qvac/sdk';
      import { copyFile, link, mkdir, mkdtemp, open, rm, symlink } from 'node:fs/promises';
      import { tmpdir } from 'node:os';
      import { basename, join, resolve } from 'node:path';
      const MODEL_STEM = 'parakeet-unified-en-0.6b';
      const COREML_FILES = [
          ['PARAKEET_UNIFIED_COREMLDATA', 'analytics/coremldata.bin'],
          ['PARAKEET_UNIFIED_COREMLDATA_1', 'coremldata.bin'],
          ['PARAKEET_UNIFIED_METADATA', 'metadata.json'],
          ['PARAKEET_UNIFIED_MODEL', 'model.mil'],
          ['PARAKEET_UNIFIED_WEIGHT', 'weights/weight.bin']
      ];
      const modelPath = process.argv[2];
      const audioPath = process.argv[3];
      async function checkModel(path) {
          const name = basename(path);
          if (!/^parakeet-unified-en-0\.6b\.(?:f16|q4_0|q8_0)\.gguf$/.test(name)) {
              throw new Error(`Expected a regenerated Unified GGUF, got: ${name}`);
          }
          const file = await open(path, 'r');
          try {
              const header = Buffer.alloc(1024 * 1024);
              const { bytesRead } = await file.read(header, 0, header.length, 0);
              if (!header.subarray(0, bytesRead).includes('parakeet.unified.left_context_frames')) {
                  throw new Error(`Unified GGUF lacks the new streaming metadata: ${path}`);
              }
          }
          finally {
              await file.close();
          }
      }
      async function stageModel(path) {
          if (process.platform !== 'darwin')
              throw new Error('Core ML requires macOS');
          await checkModel(path);
          const dir = await mkdtemp(join(tmpdir(), 'qvac-unified-coreml-'));
          try {
              const modelSrc = join(dir, basename(path));
              await symlink(resolve(path), modelSrc);
              const bundleDir = join(dir, `${MODEL_STEM}-encoder.mlmodelc`);
              for (const [name, relativePath] of COREML_FILES) {
                  const info = await getModelInfo({ name });
                  if (!info.isCached) {
                      if (!info.registrySource || !info.registryPath) {
                          throw new Error(`Registry location missing for ${name}`);
                      }
                      console.log(`▸ Downloading Core ML ${relativePath}...`);
                      await downloadAsset({ assetSrc: `registry://${info.registrySource}/${info.registryPath}` });
                  }
                  const cached = await getModelInfo({ name });
                  const sourcePath = cached.cacheFiles.find((file) => file.isCached)?.path;
                  if (!sourcePath)
                      throw new Error(`Core ML file is missing from the SDK cache: ${name}`);
                  const targetPath = join(bundleDir, relativePath);
                  await mkdir(join(targetPath, '..'), { recursive: true });
                  try {
                      await link(sourcePath, targetPath);
                  }
                  catch (error) {
                      // A hard link cannot cross filesystems, e.g. a QVAC_HOME_DIR on another drive.
                      if (error.code !== 'EXDEV')
                          throw error;
                      await copyFile(sourcePath, targetPath);
                  }
              }
              return { modelSrc, dir };
          }
          catch (error) {
              await rm(dir, { recursive: true, force: true });
              throw error;
          }
      }
      async function main() {
          if (!modelPath || !audioPath) {
              throw new Error('Usage: npx tsx examples/asr/parakeet-unified-coreml.ts ' +
                  '<regenerated-unified-gguf> <16-kHz-wav-file>');
          }
          let staged;
          let modelId;
          try {
              staged = await stageModel(modelPath);
              console.log('▸ Loading Parakeet Unified with its Core ML encoder sidecar...');
              modelId = await loadModel({
                  modelSrc: staged.modelSrc,
                  modelType: 'parakeet-transcription',
                  modelConfig: { useGPU: true }
              });
              console.log('▸ Transcribing audio...');
              const text = await transcribe({ modelId, audioChunk: audioPath });
              if (!text.trim())
                  throw new Error('Parakeet Unified returned an empty transcription');
              console.log(text);
          }
          finally {
              try {
                  if (modelId)
                      await unloadModel({ modelId });
              }
              finally {
                  if (staged)
                      await rm(staged.dir, { recursive: true, force: true });
              }
          }
      }
      main().catch((error) => {
          console.error('✖', error);
          process.exitCode = 1;
      });
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/asr/parakeet-unified-coreml.ts title="parakeet-unified-coreml.ts" lineNumbers
      /**
       * Transcribe a WAV file with Parakeet Unified and its Core ML encoder sidecar.
       *
       * From packages/sdk:
       *   npx tsx examples/asr/parakeet-unified-coreml.ts \
       *     /path/to/parakeet-unified-en-0.6b.q4_0.gguf <16-kHz-wav-file>
       *
       * The GGUF must be a regenerated Unified artifact. The five compiled Core ML
       * files are downloaded through the SDK registry and staged beside the GGUF.
       */
      import { downloadAsset, getModelInfo, loadModel, transcribe, unloadModel } from '@qvac/sdk'
      import { copyFile, link, mkdir, mkdtemp, open, rm, symlink } from 'node:fs/promises'
      import { tmpdir } from 'node:os'
      import { basename, join, resolve } from 'node:path'

      const MODEL_STEM = 'parakeet-unified-en-0.6b'
      const COREML_FILES = [
        ['PARAKEET_UNIFIED_COREMLDATA', 'analytics/coremldata.bin'],
        ['PARAKEET_UNIFIED_COREMLDATA_1', 'coremldata.bin'],
        ['PARAKEET_UNIFIED_METADATA', 'metadata.json'],
        ['PARAKEET_UNIFIED_MODEL', 'model.mil'],
        ['PARAKEET_UNIFIED_WEIGHT', 'weights/weight.bin']
      ] as const

      const modelPath = process.argv[2]
      const audioPath = process.argv[3]

      async function checkModel(path: string): Promise<void> {
        const name = basename(path)
        if (!/^parakeet-unified-en-0\.6b\.(?:f16|q4_0|q8_0)\.gguf$/.test(name)) {
          throw new Error(`Expected a regenerated Unified GGUF, got: ${name}`)
        }

        const file = await open(path, 'r')
        try {
          const header = Buffer.alloc(1024 * 1024)
          const { bytesRead } = await file.read(header, 0, header.length, 0)
          if (!header.subarray(0, bytesRead).includes('parakeet.unified.left_context_frames')) {
            throw new Error(`Unified GGUF lacks the new streaming metadata: ${path}`)
          }
        } finally {
          await file.close()
        }
      }

      async function stageModel(path: string): Promise<{ modelSrc: string; dir: string }> {
        if (process.platform !== 'darwin') throw new Error('Core ML requires macOS')
        await checkModel(path)

        const dir = await mkdtemp(join(tmpdir(), 'qvac-unified-coreml-'))
        try {
          const modelSrc = join(dir, basename(path))
          await symlink(resolve(path), modelSrc)
          const bundleDir = join(dir, `${MODEL_STEM}-encoder.mlmodelc`)

          for (const [name, relativePath] of COREML_FILES) {
            const info = await getModelInfo({ name })
            if (!info.isCached) {
              if (!info.registrySource || !info.registryPath) {
                throw new Error(`Registry location missing for ${name}`)
              }
              console.log(`▸ Downloading Core ML ${relativePath}...`)
              await downloadAsset({ assetSrc: `registry://${info.registrySource}/${info.registryPath}` })
            }

            const cached = await getModelInfo({ name })
            const sourcePath = cached.cacheFiles.find((file) => file.isCached)?.path
            if (!sourcePath) throw new Error(`Core ML file is missing from the SDK cache: ${name}`)

            const targetPath = join(bundleDir, relativePath)
            await mkdir(join(targetPath, '..'), { recursive: true })
            try {
              await link(sourcePath, targetPath)
            } catch (error) {
              // A hard link cannot cross filesystems, e.g. a QVAC_HOME_DIR on another drive.
              if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error
              await copyFile(sourcePath, targetPath)
            }
          }

          return { modelSrc, dir }
        } catch (error) {
          await rm(dir, { recursive: true, force: true })
          throw error
        }
      }

      async function main(): Promise<void> {
        if (!modelPath || !audioPath) {
          throw new Error(
            'Usage: npx tsx examples/asr/parakeet-unified-coreml.ts ' +
              '<regenerated-unified-gguf> <16-kHz-wav-file>'
          )
        }

        let staged: Awaited<ReturnType<typeof stageModel>> | undefined
        let modelId: string | undefined
        try {
          staged = await stageModel(modelPath)
          console.log('▸ Loading Parakeet Unified with its Core ML encoder sidecar...')
          modelId = await loadModel({
            modelSrc: staged.modelSrc,
            modelType: 'parakeet-transcription',
            modelConfig: { useGPU: true }
          })

          console.log('▸ Transcribing audio...')
          const text = await transcribe({ modelId, audioChunk: audioPath })
          if (!text.trim()) throw new Error('Parakeet Unified returned an empty transcription')
          console.log(text)
        } finally {
          try {
            if (modelId) await unloadModel({ modelId })
          } finally {
            if (staged) await rm(staged.dir, { recursive: true, force: true })
          }
        }
      }

      main().catch((error: unknown) => {
        console.error('✖', error)
        process.exitCode = 1
      })
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/transcription_parakeet_unified_coreml.py title="transcription_parakeet_unified_coreml.py" lineNumbers
      """Python port of packages/sdk/examples/asr/parakeet-unified-coreml.ts.

      Transcribe a WAV file with Parakeet Unified and its Core ML encoder sidecar
      (macOS only). The GGUF must be a regenerated Unified artifact. The five
      compiled Core ML files are downloaded through the SDK registry and staged
      beside the GGUF in a temporary directory, which is removed afterwards.

      TypeScript's `transcribe()` returns the joined text. Python calls the worker
      directly, so `transcribe` yields `TranscribeResponse` frames and the example
      joins their `text` itself. `get_model_info` and `download_asset` are generated
      stubs, so each takes its request model.

      RUN: python examples/transcription_parakeet_unified_coreml.py <regenerated-unified-gguf> <16-kHz-wav-file>
      """

      from __future__ import annotations

      import asyncio
      import errno
      import os
      import re
      import shutil
      import sys
      import tempfile
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          DownloadAssetRequest,
          GetModelInfoRequest,
          TranscribeRequest,
          download_asset,
          get_model_info,
          load_model,
          transcribe,
          unload_model,
      )

      MODEL_STEM = "parakeet-unified-en-0.6b"
      COREML_FILES = [
          ("PARAKEET_UNIFIED_COREMLDATA", "analytics/coremldata.bin"),
          ("PARAKEET_UNIFIED_COREMLDATA_1", "coremldata.bin"),
          ("PARAKEET_UNIFIED_METADATA", "metadata.json"),
          ("PARAKEET_UNIFIED_MODEL", "model.mil"),
          ("PARAKEET_UNIFIED_WEIGHT", "weights/weight.bin"),
      ]


      def check_model(path: Path) -> None:
          if not re.fullmatch(
              r"parakeet-unified-en-0\.6b\.(?:f16|q4_0|q8_0)\.gguf", path.name
          ):
              raise ValueError(f"Expected a regenerated Unified GGUF, got: {path.name}")

          with path.open("rb") as file:
              header = file.read(1024 * 1024)
          if b"parakeet.unified.left_context_frames" not in header:
              raise ValueError(f"Unified GGUF lacks the new streaming metadata: {path}")


      async def fetch_info(t, name: str):
          request = GetModelInfoRequest.model_validate({"type": "getModelInfo", "name": name})
          return (await get_model_info(t, request)).model_info


      async def stage_model(t, path: Path) -> tuple[str, Path]:
          if sys.platform != "darwin":
              raise RuntimeError("Core ML requires macOS")
          check_model(path)

          staging_dir = Path(tempfile.mkdtemp(prefix="qvac-unified-coreml-"))
          try:
              model_src = staging_dir / path.name
              model_src.symlink_to(path.resolve())
              bundle_dir = staging_dir / f"{MODEL_STEM}-encoder.mlmodelc"

              for name, relative_path in COREML_FILES:
                  info = await fetch_info(t, name)
                  if not info.is_cached:
                      if not info.registry_source or not info.registry_path:
                          raise RuntimeError(f"Registry location missing for {name}")
                      print(f"▸ Downloading Core ML {relative_path}...")
                      request = DownloadAssetRequest.model_validate(
                          {
                              "type": "downloadAsset",
                              "assetSrc": f"registry://{info.registry_source}/{info.registry_path}",
                          }
                      )
                      await download_asset(t, request)

                  cached = await fetch_info(t, name)
                  source_path = next(
                      (file.path for file in cached.cache_files or [] if file.is_cached), None
                  )
                  if not source_path:
                      raise RuntimeError(
                          f"Core ML file is missing from the SDK cache: {name}"
                      )

                  target_path = bundle_dir / relative_path
                  target_path.parent.mkdir(parents=True, exist_ok=True)
                  try:
                      os.link(source_path, target_path)
                  except OSError as error:
                      # A hard link cannot cross filesystems, e.g. a QVAC_HOME_DIR on
                      # another drive.
                      if error.errno != errno.EXDEV:
                          raise
                      shutil.copyfile(source_path, target_path)

              return str(model_src), staging_dir
          except BaseException:
              shutil.rmtree(staging_dir, ignore_errors=True)
              raise


      async def main() -> int:
          if len(sys.argv) < 3:
              print(
                  "Usage: python examples/transcription_parakeet_unified_coreml.py "
                  "<regenerated-unified-gguf> <16-kHz-wav-file>",
                  file=sys.stderr,
              )
              return 1
          model_path = Path(sys.argv[1])
          audio_path = sys.argv[2]

          async with Client() as client:
              t = client.transport
              staging_dir = None
              model_id = None
              try:
                  model_src, staging_dir = await stage_model(t, model_path)
                  print("▸ Loading Parakeet Unified with its Core ML encoder sidecar...")
                  model_id = await load_model(
                      t,
                      model_src=model_src,
                      model_type="parakeet-transcription",
                      model_config={"useGPU": True},
                  )

                  print("▸ Transcribing audio...")
                  # audioChunk is a typed chunk, not a bare path: JS's transcribe
                  # wrapper turns a string into {type:"filePath"} for you, but Python
                  # calls the generated stub directly, so build the chunk explicitly.
                  request = TranscribeRequest.model_validate(
                      {
                          "type": "transcribe",
                          "modelId": model_id,
                          "audioChunk": {"type": "filePath", "value": audio_path},
                      }
                  )

                  text = ""
                  async for response in transcribe(t, request):
                      if response.text:
                          text += response.text

                  if not text.strip():
                      raise RuntimeError("Parakeet Unified returned an empty transcription")
                  print(text)
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
              finally:
                  try:
                      if model_id is not None:
                          await unload_model(t, model_id)
                  finally:
                      if staging_dir is not None:
                          shutil.rmtree(staging_dir, ignore_errors=True)
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TranscriptionParakeetUnifiedCoreml.kt title="TranscriptionParakeetUnifiedCoreml.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/asr/parakeet-unified-coreml.ts.
      //
      // Transcribe a WAV file with Parakeet Unified and its Core ML encoder sidecar
      // (macOS only). The GGUF must be a regenerated Unified artifact. The five
      // compiled Core ML files are downloaded through the SDK registry and staged
      // beside the GGUF in a temporary directory, which is removed afterwards.
      //
      // As in TypeScript, `client.speech.transcribe()` returns the joined text, and
      // `client.models.info()` / `client.models.download()` take plain arguments and
      // return the typed `GetModelInfoResponse` / `DownloadAssetResponse`.
      //
      // RUN: ./gradlew -p examples run -Pexample=TranscriptionParakeetUnifiedCoreml --args="<regenerated-unified-gguf> <16-kHz-wav-file>"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacDataInput
      import io.tether.qvac.sdk.generated.schema.GetModelInfoResponseModelInfo
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.speech
      import java.io.File
      import java.io.IOException
      import java.nio.file.Files
      import java.nio.file.Path
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      private const val MODEL_STEM = "parakeet-unified-en-0.6b"
      private val COREML_FILES = listOf(
          "PARAKEET_UNIFIED_COREMLDATA" to "analytics/coremldata.bin",
          "PARAKEET_UNIFIED_COREMLDATA_1" to "coremldata.bin",
          "PARAKEET_UNIFIED_METADATA" to "metadata.json",
          "PARAKEET_UNIFIED_MODEL" to "model.mil",
          "PARAKEET_UNIFIED_WEIGHT" to "weights/weight.bin",
      )

      fun main(args: Array<String>): Unit = runBlocking {
          if (args.size < 2) {
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=TranscriptionParakeetUnifiedCoreml " +
                      "--args=\"<regenerated-unified-gguf> <16-kHz-wav-file>\"",
              )
              exitProcess(1)
          }
          val modelPath = Path.of(args[0])
          val audioPath = args[1]

          val client = QvacClient(JvmBareKitTransport.connect())
          var stagingDir: File? = null
          var modelId: String? = null
          try {
              val (modelSrc, staged) = client.stageModel(modelPath)
              stagingDir = staged
              println("▸ Loading Parakeet Unified with its Core ML encoder sidecar...")
              val loaded = client.models.load(
                  source = modelSrc,
                  modelType = "parakeet-transcription",
                  modelConfig = buildJsonObject { put("useGPU", true) },
              )
              modelId = loaded.modelId ?: error(loaded.error ?: "loadModel failed")

              println("▸ Transcribing audio...")
              val text = client.speech.transcribe(modelId, QvacDataInput.FilePath(audioPath)).text

              if (text.isBlank()) error("Parakeet Unified returned an empty transcription")
              println(text)
          } finally {
              try {
                  modelId?.let { client.models.unload(it) }
              } finally {
                  stagingDir?.deleteRecursively()
                  client.close()
              }
          }
      }

      private fun checkModel(path: Path) {
          val name = path.fileName.toString()
          require(Regex("""parakeet-unified-en-0\.6b\.(?:f16|q4_0|q8_0)\.gguf""").matches(name)) {
              "Expected a regenerated Unified GGUF, got: $name"
          }

          val header = Files.newInputStream(path).use { it.readNBytes(1024 * 1024) }
          require("parakeet.unified.left_context_frames" in String(header, Charsets.ISO_8859_1)) {
              "Unified GGUF lacks the new streaming metadata: $path"
          }
      }

      private suspend fun QvacClient.fetchInfo(name: String): GetModelInfoResponseModelInfo = models.info(name).modelInfo

      private suspend fun QvacClient.stageModel(path: Path): Pair<String, File> {
          check(System.getProperty("os.name").startsWith("Mac")) { "Core ML requires macOS" }
          checkModel(path)

          val stagingDir = Files.createTempDirectory("qvac-unified-coreml-")
          try {
              val modelSrc = stagingDir.resolve(path.fileName)
              Files.createSymbolicLink(modelSrc, path.toRealPath())
              val bundleDir = stagingDir.resolve("$MODEL_STEM-encoder.mlmodelc")

              for ((name, relativePath) in COREML_FILES) {
                  val info = fetchInfo(name)
                  if (!info.isCached) {
                      if (info.registrySource.isNullOrEmpty() || info.registryPath.isNullOrEmpty()) {
                          error("Registry location missing for $name")
                      }
                      println("▸ Downloading Core ML $relativePath...")
                      models.download("registry://${info.registrySource}/${info.registryPath}")
                  }

                  val cached = fetchInfo(name)
                  val sourcePath = cached.cacheFiles.firstOrNull { it.isCached }?.path
                      ?: error("Core ML file is missing from the SDK cache: $name")

                  val targetPath = bundleDir.resolve(relativePath)
                  Files.createDirectories(targetPath.parent)
                  try {
                      Files.createLink(targetPath, Path.of(sourcePath))
                  } catch (error: IOException) {
                      // A hard link cannot cross filesystems, e.g. a QVAC_HOME_DIR on another drive.
                      Files.copy(Path.of(sourcePath), targetPath)
                  }
              }

              return modelSrc.toString() to stagingDir.toFile()
          } catch (error: Throwable) {
              stagingDir.toFile().deleteRecursively()
              throw error
          }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### TranscribePsy

The following script transcribes a file with TranscribePsy. By default it loads the ggml GGUF; on macOS, `--coreml` loads the Core ML distribution and reports whether the encoder ran on the Neural Engine, and `--window-sec` sets an explicit long-form window. Pass the path of the audio file as the first argument:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/asr/parakeet-transcribepsy-filesystem.js title="parakeet-transcribepsy-filesystem.js" lineNumbers
      /**
       * TranscribePsy transcription from an audio file.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-transcribepsy-filesystem.ts <audio-file> [--eu [--language en|other|auto]] [--coreml] [--window-sec <seconds>]
       *
       * TranscribePsy-250M-EU-sub is a 254M Parakeet-TDT distilled for Dutch,
       * English, French, German, Italian, Polish, Portuguese and Spanish; the engine
       * detects the language, so there is nothing to set. The default constant
       * (`PARAKEET_TRANSCRIBEPSY_250M_Q8_0`) runs on ggml everywhere. On
       * macOS and iOS, `--coreml` loads the Core ML distribution instead
       * (`PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0`): the SDK downloads its
       * encoder and decoder bundles with the GGUF, and both stages run on the Neural
       * Engine. Anywhere else that constant is refused at load time.
       *
       * `--eu` loads the full 25-language TranscribePsy-250M-EU instead
       * (`PARAKEET_TRANSCRIBEPSY_250M_EU_Q8_0`): one GGUF with its CAFE language
       * adapters and gate embedded, ggml on every platform, no Core ML distribution.
       * `--language` picks its route: `en` for the English trunk, `other` for the
       * non-English adapters, or `auto` (the default) to let the gate decide from
       * the first seconds of the recording.
       *
       * Long recordings are encoded in overlapping windows, so memory stays flat
       * however long the file is. Without `--window-sec` the engine uses the 60 s
       * windows with 25 % overlap the model recommends; an explicit window is sent
       * as encoder frames (12.5 per second) with a quarter of it as context, which
       * is how a phone with little memory can trade speed for a smaller footprint.
       */
      import { loadModel, unloadModel, transcribe, PARAKEET_TRANSCRIBEPSY_250M_Q8_0, PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0, PARAKEET_TRANSCRIBEPSY_250M_EU_Q8_0 } from '@qvac/sdk';
      const ENCODER_FRAMES_PER_SECOND = 12.5;
      const RECOMMENDED_OVERLAP = 0.25;
      const EU_LANGUAGES = ['en', 'other', 'auto'];
      const USAGE = 'Usage: npx tsx examples/asr/parakeet-transcribepsy-filesystem.ts <audio-file> ' +
          '[--eu [--language en|other|auto]] [--coreml] [--window-sec <seconds>]';
      const args = process.argv.slice(2);
      const valueFlags = new Set(['--window-sec', '--language']);
      const audioFilePath = args.find((arg, index) => !arg.startsWith('--') && !valueFlags.has(args[index - 1] ?? ''));
      const useCoreml = args.includes('--coreml');
      const useEu = args.includes('--eu');
      const windowIndex = args.indexOf('--window-sec');
      const windowSeconds = windowIndex === -1 ? undefined : Number(args[windowIndex + 1]);
      const languageIndex = args.indexOf('--language');
      const language = languageIndex === -1 ? undefined : args[languageIndex + 1];
      function isEuLanguage(value) {
          return EU_LANGUAGES.includes(value ?? '');
      }
      if (!audioFilePath ||
          (windowSeconds !== undefined && !(windowSeconds > 0)) ||
          (useEu && useCoreml) ||
          // `--language` needs a value, and only the full EU model has a route to pick.
          (languageIndex !== -1 && (!useEu || !isEuLanguage(language)))) {
          console.error(USAGE);
          process.exit(1);
      }
      // An explicit window becomes the engine's frame counts; the overlap is shared
      // half and half with each neighbouring window.
      const longForm = windowSeconds === undefined
          ? {}
          : {
              longFormWindowFrames: Math.round(windowSeconds * ENCODER_FRAMES_PER_SECOND),
              longFormContextFrames: Math.round((windowSeconds * ENCODER_FRAMES_PER_SECOND * RECOMMENDED_OVERLAP) / 2)
          };
      // The EU route only means something to the full model; EU-sub has no gate.
      const route = useEu && language !== undefined ? { language } : {};
      const modelSrc = useEu
          ? PARAKEET_TRANSCRIBEPSY_250M_EU_Q8_0
          : useCoreml
              ? PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0
              : PARAKEET_TRANSCRIBEPSY_250M_Q8_0;
      const variant = useEu
          ? `EU, 25 languages, route ${language ?? 'auto'}`
          : useCoreml
              ? 'EU-sub, Core ML distribution'
              : 'EU-sub, ggml';
      try {
          console.log(`▸ Loading TranscribePsy (${variant})...`);
          const modelId = await loadModel({
              modelSrc,
              modelType: 'parakeet-transcription',
              modelConfig: { ...longForm, ...route },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(windowSeconds === undefined
              ? '▸ Transcribing with the windows the model recommends (60 s, 25 % overlap)...'
              : `▸ Transcribing in ${windowSeconds} s windows...`);
          const call = transcribe({ modelId, audioChunk: audioFilePath });
          const text = await call;
          const stats = await call.stats;
          console.log(text);
          if (stats) {
              console.log(`▸ ${stats.audioDuration?.toFixed(1) ?? '?'} s of audio, real-time factor ${stats.realTimeFactor?.toFixed(3) ?? '?'}` +
                  (useCoreml ? `, encoder on Core ML: ${stats.encoderUsedCoreml === 1 ? 'yes' : 'no'}` : ''));
          }
          await unloadModel({ modelId });
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/asr/parakeet-transcribepsy-filesystem.ts title="parakeet-transcribepsy-filesystem.ts" lineNumbers
      /**
       * TranscribePsy transcription from an audio file.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-transcribepsy-filesystem.ts <audio-file> [--eu [--language en|other|auto]] [--coreml] [--window-sec <seconds>]
       *
       * TranscribePsy-250M-EU-sub is a 254M Parakeet-TDT distilled for Dutch,
       * English, French, German, Italian, Polish, Portuguese and Spanish; the engine
       * detects the language, so there is nothing to set. The default constant
       * (`PARAKEET_TRANSCRIBEPSY_250M_Q8_0`) runs on ggml everywhere. On
       * macOS and iOS, `--coreml` loads the Core ML distribution instead
       * (`PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0`): the SDK downloads its
       * encoder and decoder bundles with the GGUF, and both stages run on the Neural
       * Engine. Anywhere else that constant is refused at load time.
       *
       * `--eu` loads the full 25-language TranscribePsy-250M-EU instead
       * (`PARAKEET_TRANSCRIBEPSY_250M_EU_Q8_0`): one GGUF with its CAFE language
       * adapters and gate embedded, ggml on every platform, no Core ML distribution.
       * `--language` picks its route: `en` for the English trunk, `other` for the
       * non-English adapters, or `auto` (the default) to let the gate decide from
       * the first seconds of the recording.
       *
       * Long recordings are encoded in overlapping windows, so memory stays flat
       * however long the file is. Without `--window-sec` the engine uses the 60 s
       * windows with 25 % overlap the model recommends; an explicit window is sent
       * as encoder frames (12.5 per second) with a quarter of it as context, which
       * is how a phone with little memory can trade speed for a smaller footprint.
       */
      import {
        loadModel,
        unloadModel,
        transcribe,
        PARAKEET_TRANSCRIBEPSY_250M_Q8_0,
        PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0,
        PARAKEET_TRANSCRIBEPSY_250M_EU_Q8_0
      } from '@qvac/sdk'

      const ENCODER_FRAMES_PER_SECOND = 12.5
      const RECOMMENDED_OVERLAP = 0.25
      const EU_LANGUAGES = ['en', 'other', 'auto'] as const
      type EuLanguage = (typeof EU_LANGUAGES)[number]

      const USAGE =
        'Usage: npx tsx examples/asr/parakeet-transcribepsy-filesystem.ts <audio-file> ' +
        '[--eu [--language en|other|auto]] [--coreml] [--window-sec <seconds>]'

      const args = process.argv.slice(2)
      const valueFlags = new Set(['--window-sec', '--language'])
      const audioFilePath = args.find(
        (arg, index) => !arg.startsWith('--') && !valueFlags.has(args[index - 1] ?? '')
      )
      const useCoreml = args.includes('--coreml')
      const useEu = args.includes('--eu')
      const windowIndex = args.indexOf('--window-sec')
      const windowSeconds = windowIndex === -1 ? undefined : Number(args[windowIndex + 1])
      const languageIndex = args.indexOf('--language')
      const language = languageIndex === -1 ? undefined : args[languageIndex + 1]

      function isEuLanguage(value: string | undefined): value is EuLanguage {
        return (EU_LANGUAGES as readonly string[]).includes(value ?? '')
      }

      if (
        !audioFilePath ||
        (windowSeconds !== undefined && !(windowSeconds > 0)) ||
        (useEu && useCoreml) ||
        // `--language` needs a value, and only the full EU model has a route to pick.
        (languageIndex !== -1 && (!useEu || !isEuLanguage(language)))
      ) {
        console.error(USAGE)
        process.exit(1)
      }

      // An explicit window becomes the engine's frame counts; the overlap is shared
      // half and half with each neighbouring window.
      const longForm =
        windowSeconds === undefined
          ? {}
          : {
              longFormWindowFrames: Math.round(windowSeconds * ENCODER_FRAMES_PER_SECOND),
              longFormContextFrames: Math.round(
                (windowSeconds * ENCODER_FRAMES_PER_SECOND * RECOMMENDED_OVERLAP) / 2
              )
            }

      // The EU route only means something to the full model; EU-sub has no gate.
      const route = useEu && language !== undefined ? { language } : {}

      const modelSrc = useEu
        ? PARAKEET_TRANSCRIBEPSY_250M_EU_Q8_0
        : useCoreml
          ? PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0
          : PARAKEET_TRANSCRIBEPSY_250M_Q8_0

      const variant = useEu
        ? `EU, 25 languages, route ${language ?? 'auto'}`
        : useCoreml
          ? 'EU-sub, Core ML distribution'
          : 'EU-sub, ggml'

      try {
        console.log(`▸ Loading TranscribePsy (${variant})...`)
        const modelId = await loadModel({
          modelSrc,
          modelType: 'parakeet-transcription',
          modelConfig: { ...longForm, ...route },
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(
          windowSeconds === undefined
            ? '▸ Transcribing with the windows the model recommends (60 s, 25 % overlap)...'
            : `▸ Transcribing in ${windowSeconds} s windows...`
        )
        const call = transcribe({ modelId, audioChunk: audioFilePath })
        const text = await call
        const stats = await call.stats

        console.log(text)
        if (stats) {
          console.log(
            `▸ ${stats.audioDuration?.toFixed(1) ?? '?'} s of audio, real-time factor ${stats.realTimeFactor?.toFixed(3) ?? '?'}` +
              (useCoreml ? `, encoder on Core ML: ${stats.encoderUsedCoreml === 1 ? 'yes' : 'no'}` : '')
          )
        }

        await unloadModel({ modelId })
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/transcription_parakeet_transcribepsy.py title="transcription_parakeet_transcribepsy.py" lineNumbers
      """Python port of packages/sdk/examples/asr/parakeet-transcribepsy-filesystem.ts.

      TranscribePsy transcription from an audio file.

      TranscribePsy-250M-EU-sub is a 254M Parakeet-TDT distilled for Dutch,
      English, French, German, Italian, Polish, Portuguese and Spanish; the engine
      detects the language, so there is nothing to set. The default constant
      (`PARAKEET_TRANSCRIBEPSY_250M_Q8_0`) runs on ggml everywhere. On macOS and
      iOS, `--coreml` loads the Core ML distribution instead
      (`PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0`): the SDK downloads its encoder and
      decoder bundles with the GGUF, and both stages run on the Neural Engine.
      Anywhere else that constant is refused at load time.

      `--eu` loads the full 25-language TranscribePsy-250M-EU instead
      (`PARAKEET_TRANSCRIBEPSY_250M_EU_Q8_0`): one GGUF with its CAFE language
      adapters and gate embedded, ggml on every platform, no Core ML distribution.
      `--language` picks its route: `en` for the English trunk, `other` for the
      non-English adapters, or `auto` (the default) to let the gate decide from the
      first seconds of the recording.

      Long recordings are encoded in overlapping windows, so memory stays flat
      however long the file is. Without `--window-sec` the engine uses the 60 s
      windows with 25 % overlap the model recommends; an explicit window is sent as
      encoder frames (12.5 per second) with a quarter of it as context, which is how
      a phone with little memory can trade speed for a smaller footprint.

      TypeScript's `transcribe()` returns the joined text and exposes `stats`
      separately. Python calls the worker directly, so `transcribe` yields
      `TranscribeResponse` frames: the example joins their `text` and reads `stats`
      off the closing frame.

      RUN: python examples/transcription_parakeet_transcribepsy.py <audio-file> [--eu [--language en|other|auto]] [--coreml] [--window-sec <seconds>]
      """

      from __future__ import annotations

      import asyncio
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TranscribeRequest,
          load_model,
          transcribe,
          unload_model,
      )
      from tetherto.qvac_sdk.models import (
          PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0,
          PARAKEET_TRANSCRIBEPSY_250M_EU_Q8_0,
          PARAKEET_TRANSCRIBEPSY_250M_Q8_0,
      )

      ENCODER_FRAMES_PER_SECOND = 12.5
      RECOMMENDED_OVERLAP = 0.25
      EU_LANGUAGES = ("en", "other", "auto")
      USAGE = (
          "Usage: python examples/transcription_parakeet_transcribepsy.py <audio-file> "
          "[--eu [--language en|other|auto]] [--coreml] [--window-sec <seconds>]"
      )


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def fmt(value: float | None, digits: int) -> str:
          """Format an optional stat, as TypeScript's `?.toFixed(n) ?? '?'`."""
          return "?" if value is None else f"{value:.{digits}f}"


      def parse_args(
          args: list[str],
      ) -> tuple[str, bool, bool, str | None, float | None] | None:
          value_flags = {"--window-sec", "--language"}
          audio_path = next(
              (
                  arg
                  for index, arg in enumerate(args)
                  if not arg.startswith("--")
                  and (index == 0 or args[index - 1] not in value_flags)
              ),
              None,
          )
          use_coreml = "--coreml" in args
          use_eu = "--eu" in args
          window_seconds = None
          if "--window-sec" in args:
              index = args.index("--window-sec")
              try:
                  window_seconds = float(args[index + 1])
              except (IndexError, ValueError):
                  return None
              if not window_seconds > 0:
                  return None
          language = None
          if "--language" in args:
              index = args.index("--language")
              language = args[index + 1] if index + 1 < len(args) else None
              # The route only means something to the full EU model; EU-sub has no gate.
              if not use_eu or language not in EU_LANGUAGES:
                  return None
          if audio_path is None or (use_eu and use_coreml):
              return None
          return audio_path, use_eu, use_coreml, language, window_seconds


      async def main() -> int:
          parsed = parse_args(sys.argv[1:])
          if parsed is None:
              print(USAGE, file=sys.stderr)
              return 1
          audio_path, use_eu, use_coreml, language, window_seconds = parsed

          # An explicit window becomes the engine's frame counts; the overlap is
          # shared half and half with each neighbouring window.
          long_form = (
              {}
              if window_seconds is None
              else {
                  "longFormWindowFrames": round(window_seconds * ENCODER_FRAMES_PER_SECOND),
                  "longFormContextFrames": round(
                      window_seconds * ENCODER_FRAMES_PER_SECOND * RECOMMENDED_OVERLAP / 2
                  ),
              }
          )

          if use_eu:
              model_src = PARAKEET_TRANSCRIBEPSY_250M_EU_Q8_0
              variant = f"EU, 25 languages, route {language or 'auto'}"
          elif use_coreml:
              model_src = PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0
              variant = "EU-sub, Core ML distribution"
          else:
              model_src = PARAKEET_TRANSCRIBEPSY_250M_Q8_0
              variant = "EU-sub, ggml"
          route = {"language": language} if use_eu and language is not None else {}

          async with Client() as client:
              t = client.transport
              try:
                  print(f"▸ Loading TranscribePsy ({variant})...")
                  model_id = await load_model(
                      t,
                      model_src=model_src,
                      model_type="parakeet-transcription",
                      model_config={**long_form, **route},
                      on_progress=print_progress,
                  )

                  print(
                      "▸ Transcribing with the windows the model recommends (60 s, 25 % overlap)..."
                      if window_seconds is None
                      else f"▸ Transcribing in {window_seconds:g} s windows..."
                  )
                  # audioChunk is a typed chunk, not a bare path: JS's transcribe
                  # wrapper turns a string into {type:"filePath"} for you, but Python
                  # calls the generated stub directly, so build the chunk explicitly.
                  request = TranscribeRequest.model_validate(
                      {
                          "type": "transcribe",
                          "modelId": model_id,
                          "audioChunk": {"type": "filePath", "value": audio_path},
                      }
                  )

                  text = ""
                  stats = None
                  async for response in transcribe(t, request):
                      if response.text:
                          text += response.text
                      if response.stats is not None:
                          stats = response.stats

                  print(text)
                  if stats is not None:
                      summary = (
                          f"▸ {fmt(stats.audio_duration, 1)} s of audio, "
                          f"real-time factor {fmt(stats.real_time_factor, 3)}"
                      )
                      if use_coreml:
                          used = "yes" if stats.encoder_used_coreml == 1 else "no"
                          summary += f", encoder on Core ML: {used}"
                      print(summary)

                  await unload_model(t, model_id)
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TranscriptionParakeetTranscribepsy.kt title="TranscriptionParakeetTranscribepsy.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/asr/parakeet-transcribepsy-filesystem.ts.
      //
      // TranscribePsy transcription from an audio file.
      //
      // TranscribePsy-250M-EU-sub is a 254M Parakeet-TDT distilled for Dutch,
      // English, French, German, Italian, Polish, Portuguese and Spanish; the engine
      // detects the language, so there is nothing to set. The default constant
      // (`Models.PARAKEET_TRANSCRIBEPSY_250M_Q8_0`) runs on ggml everywhere. On macOS
      // and iOS, `--coreml` loads the Core ML distribution instead
      // (`Models.PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0`): the SDK downloads its
      // encoder and decoder bundles with the GGUF, and both stages run on the Neural
      // Engine. Anywhere else that constant is refused at load time.
      //
      // `--eu` loads the full 25-language TranscribePsy-250M-EU instead
      // (`Models.PARAKEET_TRANSCRIBEPSY_250M_EU_Q8_0`): one GGUF with its CAFE
      // language adapters and gate embedded, ggml on every platform, no Core ML
      // distribution. `--language` picks its route: `en` for the English trunk,
      // `other` for the non-English adapters, or `auto` (the default) to let the gate
      // decide from the first seconds of the recording. The route is sent as
      // `language` in the load's `modelConfig`.
      //
      // Long recordings are encoded in overlapping windows, so memory stays flat
      // however long the file is. Without `--window-sec` the engine uses the 60 s
      // windows with 25 % overlap the model recommends; an explicit window is sent as
      // encoder frames (12.5 per second) with a quarter of it as context, which is how
      // a phone with little memory can trade speed for a smaller footprint.
      //
      // The example uses the generated `client.transcribe(TranscribeRequest)` stream
      // so the closing frame's `stats` arrive typed as `TranscribeResponseStats`
      // (`audioDuration`, `realTimeFactor`, `encoderUsedCoreml`); the text frames are
      // joined as they come. `client.speech.transcribe()` returns the same text with
      // the stats as an untyped `JsonObject`.
      //
      // RUN: ./gradlew -p examples run -Pexample=TranscriptionParakeetTranscribepsy --args="<audio-file> [--eu [--language en|other|auto]] [--coreml] [--window-sec <seconds>]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TranscribeRequest
      import io.tether.qvac.sdk.generated.schema.TranscribeRequestAudioChunk
      import io.tether.qvac.sdk.generated.schema.TranscribeRequestAudioChunkFilePath
      import io.tether.qvac.sdk.generated.schema.TranscribeResponseStats
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.transcribe
      import kotlin.math.roundToLong
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      private const val ENCODER_FRAMES_PER_SECOND = 12.5
      private const val RECOMMENDED_OVERLAP = 0.25
      private val EU_LANGUAGES = setOf("en", "other", "auto")
      private const val USAGE = "Usage: ./gradlew -p examples run -Pexample=TranscriptionParakeetTranscribepsy " +
          "--args=\"<audio-file> [--eu [--language en|other|auto]] [--coreml] [--window-sec <seconds>]\""

      private data class Options(
          val audioPath: String,
          val useEu: Boolean,
          val useCoreml: Boolean,
          val language: String?,
          val windowSeconds: Double?,
      )

      fun main(args: Array<String>): Unit = runBlocking {
          val parsed = parseArgs(args.toList())
          if (parsed == null) {
              System.err.println(USAGE)
              exitProcess(1)
          }
          val (audioPath, useEu, useCoreml, language, windowSeconds) = parsed

          // An explicit window becomes the engine's frame counts; the overlap is
          // shared half and half with each neighbouring window.
          val modelConfig = buildJsonObject {
              if (windowSeconds != null) {
                  put("longFormWindowFrames", (windowSeconds * ENCODER_FRAMES_PER_SECOND).roundToLong())
                  put(
                      "longFormContextFrames",
                      (windowSeconds * ENCODER_FRAMES_PER_SECOND * RECOMMENDED_OVERLAP / 2).roundToLong(),
                  )
              }
              // The EU route only means something to the full model; EU-sub has no gate.
              if (useEu && language != null) put("language", language)
          }

          val (modelSrc, variant) = when {
              useEu -> Models.PARAKEET_TRANSCRIBEPSY_250M_EU_Q8_0.src to "EU, 25 languages, route ${language ?: "auto"}"
              useCoreml -> Models.PARAKEET_TRANSCRIBEPSY_250M_COREML_Q8_0.src to "EU-sub, Core ML distribution"
              else -> Models.PARAKEET_TRANSCRIBEPSY_250M_Q8_0.src to "EU-sub, ggml"
          }

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ Loading TranscribePsy ($variant)...")
              val modelId = client.loadWithProgress(modelSrc, "parakeet-transcription", modelConfig = modelConfig)

              println(
                  if (windowSeconds == null) {
                      "▸ Transcribing with the windows the model recommends (60 s, 25 % overlap)..."
                  } else {
                      "▸ Transcribing in ${formatSeconds(windowSeconds)} s windows..."
                  },
              )
              val request = TranscribeRequest(
                  modelId = modelId,
                  audioChunk = TranscribeRequestAudioChunk.FilePath(TranscribeRequestAudioChunkFilePath(value = audioPath)),
              )

              val text = StringBuilder()
              var stats: TranscribeResponseStats? = null
              client.transcribe(request).collect { response ->
                  response.error?.let { error(it) }
                  response.text?.let(text::append)
                  response.stats?.let { stats = it }
              }

              println(text)
              stats?.let { s ->
                  var summary = "▸ ${fmt(s.audioDuration, 1)} s of audio, real-time factor ${fmt(s.realTimeFactor, 3)}"
                  if (useCoreml) {
                      val used = if (s.encoderUsedCoreml == 1.0) "yes" else "no"
                      summary += ", encoder on Core ML: $used"
                  }
                  println(summary)
              }

              client.models.unload(modelId)
          } finally {
              client.close()
          }
      }

      /** Format an optional stat, as TypeScript's `?.toFixed(n) ?? '?'`. */
      private fun fmt(value: Double?, digits: Int): String = value?.let { "%.${digits}f".format(it) } ?: "?"

      /** Print whole seconds without a trailing `.0`, as Python's `:g`. */
      private fun formatSeconds(seconds: Double): String =
          if (seconds % 1.0 == 0.0) seconds.toLong().toString() else seconds.toString()

      private fun parseArgs(args: List<String>): Options? {
          val valueFlags = setOf("--window-sec", "--language")
          val audioPath = args.filterIndexed { index, arg ->
              !arg.startsWith("--") && args.getOrNull(index - 1) !in valueFlags
          }.firstOrNull()
          val useCoreml = "--coreml" in args
          val useEu = "--eu" in args
          var windowSeconds: Double? = null
          val windowIndex = args.indexOf("--window-sec")
          if (windowIndex >= 0) {
              windowSeconds = args.getOrNull(windowIndex + 1)?.toDoubleOrNull() ?: return null
              if (!(windowSeconds > 0)) return null
          }
          var language: String? = null
          val languageIndex = args.indexOf("--language")
          if (languageIndex >= 0) {
              language = args.getOrNull(languageIndex + 1)
              // `--language` needs a value, and only the full EU model has a route to pick.
              if (!useEu || language !in EU_LANGUAGES) return null
          }
          if (audioPath == null || (useEu && useCoreml)) return null
          return Options(audioPath, useEu, useCoreml, language, windowSeconds)
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(
          source: String,
          modelType: String,
          modelConfig: JsonObject? = null,
      ): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Parakeet Indic Conformer

The following script shows an example of Indic-language transcription using the Parakeet Indic Conformer CTC model from a WAV file. Pass the path of a 16 kHz mono WAV file as the first argument and the audio's language code (e.g., `hi`, `ta`) as the second; the language is required. An optional third argument overrides the default model:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/asr/parakeet-indic-conformer-filesystem.js title="parakeet-indic-conformer-filesystem.js" lineNumbers
      /**
       * Indic Conformer CTC transcription from a WAV file.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-indic-conformer-filesystem.ts <wav-file> <language> [gguf]
       *
       * Loads a single GGUF checkpoint (`PARAKEET_INDIC_CONFORMER_600M_Q8_0` by
       * default) and transcribes with the batch `transcribe` API. `language` is
       * required (e.g. `hi`, `ta`) because Indic Conformer CTC masks the vocab
       * with `parakeet.ctc.lang_*` ranges. English Parakeet CTC ignores this field.
       *
       * Audio should be 16 kHz mono PCM in a WAV container.
       */
      import { loadModel, unloadModel, transcribe, PARAKEET_INDIC_CONFORMER_600M_Q8_0 } from '@qvac/sdk';
      const args = process.argv.slice(2);
      if (!args[0] || !args[1]) {
          console.error('Usage: npx tsx examples/asr/parakeet-indic-conformer-filesystem.ts ' +
              '<wav-file> <language> [indic-conformer-gguf]');
          console.error('\nExample: ... filesystem.ts speech.wav hi');
          console.error('If the model path is omitted, defaults to the registry model.');
          process.exit(1);
      }
      const audioFilePath = args[0];
      const language = args[1];
      const parakeetModelSrc = args[2] ?? PARAKEET_INDIC_CONFORMER_600M_Q8_0;
      try {
          console.log('▸ Loading Indic Conformer CTC model...');
          const modelId = await loadModel({
              modelSrc: parakeetModelSrc,
              modelType: 'parakeet-transcription',
              modelConfig: { language },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Indic Conformer CTC model loaded with ID: ${modelId}`);
          console.log(`▸ Language: ${language}`);
          console.log('▸ Transcribing audio...');
          const text = await transcribe({ modelId, audioChunk: audioFilePath });
          console.log(text);
          console.log('▸ Unloading model...');
          await unloadModel({ modelId });
          console.log('▸ Done');
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/asr/parakeet-indic-conformer-filesystem.ts title="parakeet-indic-conformer-filesystem.ts" lineNumbers
      /**
       * Indic Conformer CTC transcription from a WAV file.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-indic-conformer-filesystem.ts <wav-file> <language> [gguf]
       *
       * Loads a single GGUF checkpoint (`PARAKEET_INDIC_CONFORMER_600M_Q8_0` by
       * default) and transcribes with the batch `transcribe` API. `language` is
       * required (e.g. `hi`, `ta`) because Indic Conformer CTC masks the vocab
       * with `parakeet.ctc.lang_*` ranges. English Parakeet CTC ignores this field.
       *
       * Audio should be 16 kHz mono PCM in a WAV container.
       */
      import { loadModel, unloadModel, transcribe, PARAKEET_INDIC_CONFORMER_600M_Q8_0 } from '@qvac/sdk'

      const args = process.argv.slice(2)

      if (!args[0] || !args[1]) {
        console.error(
          'Usage: npx tsx examples/asr/parakeet-indic-conformer-filesystem.ts ' +
            '<wav-file> <language> [indic-conformer-gguf]'
        )
        console.error('\nExample: ... filesystem.ts speech.wav hi')
        console.error('If the model path is omitted, defaults to the registry model.')
        process.exit(1)
      }

      const audioFilePath = args[0]
      const language = args[1]
      const parakeetModelSrc = args[2] ?? PARAKEET_INDIC_CONFORMER_600M_Q8_0

      try {
        console.log('▸ Loading Indic Conformer CTC model...')
        const modelId = await loadModel({
          modelSrc: parakeetModelSrc,
          modelType: 'parakeet-transcription',
          modelConfig: { language },
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Indic Conformer CTC model loaded with ID: ${modelId}`)
        console.log(`▸ Language: ${language}`)

        console.log('▸ Transcribing audio...')
        const text = await transcribe({ modelId, audioChunk: audioFilePath })

        console.log(text)

        console.log('▸ Unloading model...')
        await unloadModel({ modelId })
        console.log('▸ Done')
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/transcription_parakeet_indic_conformer.py title="transcription_parakeet_indic_conformer.py" lineNumbers
      """Python port of packages/sdk/examples/asr/parakeet-indic-conformer-filesystem.ts.

      Indic Conformer CTC transcription from a WAV file. Loads a single GGUF
      checkpoint (`PARAKEET_INDIC_CONFORMER_600M_Q8_0` by default) and transcribes
      with the batch `transcribe` API. `language` is required (e.g. `hi`, `ta`)
      because Indic Conformer CTC masks the vocab with `parakeet.ctc.lang_*` ranges.
      English Parakeet CTC ignores this field.

      TypeScript's `transcribe()` returns the joined text. Python calls the worker
      directly, so `transcribe` yields `TranscribeResponse` frames and the example
      joins their `text` itself.

      Audio should be 16 kHz mono PCM in a WAV container.

      RUN: python examples/transcription_parakeet_indic_conformer.py <wav-file> <language> [indic-conformer-gguf]
      """

      from __future__ import annotations

      import asyncio
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TranscribeRequest,
          load_model,
          transcribe,
          unload_model,
      )
      from tetherto.qvac_sdk.models import PARAKEET_INDIC_CONFORMER_600M_Q8_0


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          if len(sys.argv) < 3:
              print(
                  "Usage: python examples/transcription_parakeet_indic_conformer.py "
                  "<wav-file> <language> [indic-conformer-gguf]",
                  file=sys.stderr,
              )
              print(
                  "\nExample: ... transcription_parakeet_indic_conformer.py speech.wav hi",
                  file=sys.stderr,
              )
              print(
                  "If the model path is omitted, defaults to the registry model.",
                  file=sys.stderr,
              )
              return 1
          audio_path = sys.argv[1]
          language = sys.argv[2]
          parakeet_model_src = (
              sys.argv[3] if len(sys.argv) > 3 else PARAKEET_INDIC_CONFORMER_600M_Q8_0
          )

          async with Client() as client:
              t = client.transport
              try:
                  print("▸ Loading Indic Conformer CTC model...")
                  model_id = await load_model(
                      t,
                      model_src=parakeet_model_src,
                      model_type="parakeet-transcription",
                      model_config={"language": language},
                      on_progress=print_progress,
                  )
                  print(f"▸ Indic Conformer CTC model loaded with ID: {model_id}")
                  print(f"▸ Language: {language}")

                  print("▸ Transcribing audio...")
                  # audioChunk is a typed chunk, not a bare path: JS's transcribe
                  # wrapper turns a string into {type:"filePath"} for you, but Python
                  # calls the generated stub directly, so build the chunk explicitly.
                  request = TranscribeRequest.model_validate(
                      {
                          "type": "transcribe",
                          "modelId": model_id,
                          "audioChunk": {"type": "filePath", "value": audio_path},
                      }
                  )

                  text = ""
                  async for response in transcribe(t, request):
                      if response.text:
                          text += response.text

                  print(text)

                  print("▸ Unloading model...")
                  await unload_model(t, model_id)
                  print("▸ Done")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TranscriptionParakeetIndicConformer.kt title="TranscriptionParakeetIndicConformer.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/asr/parakeet-indic-conformer-filesystem.ts.
      //
      // Indic Conformer CTC transcription from a WAV file. Loads a single GGUF
      // checkpoint (`Models.PARAKEET_INDIC_CONFORMER_600M_Q8_0` by default) and
      // transcribes with the batch `client.speech.transcribe()` API. `language` is
      // required (e.g. `hi`, `ta`) because Indic Conformer CTC masks the vocab with
      // `parakeet.ctc.lang_*` ranges. English Parakeet CTC ignores this field.
      //
      // As in TypeScript, `transcribe()` returns the joined text
      // (`QvacTranscriptionResult.text`), so there are no frames to join by hand.
      //
      // Audio should be 16 kHz mono PCM in a WAV container.
      //
      // RUN: ./gradlew -p examples run -Pexample=TranscriptionParakeetIndicConformer --args="<wav-file> <language> [indic-conformer-gguf]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacDataInput
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.speech
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(args: Array<String>): Unit = runBlocking {
          if (args.size < 2) {
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=TranscriptionParakeetIndicConformer " +
                      "--args=\"<wav-file> <language> [indic-conformer-gguf]\"",
              )
              System.err.println("\nExample: ... -Pexample=TranscriptionParakeetIndicConformer --args=\"speech.wav hi\"")
              System.err.println("If the model path is omitted, defaults to the registry model.")
              exitProcess(1)
          }
          val audioPath = args[0]
          val language = args[1]
          val parakeetModelSrc = args.getOrNull(2) ?: Models.PARAKEET_INDIC_CONFORMER_600M_Q8_0.src

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ Loading Indic Conformer CTC model...")
              val modelId = client.loadWithProgress(
                  parakeetModelSrc,
                  "parakeet-transcription",
                  modelConfig = buildJsonObject { put("language", language) },
              )
              println("▸ Indic Conformer CTC model loaded with ID: $modelId")
              println("▸ Language: $language")

              println("▸ Transcribing audio...")
              val result = client.speech.transcribe(modelId, QvacDataInput.FilePath(audioPath))

              println(result.text)

              println("▸ Unloading model...")
              client.models.unload(modelId)
              println("▸ Done")
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(
          source: String,
          modelType: String,
          modelConfig: JsonObject? = null,
      ): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Parakeet Sortformer

The following script shows an example of speaker diarization using the Parakeet Sortformer model, followed by per-segment transcription with the TDT model. Pass the path of a 16 kHz mono 16-bit WAV file as the first argument; an optional second argument overrides the default Sortformer model. To try it with a multi-speaker recording, download [`diarization-sample-16k.wav`](https://github.com/tetherto/qvac/blob/main/packages/sdk/examples/audio/diarization-sample-16k.wav) next to the example and pass its path:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/asr/parakeet-sortformer.js title="parakeet-sortformer.js" lineNumbers
      /**
       * Parakeet Sortformer diarization + TDT transcription pipeline.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-sortformer.ts <wav-file> [sortformer-gguf]
       *
       * Two-step flow: Sortformer v2.1 diarizes the audio, then TDT transcribes each
       * speaker segment. Defaults to registry GGUFs. For live streaming + AOSC, see
       * `parakeet-sortformer-streaming.ts`.
       *
       * Audio should be 16 kHz mono 16-bit PCM in a WAV container. A multi-speaker
       * sample is in the QVAC source repo but not the published npm package:
       *   https://github.com/tetherto/qvac/blob/main/packages/sdk/examples/audio/diarization-sample-16k.wav
       */
      import { loadModel, unloadModel, transcribe, PARAKEET_TDT_0_6B_V3_Q8_0, PARAKEET_SORTFORMER_4SPK_V2_1_Q8_0 } from '@qvac/sdk';
      import { join } from 'path';
      import { readFileSync, writeFileSync, mkdirSync } from 'fs';
      import { tmpdir } from 'os';
      const args = process.argv.slice(2);
      if (!args[0]) {
          console.error('Usage: npx tsx examples/asr/parakeet-sortformer.ts <wav-file> [sortformer-gguf]');
          console.error('\nIf the model path is omitted, defaults to the registry model.');
          process.exit(1);
      }
      const audioFilePath = args[0];
      const sortformerSrc = args[1] ?? PARAKEET_SORTFORMER_4SPK_V2_1_Q8_0;
      try {
          // ── Step 1: Diarize with Sortformer ──
          const sfModelId = await loadModel({
              modelSrc: sortformerSrc,
              modelType: 'parakeet-transcription'
          });
          const diarization = await transcribe({
              modelId: sfModelId,
              audioChunk: audioFilePath
          });
          await unloadModel({ modelId: sfModelId });
          const segments = parseDiarization(diarization);
          // ── Step 2: Transcribe each segment with TDT ──
          const tdtModelId = await loadModel({
              modelSrc: PARAKEET_TDT_0_6B_V3_Q8_0
          });
          const pcm = readPcm(audioFilePath);
          const sliceDir = join(tmpdir(), `qvac-diarize-${Date.now()}`);
          mkdirSync(sliceDir, { recursive: true });
          const results = [];
          for (let i = 0; i < segments.length; i++) {
              const seg = segments[i];
              const slicePath = join(sliceDir, `seg-${i}.wav`);
              if (!writeWavSlice(pcm, seg.start, seg.end, slicePath)) {
                  results.push({ ...seg, text: '[No speech detected]' });
                  continue;
              }
              const text = await transcribe({
                  modelId: tdtModelId,
                  audioChunk: slicePath
              });
              results.push({ ...seg, text: text.trim() || '[No speech detected]' });
          }
          await unloadModel({ modelId: tdtModelId });
          // ── Step 3: Merge consecutive same-speaker segments and print ──
          const merged = mergeSpeakers(results);
          console.log('\n▸ Diarized transcription');
          for (const entry of merged) {
              console.log(`Speaker ${entry.speaker} (${entry.start.toFixed(2)}s - ${entry.end.toFixed(2)}s):`);
              console.log(`  ${entry.text}\n`);
          }
          console.log('▸ Done');
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      // ── Helpers ──
      // Sortformer reports each segment as `Speaker N: HH:MM:SS.mmm - HH:MM:SS.mmm`
      function parseDiarization(text) {
          const segs = [];
          for (const line of text.split('\n')) {
              const m = line.match(/Speaker (\d+): (\d+):(\d+):([\d.]+) - (\d+):(\d+):([\d.]+)/);
              if (m) {
                  segs.push({
                      speaker: +m[1],
                      start: seconds(m[2], m[3], m[4]),
                      end: seconds(m[5], m[6], m[7])
                  });
              }
          }
          return segs.sort((a, b) => a.start - b.start);
      }
      function seconds(h, m, s) {
          return +h * 3600 + +m * 60 + +s;
      }
      function readPcm(wavPath) {
          const buf = readFileSync(wavPath);
          const dataOffset = buf.indexOf('data') + 4;
          return buf.subarray(dataOffset + 4, dataOffset + 4 + buf.readUInt32LE(dataOffset));
      }
      function writeWavSlice(pcm, startSec, endSec, outPath) {
          const SR = 16000;
          const BPS = 2;
          const startByte = Math.floor(startSec * SR) * BPS;
          const endByte = Math.min(Math.ceil(endSec * SR) * BPS, pcm.length);
          if (startByte >= endByte)
              return false;
          const slice = pcm.subarray(startByte, endByte);
          const hdr = Buffer.alloc(44);
          hdr.write('RIFF', 0);
          hdr.writeUInt32LE(36 + slice.length, 4);
          hdr.write('WAVEfmt ', 8);
          hdr.writeUInt32LE(16, 16);
          hdr.writeUInt16LE(1, 20);
          hdr.writeUInt16LE(1, 22);
          hdr.writeUInt32LE(SR, 24);
          hdr.writeUInt32LE(SR * BPS, 28);
          hdr.writeUInt16LE(BPS, 32);
          hdr.writeUInt16LE(16, 34);
          hdr.write('data', 36);
          hdr.writeUInt32LE(slice.length, 40);
          writeFileSync(outPath, Buffer.concat([hdr, slice]));
          return true;
      }
      function mergeSpeakers(entries) {
          const out = [];
          for (const e of entries) {
              const last = out[out.length - 1];
              if (last && last.speaker === e.speaker) {
                  last.text += ' ' + e.text;
                  last.end = e.end;
              }
              else {
                  out.push({ ...e });
              }
          }
          return out;
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/asr/parakeet-sortformer.ts title="parakeet-sortformer.ts" lineNumbers
      /**
       * Parakeet Sortformer diarization + TDT transcription pipeline.
       *
       * Usage:
       *   npx tsx examples/asr/parakeet-sortformer.ts <wav-file> [sortformer-gguf]
       *
       * Two-step flow: Sortformer v2.1 diarizes the audio, then TDT transcribes each
       * speaker segment. Defaults to registry GGUFs. For live streaming + AOSC, see
       * `parakeet-sortformer-streaming.ts`.
       *
       * Audio should be 16 kHz mono 16-bit PCM in a WAV container. A multi-speaker
       * sample is in the QVAC source repo but not the published npm package:
       *   https://github.com/tetherto/qvac/blob/main/packages/sdk/examples/audio/diarization-sample-16k.wav
       */
      import {
        loadModel,
        unloadModel,
        transcribe,
        PARAKEET_TDT_0_6B_V3_Q8_0,
        PARAKEET_SORTFORMER_4SPK_V2_1_Q8_0
      } from '@qvac/sdk'
      import { join } from 'path'
      import { readFileSync, writeFileSync, mkdirSync } from 'fs'
      import { tmpdir } from 'os'

      const args = process.argv.slice(2)

      if (!args[0]) {
        console.error('Usage: npx tsx examples/asr/parakeet-sortformer.ts <wav-file> [sortformer-gguf]')
        console.error('\nIf the model path is omitted, defaults to the registry model.')
        process.exit(1)
      }

      const audioFilePath = args[0]
      const sortformerSrc = args[1] ?? PARAKEET_SORTFORMER_4SPK_V2_1_Q8_0

      try {
        // ── Step 1: Diarize with Sortformer ──

        const sfModelId = await loadModel({
          modelSrc: sortformerSrc,
          modelType: 'parakeet-transcription'
        })

        const diarization = await transcribe({
          modelId: sfModelId,
          audioChunk: audioFilePath
        })
        await unloadModel({ modelId: sfModelId })

        const segments = parseDiarization(diarization)

        // ── Step 2: Transcribe each segment with TDT ──

        const tdtModelId = await loadModel({
          modelSrc: PARAKEET_TDT_0_6B_V3_Q8_0
        })

        const pcm = readPcm(audioFilePath)
        const sliceDir = join(tmpdir(), `qvac-diarize-${Date.now()}`)
        mkdirSync(sliceDir, { recursive: true })

        const results: {
          speaker: number
          start: number
          end: number
          text: string
        }[] = []

        for (let i = 0; i < segments.length; i++) {
          const seg = segments[i]!
          const slicePath = join(sliceDir, `seg-${i}.wav`)

          if (!writeWavSlice(pcm, seg.start, seg.end, slicePath)) {
            results.push({ ...seg, text: '[No speech detected]' })
            continue
          }

          const text = await transcribe({
            modelId: tdtModelId,
            audioChunk: slicePath
          })
          results.push({ ...seg, text: text.trim() || '[No speech detected]' })
        }

        await unloadModel({ modelId: tdtModelId })

        // ── Step 3: Merge consecutive same-speaker segments and print ──

        const merged = mergeSpeakers(results)

        console.log('\n▸ Diarized transcription')
        for (const entry of merged) {
          console.log(`Speaker ${entry.speaker} (${entry.start.toFixed(2)}s - ${entry.end.toFixed(2)}s):`)
          console.log(`  ${entry.text}\n`)
        }
        console.log('▸ Done')
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }

      // ── Helpers ──

      // Sortformer reports each segment as `Speaker N: HH:MM:SS.mmm - HH:MM:SS.mmm`
      function parseDiarization(text: string) {
        const segs: { speaker: number; start: number; end: number }[] = []
        for (const line of text.split('\n')) {
          const m = line.match(/Speaker (\d+): (\d+):(\d+):([\d.]+) - (\d+):(\d+):([\d.]+)/)
          if (m) {
            segs.push({
              speaker: +m[1]!,
              start: seconds(m[2]!, m[3]!, m[4]!),
              end: seconds(m[5]!, m[6]!, m[7]!)
            })
          }
        }
        return segs.sort((a, b) => a.start - b.start)
      }

      function seconds(h: string, m: string, s: string) {
        return +h * 3600 + +m * 60 + +s
      }

      function readPcm(wavPath: string): Buffer {
        const buf = readFileSync(wavPath)
        const dataOffset = buf.indexOf('data') + 4
        return buf.subarray(dataOffset + 4, dataOffset + 4 + buf.readUInt32LE(dataOffset))
      }

      function writeWavSlice(pcm: Buffer, startSec: number, endSec: number, outPath: string): boolean {
        const SR = 16000
        const BPS = 2
        const startByte = Math.floor(startSec * SR) * BPS
        const endByte = Math.min(Math.ceil(endSec * SR) * BPS, pcm.length)
        if (startByte >= endByte) return false

        const slice = pcm.subarray(startByte, endByte)
        const hdr = Buffer.alloc(44)
        hdr.write('RIFF', 0)
        hdr.writeUInt32LE(36 + slice.length, 4)
        hdr.write('WAVEfmt ', 8)
        hdr.writeUInt32LE(16, 16)
        hdr.writeUInt16LE(1, 20)
        hdr.writeUInt16LE(1, 22)
        hdr.writeUInt32LE(SR, 24)
        hdr.writeUInt32LE(SR * BPS, 28)
        hdr.writeUInt16LE(BPS, 32)
        hdr.writeUInt16LE(16, 34)
        hdr.write('data', 36)
        hdr.writeUInt32LE(slice.length, 40)

        writeFileSync(outPath, Buffer.concat([hdr, slice]))
        return true
      }

      function mergeSpeakers<T extends { speaker: number; start: number; end: number; text: string }>(
        entries: T[]
      ): T[] {
        const out: T[] = []
        for (const e of entries) {
          const last = out[out.length - 1]
          if (last && last.speaker === e.speaker) {
            last.text += ' ' + e.text
            last.end = e.end
          } else {
            out.push({ ...e })
          }
        }
        return out
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/transcription_parakeet_sortformer.py title="transcription_parakeet_sortformer.py" lineNumbers
      """Python port of packages/sdk/examples/asr/parakeet-sortformer.ts.

      Parakeet Sortformer diarization + TDT transcription pipeline. Two-step flow:
      Sortformer v2.1 diarizes the audio, then TDT transcribes each speaker segment.
      Defaults to registry GGUFs. A multi-speaker sample is in the QVAC source repo:
        https://github.com/tetherto/qvac/blob/main/packages/sdk/examples/audio/diarization-sample-16k.wav

      TypeScript's `transcribe()` returns the joined text. Python calls the worker
      directly, so `transcribe` yields `TranscribeResponse` frames and the example
      joins their `text` itself. The standard-library `wave` module reads the PCM
      and writes each segment as its own WAV, where TypeScript parses the header by
      hand.

      Audio should be 16 kHz mono 16-bit PCM in a WAV container.

      RUN: python examples/transcription_parakeet_sortformer.py <wav-file> [sortformer-gguf]
      """

      from __future__ import annotations

      import asyncio
      import math
      import re
      import sys
      import tempfile
      import wave
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          TranscribeRequest,
          load_model,
          transcribe,
          unload_model,
      )
      from tetherto.qvac_sdk.models import (
          PARAKEET_SORTFORMER_4SPK_V2_1_Q8_0,
          PARAKEET_TDT_0_6B_V3_Q8_0,
      )

      SAMPLE_RATE = 16000
      BYTES_PER_SAMPLE = 2
      # Sortformer reports each segment as `Speaker N: HH:MM:SS.mmm - HH:MM:SS.mmm`
      SEGMENT_PATTERN = re.compile(
          r"Speaker (\d+): (\d+):(\d+):([\d.]+) - (\d+):(\d+):([\d.]+)"
      )


      async def transcribe_file(t, model_id: str, audio_path: str) -> str:
          # audioChunk is a typed chunk, not a bare path: JS's transcribe wrapper
          # turns a string into {type:"filePath"} for you, but Python calls the
          # generated stub directly, so build the chunk explicitly.
          request = TranscribeRequest.model_validate(
              {
                  "type": "transcribe",
                  "modelId": model_id,
                  "audioChunk": {"type": "filePath", "value": audio_path},
              }
          )
          text = ""
          async for response in transcribe(t, request):
              if response.text:
                  text += response.text
          return text


      def parse_diarization(text: str) -> list[dict]:
          segments = [
              {
                  "speaker": int(m[1]),
                  "start": seconds(m[2], m[3], m[4]),
                  "end": seconds(m[5], m[6], m[7]),
              }
              for m in SEGMENT_PATTERN.finditer(text)
          ]
          return sorted(segments, key=lambda seg: seg["start"])


      def seconds(h: str, m: str, s: str) -> float:
          return int(h) * 3600 + int(m) * 60 + float(s)


      def read_pcm(wav_path: str) -> bytes:
          with wave.open(wav_path, "rb") as wav:
              return wav.readframes(wav.getnframes())


      def write_wav_slice(
          pcm: bytes, start_sec: float, end_sec: float, out_path: Path
      ) -> bool:
          start_byte = math.floor(start_sec * SAMPLE_RATE) * BYTES_PER_SAMPLE
          end_byte = min(math.ceil(end_sec * SAMPLE_RATE) * BYTES_PER_SAMPLE, len(pcm))
          if start_byte >= end_byte:
              return False

          with wave.open(str(out_path), "wb") as wav:
              wav.setnchannels(1)
              wav.setsampwidth(BYTES_PER_SAMPLE)
              wav.setframerate(SAMPLE_RATE)
              wav.writeframes(pcm[start_byte:end_byte])
          return True


      def merge_speakers(entries: list[dict]) -> list[dict]:
          merged: list[dict] = []
          for entry in entries:
              if merged and merged[-1]["speaker"] == entry["speaker"]:
                  merged[-1]["text"] += " " + entry["text"]
                  merged[-1]["end"] = entry["end"]
              else:
                  merged.append(dict(entry))
          return merged


      async def main() -> int:
          if len(sys.argv) < 2:
              print(
                  "Usage: python examples/transcription_parakeet_sortformer.py <wav-file> "
                  "[sortformer-gguf]",
                  file=sys.stderr,
              )
              print(
                  "\nIf the model path is omitted, defaults to the registry model.",
                  file=sys.stderr,
              )
              return 1
          audio_path = sys.argv[1]
          sortformer_src = (
              sys.argv[2] if len(sys.argv) > 2 else PARAKEET_SORTFORMER_4SPK_V2_1_Q8_0
          )

          async with Client() as client:
              t = client.transport
              try:
                  # ── Step 1: Diarize with Sortformer ──

                  sf_model_id = await load_model(
                      t, model_src=sortformer_src, model_type="parakeet-transcription"
                  )
                  diarization = await transcribe_file(t, sf_model_id, audio_path)
                  await unload_model(t, sf_model_id)

                  segments = parse_diarization(diarization)

                  # ── Step 2: Transcribe each segment with TDT ──

                  tdt_model_id = await load_model(
                      t,
                      model_src=PARAKEET_TDT_0_6B_V3_Q8_0,
                      model_type="parakeet-transcription",
                  )

                  pcm = read_pcm(audio_path)
                  results = []
                  with tempfile.TemporaryDirectory(prefix="qvac-diarize-") as slice_dir:
                      for index, seg in enumerate(segments):
                          slice_path = Path(slice_dir) / f"seg-{index}.wav"

                          if not write_wav_slice(pcm, seg["start"], seg["end"], slice_path):
                              results.append({**seg, "text": "[No speech detected]"})
                              continue

                          text = await transcribe_file(t, tdt_model_id, str(slice_path))
                          results.append(
                              {**seg, "text": text.strip() or "[No speech detected]"}
                          )

                  await unload_model(t, tdt_model_id)

                  # ── Step 3: Merge consecutive same-speaker segments and print ──

                  print("\n▸ Diarized transcription")
                  for entry in merge_speakers(results):
                      print(
                          f"Speaker {entry['speaker']} "
                          f"({entry['start']:.2f}s - {entry['end']:.2f}s):"
                      )
                      print(f"  {entry['text']}\n")
                  print("▸ Done")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TranscriptionParakeetSortformer.kt title="TranscriptionParakeetSortformer.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/asr/parakeet-sortformer.ts.
      //
      // Parakeet Sortformer diarization + TDT transcription pipeline. Two-step flow:
      // Sortformer v2.1 diarizes the audio, then TDT transcribes each speaker segment.
      // Defaults to registry GGUFs. A multi-speaker sample is in the QVAC source repo:
      //   https://github.com/tetherto/qvac/blob/main/packages/sdk/examples/audio/diarization-sample-16k.wav
      //
      // As in TypeScript, `client.speech.transcribe()` returns the joined text. The
      // JDK's `javax.sound.sampled.AudioSystem` reads the PCM and writes each segment
      // as its own WAV (Python uses the standard-library `wave` module; TypeScript
      // parses the header by hand).
      //
      // Audio should be 16 kHz mono 16-bit PCM in a WAV container.
      //
      // RUN: ./gradlew -p examples run -Pexample=TranscriptionParakeetSortformer --args="<wav-file> [sortformer-gguf]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacDataInput
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.speech
      import java.io.ByteArrayInputStream
      import java.io.File
      import java.nio.file.Files
      import javax.sound.sampled.AudioFileFormat
      import javax.sound.sampled.AudioFormat
      import javax.sound.sampled.AudioInputStream
      import javax.sound.sampled.AudioSystem
      import kotlin.math.ceil
      import kotlin.math.floor
      import kotlin.math.min
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking

      private const val SAMPLE_RATE = 16000
      private const val BYTES_PER_SAMPLE = 2
      // Sortformer reports each segment as `Speaker N: HH:MM:SS.mmm - HH:MM:SS.mmm`
      private val SEGMENT_PATTERN = Regex("""Speaker (\d+): (\d+):(\d+):([\d.]+) - (\d+):(\d+):([\d.]+)""")

      private data class Segment(val speaker: Int, val start: Double, val end: Double)

      private data class Entry(val speaker: Int, val start: Double, val end: Double, val text: String)

      fun main(args: Array<String>): Unit = runBlocking {
          if (args.isEmpty()) {
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=TranscriptionParakeetSortformer " +
                      "--args=\"<wav-file> [sortformer-gguf]\"",
              )
              System.err.println("\nIf the model path is omitted, defaults to the registry model.")
              exitProcess(1)
          }
          val audioPath = args[0]
          val sortformerSrc = args.getOrNull(1) ?: Models.PARAKEET_SORTFORMER_4SPK_V2_1_Q8_0.src

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              // ── Step 1: Diarize with Sortformer ──

              val sfModelId = client.loadModel(sortformerSrc, "parakeet-transcription")
              val diarization = client.speech.transcribe(sfModelId, QvacDataInput.FilePath(audioPath)).text
              client.models.unload(sfModelId)

              val segments = parseDiarization(diarization)

              // ── Step 2: Transcribe each segment with TDT ──

              val tdtModelId = client.loadModel(Models.PARAKEET_TDT_0_6B_V3_Q8_0.src, "parakeet-transcription")

              val pcm = readPcm(audioPath)
              val results = mutableListOf<Entry>()
              val sliceDir = Files.createTempDirectory("qvac-diarize-").toFile()
              try {
                  for ((index, seg) in segments.withIndex()) {
                      val slicePath = File(sliceDir, "seg-$index.wav")

                      if (!writeWavSlice(pcm, seg.start, seg.end, slicePath)) {
                          results += Entry(seg.speaker, seg.start, seg.end, "[No speech detected]")
                          continue
                      }

                      val text = client.speech.transcribe(tdtModelId, QvacDataInput.FilePath(slicePath.path)).text
                      results += Entry(seg.speaker, seg.start, seg.end, text.trim().ifEmpty { "[No speech detected]" })
                  }
              } finally {
                  sliceDir.deleteRecursively()
              }

              client.models.unload(tdtModelId)

              // ── Step 3: Merge consecutive same-speaker segments and print ──

              println("\n▸ Diarized transcription")
              for (entry in mergeSpeakers(results)) {
                  println("Speaker ${entry.speaker} (%.2fs - %.2fs):".format(entry.start, entry.end))
                  println("  ${entry.text}\n")
              }
              println("▸ Done")
          } finally {
              client.close()
          }
      }

      private fun parseDiarization(text: String): List<Segment> =
          SEGMENT_PATTERN.findAll(text)
              .map { m ->
                  val (speaker, startH, startM, startS, endH, endM, endS) = m.destructured
                  Segment(speaker.toInt(), seconds(startH, startM, startS), seconds(endH, endM, endS))
              }
              .sortedBy { it.start }
              .toList()

      private fun seconds(h: String, m: String, s: String) = h.toInt() * 3600 + m.toInt() * 60 + s.toDouble()

      private fun readPcm(wavPath: String): ByteArray =
          AudioSystem.getAudioInputStream(File(wavPath)).use { it.readAllBytes() }

      private fun writeWavSlice(pcm: ByteArray, startSec: Double, endSec: Double, outPath: File): Boolean {
          val startByte = floor(startSec * SAMPLE_RATE).toInt() * BYTES_PER_SAMPLE
          val endByte = min(ceil(endSec * SAMPLE_RATE).toInt() * BYTES_PER_SAMPLE, pcm.size)
          if (startByte >= endByte) return false

          val format = AudioFormat(SAMPLE_RATE.toFloat(), BYTES_PER_SAMPLE * 8, 1, true, false)
          val slice = pcm.copyOfRange(startByte, endByte)
          AudioInputStream(ByteArrayInputStream(slice), format, (slice.size / BYTES_PER_SAMPLE).toLong()).use { stream ->
              AudioSystem.write(stream, AudioFileFormat.Type.WAVE, outPath)
          }
          return true
      }

      private fun mergeSpeakers(entries: List<Entry>): List<Entry> {
          val merged = mutableListOf<Entry>()
          for (entry in entries) {
              val last = merged.lastOrNull()
              if (last != null && last.speaker == entry.speaker) {
                  merged[merged.lastIndex] = last.copy(text = last.text + " " + entry.text, end = entry.end)
              } else {
                  merged += entry
              }
          }
          return merged
      }

      /** Load [source] as [modelType] and return its model id. */
      private suspend fun QvacClient.loadModel(source: String, modelType: String): String {
          val loaded = models.load(source, modelType)
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

<Callout type="success">
  **Tip:** all examples throughout this documentation are self-contained and runnable. For instructions on how to run them, see the [JS/TS quickstart](/sdk/v0.23/js-ts-sdk#quickstart), the [Python quickstart](/sdk/v0.23/python-sdk#quickstart), or the [Kotlin quickstart](/sdk/v0.23/kotlin-sdk#quickstart).
</Callout>
