speech

package
v0.11.3 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 12 Imported by: ? 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 speech binds the whole C API of speech.cpp's libspeech (speech.h of speech.cpp 0.11.3, C API 4.3) without cgo.

Load opens the library once per process; every other function needs it. Every object the library returns is a Go type with an explicit, idempotent Close; nothing is freed by a finalizer. The package keeps the set of loaded models, and FreeAll frees every one of them together with the requests and streaming objects made for it: on Metal a process that ends with a model loaded aborts, so a program calls FreeAll (or closes its models) before it exits.

Threads, as speech.h says: a model serves one request at a time; a Request, Detection, Diarization, Enhancement or Dialogue is used by one goroutine at a time, except Request.Cancel, which any goroutine may call; ModelInfo may be read from any goroutine. Close must not run while the object is in use. A callback (audio, frame, progress) runs on the goroutine that made the call and must not call into the library with the same model.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCancelled       = errors.New("speech: cancelled")
	ErrInvalidArgument = errors.New("speech: invalid_argument")
	ErrUnsupported     = errors.New("speech: unsupported")
	ErrOutOfRange      = errors.New("speech: out_of_range")
	ErrModelFile       = errors.New("speech: model_file")
	ErrDevice          = errors.New("speech: device")
	ErrOutOfMemory     = errors.New("speech: out_of_memory")
	ErrIO              = errors.New("speech: io")
	ErrInternal        = errors.New("speech: internal")
)

One sentinel per status that is not StatusOK; every *Error matches the one of its status with errors.Is.

View Source
var ErrClosed = errors.New("speech: object is closed")

ErrClosed is returned by a method of an object whose Close has run.

View Source
var ErrNotLoaded = errors.New("speech: libspeech is not loaded (call speech.Load first)")

ErrNotLoaded is returned by a call made before Load succeeded.

Functions

func APIVersion

func APIVersion() (major, minor int, err error)

APIVersion is the C API version of the loaded library (speech_api_version_major and _minor).

func DeviceCount

func DeviceCount() int

DeviceCount is speech_device_count. The first call that touches a device sets ggml up for the process, and must not run while another thread reads the environment (speech.h, Devices).

func DeviceDescription

func DeviceDescription(index int) (string, bool)

DeviceDescription is speech_device_description, with false past the last device.

func DeviceMemory

func DeviceMemory(index int) (total, free uint64, err error)

DeviceMemory is speech_device_memory: the device's total memory and what is free now, in bytes.

func DeviceName

func DeviceName(index int) (string, bool)

DeviceName is speech_device_name, with false past the last device.

func FreeAll

func FreeAll()

FreeAll closes every loaded model with the requests and streaming objects made for it, for a program's shutdown: on Metal a process that ends with a model loaded aborts. Nothing may be in use while it runs.

func LibraryPath

func LibraryPath() string

LibraryPath is the file Load opened, or "" before Load.

func Load

func Load(path string) error

Load opens libspeech at path, a library file or a directory holding it, checks its C API version (see loader.Open) and binds every function of speech.h. It is done once per process: a later call with the same file returns nil, and one with another file returns an error, since a process cannot hold two of them.

func Loaded

func Loaded() bool

Loaded reports whether Load has succeeded.

func LoadedModels

func LoadedModels() int

LoadedModels is the number of models loaded and not yet closed.

func MakeVoice

func MakeVoice(modelPath, referencePath, voicePath string, params *LoadParams) error

MakeVoice is speech_voice_make: makes a voice file at voicePath from the WAVE recording at referencePath for the model file at modelPath, running the codec's encoder on the device params name (the defaults for nil).

func MakeVoiceFrom

func MakeVoiceFrom(modelPath string, voice *VoiceParams, voicePath string, params *LoadParams) error

MakeVoiceFrom is speech_voice_make_from: makes a voice file at voicePath of voice for the model file at modelPath.

func OptionCount

func OptionCount() int

OptionCount is speech_option_count: the options the loaded library knows, the values from 0 to one below it.

func Quantize

func Quantize(modelPath, typ, outPath string) error

Quantize is speech_quantize: writes the F32 model file at modelPath to outPath with its weights in typ ("F16", "Q8_0", "Q6_K", "Q5_K", "Q4_K" or "IQ4_NL").

func SetLogHandler

func SetLogHandler(fn LogFunc) error

SetLogHandler sends every later log message of the library and of ggml to fn (speech_log_set), or drops every message when fn is nil. Until it is called the library writes warnings and errors to stderr. It holds for the whole process. A panic in fn is recovered and written to stderr, since it cannot unwind through the library.

func StatusName

func StatusName(s Status) (string, bool)

StatusName is speech_status_name: the library's name of s, with false for a value the library does not know.

func Version

func Version() (string, error)

Version is the release of speech.cpp the loaded library was built from, such as "0.11.3".

Types

type AudioFunc

type AudioFunc func(samples []float32) Control

AudioFunc receives audio of a synthesis or an enhancement. samples is a copy the function may keep.

type Control

type Control int32

