Browse documentation
aner.speech

Aner Speech

Analyze speech activity, transcribe with a pinned optional local native model, decode explicit CTC logits and evaluate timed transcripts.

ImplementedAner 0.1.0 or newer

aner.speech provides native speech activity timing, bounded transcripts, explicit CTC decoding, word/character error metrics, and an optional local Whisper inference backend. These APIs target 0.0.9-dev.2 and are unpublished. They run through Aner's native interpreter and C++ libraries; aner build does not yet lower speech programs to standalone executables.

Use Audio for capture, PCM, decoding and resampling; Signal for numerical features; Media for one shared audio/video demux clock. The generated media API lists every source signature, named argument and default.

Implemented boundary

OperationCurrent behavior
Energy activityStateful fixed window RMS hysteresis, minimum active duration, pre roll, hangover, maximum duration splits and explicit discontinuities
Streaming analysisBorrow an AudioBlock synchronously into a reusable SpeechActivity slot without freezing or exporting a Tensor
Transcript importChecked UTF-8 segment texts, CPU N × 2 intervals, language/model labels and explicit source/session identifiers
CTC outputDeterministic greedy decoding of supplied CPU logits using an explicit blank ID and literal vocabulary pieces
Local ASRPinned optional whisper.cpp engine, local GGML weights, bounded CPU execution, segment/token estimates and exact model byte identity
EvaluationWER over whitespace separated words and CER over Unicode scalar values, with explicit case/space policies
NLP integrationtranscript.corpus(...) returns an inference role TextCorpus with a caller supplied document ID

Energy activity does not distinguish speech from music, machinery or a test tone. CTC decoding consumes an already trained model's declared output contract; it does not create a recognizer. The first local ASR profile is CPU. Prefix beam CTC decoding, diarization, speaker recognition, speech synthesis, continuous partial ASR, full duplex playback/capture and acoustic echo cancellation remain future work.

First activity example

The complete activity example uses a finite tone and silence fixture, then processes synthetic blocks through the same stateful detector.

aner
import aner.audio
import aner.speech

let detector = speech.vad(rate: 16000, onset: 0.05, offset: 0.02,
    min_speech_ms: 60, silence_ms: 100, pre_roll_ms: 40)
let activity = speech.activity()
let fixture = audio.tone(seconds: 0.4, rate: 16000, amplitude: 0.2)
detector.process_into(fixture, activity)
detector.flush_into(activity)
for index in Range(activity.count()) {
    print(activity.start(index))
    print(activity.end(index))
    print(activity.forced(index))
}

SpeechVAD retains partial windows and state across calls. SpeechActivity is a reusable result slot: every successful process_into or flush_into replaces its results. Consume completed intervals before the next call. An active interval is returned when it closes; speaking() reports whether a confirmed interval is still open. Copies of either native handle alias its state, so serialize access to aliases.

The detector publishes timestamps and identities, not retained audio. Pre roll extends an interval's start; an application that needs those samples must retain a separately budgeted ring or reread the matching recording range.

Activity parameters and exact timing

ParameterDefaultMeaning
rate16000Required matching input sample rate; range 1..384000
onset0.02Start candidate activity when window RMS is at least this value; finite in (0,1]
offset0.01Retain activity while RMS is greater than this value; finite in [0,onset]
min_speech_ms100Minimum accumulated active samples before confirming a candidate; 0..60000
silence_ms200Below release hangover before a natural close; 0..60000
pre_roll_ms100Extend the start into already observed preceding audio; 0..60000
max_speech_ms30000Maximum interval length, including pre roll; 1..3600000
window_ms20Fixed RMS observation window; 1..1000

Durations round upward to sample frames. max_speech_ms must be at least min_speech_ms + pre_roll_ms + window_ms. Minimum confirmation counts active samples; subthreshold gaps shorter than hangover can occur within one candidate. Hangover may include observed quiet samples, but flush does not invent future quiet audio.

RMS averages squared samples across the window and all input channels. This activity calculation does not downmix channels, so opposite polarity stereo cannot cancel its energy. A source rate mismatch is rejected; resample deliberately or construct the VAD at that source rate. rate is independent of Whisper's required 16 kHz input.

The implementation accumulates the same fixed windows when input is split into arbitrary block sizes. It retains only partial window sums and scalar state. A source/session change, changed channel count, gap_before, or noncontiguous first_sample closes a confirmed previous interval with forced = true, clears the partial window, and begins a new timeline. Pre roll cannot cross that boundary. Maximum duration cuts and explicit flushes are also forced; a normal hangover endpoint is not.

Intervals use first_sample / sample_rate source sample seconds. activity_source_id(index) and activity_session_id(index) identify each interval's source. These values do not establish a shared wall clock between independent microphones.

