media

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 100 Imported by: 1 module, 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 media provides image and video generation, text to speech, transcription, voice mode, and wake word tools

Index

Constants

View Source
const DefaultDeepInfraBaseURL = "https://api.deepinfra.com/v1/openai"

Default DeepInfra OpenAI compatible origin

View Source
const DefaultTTSOutputFormat = "mp3"
View Source
const DefaultXAIBaseURL = "https://api.x.ai/v1"

Default xAI REST origin

View Source
const MediaCacheMaxAgeHours = 24

Age in hours after which transient media caches are swept

View Source
const StreamingFinalizeTimeout = streamingFinalizeTimeout

Default wait of a live transcription finalize in seconds

View Source
const UserAgent = "Icebath-Agent/1.0"

Icebath user agent sent to every vendor HTTP endpoint

View Source
const WakeSampleRate = 16000

WakeSampleRate is the 16 kHz mono int16 rate every wake engine consumes

Variables

View Source
var ErrPilkMissing = errors.New("the pilk Python package is not installed in the managed environment")

Failure of a managed environment that has no pilk package

View Source
var WakeProviderNames = []string{"porcupine", "sherpa", "sherpa-onnx", "kws", "open", "openwakeword", "oww", "local"}

WakeProviderNames lists the provider aliases in their declared order

View Source
var WakeProviderPreference = []string{"openwakeword", "sherpa", "porcupine"}

WakeProviderPreference is the auto resolution order of the wake engines

View Source
var WakeProviders = map[string]WakeProviderEntry{
	"porcupine":    {"_PorcupineEngine", "wake-porcupine"},
	"sherpa":       {"_SherpaKwsEngine", "wake-sherpa"},
	"sherpa-onnx":  {"_SherpaKwsEngine", "wake-sherpa"},
	"kws":          {"_SherpaKwsEngine", "wake-sherpa"},
	"open":         {"_SherpaKwsEngine", "wake-sherpa"},
	"openwakeword": {"_OpenWakeWordEngine", "wake-openwakeword"},
	"oww":          {"_OpenWakeWordEngine", "wake-openwakeword"},
	"local":        {"_OpenWakeWordEngine", "wake-openwakeword"},
}

WakeProviders maps every provider alias to its engine class and pm extra

Functions

func AcquireTTSLease

func AcquireTTSLease(ctx context.Context, env *tools.Env, lease string, ttsConfig map[string]any) map[string]any

Registers a lease and warms the provider, cancelling any pending unload

func AudioIsSilent

func AudioIsSilent() bool

AudioIsSilent reports an armed stream that opens fine but delivers only silence

func CheckTTSRequirements

func CheckTTSRequirements(ctx context.Context) bool

CheckTTSRequirements reports the configured text to speech provider usable for gateway auto TTS

func CleanupTempRecordings

func CleanupTempRecordings(maxAgeSeconds int) int

CleanupTempRecordings deletes voice recordings older than maxAgeSeconds and returns how many went

func FindFFmpegBinary

func FindFFmpegBinary() string

Shared ffmpeg discovery over PATH and the Homebrew and local prefixes, empty when absent

func FullDuplexListen

func FullDuplexListen(shouldStop func() bool, o DuplexOptions) string

FullDuplexListen listens through generation and playback, returning the WAV of the utterance that barged in

func GetLastMatch

func GetLastMatch() (phrase, profile string, ok bool)

GetLastMatch returns the phrase and profile of the latest fire when the engine routes per phrase

func ImageGenScopedRegistry

func ImageGenScopedRegistry() plugins.ScopedRegistry

Plugin facing registry that register_image_gen_provider writes into, a plugin host object stored as the provider adapted from it

func IsAudioOutputActive

func IsAudioOutputActive() bool

IsAudioOutputActive reports whether any real speaker playback is in flight

func IsContinuousActive

func IsContinuousActive() bool

IsContinuousActive reports whether a continuous voice loop is running

func IsListening

func IsListening() bool

IsListening reports an armed detector with a live reader

func IsTTSEcho

func IsTTSEcho(transcript, spokenText string) bool

Whether a transcript reads as speaker bleed of the spoken reply at the default similarity

func IsVoiceStopPhrase

func IsVoiceStopPhrase(transcript string) bool

Whether the whole utterance is a configured voice stop phrase

func IsWhisperHallucination

func IsWhisperHallucination(transcript string) bool

Whether a transcript is empty or a known Whisper hallucination, for callers outside the package

func ListeningFor

func ListeningFor(owner any) (phrase, provider string, ok bool)