Control is what a callback returns: Continue, or Stop to stop the call it runs in, which then returns an error that matches ErrCancelled.

const (
	Continue Control = 0
	Stop     Control = 1
)

The values a callback returns.

type Detection

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

Detection is speech_detection: a detection of audio that arrives a piece at a time. It is used by one goroutine at a time; its model's Close frees it if the caller has not.

func (*Detection) Close

func (d *Detection) Close()

Close is speech_detection_free. It is idempotent.

func (*Detection) End

func (d *Detection) End() error

End is speech_detection_end: ends the audio and gives every region left.

func (*Detection) Ending

func (d *Detection) Ending() (ending bool, end float64)

Ending is speech_detection_ending: whether the speech of the region Speaking reports has stopped, with the end it is given with if no speech starts again.

func (*Detection) Push

func (d *Detection) Push(samples []float32) error

Push is speech_detection_push: the next mono samples at the detection's rate, copied.

func (*Detection) Region

func (d *Detection) Region(index int) (Region, error)

Region is speech_detection_region: the region at index in the order given. A region once given never changes.

func (*Detection) RegionCount

func (d *Detection) RegionCount() int

RegionCount is speech_detection_region_count: the regions given so far.

func (*Detection) Regions

func (d *Detection) Regions() ([]Region, error)

Regions lists the regions given so far.

func (*Detection) Speaking

func (d *Detection) Speaking() (speaking bool, start float64, kept bool)

Speaking is speech_detection_speaking: whether a region has begun that is not given yet, with the start it will have and whether it is certain to be given.

type Device

type Device struct {
	Index       int
	Name        string // as a load parameter gives it, such as "MTL0" or "CPU"
	Description string
	Kind        DeviceKind
	TotalMemory uint64 // bytes
	FreeMemory  uint64 // bytes, when Devices was called
}

Device is one device the library can run a model on.

func Devices

func Devices() ([]Device, error)

Devices lists every device with its kind and memory.

type DeviceKind

type DeviceKind int32

DeviceKind is speech_device_kind.

const (
	DeviceCPU  DeviceKind = 0
	DeviceGPU  DeviceKind = 1 // a GPU with memory of its own
	DeviceIGPU DeviceKind = 2 // a GPU that shares the CPU's memory
)

The device kinds of speech.h.

func DeviceKindOf

func DeviceKindOf(index int) (DeviceKind, error)

DeviceKindOf is speech_device_get_kind.

func (DeviceKind) String

func (k DeviceKind) String() string

type Dialogue

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

Dialogue is speech_dialogue: a conversation with a dialogue model, which passes a frame of its audio and text to its callback for each frame of audio it hears. It is used by one goroutine at a time; its model's Close frees it if the caller has not.

func (*Dialogue) Close

func (d *Dialogue) Close()

Close is speech_dialogue_free. It is idempotent.

func (*Dialogue) End

func (d *Dialogue) End() error

End is speech_dialogue_end: ends the conversation, dropping audio short of a whole frame.

func (*Dialogue) Push

func (d *Dialogue) Push(samples []float32) error

Push is speech_dialogue_push: the next mono samples the model hears; it passes the model's next frame for each whole frame of them before it returns.

type DialogueFunc

type DialogueFunc func(samples []float32, text string) Control

DialogueFunc receives a frame of a conversation: the model's audio (a copy the function may keep) and the text it began to say in the frame, often "", a space where it fell silent.

type Diarization

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

Diarization is speech_diarization: a diarization of audio that arrives a piece at a time. It is used by one goroutine at a time; its model's Close frees it if the caller has not.

func (*Diarization) Close

func (d *Diarization) Close()

Close is speech_diarization_free. It is idempotent.

func (*Diarization) End

func (d *Diarization) End() error

End is speech_diarization_end: ends the audio and gives every segment left.

func (*Diarization) Push

func (d *Diarization) Push(samples []float32) error

Push is speech_diarization_push: the next mono samples at the diarization's rate, copied.

func (*Diarization) Segment

func (d *Diarization) Segment(index int) (Segment, error)

Segment is speech_diarization_segment: the segment at index in the order given (Text "").

func (*Diarization) SegmentCount

func (d *Diarization) SegmentCount() int

SegmentCount is speech_diarization_segment_count: the segments given so far.

func (*Diarization) Segments

func (d *Diarization) Segments() ([]Segment, error)

Segments lists the segments given so far.

func (*Diarization) Settled

func (d *Diarization) Settled() float64

Settled is speech_diarization_settled: the time before which the diarization is final; +Inf once the audio ended.

func (*Diarization) Speaking

func (d *Diarization) Speaking(speaker int) (speaking bool, start float64)

Speaking is speech_diarization_speaking: whether speaker has a segment that began before Settled and goes on past it, with its start.

type Enhancement

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

Enhancement is speech_enhancement: an enhancement of audio that arrives a piece at a time, passing the enhanced audio to its callback during Push and End. It is used by one goroutine at a time; its model's Close frees it if the caller has not.

func (*Enhancement) Close

func (e *Enhancement) Close()