aner
let source = audio.synthetic(frames: 16000, rate: 16000,
    amplitude: 0.2, block_frames: 137)
let block = audio.block_slot()
while source.read_into(block) == "ready" {
    detector.process_into(block, activity)
    for index in Range(activity.count()) { print(activity.end(index)) }
}
source.close()
detector.flush_into(activity)

This finite synthetic loop ends naturally. A live application must distinguish timeout, end, failed, closed and cancelled; inspect the source's error on failure. VAD does not turn missing capture samples into silence.

activity(max_segments: 1024) permits 1..4096 intervals per call. Two bounded native interval buffers are reused. If one call would exceed capacity, the call fails without consuming VAD input or replacing published results. Use a larger slot or smaller input chunks and retry; do not silently discard activity events.

Native local transcription

Local inference is optional and requires a binary built with ANER_USE_SPEECH_NATIVE=ON. Check speech.available() and speech.backend_identity() before loading a model. Availability means an engine was compiled; it does not mean any weights are installed.

The engine is pinned to whisper.cpp v1.7.6, commit a8d002cfd879315632a579e73f0148d06959de36. Aner calls its native C API. Inference launches no shell command, another language runtime process, external service, model download or network request.

aner
import aner.audio
import aner.speech

let recognizer = speech.load("models/ggml-tiny.en.bin",
    device: "cpu", threads: 4, max_seconds: 60.0)
let recording = audio.load("data/jfk.wav", max_seconds: 60.0)
let transcript = recognizer.transcribe(recording,
    language: "en", token_timestamps: true)
print(transcript.text())
print(transcript.model())
for index in Range(transcript.count()) {
    print(transcript.start(index))
    print(transcript.end(index))
    print(transcript.segment_text(index))
}
recognizer.close()

The complete transcription example adds explicit backend inspection and an NLP corpus bridge. Supply the local files shown above before executing the ASR branch; they are not bundled into the example or public assets.

Model admission and execution

load(path, device: "cpu", threads: 4, max_seconds: 300.0) accepts local regular non symlink weight files of at most 512 MiB. The bounded profile checks official tiny/base/small Whisper geometries before backend initialization. English only .en and matching multilingual variants are supported within that profile. Medium/large/turbo geometries and arbitrary GGUF/ONNX models are rejected. Qualification in this increment used tiny.en; accepting another compatible file does not establish its accuracy or performance on a particular host.

The weight bytes are read once into a bounded buffer. Before invoking the external loader, a complete container preflight checks finite 80 × 201 mel filters, bounded vocabulary counts/pieces, supported encodings, tensor rank/name/dimensions, quantization blocks, duplicate names, exact payload bounds and the expected tensor count for the declared geometry. Truncated or oversized metadata is rejected without allocating from its untrusted lengths. The validated bytes are then hashed and passed to the native buffer loader. model() binds a readable model kind to SHA-256 of the exact bytes loaded. The temporary input buffer is released after initialization; backend weights and working memory remain resident until close. This file bound is not a process RSS quota: the engine, weights, activations, input clip and resampled audio need additional memory.

threads is explicit in 1..64. device must currently be "cpu"; there is no silent GPU fallback. max_seconds is positive and at most 600; transcription rejects a longer clip before inference. Keep one loaded model for repeated calls rather than loading weights per chunk.

Each model handle owns one context. Copies share it, and concurrent transcription through aliases is rejected instead of creating an unbounded inference queue. close() closes aliases and waits for accepted work to observe cancellation; native work is checked between backend computation stages, not forcibly preempted inside a kernel. The native C++ Control also supports cooperative cancellation. A cancelled or failed call publishes no partial transcript.

Input conversion and silence

Aner accepts finite Float32 interleaved audio. It downmixes/resamples once through aner.audio to 16 kHz mono for Whisper. Already compatible input shares the existing clip. Arbitrary rate conversion follows the optional audio resampler's capability; WAV plus 16 kHz mono ASR needs no external conversion command. For stereo, the explicit mono recipe is an equal channel average; select a channel yourself when averaging would cancel useful content.

Empty input and near digital silence are checked before inference; the guard also checks converted mono audio. Its peak threshold is 1e-4 and RMS threshold is 1e-5, with both required for the near silence shortcut. The engine's per segment no speech probability is additionally filtered at 0.6.

These guards do not classify every background sound correctly. A tone, music or noise can produce transcription errors or invented words. Whisper's original model card describes this limitation. Use representative held out audio and measured WER/CER, and retain the source recording for review when the application requires it. The detector's RMS thresholds and ASR token scores are not calibrated probabilities of speech correctness.

Languages, segments and tokens

language: "en" is the default. A supported language code selects transcription in that source language; "auto" requests identification. Silence with auto identification retains "und" because no language was inferred. translate: true is the separate multilingual to English task. English only weights reject another requested source language or translation. Unsupported language codes are rejected even for silent input.