Phrase and provider owner's running detector was built for, false when owner holds no detector

func LoadOpenWakeWordLibrary

func LoadOpenWakeWordLibrary(ctx context.Context) error

Loads the tensorflowlite_c library from the pyopen_wakeword package in the runtime environment

func LoadPorcupineLibrary

func LoadPorcupineLibrary(ctx context.Context) error

Loads the Porcupine library from the pvporcupine package in the runtime environment

func LoadTTSConfig

func LoadTTSConfig(ctx context.Context, env *tools.Env) map[string]any

Text to speech section of the active config with its defaults

func LoadWakeWordConfig

func LoadWakeWordConfig(ctx context.Context) map[string]any

LoadWakeWordConfig returns the wake_word config section shape guarded to a dict

func MarkAudioOutputActive

func MarkAudioOutputActive(active bool)

MarkAudioOutputActive counts one real speaker playback in or out, never below zero

func MarkSpeechInterrupted

func MarkSpeechInterrupted()

MarkSpeechInterrupted latches that the user cut a spoken reply off before it finished

func OwnsListener

func OwnsListener(owner any) bool

OwnsListener reports whether owner holds the wake word lease

func PauseListening

func PauseListening(owner any) bool

PauseListening releases the microphone only when owner holds the lease

func PlayAudioFile

func PlayAudioFile(filePath string) bool

PlayAudioFile plays a file through sounddevice or the system players, counted as speaker output throughout

func PlayBeep

func PlayBeep(ctx context.Context, frequency int, duration float64, count int)

PlayBeep plays count sine beeps at the configured volume, through a temp file on macOS

func RegisterTranscriptionProvider

func RegisterTranscriptionProvider(p TranscriptionProvider, scope string) error

Registers a plugin transcription provider, a built in name ignored with a warning

func ReleaseTTSLease

func ReleaseTTSLease(ctx context.Context, env *tools.Env, lease string) map[string]any

Drops a lease, the last one out starting the keep warm window before resident models unload

func ReleaseTTSProvider

func ReleaseTTSProvider(ctx context.Context, env *tools.Env, providerName string) map[string]any

Clears the resident local model caches, one named provider or all and the configured user provider signalled

func ResumeListening

func ResumeListening(owner any) (bool, error)

ResumeListening reopens the microphone only when owner holds the lease

func SaveURLImage

func SaveURLImage(ctx context.Context, env *tools.Env, rawURL, prefix string) (string, error)

Downloads a provider image URL into the generated images cache with the sixty second and 25 MiB defaults

func SetVoiceBusyProbe

func SetVoiceBusyProbe(probe func() bool)

SetVoiceBusyProbe registers the agent busy probe that holds silent cycles, nil clearing it

func SherpaOnnxAvailable

func SherpaOnnxAvailable() bool

Whether the speech engine behind the sherpa wake word publishes a library for this platform

func SilentAudioHint

func SilentAudioHint(details WakeInputDeviceDetails) string

SilentAudioHint returns the platform remediation for an armed stream delivering silence

func SilkToWAVAtRate

func SilkToWAVAtRate(ctx context.Context, src, dst string, rate int) error

Decodes a SILK file to WAV at the sample rate with pilk in the managed interpreter, ErrPilkMissing without pilk

func SpeakText

func SpeakText(ctx context.Context, text string, stop *pythread.Event)

SpeakText synthesizes and plays text, pausing live capture so the reply never feeds back into the mic

func SpeechSample

func SpeechSample(ctx context.Context) (string, string, error)

Bundled voice sample on disk with the words it speaks, the reference a speech to text check transcribes

func StartContinuous

func StartContinuous(ctx context.Context, o ContinuousOptions) (bool, error)

StartContinuous starts the VAD driven loop, false while a stop is still transcribing

func StartThinkingSound

func StartThinkingSound(ctx context.Context, shouldPlay func() bool) bool

StartThinkingSound starts the ambient blip loop once, false when voice.thinking_sound disables it

func StopContinuous

func StopContinuous(ctx context.Context, forceTranscribe bool)

StopContinuous ends the loop and releases the mic, transcribing the live capture first when forced

func StopListening

func StopListening(owner any) bool

StopListening fully stops the detector only when owner holds the lease

func StopPlayback

func StopPlayback()

StopPlayback terminates the running player process and stops sounddevice playback

func StopThinkingSound

func StopThinkingSound()

StopThinkingSound stops the blip loop at once, a no op when none runs

func StreamTTSToFiles

