training

package
v0.77.4 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 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 training captures wake-word activations for model training. A Capture keeps a rolling pre-roll buffer of the wake-word PCM stream and, on each DetectionEvent, writes pre-roll plus post-roll audio to disk as a WAV file with a JSON sidecar (Record) describing the trigger. An opt-in Uploader ships those records to a SpeechKit server. Every switch defaults to off: nothing is recorded or sent unless the host enables it.

Stability: Beta — API-checked; may change with a changelog callout.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EraseCaptureDir added in v0.74.0

func EraseCaptureDir(dir string) (int, error)

EraseCaptureDir deletes every activation clip and sidecar in dir, for a privacy erasure. Like PruneCaptureDir it touches only files named the way Capture names them. It returns the number of files removed; the first deletion error is returned after the sweep completes.

func PruneCaptureDir added in v0.74.0

func PruneCaptureDir(dir string, maxAge time.Duration, maxFiles int, now time.Time) (int, error)

PruneCaptureDir enforces the local retention limits on a capture directory: activation pairs (WAV + JSON sidecar) older than maxAge are deleted, and when more than maxFiles pairs remain the oldest are deleted until maxFiles are left. A zero maxAge or maxFiles disables that limit. A pair's age is its oldest file's modification time, so rewriting the sidecar (e.g. marking it uploaded) never extends retention. It returns the number of pairs removed; the first deletion error is returned after the sweep completes.

Types

type Capture

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

Capture buffers the rolling PCM stream around wake-word detections and writes each detection's audio to disk as a WAV file plus a JSON sidecar describing the trigger.

All audio is 16 kHz mono S16 PCM matching the wake-word pipeline (wakeword.SampleRate / Channels / BytesPerSample). The pre-roll and post-roll knobs are expressed in milliseconds and converted to samples at construction time.

Lifecycle (sidecar usage):

c, err := training.NewCapture(training.CaptureConfig{
    Enabled:    cfg.LocalCaptureEnabled,
    Dir:        cfg.LocalCaptureDir,
    PreRollMs:  cfg.PreRollMs,
    PostRollMs: cfg.PostRollMs,
    Backend:    "sherpa-onnx-zipformer-kws",
    OnWrite:    func(rec training.Record) { emit(...) },
})
defer c.Close()
// in the PCM handler:
c.Ingest(pcm)
// on detection:
c.Trigger(detectionEvent)

Capture is goroutine-safe: Ingest and Trigger may be called concurrently, though typical sidecars use one PCM thread for both.

func NewCapture

func NewCapture(cfg CaptureConfig) (*Capture, error)

NewCapture validates cfg and returns a ready-to-use capture. When cfg.Enabled is false the returned capture is inert.

func (*Capture) Close

func (c *Capture) Close() error

Close flushes any still-pending captures with whatever audio they already have so training clips are not silently lost on shutdown. Close is idempotent.

func (*Capture) Enabled

func (c *Capture) Enabled() bool

Enabled reports whether the capture actively writes to disk.

func (*Capture) Ingest

func (c *Capture) Ingest(pcm []byte)

Ingest pushes a fresh PCM buffer through the ring and any pending post-roll collectors.

func (*Capture) Trigger

func (c *Capture) Trigger(ev wakeword.DetectionEvent)

Trigger reacts to a wake-word DetectionEvent by snapshotting the current pre-roll ring and starting a post-roll collector. When post-roll is zero the capture flushes immediately.

type CaptureConfig

type CaptureConfig struct {
	// Enabled is the master switch. When false NewCapture still returns a
	// non-nil capture but Ingest/Trigger become no-ops, so the sidecar can
	// wire the same call sites regardless of user opt-in state.
	Enabled bool

	// Dir is the filesystem root where captures land. Must already exist
	// (the constructor does NOT create it). Each capture writes two files:
	// <prefix>.wav and <prefix>.json.
	Dir string

	// PreRollMs and PostRollMs determine how much audio gets captured
	// before and after a trigger. Internally converted to samples at the
	// canonical wakeword.SampleRate.
	PreRollMs  int
	PostRollMs int

	// Backend identifies the detector backend that produced the trigger
	// (e.g. "sherpa-onnx-zipformer-kws" / "livekit-openwakeword-onnx" /
	// "stt_phrase"). Echoed into the JSON sidecar so labelers know which
	// detector to test against.
	Backend string

	// OnWrite is an optional callback invoked once per completed capture
	// flush. Nil is allowed.
	OnWrite RecordHandler

	// TimeSource overrides time.Now for tests.
	TimeSource func() time.Time
}

