wakeword

package
v0.81.14 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 13 Imported by: 2 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 wakeword exposes embeddable SpeechKit wake-word contracts: the phrase catalog, detection events, the hotkey Dispatcher, AutoEndPolicy and the engine-neutral Detector and Pipeline. The package links no keyword-spotting engine; import pkg/speechkit/wakeword/sherpa (or register another Engine) to run detection.

Stability: Stable — no breaking change without a minor version bump and a changelog callout.

Index

Constants

View Source
const (
	SampleRate     = 16000
	BytesPerSample = 2
	Channels       = 1
	FrameSamples   = 1280
	FrameBytes     = FrameSamples * BytesPerSample
	FrameDur       = 80 * time.Millisecond
	SourceWakeword = "wakeword"
)

Audio contract of the wake-word pipeline: 16 kHz mono S16 PCM delivered in 80 ms frames, matching pkg/speechkit/audio so one capture session can fan out to VAD and wake-word without resampling.

Variables

View Source
var ErrCgoRequired = errors.New("wakeword: sherpa-onnx KWS requires cgo build (set CGO_ENABLED=1)")

ErrCgoRequired is returned by an engine constructor such as sherpa.NewDetector in a build without cgo. It exists in every build so hosts can write errors.Is(err, wakeword.ErrCgoRequired) regardless of how they compile.

View Source
var ErrEngineUnavailable = errors.New("wakeword: no keyword-spotting engine registered (import an engine package such as pkg/speechkit/wakeword/sherpa)")

ErrEngineUnavailable is returned by NewDetector when no keyword-spotting Engine is registered, or when DetectorConfig.Engine names one that is not. The root package ships no engine: import an engine package such as pkg/speechkit/wakeword/sherpa, which registers itself on import.

Functions

func EncodeKeywords added in v0.50.0

func EncodeKeywords(tokensPath string, rawKeywords []string) ([]string, error)

EncodeKeywords converts inline raw keyword phrases into the space-separated BPE-token format sherpa-onnx keyword spotting expects, using greedy longest-match over the model's tokens.txt vocabulary.

Each input line may carry trailing metadata fields (":<boost>", "#<threshold>", "@<label>") which are preserved verbatim after the tokens. Lines that already contain the word-boundary marker are treated as pre-encoded and returned unchanged (idempotent).

Greedy longest-match approximates the true SentencePiece/BPE segmentation and is intended for short wake phrases. For long or ambiguous phrases prefer generating keywords.txt with the model's bpe.model (sherpa-onnx ships a text2token tool for this).

func FrameDuration

func FrameDuration() time.Duration

FrameDuration returns the fixed PCM frame duration.

func RegisterEngine added in v0.73.0

func RegisterEngine(name string, factory EngineFactory) error

RegisterEngine makes factory available to NewDetector under name. The first registered engine is the default; DetectorConfig.Engine selects another by name. An empty name, a nil factory, or a name registered twice is an error.

func ValidateKeywordsFile added in v0.50.0

func ValidateKeywordsFile(path string) error

ValidateKeywordsFile checks that a keywords file looks BPE-tokenized rather than raw text. It catches the common silent failure where sherpa-onnx never matches because it was handed plain words (e.g. "kombify") instead of the tokenized form ("▁COM B IF Y ..."). Leading-'#' lines are treated as comments (an inline "#<threshold>" suffix never starts a line).

Types

type AutoEndConfig

type AutoEndConfig struct {
	SilenceCutoff time.Duration
	ExitPhrases   []string
}

AutoEndConfig controls when a wake-triggered session automatically ends.

func DefaultAutoEndConfig

func DefaultAutoEndConfig() AutoEndConfig

DefaultAutoEndConfig returns SpeechKit's framework baseline.

type AutoEndPolicy

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

AutoEndPolicy watches activity/transcripts and fires an end signal once.

func NewAutoEndPolicy

func NewAutoEndPolicy(cfg AutoEndConfig, logger *slog.Logger) *AutoEndPolicy

NewAutoEndPolicy constructs a policy from config.

func (*AutoEndPolicy) Close

func (p *AutoEndPolicy) Close()

Close stops timers and closes EndSignal if it has not fired.

func (*AutoEndPolicy) Config

func (p *AutoEndPolicy) Config() AutoEndConfig

Config returns a copy of the policy config.

func (*AutoEndPolicy) EndSignal

func (p *AutoEndPolicy) EndSignal() <-chan EndReason

EndSignal fires when the policy decides the session should end.

func (*AutoEndPolicy) NotifyActivity

func (p *AutoEndPolicy) NotifyActivity()

NotifyActivity resets the silence timer.

func (*AutoEndPolicy) NotifyTranscript

func (p *AutoEndPolicy) NotifyTranscript(text string)