func StreamTTSToFiles(ctx context.Context, textQueue TextQueue, stopEvent, ttsDoneEvent Event, provider string, deliver func(path string) bool)

Cuts queued text deltas into sentences and hands each sentence's audio file to deliver in order, the file removed after

func StreamTTSToSpeaker

func StreamTTSToSpeaker(ctx context.Context, textQueue TextQueue, stopEvent, ttsDoneEvent Event, displayCallback func(string), provider string)

Cuts queued text deltas into sentences and speaks each one as soon as it completes

func TTSScopedRegistry

func TTSScopedRegistry() plugins.ScopedRegistry

Plugin facing registry that register_tts_provider writes into, a plugin host object stored as the provider adapted from it

func TakeSpeechInterrupted

func TakeSpeechInterrupted() bool

TakeSpeechInterrupted pops the latch, true when a barge in happened within the last two minutes

func TextToSpeechTool

func TextToSpeechTool(ctx context.Context, text, outputPath string) (string, error)

TextToSpeechTool speaks text into the output path for gateway auto TTS, returning the tool result envelope

func TranscribeAudio

func TranscribeAudio(ctx context.Context, filePath, model, source string) (map[string]any, error)

TranscribeAudio validates, preprocesses supported inputs and dispatches transcription, source labelling the caller surface

func TranscribeAudioLocalFallback

func TranscribeAudioLocalFallback(ctx context.Context, filePath, model string) (map[string]any, error)

TranscribeAudioLocalFallback tries an installed local backend without installing anything or falling through to cloud

func TranscribeRecording

func TranscribeRecording(ctx context.Context, wavPath, model string) (map[string]any, error)

TranscribeRecording returns the live transcript or transcribes the WAV, filtering Whisper hallucinations

func TranscriptionScopedRegistry

func TranscriptionScopedRegistry() plugins.ScopedRegistry

Plugin facing registry that register_transcription_provider writes into, a plugin host object stored as the provider adapted from it

func VideoGenScopedRegistry

func VideoGenScopedRegistry() plugins.ScopedRegistry

Plugin facing registry that register_video_gen_provider writes into, a plugin host object stored as the provider adapted from it

func VoiceStopHint

func VoiceStopHint() string

Spoken stop hint from the first configured stop phrase, empty when disabled

func WakePhrase

func WakePhrase(ctx context.Context, cfg map[string]any) string

Wake phrase of the config, the icebath default when blank

func WakeSurfaceEnabled

func WakeSurfaceEnabled(ctx context.Context, surface string, cfg map[string]any) bool

WakeSurfaceEnabled reports whether a cli, tui or gui surface may host the enabled listener

func WarmTTSProvider

func WarmTTSProvider(ctx context.Context, env *tools.Env, ttsConfig map[string]any, providerName string) map[string]any

Warms the configured or named TTS provider, loading local engines and signalling user providers

Types

type AudioEnvironment

type AudioEnvironment struct {
	Available bool     `json:"available"`
	Warnings  []string `json:"warnings"`
	Notices   []string `json:"notices"`
}

AudioEnvironment is the detect_audio_environment verdict

func DetectAudioEnvironment

func DetectAudioEnvironment() (AudioEnvironment, error)

Whether this host can record and play audio, with blocking warnings and informational notices

type AudioRecorder

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

AudioRecorder captures through PortAudio with speech confirmation, silence auto stop and a length cap

func NewAudioRecorder

func NewAudioRecorder() *AudioRecorder

NewAudioRecorder is an idle recorder with the default silence parameters

func (*AudioRecorder) Cancel

func (r *AudioRecorder) Cancel()

func (*AudioRecorder) CurrentRMS

func (r *AudioRecorder) CurrentRMS() int

Level of the latest audio block

func (*AudioRecorder) ElapsedSeconds

func (r *AudioRecorder) ElapsedSeconds() float64

Seconds since recording started, zero while idle

func (*AudioRecorder) IsRecording

func (r *AudioRecorder) IsRecording() bool

func (*AudioRecorder) PeakRMS

func (r *AudioRecorder) PeakRMS() int

PeakRMS is the loudest frame level of the current capture

func (*AudioRecorder) SetMaxRecordingSeconds

func (r *AudioRecorder) SetMaxRecordingSeconds(seconds float64)

func (*AudioRecorder) SetOnLivePartial

func (r *AudioRecorder) SetOnLivePartial(fn func(string))

func (*AudioRecorder) SetSilenceDuration

func (r *AudioRecorder) SetSilenceDuration(seconds float64)

func (*AudioRecorder) SetSilenceThreshold