CaptureConfig is the constructor input of NewCapture.

type Record

type Record struct {
	ID         string    `json:"id"`
	PhraseID   string    `json:"phrase_id"`
	Phrase     string    `json:"phrase"`
	Backend    string    `json:"backend"`
	Score      float32   `json:"score"`
	CapturedAt time.Time `json:"captured_at"`
	PreRollMs  int       `json:"pre_roll_ms"`
	PostRollMs int       `json:"post_roll_ms"`
	SampleRate int       `json:"sample_rate"`
	AudioPath  string    `json:"audio_path"`
	AudioBytes int       `json:"audio_bytes"`
	Label      string    `json:"label,omitempty"`
	Uploaded   bool      `json:"uploaded"`
}

Record is the metadata describing one written capture. The JSON sidecar uses the same field names (lower_snake_case), so this struct is the canonical schema.

type RecordHandler

type RecordHandler func(Record)

RecordHandler is the OnWrite callback shape. A flush that failed before any disk write reports a zero Record (empty ID).

type Uploader

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

Uploader scans a local capture directory for activation recordings produced by Capture and uploads them to a remote SpeechKit server's POST /v1/wakeword/activations endpoint.

Behaviour:

  • The scan interval is configurable; 5 min is a reasonable production default, tests can drop to 50 ms.
  • Records whose sidecar already has `"uploaded": true` are skipped.
  • When OnlyLabeled is true, records whose `label` field is empty are skipped too, so a host can gate "send to server" behind explicit labelling.
  • After a 201 (or a 409 "already exists") the sidecar JSON is rewritten with `uploaded: true`; the WAV stays on disk for local review.
  • On 503 (server has the feature disabled) and on 5xx / network errors the uploader logs and waits for the next tick; nothing on disk is mutated, so retry is automatic.

All work happens on the goroutine that calls Run, which blocks until ctx is cancelled or Close is called.

func NewUploader

func NewUploader(cfg UploaderConfig) (*Uploader, error)

NewUploader validates cfg and returns a ready uploader.

func (*Uploader) Close

func (u *Uploader) Close()

Close marks the uploader as closed; the next tick makes Run return. Safe to call multiple times.

func (*Uploader) Run

func (u *Uploader) Run(ctx context.Context) error

Run scans once immediately and then on every tick until ctx is cancelled (returning ctx.Err()) or Close is called (returning nil). Call it once; concurrent Run calls are not supported.

type UploaderConfig

type UploaderConfig struct {
	// Dir is the local capture directory that Capture writes into (one .wav
	// + .json pair per activation).
	Dir string

	// ServerURL is the base URL of the SpeechKit server, e.g.
	// "https://speechkit.example.com". The uploader appends
	// "/v1/wakeword/activations" itself.
	ServerURL string

	// BearerToken authenticates the upload requests. Optional; the caller
	// resolves it from its own secret source so secrets handling stays in
	// one place.
	BearerToken string

	// Interval between scans. Zero is rejected by NewUploader; production
	// should pass at least 30 s.
	Interval time.Duration

	// OnlyLabeled uploads only records whose sidecar JSON has a non-empty
	// `label` field.
	OnlyLabeled bool

	// HTTPClient overrides the default *http.Client (optional; tests use a
	// custom transport). When nil a 30 s-timeout netsec client is used that
	// validates every dial target against the URL policy (see Validation)
	// and follows no redirects. A caller-supplied client is used as is.
	HTTPClient *http.Client

	// Validation optionally replaces the default URL policy for ServerURL
	// (also applied to every dial by the default client). The default
	// accepts https to any host and plain http only to loopback or
	// private-network addresses, because the clips are raw microphone audio
	// and the request carries a bearer token. Hosts pass their network-scope
	// policy here (e.g. local-network-only).
	Validation *netsec.ValidationOptions

	// Logger is optional; defaults to slog.Default.
	Logger *slog.Logger
}

UploaderConfig configures one Uploader. Fields are required unless marked optional.

Jump to

Keyboard shortcuts

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