NotifyTranscript checks text against configured exit phrases.

func (*AutoEndPolicy) Start

func (p *AutoEndPolicy) Start()

Start arms the silence timer.

type Config

type Config struct {
	Enabled              bool
	Phrase               string
	ModelDir             string
	KeywordsFile         string
	Keywords             []string
	DefaultMode          string
	Threshold            float32
	MinConsecutiveFrames int
	Cooldown             time.Duration
	AutoEnd              AutoEndConfig
}

Config controls wake-word pipeline behavior.

type DetectionEvent

type DetectionEvent struct {
	Phrase  string
	Keyword string
	Mode    string
	// Probability is a confidence lower bound for the detection. The
	// sherpa-onnx KWS binding exposes no exact per-detection score, so the
	// live pipeline reports the effective keyword threshold the detection
	// cleared (i.e. "at least this confident") rather than a fabricated 1.0.
	Probability float32
	At          time.Time
}

DetectionEvent is emitted when a keyword fires.

type Detector

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

Detector is a loaded keyword-spotting model, ready to back Pipeline streams. It is engine-neutral: NewDetector resolves the registered Engine and the Detector only owns its lifetime. The struct stays comparable (no slices or maps) so it remains a drop-in for the previous no-cgo surface.

func NewDetector

func NewDetector(cfg DetectorConfig) (*Detector, error)

NewDetector validates cfg, stages inline Keywords as a BPE-tokenised keywords file, and loads the model through the selected registered Engine. It returns ErrEngineUnavailable when no engine is registered: import pkg/speechkit/wakeword/sherpa (or register your own engine) first.

func (*Detector) Close

func (d *Detector) Close() error

Close releases the engine's model. Safe to call more than once.

func (*Detector) Threshold added in v0.50.0

func (d *Detector) Threshold() float32

Threshold returns the configured keyword detection threshold (0 if unset).

type DetectorConfig

type DetectorConfig struct {
	Encoder      string   // encoder ONNX
	Decoder      string   // decoder ONNX
	Joiner       string   // joiner ONNX
	Tokens       string   // tokens.txt (BPE token table)
	KeywordsFile string   // BPE-tokenised keywords file; takes precedence over Keywords
	Keywords     []string // raw phrases, BPE-encoded by NewDetector via EncodeKeywords

	// NumThreads bounds the engine's CPU parallelism; zero lets the engine
	// choose.
	NumThreads int

	// Threshold is the keyword detection threshold in (0, 1]; zero keeps the
	// engine default.
	Threshold float32

	// Debug enables the engine's verbose native logging.
	Debug bool

	// Engine selects a registered engine by name (see RegisterEngine). Empty
	// uses the first registered engine.
	Engine string
}

DetectorConfig bundles the file-system inputs of a keyword-spotting model. All paths must be absolute; NewDetector never resolves them against a model directory so host wiring stays explicit.

type Dispatcher

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

Dispatcher converts DetectionEvents into synthetic hotkey events.

func NewDispatcher

func NewDispatcher(sink HotkeySink, opts DispatcherOptions) *Dispatcher

NewDispatcher constructs a Dispatcher with the given sink and options.

func (*Dispatcher) Close

func (d *Dispatcher) Close(ctx context.Context) error

Close blocks further events and waits for in-flight dispatches.

func (*Dispatcher) Emit

func (d *Dispatcher) Emit(ev DetectionEvent)

Emit implements Sink. It is non-blocking for the caller.

type DispatcherOptions

type DispatcherOptions struct {
	SyntheticRelease bool
	ReleaseAfter     time.Duration
	Logger           *slog.Logger
}

DispatcherOptions tweaks Dispatcher behavior.

type EndReason

type EndReason string

EndReason is the result emitted by AutoEndPolicy.

const (
	EndReasonSilence    EndReason = "silence"
	EndReasonExitPhrase EndReason = "exit_phrase"
)

EndReason values: the silence cutoff elapsed, or a transcript matched an exit phrase.

type Engine added in v0.73.0

type Engine interface {
	// NewStream opens one streaming decode session against the model.
	NewStream() (EngineStream, error)
	// Close releases the model. It must be safe to call more than once.
	Close() error
}

Engine is a loaded keyword-spotting model. The root package ships no engine: an engine package registers its EngineFactory with RegisterEngine (pkg/speechkit/wakeword/sherpa does so on import) and NewDetector picks it up. Pipeline drives the Engine through EngineStream and owns every engine-neutral behaviour itself: PCM conversion, debounce, cooldown, pause and the reported detection probability.

type EngineFactory added in v0.73.0

type EngineFactory func(cfg DetectorConfig) (Engine, error)

EngineFactory loads an Engine for cfg. When it runs, NewDetector has already checked that the model asset paths exist and materialised cfg.KeywordsFile as a BPE-tokenised keywords file.