Close is speech_enhancement_free. It is idempotent.

func (*Enhancement) End

func (e *Enhancement) End() error

End is speech_enhancement_end: ends the audio and passes every sample not yet passed.

func (*Enhancement) Push

func (e *Enhancement) Push(samples []float32) error

Push is speech_enhancement_push: the next mono samples; the enhanced samples they settle reach the callback before it returns. After Stop from the callback it returns an error matching ErrCancelled and takes no more audio.

type Error

type Error struct {
	Op      string // the C function that failed, such as "speech_transcribe"
	Status  Status
	Name    string // the status' name, as speech_status_name gives it
	Message string // speech_last_error of the call
	Option  string // speech_last_error_option of the call: an option's name or an input ("audio", "path", ...), or ""
}

Error is a failed call: its status, the status' name, the library's message and the input it concerns. SPEECH_CANCELLED is an *Error too, matching ErrCancelled.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the sentinel of the error's status, or nil for a status speech.h does not declare.

type LoadParams

type LoadParams struct {
	// Device is "auto" (the default when empty), "gpu", "cpu" or a device's name as DeviceName gives it.
	Device string
	// Threads the CPU computes with, 1 or more; 0 leaves the library's default.
	Threads int
	// Warmup runs a short request of the model's task while loading, so that a GPU's kernels compile before the first
	// request.
	Warmup bool
}

LoadParams are what LoadModel, MakeVoice and MakeVoiceFrom take besides the path (speech_load_params). The zero value, like a nil *LoadParams, is the library's defaults: device "auto", the library's threads, no warm-up.

type LogFunc

type LogFunc func(level LogLevel, text string)

LogFunc receives the library's log messages and ggml's: text is one line or a piece of one, as ggml writes it. It is called on whichever thread is inside the library, so it must be safe for concurrent use.

type LogLevel

type LogLevel int32

LogLevel is speech_log_level: how much a log message matters.

const (
	LogDebug LogLevel = 0
	LogInfo  LogLevel = 1
	LogWarn  LogLevel = 2
	LogError LogLevel = 3
)

The log levels of speech.h.

func (LogLevel) String

func (l LogLevel) String() string

type MetaEntry

type MetaEntry struct {
	Key   string
	Value string
}

MetaEntry is one metadata entry of the model file: its key and its value as JSON text.

type Model

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

Model is speech_model: a loaded model on its device, with its voices. A model serves one request at a time.

The model keeps the requests and streaming objects made for it; Close frees them before the model, as speech.h requires, and FreeAll does so for every loaded model.

func LoadModel

func LoadModel(path string, params *LoadParams) (*Model, error)

LoadModel is speech_model_load: loads the model file at path on the device params name (the defaults for nil).

func (*Model) AddVoice

func (m *Model) AddVoice(name, path string) error

AddVoice is speech_voice_add: adds a voice named name from a voice file or a WAVE recording at path.

func (*Model) Close

func (m *Model) Close()

Close frees every request and streaming object made for the model and still open, then the model (speech_model_free). None of them may be in use. A Close that comes while another goroutine makes a request or a streaming object, reads the model's Info or adds a voice waits for that call, then frees what it made; those calls return ErrClosed once Close has begun. A callback must not close its own model. It is idempotent.

func (*Model) Info

func (m *Model) Info() (*ModelInfo, error)

Info is speech_model_get_info: the model's information now, with its device and the voices added so far. The caller closes it.

func (*Model) NewRequest

func (m *Model) NewRequest() (*Request, error)

NewRequest is speech_request_new: a request for the model with no input and no option set. Model.Close frees it if the caller has not.

func (*Model) Path

func (m *Model) Path() string

Path is the file the model was loaded from.

type ModelInfo

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

ModelInfo is speech_model_info: what a model file says about its model, read without the weights (OpenModelInfo), or taken from a loaded model (Model.Info). It never changes once made and any goroutine may read it. Its methods return zero values once it is closed.

func OpenModelInfo

func OpenModelInfo(path string) (*ModelInfo, error)

OpenModelInfo is speech_model_info_open: the information of the model file at path, checked as loading checks it short of the weights, without touching a device.

func (*ModelInfo) Architecture

func (mi *ModelInfo) Architecture() string

Architecture is general.architecture, the family, such as "fastconformer".

func (*ModelInfo) Basename

func (mi *ModelInfo) Basename() string

Basename is general.basename, the model's line.

func (*ModelInfo) Close

func (mi *ModelInfo) Close()

Close is speech_model_info_free. It is idempotent.

func (*ModelInfo) Device

func (mi *ModelInfo) Device() (string, bool)

Device is the device a loaded model runs on, with false for information read from a file.

func (*ModelInfo) FileBytes

func (mi *ModelInfo) FileBytes() uint64

FileBytes is the size of the model file.

func (*ModelInfo) Finetune

func (mi *ModelInfo) Finetune() (string, bool)

Finetune is general.finetune, with false for a model that has none.

func (*ModelInfo) FrameSamples

func (mi *ModelInfo) FrameSamples() int