func (r *AudioRecorder) SetSilenceThreshold(threshold float64)

func (*AudioRecorder) Shutdown

func (r *AudioRecorder) Shutdown()

Discards the recording and releases the input stream

func (*AudioRecorder) Start

func (r *AudioRecorder) Start(ctx context.Context, onSilenceStop func()) error

Starts capture at the input device rate, a PortAudio that cannot load reported with its remedy

func (*AudioRecorder) Stop

func (r *AudioRecorder) Stop() (string, error)

Ends capture and returns the WAV path, parking the live session under it

func (*AudioRecorder) SupportsSilenceAutostop

func (r *AudioRecorder) SupportsSilenceAutostop() bool

type ContinuousCallbacks

type ContinuousCallbacks struct {
	OnTranscript  func(string)
	OnStatus      func(string)
	OnSilentLimit func()
	OnStopPhrase  func(string)
}

Callbacks of the active continuous loop

type ContinuousOptions

type ContinuousOptions struct {
	ContinuousCallbacks
	SilenceThreshold    float64
	SilenceDuration     float64
	AutoRestart         bool
	MaxRecordingSeconds any
	OnPartial           func(string)
}

Options of one continuous voice loop

type DuplexOptions

type DuplexOptions struct {
	IsPlaying         func() bool
	OnTrigger         func(phase string)
	Multiplier        float64
	SustainedMS       int
	CalibrationMS     int
	GraceMS           int
	PreRollMS         int
	EndpointSilenceMS int
	MaxUtteranceMS    int
}

DuplexOptions are the full_duplex_listen keywords, a zero Multiplier meaning the default

func DefaultDuplexOptions

func DefaultDuplexOptions() DuplexOptions

DefaultDuplexOptions are the full_duplex_listen defaults

type Event

type Event interface {
	Set()
	Clear()
	IsSet() bool
	Wait(timeout time.Duration) bool
}

Threading event surface of the stop and done signals

type ImageGenProvider

type ImageGenProvider interface {
	provider.CatalogProviderBase
	// Whether credentials resolve under the profile home and secret scope the context binds
	AvailableIn(ctx context.Context) bool
	Capabilities() map[string]any
	Generate(ctx context.Context, env *tools.Env, req ImageGenRequest) (map[string]any, error)
}

Image generation backend selected by image_gen.provider

func GetActiveImageGenProvider

func GetActiveImageGenProvider(ctx context.Context, env *tools.Env) ImageGenProvider

Configured provider even when unavailable, else the single available one, else an available fal

func GetImageGenProvider

func GetImageGenProvider(ctx context.Context, name, scope string) ImageGenProvider

Provider registered under the name, scoped registration first, nil when absent

func ListImageGenProviders

func ListImageGenProviders(ctx context.Context, scope string) []ImageGenProvider

Registered image generation providers sorted by name

type ImageGenRequest

type ImageGenRequest struct {
	Prompt             string
	AspectRatio        string
	ImageURL           string
	ReferenceImageURLs []string
	Kwargs             map[string]any
}

One image_generate call as the provider sees it, Kwargs carrying upscale, model and creative controls

type Resampler

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

Resampler converts s16le mono PCM between rates across chunk boundaries, averaging integer ratios

func NewResampler

func NewResampler(src, dst int) *Resampler

NewResampler resamples from src to dst Hz

func (*Resampler) Resample

func (r *Resampler) Resample(pcm []byte) []byte

Resample converts one chunk, carrying the unconsumed tail into the next call

type SentenceChunker

type SentenceChunker struct {
	MinLen int
	// contains filtered or unexported fields
}

SentenceChunker cuts streamed LLM text into speakable sentences, dropping think blocks and merging short heads

func NewSentenceChunker

func NewSentenceChunker(minLen int) *SentenceChunker

NewSentenceChunker merges fragments shorter than minLen into the next sentence

func SentenceChunkerFromConfig

func SentenceChunkerFromConfig(ttsConfig map[string]any) *SentenceChunker

SentenceChunkerFromConfig honours tts.streaming.min_len with a floor of 1, the default 20 for a bad value

func (*SentenceChunker) Buffered

func (c *SentenceChunker) Buffered() string

Text held back for the next sentence, the chunker buf the idle flush inspects

func (*SentenceChunker) Feed

func (c *SentenceChunker) Feed(delta string) []string

Feed absorbs a delta and returns every complete sentence ready to speak, none while a think tag is open

func (*SentenceChunker) Flush

func (c *SentenceChunker) Flush() []string

Flush drains the tail, never speaking an unterminated reasoning block