Greedy decoding uses zero temperature and no temperature fallback. Each call disables previous text context, so one request cannot inherit another recording's text. Chunk boundaries can reduce recognition quality because context is deliberately independent; stable text across calls is not a streaming decoder promise.

Transcript segments expose start, end, segment_text, and score. score = -1 means unavailable; when provided it is mean text token probability. token_count, token_id, token_start, token_end, token_score and token_timed inspect text tokens. Special decoder tokens are omitted. Raw BPE byte fragments are not exposed as potentially malformed Unicode strings.

Whisper segment times come from the decoder's timestamp grid; optional token alignment is an upstream estimate. token_timed distinguishes an estimated token interval from unavailable alignment. Neither represents measured word boundaries, phonemes, speakers or diarization. See the pinned token timestamp interface.

ASR times include the input clip's source sample origin. A sliced clip beginning at source sample 32000 at 16 kHz begins at source time 2.0, rather than resetting its transcript to zero. Times are clamped to observed clip duration. Transcripts retain source/session IDs, language, backend, model byte identity and a clock label.

Map speech timing to a video presentation clock

The speech clock is "source-samples". It is independent of a container's initial PTS or a microphone's arrival time. A transcript imported from supplied ranges uses "supplied-seconds"; external CTC output uses "ctc-frame-grid". Those labels identify timing provenance and do not infer synchronization.

When the matching audio anchor has valid PTS, anchor.timeline(seconds) explicitly maps source sample seconds to its presentation clock:

text
presentation_seconds = anchor.pts_ns / 1e9
                     + source_sample_seconds
                     - anchor.first_sample / anchor.rate
aner
let transcript = recognizer.transcribe(recording)
if recording.has_pts() {
    for index in Range(transcript.count()) {
        print(recording.timeline(transcript.start(index)))
    }
}

Retain the matching immutable clip or freeze an anchor block before reusing its capture slot. Check source/session identity before applying an anchor to another result. Mapping requires PTS and does not align unrelated devices. For a recording with both tracks, use one MediaSession so audio/video share the demuxed origin.

Bounded long recording workflows

audio.load is an explicit bounded collection. Use audio.file when an entire recording should not be retained in RAM. Process its reusable blocks, retain one resampler across a continuous source, and flush it once at the end. Reset on explicit discontinuities instead of interpolating over missing samples. The file source backpressures; live capture overload follows the audio source's explicit loss/failure policy.

A transcription request receives one bounded immutable AudioClip. An application can assemble a bounded utterance or file chunk, transcribe it, publish its result, then recycle that chunk. Use the VAD intervals as timing guidance while retaining the actual required samples separately. This increment does not supply an automatic utterance assembler or rolling Whisper decoder.

Decoding each very short capture block independently loses linguistic context. Choose chunk duration deliberately and evaluate boundary errors. A finite file can also be split into already prepared local clips before processing. Neither method requires collecting hours of audio or transcripts into one List.

Keep rate conversion state across continuous chunk boundaries. Repeatedly calling offline audio.resample on unrelated short pieces restarts filter state; a retained AudioResampler avoids that behavior. Once chunks are 16 kHz mono, transcription performs no further rate conversion.

Typed transcript import and CTC

aner
import aner.tensor
import aner.speech

let transcript = speech.transcript(List("Hello ", "world"),
    [[0.0, 0.2], [0.2, 0.6]], language: "en", model: "manual-fixture")
print(transcript.text())

Each CPU N × 2 row is [start_seconds, end_seconds]. Text count must match. Ranges must be finite, nonnegative, ordered and nonoverlapping. Text is validated UTF-8 without embedded NUL. Segment strings concatenate literally, so separators belong to the supplied text. Explicit source/session IDs default to zero; model and language labels are caller provenance rather than proof of inference.

SpeechTranscript is an immutable native snapshot. It retains at most 4096 segments, 65536 tokens and 1 MiB of combined text. Scalars/getters do not create per segment managed class objects. Keep only the results needed by the application; putting every transcript into a List still retains them deliberately.

aner
let decoded = speech.ctc_greedy(logits, List("", "h", "i"),
    blank: 0, frame_seconds: 0.02, model: "external-ctc-v1")
print(decoded.text())

The complete CTC example supplies its synthetic logits and checks timing and metrics. The decoder accepts a finite CPU rank two [time, vocabulary] Tensor with an exactly matching vocabulary. It permits up to 65536 time steps, 65536 vocabulary entries and four million logits, subject to the active Tensor budget. Vocabulary strings are individually bounded and total at most 4 MiB.