FrameSamples is the samples of a dialogue model's frame; 0 for other tasks.

func (*ModelInfo) Incremental

func (mi *ModelInfo) Incremental() bool

Incremental reports whether a synthesis model passes audio while it still generates the rest.

func (*ModelInfo) JSON

func (mi *ModelInfo) JSON() string

JSON is all of the information as one JSON object, as `speech info --json` writes it.

func (*ModelInfo) Language

func (mi *ModelInfo) Language(index int) (string, bool)

Language is the language at index as a BCP 47 tag, with false past the end.

func (*ModelInfo) LanguageCount

func (mi *ModelInfo) LanguageCount() int

LanguageCount is speech_model_info_language_count.

func (*ModelInfo) Languages

func (mi *ModelInfo) Languages() []string

Languages lists the model's languages.

func (*ModelInfo) Layout

func (mi *ModelInfo) Layout() uint32

Layout is the version of the family's file layout the file has.

func (*ModelInfo) License

func (mi *ModelInfo) License() string

License is general.license, an SPDX expression.

func (*ModelInfo) MaxTextTokens

func (mi *ModelInfo) MaxTextTokens() int

MaxTextTokens is the most tokens of text a synthesis request may have; 0 for other tasks.

func (*ModelInfo) Meta

func (mi *ModelInfo) Meta() []MetaEntry

Meta lists every metadata entry.

func (*ModelInfo) MetaCount

func (mi *ModelInfo) MetaCount() int

MetaCount is the number of metadata entries in the model file.

func (*ModelInfo) MetaKey

func (mi *ModelInfo) MetaKey(index int) (string, bool)

MetaKey is the key of the metadata entry at index, with false past the end.

func (*ModelInfo) MetaValue

func (mi *ModelInfo) MetaValue(index int) (string, bool)

MetaValue is the value of the metadata entry at index as JSON text, with false past the end.

func (*ModelInfo) Name

func (mi *ModelInfo) Name() string

Name is general.name, such as "parakeet-tdt-0.6b-v3".

func (*ModelInfo) OptionAt

func (mi *ModelInfo) OptionAt(index int) Option

OptionAt is the option at index of those the model takes, in the vocabulary's order.

func (*ModelInfo) OptionChoice

func (mi *ModelInfo) OptionChoice(o Option, index int) (string, bool)

OptionChoice is the value at index of those a string option takes, with false past the end.

func (*ModelInfo) OptionChoiceCount

func (mi *ModelInfo) OptionChoiceCount(o Option) int

OptionChoiceCount is the number of values a string option takes; 0 for free text and other types.

func (*ModelInfo) OptionChoices

func (mi *ModelInfo) OptionChoices(o Option) []string

OptionChoices lists the values a string option takes.

func (*ModelInfo) OptionCount

func (mi *ModelInfo) OptionCount() int

OptionCount is the number of options the model takes.

func (*ModelInfo) OptionDefaultBool

func (mi *ModelInfo) OptionDefaultBool(o Option) (bool, error)

OptionDefaultBool is the default of a boolean option.

func (*ModelInfo) OptionDefaultFloat

func (mi *ModelInfo) OptionDefaultFloat(o Option) (float64, error)

OptionDefaultFloat is the default of a number option.

func (*ModelInfo) OptionDefaultInt

func (mi *ModelInfo) OptionDefaultInt(o Option) (int64, error)

OptionDefaultInt is the default of an integer option.

func (*ModelInfo) OptionDefaultString

func (mi *ModelInfo) OptionDefaultString(o Option) (string, error)

OptionDefaultString is the default of a string option.

func (*ModelInfo) OptionHasDefault

func (mi *ModelInfo) OptionHasDefault(o Option) bool

OptionHasDefault reports whether o has a default the model uses when a request does not set it.

func (*ModelInfo) OptionRange

func (mi *ModelInfo) OptionRange(o Option) (Range, error)

OptionRange is speech_model_info_option_range.

func (*ModelInfo) OptionRequired

func (mi *ModelInfo) OptionRequired(o Option) bool

OptionRequired reports whether a request to the model must set o.

func (*ModelInfo) OptionSteers

func (mi *ModelInfo) OptionSteers(o Option) bool

OptionSteers reports whether o's value steers the model, rather than only being checked.

func (*ModelInfo) Options

func (mi *ModelInfo) Options() []Option

Options lists the options the model takes.

func (*ModelInfo) Organization

func (mi *ModelInfo) Organization() string

Organization is general.organization, such as "nvidia".

func (*ModelInfo) SampleRate

func (mi *ModelInfo) SampleRate() int

SampleRate in Hz of the audio the model makes or takes; 0 for an enhancement model.

func (*ModelInfo) SizeLabel

func (mi *ModelInfo) SizeLabel() string

SizeLabel is general.size_label, such as "0.6B".

func (*ModelInfo) Source

func (mi *ModelInfo) Source() (repository, revision string, err error)

Source is speech_model_info_source: the repository URL the file was converted from and the revision converted.

func (*ModelInfo) Speakers

func (mi *ModelInfo) Speakers() int