type StreamingSession

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

StreamingSession feeds 16 kHz PCM to a live STT provider on one worker and reports partial and final text

func NewElevenLabsRealtimeSession

func NewElevenLabsRealtimeSession(ctx context.Context, apiKey, baseURL, language string, onPartial func(string)) (*StreamingSession, error)

NewElevenLabsRealtimeSession is an ElevenLabs Scribe realtime session committing on VAD

func NewOpenAIRealtimeSession

func NewOpenAIRealtimeSession(ctx context.Context, apiKey, baseURL, model, language, prompt string, onPartial func(string)) (*StreamingSession, error)

NewOpenAIRealtimeSession is a Realtime transcription session resampling 16 kHz input to 24 kHz

func NewXAIStreamingSession

func NewXAIStreamingSession(ctx context.Context, apiKey, baseURL, model, language string, onPartial func(string)) (*StreamingSession, error)

NewXAIStreamingSession is an xAI STT websocket session with interim results

func OpenStreamingSession

func OpenStreamingSession(ctx context.Context, onPartial func(string), sttConfig map[string]any) (*StreamingSession, error)

OpenStreamingSession starts a live session for the active provider, nil when streaming is off or none opens

func (*StreamingSession) Cancel

func (s *StreamingSession) Cancel()

Cancel stops the worker and finishes with a cancelled envelope

func (*StreamingSession) EndAudio

func (s *StreamingSession) EndAudio()

EndAudio marks the end of speech so the provider flushes

func (*StreamingSession) Finalize

func (s *StreamingSession) Finalize(timeout float64) map[string]any

Finalize waits for the transcript envelope, cancelling with an error envelope when the timeout passes

func (*StreamingSession) PartialTranscript

func (s *StreamingSession) PartialTranscript() string

PartialTranscript is the latest non final text

func (*StreamingSession) Provider

func (s *StreamingSession) Provider() string

Provider name of the session

func (*StreamingSession) PushAudio

func (s *StreamingSession) PushAudio(pcm []byte)

PushAudio queues PCM until the session finishes

func (*StreamingSession) SetInputRate

func (s *StreamingSession) SetInputRate(rate int)

SetInputRate resamples pushed audio to 16 kHz when the capture rate differs

func (*StreamingSession) Start

func (s *StreamingSession) Start() *StreamingSession

Start runs the provider worker

type StreamingTTSClass

type StreamingTTSClass struct {
	Available func(ctx context.Context, env *tools.Env) bool
	New       func(env *tools.Env, ttsConfig map[string]any, section any) (StreamingTTSProvider, error)
}

Availability probe and constructor of one registered chunked streamer

type StreamingTTSProvider

type StreamingTTSProvider interface {
	SampleRate() int
	Channels() int
	SampleWidth() int
	Stream(ctx context.Context, text string) (iter.Seq2[[]byte, error], error)
}

Yields int16 little endian mono PCM chunks of one sentence at its current sample rate

func ResolveStreamingProvider

func ResolveStreamingProvider(ctx context.Context, env *tools.Env, ttsConfig map[string]any, preferred string) (StreamingTTSProvider, error)

Returns a ready chunked streamer for the configured provider, nil meaning per sentence synthesis

type TTSNotImplementedError

type TTSNotImplementedError struct{ Message string }

Raised by a provider that has no streaming synthesis

func (*TTSNotImplementedError) Error

func (e *TTSNotImplementedError) Error() string

type TTSOptions

type TTSOptions struct {
	Voice  *string
	Model  *string
	Speed  *float64
	Format string
	Extra  map[string]any
}

Synthesis keyword arguments, a nil pointer meaning the provider default

type TTSProvider

type TTSProvider interface {
	provider.CatalogProviderBase
	ListVoices() []map[string]any
	DefaultVoice() string
	Synthesize(ctx context.Context, text, outputPath string, opts TTSOptions) (string, error)
	Stream(ctx context.Context, text string, opts TTSOptions) (iter.Seq2[[]byte, error], error)
	Warm(ctx context.Context) error
	Release(ctx context.Context) error
	VoiceCompatible() bool
	StreamsPCM() bool
	StreamSampleRate() any
}

Text to speech backend serviced when tts.provider names neither a built in nor a command provider

func GetTTSProvider

func GetTTSProvider(ctx context.Context, name any, scope string) TTSProvider

Provider registered under a string name, scoped registration first, nil for a non string or absent name

func ListTTSProviders

func ListTTSProviders(ctx context.Context, scope string) []TTSProvider