At each step it chooses the largest logit; exact ties choose the lowest ID. Consecutive repeats collapse, while a blank separates repeated output tokens. Strings concatenate literally. No word delimiter, BPE/SentencePiece recipe, tokenizer download, language model or beam search is inferred. frame_seconds must be finite in (0,60]; origin_seconds must be finite and nonnegative. Tokens retain the selected path's timing grid and scores computed using stable softmax.

WER and CER

aner
print(speech.wer("one two three", "one four three"))
print(speech.wer("Hello WORLD", "hello world", casefold: true))
print(speech.cer("café", "cafe"))
print(speech.cer("a b", "ab", include_spaces: false))

WER is (substitutions + deletions + insertions) / reference_words. Words split on Unicode whitespace. CER uses Unicode scalar values rather than UTF-8 bytes or grapheme clusters. Both preserve punctuation and case by default. Unicode casefold is opt in; CER can additionally ignore whitespace. Unicode normalization is not implicit. Apply the same declared recipe to reference and hypothesis before comparing experiments.

Rates can exceed one because insertions are not capped by reference length. Empty/empty returns zero. An empty reference with a nonempty hypothesis has an undefined denominator and is rejected by wer/cer; the native detailed ErrorRate result retains counts and defined = false.

Work is bounded to 10000 units on either side and sixteen million reference/hypothesis unit pairs, using two dynamic programming rows. Native detailed results retain substitution/deletion/insertion counts. Equal cost edit paths prefer a diagonal step, then deletion, then insertion; this fixes count attribution without changing minimum edit distance.

The NLP bridge accepts the resulting text:

aner
import aner.nlp
let documents = transcript.corpus(id: "recording-001", role: "inference")
print(documents.rows())

The ID and role are explicit. This bridge does not fit a vectorizer, attach acoustic features, or merge arbitrary model checkpoints. Reuse an already fitted text pipeline with its declared preprocessing.

Build and reproduce model conformance

Prepare the official source checkout outside public assets, preserving its exact revision and unchanged tracked files. CMake never fetches source or models.

sh
cmake -S . -B build/speech -DCMAKE_BUILD_TYPE=Release \
  -DANER_USE_LLM_NATIVE=OFF -DANER_USE_SPEECH_NATIVE=ON \
  -DANER_WHISPER_SOURCE_DIR=/path/to/whisper.cpp-v1.7.6
cmake --build build/speech --target aner aner_speech_tests
./build/speech/aner --version
./build/speech/aner_speech_tests

The current optional llama.cpp and whisper.cpp integrations contain private GGML targets/symbols from different pinned revisions. Their combined in process configuration is rejected. A future combined profile needs a qualified shared backend or isolated process boundary; disabling either engine is an explicit build choice.

For the model test, obtain ggml-tiny.en.bin from the upstream documented model location, verify the checksum, and retain the source checkout's samples/jfk.wav. No asset is fetched during CTest or source execution.

Qualification assetIdentity
whisper.cppv1.7.6, commit a8d002cfd879315632a579e73f0148d06959de36
ggml-tiny.en.bin77704715 bytes; SHA-256 921e4cf8686fdd993dcd081a5da5b6c365bfde1162e72b08d75ac75289920b1f
Upstream model checksumSHA 1 c78c86eb1a8faa21b369bcd33207cc90d64ae9df, matching the pinned model table
samples/jfk.wav352078 bytes; SHA-256 59dfb9a4acb36fe2a2affc14bacbee2920ff435cb13cc314a08c13f66ba7860e

The engine's MIT license and original Whisper model weight license apply to their respective assets. Checkpoint and fixture files stay outside canonical/public assets in this development qualification.

sh
./build/speech/aner_speech_tests \
  --model models/ggml-tiny.en.bin \
  --audio data/jfk.wav

To register that explicit local fixture with CTest, configure ANER_SPEECH_TEST_MODEL and ANER_SPEECH_TEST_AUDIO to existing absolute paths. Omitting them keeps the model conformance group unregistered; the dependency free analysis tests remain available.

The recorded CPU run recognized the clean JFK fixture with 2 segments and 23 text tokens. WER against the declared punctuated reference was 0.0909091, with casefold enabled and punctuation retained. This verifies one model, fixture, settings and host path. It does not establish general recognition accuracy, multilingual coverage, real time throughput or another platform's qualification. Source rate, noise, accent, language and chunk boundary tests need representative data before making those claims.

Native tests additionally cover arbitrary block VAD invariance, source offsets, gaps, maximum splits, overflow rollback, borrowed block aliases, CTC repeats/blanks/ties, transcript validation, Unicode edit counts, silence after downmix, cancellation and model alias closure. No reviewed CLI digest, publication, installation or GitHub Actions execution is performed by these commands.

See the complete callable index for the native module and method name catalogue.

Aner documentation · Reference and guides