Speakers is the most speakers a diarization model tells apart; 0 for other tasks.

func (*ModelInfo) Takes

func (mi *ModelInfo) Takes(o Option) bool

Takes reports whether the model takes o.

func (*ModelInfo) Task

func (mi *ModelInfo) Task() Task

Task is what the model does.

func (*ModelInfo) TextTokens

func (mi *ModelInfo) TextTokens(text string) (int, error)

TextTokens is speech_model_info_text_tokens: the model's tokens text takes, as a synthesis request counts them.

func (*ModelInfo) Threads

func (mi *ModelInfo) Threads() int

Threads is the threads the CPU computes a loaded model's graphs with; 0 for information read from a file and for a model none of whose graphs runs on the CPU.

func (*ModelInfo) Version

func (mi *ModelInfo) Version() (string, bool)

Version is general.version, such as "v3", with false for a model whose name has none.

func (*ModelInfo) VoiceCodec

func (mi *ModelInfo) VoiceCodec() (string, bool)

VoiceCodec is the hash a voice file must carry for the model, with false for a model that takes no voice files.

func (*ModelInfo) VoiceCount

func (mi *ModelInfo) VoiceCount() int

VoiceCount is speech_model_info_voice_count: the model's own voices, then those added with Model.AddVoice.

func (*ModelInfo) VoiceDescription

func (mi *ModelInfo) VoiceDescription(index int) (string, bool)

VoiceDescription is the model's English description of the voice at index, "" when there is none.

func (*ModelInfo) VoiceFiles

func (mi *ModelInfo) VoiceFiles() bool

VoiceFiles reports whether the model takes voices made from reference recordings.

func (*ModelInfo) VoiceGender

func (mi *ModelInfo) VoiceGender(index int) (string, bool)

VoiceGender is "female" or "male" for the voice at index, "" when the file does not say.

func (*ModelInfo) VoiceLanguage

func (mi *ModelInfo) VoiceLanguage(index int) (string, bool)

VoiceLanguage is the language the voice at index was recorded in, "" when the file does not say.

func (*ModelInfo) VoiceName

func (mi *ModelInfo) VoiceName(index int) (string, bool)

VoiceName is the name of the voice at index, which OptionVoice takes; false past the end.

func (*ModelInfo) VoiceRecordings

func (mi *ModelInfo) VoiceRecordings() bool

VoiceRecordings reports whether Model.AddVoice takes a WAVE recording as well as a voice file.

func (*ModelInfo) Voices

func (mi *ModelInfo) Voices() []Voice

Voices lists the model's voices.

func (*ModelInfo) WeightBytes

func (mi *ModelInfo) WeightBytes() uint64

WeightBytes is what the model's weights take on a device.

func (*ModelInfo) WeightType

func (mi *ModelInfo) WeightType() string

WeightType is general.file_type as ggml names it, such as "Q4_K".

type Option

type Option int32

Option is speech_option: one name of the vocabulary of what a request may ask. A later minor version of the C API only appends values; OptionCount gives the number the loaded library knows.