Registered TTS providers sorted by name

type TTSProviderDefaults

type TTSProviderDefaults struct {
	provider.CatalogProviderDefaults
}

Embeddable TTSProvider defaults dispatching through Self, which also binds the catalog defaults

func NewTTSProviderDefaults

func NewTTSProviderDefaults(self TTSProvider) TTSProviderDefaults

Defaults bound to the outer provider

func (TTSProviderDefaults) DefaultVoice

func (d TTSProviderDefaults) DefaultVoice() string

Id of the first voice entry, empty when the catalog is empty or the entry has no string id

func (TTSProviderDefaults) ListVoices

func (TTSProviderDefaults) ListVoices() []map[string]any

Voice catalog entries, empty unless overridden

func (TTSProviderDefaults) Release

Frees resident resources when the last speech lease ends, nothing unless overridden

func (TTSProviderDefaults) Stream

Refuses streaming so the dispatcher falls back to synthesize and a whole file read

func (TTSProviderDefaults) StreamSampleRate

func (TTSProviderDefaults) StreamSampleRate() any

No PCM sample rate unless the provider declares one

func (TTSProviderDefaults) StreamsPCM

func (TTSProviderDefaults) StreamsPCM() bool

Raw PCM streaming is off unless the provider opts in

func (TTSProviderDefaults) VoiceCompatible

func (TTSProviderDefaults) VoiceCompatible() bool

Output is not voice bubble material unless the provider opts in

func (TTSProviderDefaults) Warm

Pre loads resident resources when speech output turns on, nothing unless overridden

type TermuxAudioRecorder

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

TermuxAudioRecorder records through termux-microphone-record without live silence detection

func NewTermuxAudioRecorder

func NewTermuxAudioRecorder() *TermuxAudioRecorder

NewTermuxAudioRecorder is an idle Termux API recorder

func (*TermuxAudioRecorder) Cancel

func (r *TermuxAudioRecorder) Cancel()

Stops the microphone and deletes the partial recording

func (*TermuxAudioRecorder) CurrentRMS

func (r *TermuxAudioRecorder) CurrentRMS() int

Level of the latest audio block

func (*TermuxAudioRecorder) ElapsedSeconds

func (r *TermuxAudioRecorder) ElapsedSeconds() float64

Seconds since recording started, zero while idle

func (*TermuxAudioRecorder) IsRecording

func (r *TermuxAudioRecorder) IsRecording() bool

func (*TermuxAudioRecorder) SetMaxRecordingSeconds

func (r *TermuxAudioRecorder) SetMaxRecordingSeconds(seconds float64)

func (*TermuxAudioRecorder) SetOnLivePartial

func (r *TermuxAudioRecorder) SetOnLivePartial(fn func(string))

func (*TermuxAudioRecorder) SetSilenceDuration

func (r *TermuxAudioRecorder) SetSilenceDuration(seconds float64)

func (*TermuxAudioRecorder) SetSilenceThreshold

func (r *TermuxAudioRecorder) SetSilenceThreshold(threshold float64)

func (*TermuxAudioRecorder) Shutdown

func (r *TermuxAudioRecorder) Shutdown()

func (*TermuxAudioRecorder) Start

func (r *TermuxAudioRecorder) Start(context.Context, func()) error

Starts termux-microphone-record into a new AAC file, failing when the API package or app is missing

func (*TermuxAudioRecorder) Stop

func (r *TermuxAudioRecorder) Stop() (string, error)

Stops the microphone and returns the AAC path, empty for sub 0.3 second taps and empty files

func (*TermuxAudioRecorder) SupportsSilenceAutostop

func (r *TermuxAudioRecorder) SupportsSilenceAutostop() bool

type TextQueue

type TextQueue interface {
	Get(timeout time.Duration) (any, bool)
}

Queue of text deltas the speaker drains, a nil item ending the text

type TranscribeOptions

type TranscribeOptions struct {
	Model    any
	Language any
	Extra    map[string]any
}

Model, language and extra keyword arguments of one plugin transcribe call, nil meaning unset

type TranscriptionProvider

type TranscriptionProvider interface {
	provider.CatalogProviderBase
	Transcribe(ctx context.Context, filePath string, opts TranscribeOptions) (any, error)
	StreamingCapable() bool
	OpenStreamSession(ctx context.Context, language, prompt any) (TranscriptionStreamSession, error)
}

Pluggable speech to text backend registered by plugins under a non built in name

func GetTranscriptionProvider

func GetTranscriptionProvider(ctx context.Context, name, scope string) TranscriptionProvider