type EngineStream added in v0.73.0

type EngineStream interface {
	// AcceptWaveform appends mono float32 samples in [-1, 1] at SampleRate.
	AcceptWaveform(samples []float32)
	// IsReady reports whether enough audio is buffered for another Decode.
	IsReady() bool
	// Decode runs one decode step and returns the spotted keyword, or ""
	// when the step produced none.
	Decode() string
	// Reset clears the decoder state after a detection or on Pipeline.Reset.
	Reset()
	// Close releases the stream. It must be safe to call more than once.
	Close() error
}

EngineStream is one streaming keyword-spotting session over an Engine. Pipeline serialises every call on a stream, so implementations need no locking of their own.

type HotkeyEvent

type HotkeyEvent struct {
	KeyDown bool
	Binding string
	Source  string
}

HotkeyEvent is the minimal event shape needed to bridge wake-word triggers into a host's mode activation path.

type HotkeySink

type HotkeySink interface {
	Submit(HotkeyEvent)
}

HotkeySink consumes synthetic key events.

type HotkeySinkFunc

type HotkeySinkFunc func(HotkeyEvent)

HotkeySinkFunc adapts a plain function to HotkeySink.

func (HotkeySinkFunc) Submit

func (f HotkeySinkFunc) Submit(ev HotkeyEvent)

Submit calls f.

type PhraseCatalogEntry

type PhraseCatalogEntry struct {
	ID           string
	DisplayName  string
	KeywordLabel string
	Notes        string
}

PhraseCatalogEntry describes a curated wake phrase.

func DefaultCatalog

func DefaultCatalog() []PhraseCatalogEntry

DefaultCatalog returns SpeechKit's curated wake-phrase list.

func LookupPhrase

func LookupPhrase(id string) *PhraseCatalogEntry

LookupPhrase returns the catalog entry matching id, or nil if none does. The lookup is case-insensitive, trims surrounding whitespace and accepts legacy aliases such as "hey_quby" for "hey_kubi".

type Pipeline

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

Pipeline streams PCM audio through a Detector's engine and emits a DetectionEvent via Sink whenever the engine spots a keyword Config.MinConsecutiveFrames decodes in a row, outside the current cooldown window. It is pure Go: PCM conversion, debounce, cooldown, pause and the reported probability live here, so every Engine behaves the same.

Pipeline is safe for concurrent use. One Pipeline backs one audio source.

func NewPipeline

func NewPipeline(detector *Detector, sink Sink, cfg Config) (*Pipeline, error)

NewPipeline wires a Detector and Sink together. Invalid Config fields are coerced to defaults so hosts do not mirror the normalisation.

func (*Pipeline) Close

func (p *Pipeline) Close() error

Close releases the engine stream. Subsequent FeedPCM calls error. The Detector is not closed: the host that constructed both owns its lifetime.

func (*Pipeline) Config

func (p *Pipeline) Config() Config

Config returns a copy of the resolved pipeline config (with defaults applied).

func (*Pipeline) FeedPCM

func (p *Pipeline) FeedPCM(pcm []byte) (decodes int, peakProb float32, err error)

FeedPCM ingests raw S16LE mono PCM at SampleRate, drains every ready decode window and returns the number of decode steps plus the probability lower bound of the last detection emitted during this call (0 if none).

func (*Pipeline) Pause added in v0.50.0

func (p *Pipeline) Pause()

Pause suppresses detection and stops feeding audio to the engine. It is safe to call from any goroutine and is idempotent. Use it around TTS playback (or any host self-audio) to prevent barge-in self-triggering.

func (*Pipeline) Paused added in v0.50.0

func (p *Pipeline) Paused() bool

Paused reports whether detection is currently suppressed.

func (*Pipeline) Reset

func (p *Pipeline) Reset()

Reset clears rolling engine state and the debounce maps. Hosts call it after a detection-triggered mode change so the same utterance cannot re-fire once the cooldown lapses.

func (*Pipeline) Resume added in v0.50.0

func (p *Pipeline) Resume()

Resume re-enables detection and clears any partial match / debounce state so audio buffered during the pause cannot produce a stale trigger.

type Sink

type Sink interface {
	Emit(DetectionEvent)
}

Sink receives DetectionEvents from a wake-word pipeline.

type SinkFunc

type SinkFunc func(DetectionEvent)

SinkFunc adapts a plain function to Sink.

func (SinkFunc) Emit

func (f SinkFunc) Emit(ev DetectionEvent)

Emit calls f.

Directories

Path Synopsis
Package sherpa is the sherpa-onnx keyword-spotting engine for pkg/speechkit/wakeword.
Package sherpa is the sherpa-onnx keyword-spotting engine for pkg/speechkit/wakeword.

Jump to

Keyboard shortcuts

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