const (
	OptionVoice                    Option = 0  // "voice"
	OptionLanguage                 Option = 1  // "language"
	OptionSeed                     Option = 2  // "seed"
	OptionSpeed                    Option = 3  // "speed"
	OptionSeconds                  Option = 4  // "seconds"
	OptionDurationScale            Option = 5  // "duration_scale"
	OptionSteps                    Option = 6  // "steps"
	OptionMaxSeconds               Option = 7  // "max_seconds"
	OptionTimestamps               Option = 8  // "timestamps"
	OptionPrompt                   Option = 9  // "prompt"
	OptionDecoding                 Option = 10 // "decoding"
	OptionDoSample                 Option = 11 // "do_sample"
	OptionTopK                     Option = 12 // "top_k"
	OptionTopP                     Option = 13 // "top_p"
	OptionTemperature              Option = 14 // "temperature"
	OptionRepetitionPenalty        Option = 15 // "repetition_penalty"
	OptionCodePredictorDoSample    Option = 16 // "code_predictor_do_sample"
	OptionCodePredictorTopK        Option = 17 // "code_predictor_top_k"
	OptionCodePredictorTopP        Option = 18 // "code_predictor_top_p"
	OptionCodePredictorTemperature Option = 19 // "code_predictor_temperature"
	OptionInstructions             Option = 20 // "instructions"
	OptionCfgScaleText             Option = 21 // "cfg_scale_text"
	OptionCfgScaleSpeaker          Option = 22 // "cfg_scale_speaker"
	OptionCfgGuidanceMode          Option = 23 // "cfg_guidance_mode"
	OptionCfgMinT                  Option = 24 // "cfg_min_t"
	OptionCfgMaxT                  Option = 25 // "cfg_max_t"
	OptionTruncationFactor         Option = 26 // "truncation_factor"
	OptionRescaleK                 Option = 27 // "rescale_k"
	OptionRescaleSigma             Option = 28 // "rescale_sigma"
	OptionSpeakerUncondMode        Option = 29 // "speaker_uncond_mode"
	OptionSwayCoeff                Option = 30 // "sway_coeff"
	OptionKeepTail                 Option = 31 // "keep_tail"
	OptionTailWindowSize           Option = 32 // "tail_window_size"
	OptionTailStdThreshold         Option = 33 // "tail_std_threshold"
	OptionTailMeanThreshold        Option = 34 // "tail_mean_threshold"
	OptionSpeakerKvScale           Option = 35 // "speaker_kv_scale"
	OptionSpeakerKvMinT            Option = 36 // "speaker_kv_min_t"
	OptionSpeakerKvMaxLayers       Option = 37 // "speaker_kv_max_layers"
	OptionCfgScaleInstructions     Option = 38 // "cfg_scale_instructions"
	OptionThreshold                Option = 39 // "threshold"
	OptionMinSpeechDurationMs      Option = 40 // "min_speech_duration_ms"
	OptionMinSilenceDurationMs     Option = 41 // "min_silence_duration_ms"
	OptionSpeechPadMs              Option = 42 // "speech_pad_ms"
	OptionMaxSpeechDurationS       Option = 43 // "max_speech_duration_s"
	OptionDecodeOnCpu              Option = 44 // "decode_on_cpu"
	OptionDraft                    Option = 45 // "draft"
	OptionExpertsOnCpu             Option = 46 // "experts_on_cpu"
	OptionStreamingMode            Option = 47 // "streaming_mode"
	OptionSpkcacheLen              Option = 48 // "spkcache_len"
	OptionFifoLen                  Option = 49 // "fifo_len"
	OptionChunkLen                 Option = 50 // "chunk_len"
	OptionChunkRightContext        Option = 51 // "chunk_right_context"
	OptionSpkcacheUpdatePeriod     Option = 52 // "spkcache_update_period"
	OptionOnset                    Option = 53 // "onset"
	OptionOffset                   Option = 54 // "offset"
	OptionPadOnset                 Option = 55 // "pad_onset"
	OptionPadOffset                Option = 56 // "pad_offset"
	OptionMinDurationOn            Option = 57 // "min_duration_on"
	OptionMinDurationOff           Option = 58 // "min_duration_off"
	OptionSpeakers                 Option = 59 // "speakers"
	OptionKeywords                 Option = 60 // "keywords"
	OptionKeywordsAlpha            Option = 61 // "keywords_alpha"
	OptionKeywordsGuard            Option = 62 // "keywords_guard"
	OptionChunkSizeInSeconds       Option = 63 // "chunk_size_in_seconds"
	OptionHopLengthPortion         Option = 64 // "hop_length_portion"
	OptionBwe                      Option = 65 // "bwe"
	OptionPersona                  Option = 66 // "persona"
	OptionName                     Option = 67 // "name"
	OptionGender                   Option = 68 // "gender"
	OptionBackchannel              Option = 69 // "backchannel"
	OptionOtherName                Option = 70 // "other_name"
	OptionRelationship             Option = 71 // "relationship"
	OptionSituation                Option = 72 // "situation"
	OptionGuidanceScale            Option = 73 // "guidance_scale"
	OptionEopBias                  Option = 74 // "eop_bias"
	OptionSpeakFirst               Option = 75 // "speak_first"
)

The options of speech.h (C API 4.3), with their fixed names.

func OptionFromName

func OptionFromName(name string) (Option, error)

OptionFromName is speech_option_from_name: the option named name in snake_case.

func Options

func Options() []Option

Options lists every option the loaded library knows.

func (Option) Name

func (o Option) Name() (string, bool)

Name is speech_option_name: the option's fixed name in snake_case, with false for a value the library does not know or before Load.

func (Option) String

func (o Option) String() string

String is the option's name, or "option(N)" where the library gives none.

func (Option) Type

func (o Option) Type() Type

Type is speech_option_type. Before Load it returns 0, which is TypeString: check Loaded first.

type ProgressFunc

type ProgressFunc func(done float64) Control

ProgressFunc receives how far a request has come, from 0 to 1.

type Range

type Range struct {
	Min          float64
	Max          float64
	MinExclusive bool // the minimum itself lies outside the range
}

Range is the range of an integer or number option; Min and Max are infinite where the option has no bound.

func (Range) Contains

func (r Range) Contains(v float64) bool

Contains reports whether v lies within r.

type Region

type Region struct {
	Start float64
	End   float64
}

Region is a region of a detection, in seconds from the start of the audio pushed.

type Request

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

Request is speech_request: the input and options of one run of a model's task, and its result. It checks every value as it is set against what its model declares. A request is used by one goroutine at a time, except Cancel, which any goroutine may call. A request that has started its work runs once.

func (*Request) Cancel

func (r *Request) Cancel()

Cancel is speech_request_cancel: stops the request at the next point where its work can stop, after which the run returns an error matching ErrCancelled; one cancelled before it runs does no work. Any goroutine may call it; on a closed request it does nothing.

func (*Request) Close

func (r *Request) Close()

Close is speech_request_free: frees the request and its result. It must not be running. It is idempotent.

func (*Request) Detect