Provider registered under a name, scoped registration first, nil when absent

type TranscriptionProviderDefaults

type TranscriptionProviderDefaults struct {
	provider.CatalogProviderDefaults
}

Embeddable TranscriptionProvider defaults dispatching through Self

func NewTranscriptionProviderDefaults

func NewTranscriptionProviderDefaults(self TranscriptionProvider) TranscriptionProviderDefaults

Defaults bound to the outer provider

func (TranscriptionProviderDefaults) OpenStreamSession

Refuses live sessions for providers without streaming support

func (TranscriptionProviderDefaults) StreamingCapable

func (TranscriptionProviderDefaults) StreamingCapable() bool

Live streaming is off unless the provider opts in

type TranscriptionStreamSession

type TranscriptionStreamSession interface {
	PushAudio(chunk []byte) error
	Finalize() (map[string]any, error)
	PartialTranscript() (string, error)
}

Live 16 kHz mono s16le PCM to transcript session for one utterance

type TranscriptionStreamSessionDefaults

type TranscriptionStreamSessionDefaults struct{}

Embeddable stream session default with no partial transcript

type VideoGenProvider

type VideoGenProvider interface {
	provider.CatalogProviderBase
	Capabilities() map[string]any
	Generate(ctx context.Context, env *tools.Env, req VideoGenRequest) (map[string]any, error)
}

Video generation backend selected by video_gen.provider

func GetActiveVideoGenProvider

func GetActiveVideoGenProvider(ctx context.Context, env *tools.Env) VideoGenProvider

Configured provider failing closed when unregistered, else the single available registered provider

func GetVideoGenProvider

func GetVideoGenProvider(ctx context.Context, name, scope string) VideoGenProvider

Provider registered under the name, scoped registration first, nil when absent

func ListVideoGenProviders

func ListVideoGenProviders(ctx context.Context, scope string) []VideoGenProvider

Registered video generation providers sorted by name

type VideoGenRequest

type VideoGenRequest struct {
	Prompt             string
	Model              string
	ImageURL           string
	ReferenceImageURLs []string
	Duration           *int
	AspectRatio        string
	Resolution         string
	NegativePrompt     string
	Audio              *bool
	Seed               *int
	Kwargs             map[string]any
}

One video_generate call as the provider sees it, empty strings standing for omitted arguments

type VoiceRecorder

type VoiceRecorder interface {
	Start(ctx context.Context, onSilenceStop func()) error
	Stop() (string, error)
	Cancel()
	Shutdown()
	IsRecording() bool
	ElapsedSeconds() float64
	CurrentRMS() int
	SupportsSilenceAutostop() bool
	SetOnLivePartial(fn func(string))
	SetSilenceThreshold(threshold float64)
	SetSilenceDuration(seconds float64)
	SetMaxRecordingSeconds(seconds float64)
}

VoiceRecorder is the push to talk recorder create_audio_recorder returns

func CreateAudioRecorder

func CreateAudioRecorder() VoiceRecorder

CreateAudioRecorder picks the Termux API recorder when it can capture, else the PortAudio recorder

type VoiceRequirements

type VoiceRequirements struct {
	Available      bool             `json:"available"`
	AudioAvailable bool             `json:"audio_available"`
	STTAvailable   bool             `json:"stt_available"`
	Details        string           `json:"details"`
	Environment    AudioEnvironment `json:"environment"`
}

VoiceRequirements is the check_voice_requirements verdict

func CheckVoiceRequirements

func CheckVoiceRequirements(ctx context.Context) (VoiceRequirements, error)

CheckVoiceRequirements reports whether capture, an STT provider and the host environment allow voice mode

type WakeDetectorOptions

type WakeDetectorOptions struct {
	Cooldown    *float64
	OnFailure   func(*WakeWordDetector)
	InputDevice any
}

WakeDetectorOptions are the optional keywords of the detector constructor

type WakeEngine

type WakeEngine interface {
	FrameLength() int
	Process(frame []int16) (bool, error)
	Reset() error
	Close()
}

WakeEngine is the hotword engine contract, int16 frames in and a fire verdict out

type WakeInputDeviceDetails

type WakeInputDeviceDetails struct {
	Selector          any      `json:"selector"`
	Error             *string  `json:"error,omitempty"`
	Name              *string  `json:"name,omitempty"`
	MaxInputChannels  *int     `json:"max_input_channels,omitempty"`
	DefaultSamplerate *float64 `json:"default_samplerate,omitempty"`
	HostAPIIndex      *int     `json:"hostapi_index,omitempty"`
	HostAPI           *string  `json:"hostapi,omitempty"`
}

