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
- Variables
- func EncodeKeywords(tokensPath string, rawKeywords []string) ([]string, error)
- func FrameDuration() time.Duration
- func RegisterEngine(name string, factory EngineFactory) error
- func ValidateKeywordsFile(path string) error
- type AutoEndConfig
- type AutoEndPolicy
- type Config
- type DetectionEvent
- type Detector
- type DetectorConfig
- type Dispatcher
- type DispatcherOptions
- type EndReason
- type Engine
- type EngineFactory
- type EngineStream
- type HotkeyEvent
- type HotkeySink
- type HotkeySinkFunc
- type PhraseCatalogEntry
- type Pipeline
- type Sink
- type SinkFunc
Constants ¶
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 ¶
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.
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
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 ¶
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
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 ¶
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.
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.
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 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 ¶
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.
type PhraseCatalogEntry ¶
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 ¶
NewPipeline wires a Detector and Sink together. Invalid Config fields are coerced to defaults so hosts do not mirror the normalisation.
func (*Pipeline) Close ¶
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 ¶
Config returns a copy of the resolved pipeline config (with defaults applied).
func (*Pipeline) FeedPCM ¶
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
Paused reports whether detection is currently suppressed.
type Sink ¶
type Sink interface {
Emit(DetectionEvent)
}
Sink receives DetectionEvents from a wake-word pipeline.