func (r *Request) Detect() error

Detect is speech_detect: finds the regions of the request's audio where someone speaks (Result segments).

func (*Request) Diarize

func (r *Request) Diarize() error

Diarize is speech_diarize: finds who speaks where in the request's audio (Result segments with speakers).

func (*Request) Enhance

func (r *Request) Enhance(onAudio AudioFunc) error

Enhance is speech_enhance: enhances the request's audio, passing it to onAudio as each piece settles.

func (*Request) Model

func (r *Request) Model() *Model

Model is the model the request was made for.

func (*Request) Result

func (r *Request) Result() (*Result, bool)

Result is speech_request_result: the result of a request that ran to SPEECH_OK or SPEECH_CANCELLED, with false before it has run, after it failed and once it is closed. It lives until the request is closed.

func (*Request) SetAudio

func (r *Request) SetAudio(samples []float32, sampleRate int) error

SetAudio is speech_request_set_audio: mono samples, nominally within [-1, 1], at sampleRate Hz, copied.

func (*Request) SetBool

func (r *Request) SetBool(o Option, value bool) error

SetBool is speech_request_set_bool.

func (*Request) SetFloat

func (r *Request) SetFloat(o Option, value float64) error

SetFloat is speech_request_set_float. NaN and the infinities are refused.

func (*Request) SetInt

func (r *Request) SetInt(o Option, value int64) error

SetInt is speech_request_set_int.

func (*Request) SetProgress

func (r *Request) SetProgress(fn ProgressFunc) error

SetProgress is speech_request_set_progress: fn receives how far the request has come while it does work that passes no audio, on the goroutine that runs the request; returning Stop stops it. nil removes the callback.

func (*Request) SetString

func (r *Request) SetString(o Option, value string) error

SetString is speech_request_set_string.

func (*Request) SetText

func (r *Request) SetText(text string) error

SetText is speech_request_set_text: the text a synthesis request speaks.

func (*Request) StartDetection

func (r *Request) StartDetection(sampleRate int) (*Detection, error)

StartDetection is speech_detection_start: a detection of audio at sampleRate Hz with the request's options. The request must have no audio; it is left as it was.

func (*Request) StartDialogue

func (r *Request) StartDialogue(sampleRate int, onFrame DialogueFunc) (*Dialogue, error)

StartDialogue is speech_dialogue_start: a conversation hearing audio at sampleRate Hz with the request's options. It runs the prompt and passes the model's first frame to onFrame before it returns. If onFrame asks to stop there, the conversation is freed and the error matches ErrCancelled.

func (*Request) StartDiarization

func (r *Request) StartDiarization(sampleRate int) (*Diarization, error)

StartDiarization is speech_diarization_start: a diarization of audio at sampleRate Hz with the request's options.

func (*Request) StartEnhancement

func (r *Request) StartEnhancement(sampleRate int, onAudio AudioFunc) (*Enhancement, error)

StartEnhancement is speech_enhancement_start: an enhancement of audio at sampleRate Hz with the request's options, passing the enhanced audio to onAudio. The request must have no audio; it may be closed afterwards.

func (*Request) Synthesize

func (r *Request) Synthesize(onAudio AudioFunc) error

Synthesize is speech_synthesize: speaks the request, passing its audio to onAudio as it is made, at the model's sample rate. Returning Stop from onAudio ends it with an error matching ErrCancelled.

func (*Request) Transcribe

func (r *Request) Transcribe() error

Transcribe is speech_transcribe: recognizes the speech in the request's audio, whole.

type Result

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

Result is speech_result: what a request did. It lives as long as its request; its methods return zero values once the request is closed.

func (*Result) Language

func (res *Result) Language(index int) (string, bool)

Language is the language at index as a BCP 47 tag, with false past the end.

func (*Result) LanguageCount

func (res *Result) LanguageCount() int

LanguageCount is the number of languages a recognition heard.

func (*Result) Languages

func (res *Result) Languages() []string

Languages lists the languages a recognition heard.

func (*Result) Samples

func (res *Result) Samples() uint64

Samples is the number of samples a synthesis or an enhancement passed to its callback.

func (*Result) Seed

func (res *Result) Seed() int64

Seed is the seed a synthesis used; -1 for other tasks, and 0 (like every method) once the request is closed.

func (*Result) Segment

func (res *Result) Segment(index int) (Segment, error)

Segment is the segment at index with its speaker (speech_result_segment and speech_result_segment_speaker).

func (*Result) SegmentCount

func (res *Result) SegmentCount() int

SegmentCount is speech_result_segment_count.

func (*Result) SegmentSpeaker

func (res *Result) SegmentSpeaker(index int) int

SegmentSpeaker is speech_result_segment_speaker: the speaker of the segment at index, or -1.

func (*Result) Segments

func (res *Result) Segments() ([]Segment, error)

Segments lists every segment.

func (*Result) Stop

func (res *Result) Stop() StopReason

Stop is why the request ended.

func (*Result) Text

func (res *Result) Text() (string, bool)

Text is the text a recognition found, with false for a model of another task.

