sttclient

package
v0.206.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sttclient calls a whisper.cpp whisper-server (over llama-swap's /upstream/<model>/inference passthrough) to transcribe a 16 kHz mono WAV. It requests response_format=verbose_json so the reply carries per-segment timestamps (the {gist, segments[]} citation pattern). Audio bytes go straight to whisper-server and NEVER touch the text Gemma cascade. Pure net/http + mime/multipart; no cgo, no cloud.

Index

Constants

This section is empty.

Variables

View Source
var ErrUpstreamNoSpeech = errors.New("stt upstream: no speech found")

ErrUpstreamNoSpeech is the verdict "the audio had no speech": Transcribe and TranscribeOAI return it, wrapped, in place of an empty Result when the upstream ANSWERED, successfully, with an empty transcript. Transcribe also returns it for the one failure that is the F-35 crash when this process can vouch for itself: an empty-body 5xx in a call that ran alone (see lineMark.ranAlone, and the comment at the call site). Any other failure to get an answer is ErrUpstreamVanished, never this (register C-91). Until 2026-10-01 every empty-body 5xx was read as no speech (root-caused 2026-09-23, F-35: whisper-server exits on audio with no speech content), but the same bare status, or a read cut off mid-answer, follows a model that is unloaded, swapped or restarted under a call, and audio WITH speech was reported to its caller as silent. A status cannot tell the two apart; an answer can, and so can a process that knows it did nothing to the upstream while the call ran. Callers treat this as "no speech found", not as an infrastructure failure, and have nothing to retry.

View Source
var ErrUpstreamVanished = errors.New("stt upstream: the upstream vanished mid-request")

ErrUpstreamVanished marks a call whose upstream went away under it: the answer was an empty-body 5xx (llama-swap's bare answer when its connection to the model drops) or was cut off mid-read, and this process cannot rule out that something else caused it. An unload, a swap, a restart and a crash all look like that, so it is a failed call, which a caller can retry, and never a verdict about the audio: tell it from ErrUpstreamNoSpeech with errors.Is. Transcribe returns it for a call that was not alone (lineMark.ranAlone), TranscribeOAI for every such answer: nothing says llama-server's mtmd path exits on audio without speech, as whisper.cpp does.

Functions

func ParseASRText added in v0.206.0

func ParseASRText(raw string) (lang, text string)

ParseASRText splits a Qwen3-ASR-style transcript. The model prefixes its output with a detected-language span: "language English<asr_text>the transcript…". The prefix is consumed ONLY when it matches that exact shape; otherwise the whole trimmed input is the transcript and language is unknown ("").

func Pending added in v0.206.0

func Pending() int

Pending reports how many transcriptions in this process are waiting for the whisper upstream or running on it (register C-91): the count UnloadIfIdle reads. It exists so a test can wait until a second call is in line instead of sleeping and hoping.

func Queued added in v0.206.0

func Queued() func()

Queued notes that one more transcription is waiting behind the caller's own gate and will use the upstream as soon as the gate lets it through; the returned func (idempotent) takes it back, and the caller calls it once the job has joined the line (or been abandoned). While any is outstanding, UnloadIfIdle leaves the model loaded, so a burst held at a node's gate pays one cold start, not one per job (register C-91, D18).

func QueuedNow added in v0.206.0

func QueuedNow() int

QueuedNow reports how many jobs are held back by a Queued gate right now, so a test can wait until one is in line instead of sleeping.

func SRT

func SRT(segs []Segment) string

SRT renders segments as SubRip text (1-indexed, HH:MM:SS,mmm timestamps).

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client posts audio to whisper-server through llama-swap on base (e.g. http://127.0.0.1:11436). Every inference is serialized by the process-global inferMu (whisper-server is single-slot and crashes on overlapping requests).

func New

func New(base string, timeout time.Duration) *Client

New builds a client. timeout bounds one transcription (long audio).

func (*Client) Transcribe

func (c *Client) Transcribe(ctx context.Context, model, wavPath string, p Params) (Result, error)

Transcribe uploads wavPath to the whisper upstream `model` and returns the parsed verbose_json. The multipart body is built in memory (wavs are 16 kHz mono — ~2 MB/min — comfortable in 64 GB RAM).

func (*Client) TranscribeOAI added in v0.206.0

func (c *Client) TranscribeOAI(ctx context.Context, model, wavPath string) (Result, error)

TranscribeOAI uploads wavPath to the model's OpenAI-compatible transcriptions endpoint and adapts the reply to the whisper-shaped Result: parsed language, the transcript, and ONE synthesized segment spanning the whole clip (SRT and the segments.json consumers rely on segments existing; timestamps are not available on this path). Serialized by the same process-global mutex as Transcribe — the mtmd upstream is served single-slot too.

func (*Client) Unload

func (c *Client) Unload(ctx context.Context, model string) error

Unload force-frees the whisper upstream's VRAM immediately (zero-always-warm), rather than waiting for the ttl:300 idle timer. Best-effort: any error is the caller's to ignore.

Routed through pkg/llamaswap rather than posting /api/models/unload/{model} raw, which buys two guards this call site never had: the name is resolved through the roster first (the harness binds ALIASES — `whisper`, `stt` — and only the canonical id is guaranteed to key the unload route), and a seat the llama-swap config marks resident is REFUSED instead of taken down.

Drain is deliberately off: the pre-existing behavior was an unconditional unload. Unload itself holds NOTHING — the single-slot inference mutex is released when Transcribe returns, so a caller that fires it right after a call lands it on whatever the next call has in flight (register C-91; this comment used to say the caller holds the mutex, which no caller did). The zero-always-warm caller uses UnloadIfIdle, which unloads holding that mutex and only when nothing is in line, so there is nothing in flight to drain. Passing UnloadOpts{Drain: true} is the one-line change if a future caller unloads a seat it does not own.

func (*Client) UnloadIfIdle added in v0.206.0

func (c *Client) UnloadIfIdle(ctx context.Context) error

UnloadIfIdle is Unload for the zero-always-warm caller (register C-91): it frees the upstream only when this is the last transcription of a burst, only once per burst, and then frees every model the burst warmed.

The caller used to unload after EVERY call, holding nothing: inferMu is released when Transcribe returns, so a call that finished while others were in line sent its unload while the next one's inference was on the upstream, and llama-swap answered that call "matrix: model unloaded" with a 500 (or cut its read off). The calls queued behind it paid a cold start each, whatever the order. Here the unload goes out holding inferMu, which keeps the next inference off the upstream until it is done, and only when nothing is in line:

  • another call is waiting or running (sttCalls): that call is the last one out and unloads then, so a burst of N pays one cold start, not N;
  • no model was used since the last unload (warmed): a call of the same burst already freed it, or this call never reached the upstream (the card was fenced, the wav would not read).

What it frees is every model warmed on this client's base, not the model of the call that happens to be last out. A burst can mix stt_model with stt_model_hq, or the two protocols on two models; they share the one slot, so they are one burst, and the call that finishes last knows only its own model. Unloading just that one left the first finisher's model loaded until llama-swap's ttl, with nothing logged to say so. A call that never reached the upstream warmed nothing, so on its own it still unloads nothing; as the last one out it frees what the calls before it warmed.

Each model is unloaded on its own. One that fails stays marked warm, so the next call out retries it, and it does not stop the others; every failure is returned, joined, each naming its model, and the ttl is the backstop. The caller logs the error and does not fail the transcription for it.

It never BLOCKS on inferMu, because a finished call must not hold its own answer back for the length of the next call's inference: a 30-minute transcription would delay a ten-second one's result by 30 minutes. That is safe because a failed TryLock always means somebody else has the unload covered: the holder is a call that came in after the check above (it is the last one out), or another UnloadIfIdle that has already seen an empty line and will unload what was used. The decision is taken on sttCalls BEFORE the lock, so a call that only looked and went away never holds the slot against another.

The last call out unloads even when it failed: the pipeline calls this after every call, so a burst whose final call was refused by the fence still frees the models its earlier calls warmed.

func (*Client) WithFenceWait added in v0.206.0

func (c *Client) WithFenceWait(d time.Duration) *Client

WithFenceWait sets how long a transcription waits for a card a render holds (register C-89) and returns the client, so it chains at construction: New(...).WithFenceWait(p.gpuWait()).

The wait used to BE the client's timeout, which for a transcription is stt_request_timeout_sec (1,800 s: long audio decodes at 5-8x realtime) — the same limit at which the MCP client aborts an idle call, so a held card made the two race, while every other GPU door gave up after gpu_wait_ms (90 s by default). The fence wait is its own budget now, and the client's timeout only CAPS it (min of the two), because a wait cannot outlast the request it is part of.

Zero is a value, not "unset": gpu_wait_ms 0 means a single try for every GPU door, and a zero here is one inspection of the lease. Only a client that never called this waits its HTTP timeout, as before.

type Params

type Params struct {
	Language      string  // "" => auto-detect (sent as language=auto)
	BeamSize      int     // -bs; default greedy in whisper, so 5 is set explicitly
	BestOf        int     // -bo; candidates for temperature fallback
	MaxContext    int     // -mc; condition-on-previous-text cap (kills repetition loops)
	EntropyThold  float64 // -et; raise to fire the repetition detector sooner
	NoSpeechThold float64 // -nth
	Temperature   float64 // base decode temperature (fallback steps up from here)
	VAD           bool    // enable Silero VAD (server loaded with -vm)
	VADThreshold  float64 // -vt
	MaxLen        int     // -ml; subtitle-sized segments (chars)
	SplitOnWord   bool    // -sow; split at word boundaries for clean SRT
}

Params are the per-request decode knobs whisper-server accepts as form fields. Defaults (DefaultParams) are the research-tuned profile for noisy EN/ES field audio; Language is set by the caller per call.

func DefaultParams

func DefaultParams() Params

DefaultParams returns the tuned profile for noisy EN/ES field audio.

func (Params) ResponseFormat

func (Params) ResponseFormat() string

ResponseFormat is fixed: verbose_json is the ONLY format that returns segments.

type Result

type Result struct {
	Language string    `json:"language"`
	Duration float64   `json:"duration"`
	Text     string    `json:"text"`
	Segments []Segment `json:"segments"`
	// WordsReliable is the self-check of the word timestamps (D-38, issue #169): false when the FIRST
	// word of some segment starts wordDriftThresholdSec or more away from that segment's start, true
	// when the first word of every segment that carries words starts within it, nil (the key is
	// absent) when no segment carries words. True is a statement about those first words only: a
	// later word that sits far outside its segment still reads true (words[0] is the issue's own
	// formula, and a stricter bound on every word waits for a measurement of honest audio). It flags
	// the symptom and names no cause: whisper-server was seen to hand back word times lagging their
	// segment by minutes on a long file, and a consumer that cuts audio at whole-word boundaries needs
	// to know not to trust them. Set by Transcribe from checkWordDrift; pipeline and sttremote publish
	// it in the transcribe payload.
	WordsReliable *bool `json:"words_reliable,omitempty"`
	// WordsDriftSec is the largest |segment.start - words[0].start| over the segments that carry
	// words, in seconds: the number behind WordsReliable. Zero (and absent) when WordsReliable is nil
	// or the words agree to the millisecond.
	WordsDriftSec float64 `json:"words_drift_sec,omitempty"`
}

Result is the parsed whisper-server verbose_json response.

type Segment

type Segment struct {
	ID           int     `json:"id"`
	Start        float64 `json:"start"`
	End          float64 `json:"end"`
	Text         string  `json:"text"`
	Words        []Word  `json:"words"`
	AvgLogprob   float64 `json:"avg_logprob"`
	NoSpeechProb float64 `json:"no_speech_prob"`
}

Segment is one timestamped span of the transcript (start/end in seconds), plus the per-word array and decode-confidence fields whisper-server already returns. These flow through to the on-disk .segments.json (pipeline writes the full tr.Segments) for downstream consumers that need word-accurate timing and per-word confidence.

type Word

type Word struct {
	Word        string  `json:"word"`
	Start       float64 `json:"start"`
	End         float64 `json:"end"`
	Probability float64 `json:"probability"`
}

Word is one timestamped word with whisper's per-word confidence. whisper-server emits words[] in verbose_json BY DEFAULT (no extra request field needed — adding token_timestamps can segfault this build); the dataset/segmentation tooling uses these to cut only at whole-word boundaries and to drop low-confidence stumbles.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL