wakeword

package
v0.51.1 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package wakeword exposes embeddable SpeechKit wake-word contracts.

Index

Constants

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

Variables

This section is empty.

Functions

func EncodeKeywords added in v0.51.1

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 (see examples/kombify-box-satellite/tools/make-keywords.ps1).

func FrameDuration

func FrameDuration() time.Duration

FrameDuration returns the fixed PCM frame duration.

func ValidateKeywordsFile added in v0.51.1

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 owns the sherpa-onnx KeywordSpotter.

func NewDetector

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

NewDetector loads the sherpa-onnx KWS model.

func (*Detector) Close

func (d *Detector) Close() error

Close releases the underlying KeywordSpotter.

func (*Detector) Threshold added in v0.51.1

func (d *Detector) Threshold() float32

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

type DetectorConfig

type DetectorConfig struct {
	Encoder      string
	Decoder      string
	Joiner       string
	Tokens       string
	KeywordsFile string
	Keywords     []string
	NumThreads   int
	Threshold    float32
	Debug        bool
}

DetectorConfig bundles file-system inputs for the sherpa-onnx KWS engine.

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"
)

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.

type Pipeline

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

Pipeline streams PCM audio into a sherpa-onnx KeywordSpotter.

func NewPipeline

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

NewPipeline wires a Detector and Sink together.

func (*Pipeline) Close

func (p *Pipeline) Close() error

Close releases the streaming handle.

func (*Pipeline) Config

func (p *Pipeline) Config() Config

Config returns a copy of the resolved pipeline config.

func (*Pipeline) FeedPCM

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

FeedPCM ingests raw S16 mono PCM at SampleRate.

func (*Pipeline) Pause added in v0.51.1

func (p *Pipeline) Pause()

Pause suppresses detection and stops feeding audio to the stream. 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.51.1

func (p *Pipeline) Paused() bool

Paused reports whether detection is currently suppressed.

func (*Pipeline) Reset

func (p *Pipeline) Reset()

Reset clears rolling detector state and debounce maps.

func (*Pipeline) Resume added in v0.51.1

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 exposes the sherpa-onnx wake-word detector adapter.
Package sherpa exposes the sherpa-onnx wake-word detector adapter.

Jump to

Keyboard shortcuts

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