func (*Result) Token

func (res *Result) Token(index int) (Token, error)

Token is speech_result_token: the token at index.

func (*Result) TokenCount

func (res *Result) TokenCount() int

TokenCount is speech_result_token_count.

func (*Result) Tokens

func (res *Result) Tokens() ([]Token, error)

Tokens lists every token.

func (*Result) Untimed

func (res *Result) Untimed() (string, bool)

Untimed is why a recognition that set timestamps or speakers has neither tokens nor segments, with false where it has them or set neither.

type Segment

type Segment struct {
	Start   float64
	End     float64
	Text    string
	Speaker int
}

Segment is a segment of a recognition (with timestamps or speakers), a region of a detection (Text "") or a segment of a diarization (Text ""), in seconds from the start of the audio. Speaker is -1 where there is none.

type Status

type Status int32

Status is speech_status: what a call that can fail returns. A negative value is an error.

const (
	StatusOK              Status = 0
	StatusCancelled       Status = 1
	StatusInvalidArgument Status = -1
	StatusUnsupported     Status = -2
	StatusOutOfRange      Status = -3
	StatusModelFile       Status = -4
	StatusDevice          Status = -5
	StatusOutOfMemory     Status = -6
	StatusIO              Status = -7
	StatusInternal        Status = -8
)

The statuses of speech.h.

func (Status) String

func (s Status) String() string

String is the status' name in snake_case, as speech_status_name gives it, or "status(N)" for one speech.h does not declare.

type StopReason

type StopReason int32

StopReason is speech_stop: why a request ended.

const (
	StopComplete   StopReason = 0
	StopMaxSeconds StopReason = 1
	StopModelLimit StopReason = 2
	StopCancelled  StopReason = 3
)

The stop reasons of speech.h.

func (StopReason) Name

func (s StopReason) Name() (string, bool)

Name is speech_stop_name, with false for a value the library does not know or before Load.

func (StopReason) String

func (s StopReason) String() string

String is the stop reason's name, or "stop(N)" where the library gives none.

type Task

type Task int32

Task is speech_task: what a model does.

const (
	TaskSynthesis   Task = 0
	TaskRecognition Task = 1
	TaskDetection   Task = 2
	TaskDiarization Task = 3
	TaskEnhancement Task = 4
	TaskDialogue    Task = 5
)

The tasks of speech.h.

func (Task) String

func (t Task) String() string

type Token

type Token struct {
	Start float64
	End   float64
	Text  string
}

Token is a token of a recognition with timestamps, in seconds.

type Type

type Type int32

Type is speech_type: the type of an option's values, which names the setter that takes them.

const (
	TypeString Type = 0
	TypeInt    Type = 1
	TypeFloat  Type = 2
	TypeBool   Type = 3
)

The option types of speech.h.

func (Type) String

func (t Type) String() string

type Voice

type Voice struct {
	Name        string
	Language    string // BCP 47 tag, or "" when the file does not say
	Gender      string // "female", "male" or ""
	Description string // in English, or ""
}

Voice describes one voice of a model.

type VoiceParams

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

VoiceParams is speech_voice_params: what MakeVoiceFrom makes a voice file of (several references and their loudness, an embedding, or recordings with transcripts and speakers). It is used by one goroutine at a time.

func NewVoiceParams

func NewVoiceParams() (*VoiceParams, error)

NewVoiceParams is speech_voice_params_new: parameters without a reference, at the model's loudness.

func (*VoiceParams) AddReference

func (vp *VoiceParams) AddReference(path string) error

AddReference is speech_voice_params_add_reference: adds the WAVE recording at path.

func (*VoiceParams) AddVoice

func (vp *VoiceParams) AddVoice(path string) error

AddVoice is speech_voice_params_add_voice: adds the references of the voice file at path as they are.

func (*VoiceParams) Close

func (vp *VoiceParams) Close()

Close is speech_voice_params_free. It is idempotent.

func (*VoiceParams) KeepLoudness

func (vp *VoiceParams) KeepLoudness() error

KeepLoudness is speech_voice_params_keep_loudness: keeps each reference's loudness as recorded.

func (*VoiceParams) SetEmbedding

func (vp *VoiceParams) SetEmbedding(values []float32, tokens, dim int) error

SetEmbedding is speech_voice_params_set_embedding: a speaker-inversion embedding of tokens vectors of dim values, row by row, in place of references. len(values) must be tokens*dim.

func (*VoiceParams) SetLoudness

func (vp *VoiceParams) SetLoudness(lufs float64) error

SetLoudness is speech_voice_params_set_loudness: brings each reference to lufs before it is encoded.

func (*VoiceParams) SetSpeaker

func (vp *VoiceParams) SetSpeaker(speaker int) error

SetSpeaker is speech_voice_params_set_speaker: the speaker, from 0, of what was added last.

func (*VoiceParams) SetTranscript

func (vp *VoiceParams) SetTranscript(text string) error

SetTranscript is speech_voice_params_set_transcript: the words of the reference added last.

Jump to

Keyboard shortcuts

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