WakeInputDeviceDetails is the JSON safe diagnostic of one PortAudio input selector

func GetInputDeviceStatus

func GetInputDeviceStatus(ctx context.Context, cfg map[string]any) WakeInputDeviceDetails

GetInputDeviceStatus returns the active or configured PortAudio input diagnostics for status UIs

type WakeProfilePhrase

type WakeProfilePhrase struct {
	Profile string
	Phrase  string
}

WakeProfilePhrase pairs a wake enabled profile with its own wake phrase

func EnrolledProfilePhrases

func EnrolledProfilePhrases(ctx context.Context) []WakeProfilePhrase

EnrolledProfilePhrases maps every wake enabled profile to its phrase read raw from its own config

type WakeProviderEntry

type WakeProviderEntry struct {
	Engine string
	Extra  string
}

WakeProviderEntry names the engine class and the pm extra of one provider alias

type WakeRequirements

type WakeRequirements struct {
	Available           bool   `json:"available"`
	Provider            string `json:"provider"`
	DepsAvailable       bool   `json:"deps_available"`
	AudioAvailable      bool   `json:"audio_available"`
	LocalInputAvailable bool   `json:"local_input_available"`
	AccessKeySet        bool   `json:"access_key_set"`
	STTAvailable        bool   `json:"stt_available"`
	TTSAvailable        bool   `json:"tts_available"`
	Phrase              string `json:"phrase"`
	Hint                string `json:"hint"`
}

WakeRequirements reports whether wake word detection can run with a remediation hint

func CheckWakeWordRequirements

func CheckWakeWordRequirements(ctx context.Context, cfg map[string]any, supported func(string) (bool, error)) (WakeRequirements, error)

CheckWakeWordRequirements probes engine support, deps, key, mic, STT and TTS without installing anything

type WakeWordDetector

type WakeWordDetector struct {
	Engine WakeEngine
	// contains filtered or unexported fields
}

WakeWordDetector is the background hotword listener, the engine kept across pause and resume

func NewWakeWordDetector

func NewWakeWordDetector(engine WakeEngine, onWake func() error, opts WakeDetectorOptions) *WakeWordDetector

NewWakeWordDetector builds an idle detector over an engine and the wake callback

func StartListening

func StartListening(ctx context.Context, onWake func() error, owner any, cfg map[string]any) (*WakeWordDetector, error)

StartListening claims, builds and starts the detector, idempotent for its owner and WakeWordInUse for others

func (*WakeWordDetector) AudioSilent

func (d *WakeWordDetector) AudioSilent() bool

AudioSilent reports an open stream delivering only near silent frames

func (*WakeWordDetector) InputDeviceDetails

func (d *WakeWordDetector) InputDeviceDetails() WakeInputDeviceDetails

InputDeviceDetails returns a copy of the diagnostics of the device the detector opened

func (*WakeWordDetector) Pause

func (d *WakeWordDetector) Pause()

Pause releases the microphone and keeps the engine

func (*WakeWordDetector) Resume

func (d *WakeWordDetector) Resume() error

Resume reopens the microphone with the kept engine

func (*WakeWordDetector) Running

func (d *WakeWordDetector) Running() bool

Running reports a live reader goroutine

func (*WakeWordDetector) Start

func (d *WakeWordDetector) Start() error

Opens the microphone and begins listening, a no op while running

func (*WakeWordDetector) Stop

func (d *WakeWordDetector) Stop()

Stop halts the reader and tears the engine down

type WakeWordError

type WakeWordError struct {
	Class string
	Msg   string
	Cause error
}

WakeWordError is a Python exception of the wake word API with its class and cause

func (*WakeWordError) Error

func (e *WakeWordError) Error() string

func (*WakeWordError) Unwrap

func (e *WakeWordError) Unwrap() error

type WakeWordInUse

type WakeWordInUse struct {
	Msg   string
	Cause error
}

WakeWordInUse reports another surface or process owning the wake word microphone

func (*WakeWordInUse) Error

func (e *WakeWordInUse) Error() string

func (*WakeWordInUse) Unwrap

func (e *WakeWordInUse) Unwrap() error

type WaveFile

type WaveFile struct {
	Channels, SampWidth, FrameRate int
	Frames                         []byte
}

Channel count, sample width in bytes, frame rate and frame bytes of a WAV file

func ReadWave

func ReadWave(path string) (*WaveFile, error)

Header fields and frames of a PCM WAV file read the way the wave module opens one

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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