speechcpp

package module
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: 8 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.

README

speech-cpp-go

Go bindings for speech.cpp's libspeech, without cgo: the shared library is opened at run time through purego. What bucky is for whisper.cpp.

Pinned to speech.cpp 0.11.3, C API 4.3. The loader refuses a library with another API major or a lower minor.

What it holds

Package Role
pkg/speech Every SPEECH_API function of speech.h (141): models, model information, devices, options, logs, voices, quantize, requests, the five one-shot tasks (synthesize, transcribe, detect, diarize, enhance), the four streaming objects (detection, diarization, enhancement, dialogue), results
pkg/loader Opens libspeech from a file or directory and checks its API version
pkg/download Installs a libspeech release archive (checked against the release's SHA256SUMS) and fetches models by catalog name (checked against their SHA-256, with progress and resume)
pkg/download/catalog The model catalog of the pinned release, embedded
root (speechcpp) A live transcription session: push PCM, Silero detection cuts the utterances, each is transcribed, with periodic partials

The library never reaches the network by itself and never runs the speech executable.

Targets

The Go packages build with CGO_ENABLED=0 for darwin, linux and windows on amd64 and arm64. speech.cpp publishes libspeech for these only:

Target Backends
linux/amd64 (AVX2, FMA, F16C; glibc 2.34 or newer) cpu, vulkan
darwin/arm64 metal
windows/amd64 vulkan

pkg/download returns ErrUnsupportedTarget for any other target; pkg/loader still opens a library you built yourself. The Vulkan builds need the Vulkan loader installed.

Tested on macOS arm64 and on Linux x64 (CPU build, in a container). Windows is compiled and vetted only; it has not been run. On Windows the progress callback goes through ffi's embedded libffi, because Go's Windows callbacks take no floating-point argument; Linux and macOS need no libffi. Importing pkg/speech on Windows therefore initialises ffi, whose init writes its embedded libffi-8.dll to <user cache dir>\github.com\jupiterrider\ffi\libffi\3.8.0\ (os.UserCacheDir, %LocalAppData% by default; FFI_NO_EMBED=1 skips it) and loads it. If it cannot write there it does not fail, it falls back to a libffi-8.dll on the DLL search path; if that cannot be loaded either, the program panics at start-up, before main. On windows/arm64 ffi v0.8.0 does not extract its embedded DLL at all, so libffi-8.dll must be on the search path.

Example

inst, err := download.Library(ctx, download.HostTarget(download.BackendMetal), "", "lib")
if err != nil {
	return err
}
if err := speech.Load(inst.LibraryPath()); err != nil {
	return err
}
defer speech.FreeAll() // free every model before the process ends

recPath, err := download.Model(ctx, "parakeet-tdt-0.6b-v3", "q8_0", "models")
if err != nil {
	return err
}
vadPath, err := download.Model(ctx, "silero-vad", "", "models")
if err != nil {
	return err
}

rec, err := speech.LoadModel(recPath, nil)
if err != nil {
	return err
}
vad, err := speech.LoadModel(vadPath, &speech.LoadParams{Device: "cpu"})
if err != nil {
	return err
}

s, err := speechcpp.NewSession(rec, vad, speechcpp.Config{
	SampleRate:      16000,
	PartialInterval: 700 * time.Millisecond,
	Detection: []speechcpp.Setting{
		speechcpp.MinSilence(500 * time.Millisecond),
		speechcpp.MaxSpeech(20 * time.Second), // bounds the region a live session keeps and re-transcribes
	},
})
if err != nil {
	return err
}
defer s.Close()

go func() {
	for ev := range s.Events() {
		fmt.Println(ev.Kind, ev.Text)
	}
}()

// s.Push(samples) with mono float32 PCM as it arrives; s.End() when the input is over.

Rules of the library worth knowing

  • A model serves one request at a time; requests on one model wait for each other. A request or a streaming object is used by one goroutine at a time; Request.Cancel may be called from any.
  • Every object has an explicit Close; nothing is freed by a finalizer. speech.FreeAll frees every loaded model with its requests, for a shutdown path.
  • A live session without max_speech_duration_s (speechcpp.MaxSpeech) keeps the audio of the region under way and re-transcribes all of it for every partial, so an unbroken stretch of speech makes the region, the memory and each recognition grow without bound. Always set MaxSpeech in Config.Detection.
  • Errors are *speech.Error (status, name, message, the option concerned) and match one sentinel per status with errors.Is; a cancelled call is speech.ErrCancelled.

Development

make test              # unit tests
make test-integration  # fetches the library, the models (optional ones too, about 6.3 GB) into .cache/ first
make test-linux        # both, in a linux/amd64 container
make build-all lint
make catalog MODELS_JSON=models.json   # regenerate the catalog from `speech models --json`

test-integration and test-linux set SPEECH_CPP_REQUIRE_ALL=1: a test whose optional model is missing fails instead of skipping. make test-integration OPTIONAL_MODELS=<name:type,...> REQUIRE_ALL=0 fetches fewer models (the dialogue model haru-4b:q4_k alone is 4.5 GB; go run ./cmd/speech-testdata -h lists the flags) and lets the tests of the missing ones skip.

Integration tests use four LibriSpeech test-clean utterances (CC BY 4.0, Panayotov et al., ICASSP 2015), fetched by cmd/speech-testdata.

Licences

This module: see LICENSE. speech.cpp is MIT. Model weights belong to their authors and carry their own licences (parakeet CC BY 4.0, Qwen3 Apache-2.0, Silero VAD MIT, and others with commercial or ethical restrictions): read a model's licence before you ship it.

Documentation

Overview

Package speechcpp is a live transcription session on speech.cpp's libspeech: audio pushed a piece at a time runs through a streaming detection (Silero VAD), and each region the detection finds is transcribed by a recognition model. The bindings it is built on are in pkg/speech, the library loader in pkg/loader and the downloader of libraries and models in pkg/download.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrClosed      = errors.New("speechcpp: session is closed")
	ErrEnded       = errors.New("speechcpp: session's input has ended")
	ErrConfig      = errors.New("speechcpp: invalid session configuration")
	ErrSettingType = errors.New("speechcpp: setting value of an unsupported type")
)

Errors of a session's own states. A failure of the library is a *speech.Error, wrapped or as is.

Functions

This section is empty.

Types

type Config

type Config struct {
	// SampleRate is the rate in Hz of the mono audio given to Push; the library resamples it to the models' rates.
	SampleRate int

	// PartialInterval is how much pushed audio passes between partials of the region under way; 0 turns partials
	// off. It is counted in audio pushed, not wall-clock time, so audio pushed at real time gets a partial about every
	// interval. At most one partial waits for the recognizer at a time: a newer one replaces it.
	PartialInterval time.Duration

	// Detection are the options of the detection (threshold, min_speech_duration_ms, min_silence_duration_ms,
	// speech_pad_ms, max_speech_duration_s; see Threshold and the other typed settings). The library's defaults hold
	// for those left out.
	Detection []Setting

	// Recognition are the options of every request the session makes on the recognition model, partials and finals
	// alike (language, prompt, timestamps, ...).
	Recognition []Setting
}

Config is what a session is made with.

type Event

type Event struct {
	Kind EventKind

	// Region is the region's index in the order the detection gives regions, from 0. A partial carries the index its
	// region will be given with.
	Region int

	// Start and End are the region's bounds in seconds of the audio pushed: for a final or an error the region as the
	// detection gave it; for a partial the region's start and the end of the audio recognized so far.
	Start float64
	End   float64

	Text      string
	Languages []string // the languages the recognition heard, as BCP 47 tags

	// Segments and Tokens are set when the recognition settings ask for timestamps; their times are in seconds of the
	// audio pushed, as Start and End are. Untimed is the library's reason where it asked for them and got none.
	Segments []speech.Segment
	Tokens   []speech.Token
	Untimed  string

	// Early reports, on a final, that its recognition started when speech_detection_ending said the region's speech
	// had stopped, before the detection gave the region.
	Early bool

	// Err is set on an EventError.
	Err error
}

Event is what a session reports about one region.

type EventKind

type EventKind int

EventKind says what an Event reports.

const (
	// EventPartial is the text of the region under way so far. It comes only while the region is certain to be given
	// (speech_detection_speaking's kept) and its speech has not stopped; it never comes after its region's final or
	// error, nor for a region before the latest one finalised.
	EventPartial EventKind = iota + 1

	// EventFinal is the text of a region as the detection gave it. Each region given gets exactly one final or one
	// error, in the order the regions were given.
	EventFinal

	// EventError is a region whose recognition failed; Err holds why (a *speech.Error where the library failed). The
	// session goes on with the regions after it.
	EventError
)

The kinds of event a session delivers.

func (EventKind) String

func (k EventKind) String() string

type Session

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

Session is a live transcription. One goroutine pushes audio with Push and ends it with End; any goroutine reads Events; Close may be called from any goroutine at any time.

For each region the detection finds, the session delivers zero or more partials while the region is under way, then exactly one final (or one error where its recognition failed), regions in order. The final's recognition starts as soon as speech_detection_ending says the region's speech has stopped and the audio up to the end it reports has been pushed; if speech resumes, or the region is given with other bounds, that recognition is cancelled or its result dropped, and the region given is recognized again, so a final is always the text of the region as the detection gave it.

Push never waits for a recognition or for the reader of Events: recognitions run on the session's goroutine, one at a time, and events wait in a queue. Finals and errors are never dropped; a partial still waiting in the queue is replaced by a newer partial of the same region, so a slow reader sees fewer partials, never stale ones after newer ones. The queue holds at most one partial and the finals and errors not yet read.

The session keeps the audio of the region under way and about a second before it (more where the padding and minimum durations of the detection reach further); with max_speech_duration_s set, that also bounds what it keeps. Audio of a region is let go once its final's recognition has its copy.

The models stay the caller's: the session frees only its detection and its requests. Two sessions may share a recognition model; their requests wait for each other. The models must stay loaded until Close returns.

func NewSession

func NewSession(recognition, detection *speech.Model, cfg Config) (*Session, error)

NewSession starts a live session: a detection on the detection model (Silero VAD) with cfg.Detection, and recognitions on the recognition model with cfg.Recognition. A setting the library refuses is its *speech.Error; the recognition settings are checked here once and applied to every request.

Example

A live transcription of 16 kHz audio with parakeet and Silero VAD: a partial every 700 ms of audio while someone speaks, a final per utterance. The paths are examples; pkg/download fetches the library and the models.

package main

import (
	"fmt"
	"log"
	"time"

	speechcpp "github.com/dlsniper/speech-cpp-go"
	"github.com/dlsniper/speech-cpp-go/pkg/speech"
)

func main() {
	if err := speech.Load(".cache/lib/macos-arm64-metal/libspeech.4.dylib"); err != nil {
		log.Fatal(err)
	}
	defer speech.FreeAll() // on Metal a process that ends with a model loaded aborts

	rec, err := speech.LoadModel(".cache/models/parakeet-tdt-0.6B-v3-Q4_K.gguf", nil)
	if err != nil {
		log.Fatal(err)
	}
	vad, err := speech.LoadModel(".cache/models/silero-vad-309K-v6.2-F32.gguf", nil)
	if err != nil {
		log.Fatal(err)
	}

	s, err := speechcpp.NewSession(rec, vad, speechcpp.Config{
		SampleRate:      16000,
		PartialInterval: 700 * time.Millisecond,
		Detection: []speechcpp.Setting{
			speechcpp.MinSilence(500 * time.Millisecond),
			speechcpp.MaxSpeech(20 * time.Second), // bounds the region a live session keeps and re-transcribes
		},
		Recognition: []speechcpp.Setting{speechcpp.Language("auto")},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer s.Close()

	done := make(chan struct{})
	go func() {
		defer close(done)
		for ev := range s.Events() {
			switch ev.Kind {
			case speechcpp.EventPartial:
				fmt.Printf("… %s\n", ev.Text)
			case speechcpp.EventFinal:
				fmt.Printf("[%.2f–%.2f] %s\n", ev.Start, ev.End, ev.Text)
			case speechcpp.EventError:
				fmt.Printf("[%.2f–%.2f] error: %v\n", ev.Start, ev.End, ev.Err)
			}
		}
	}()

	// Push 20 ms of microphone audio at a time; silence stands in for it here.
	for range 50 {
		if err := s.Push(make([]float32, 320)); err != nil {
			log.Fatal(err)
		}
	}
	if err := s.End(); err != nil { // the last utterance's final, then Events closes
		log.Fatal(err)
	}
	<-done
}

func (*Session) Close

func (s *Session) Close()

Close stops the session: it cancels the recognition under way, drops every event not read, closes Events, and frees the detection and the session's requests (not the models). It returns once nothing of the session runs any more; no event is delivered after it returns. It is idempotent and safe from any goroutine.

func (*Session) End

func (s *Session) End() error

End ends the input: the detection gives the regions left, and End returns once every final (or error) is queued for Events, which then closes when they have been read. It returns the detection's error, if any; ErrEnded when called again; ErrClosed when the session is closed before or while it runs. Close is still needed afterwards.

func (*Session) Events

func (s *Session) Events() <-chan Event

Events delivers the session's events. It is closed once End has run and every event was read, or by Close; no event is delivered after Close returns.

func (*Session) Push

func (s *Session) Push(samples []float32) error

Push gives the session the next mono samples at its rate, copied. It runs the detection on them on the calling goroutine and queues the recognitions they make due; it never waits for a recognition or for the reader of Events. After End it returns ErrEnded, after Close ErrClosed, and after a failed detection push that push's error.

type Setting

type Setting struct {
	Option speech.Option
	Value  any
}

Setting is one option of a request and its value: a string, a bool, an int or int64, or a float64 or float32, matching the option's type (speech.Option.Type). The library checks the value against what the model declares; a value it refuses is a *speech.Error naming the option.

func Language

func Language(tag string) Setting

Language is "language" (recognition): "auto" or a BCP 47 tag of one of the model's languages.

func MaxSpeech

func MaxSpeech(d time.Duration) Setting

MaxSpeech is "max_speech_duration_s" (detection): the longest a region may be, its padding included. It also bounds the audio a session keeps of the region under way.

func MinSilence

func MinSilence(d time.Duration) Setting

MinSilence is "min_silence_duration_ms" (detection): how long the silence after speech lasts before the region ends.

func MinSpeech

func MinSpeech(d time.Duration) Setting

MinSpeech is "min_speech_duration_ms" (detection): the shortest a region may last, before its padding, to be kept.

func Prompt

func Prompt(text string) Setting

Prompt is "prompt" (recognition): what the model is told of the audio before it hears it, taken as context.

func SpeechPad

func SpeechPad(d time.Duration) Setting

SpeechPad is "speech_pad_ms" (detection): the padding added before and after each region.

func Threshold

func Threshold(p float64) Setting

Threshold is "threshold" (detection): the speech probability, from 0 to 1, from which a chunk counts as speech.

func Timestamps

func Timestamps(on bool) Setting

Timestamps is "timestamps" (recognition): whether events carry segments and tokens with their times.

Directories

Path Synopsis
cmd
speech-catalog command
Command speech-catalog turns the output of speech.cpp's `speech models --json` into the model manifest that pkg/download/catalog embeds.
Command speech-catalog turns the output of speech.cpp's `speech models --json` into the model manifest that pkg/download/catalog embeds.
speech-testdata command
Command speech-testdata builds the data the integration tests read, under one directory (.cache by default), from nothing:
Command speech-testdata builds the data the integration tests read, under one directory (.cache by default), from nothing:
internal
catalogfile
Package catalogfile turns the output of speech.cpp's `speech models --json` into the model manifest embedded by pkg/download/catalog, and reads that manifest back.
Package catalogfile turns the output of speech.cpp's `speech models --json` into the model manifest embedded by pkg/download/catalog, and reads that manifest back.
flac
Package flac decodes a FLAC stream into PCM samples, with the standard library only.
Package flac decodes a FLAC stream into PCM samples, with the standard library only.
testaudio
Package testaudio holds what the integration tests share to read audio and score a transcript: a WAVE reader, the word normalization and the word error rate.
Package testaudio holds what the integration tests share to read audio and score a transcript: a WAVE reader, the word normalization and the word error rate.
testenv
Package testenv says where the integration tests find their data: libspeech, the models and the audio that cmd/speech-testdata builds under the module's .cache directory, or what SPEECH_CPP_LIB, SPEECH_CPP_MODELS and SPEECH_CPP_AUDIO name instead.
Package testenv says where the integration tests find their data: libspeech, the models and the audio that cmd/speech-testdata builds under the module's .cache directory, or what SPEECH_CPP_LIB, SPEECH_CPP_MODELS and SPEECH_CPP_AUDIO name instead.
pkg
download
Package download fetches speech.cpp's shared library and its models.
Package download fetches speech.cpp's shared library and its models.
download/catalog
Package catalog is speech.cpp's model catalog for the pinned release, embedded in the module: each model's name, task, languages and weight files, and per file its Hugging Face URL pinned to a revision, size and SHA-256.
Package catalog is speech.cpp's model catalog for the pinned release, embedded in the module: each model's name, task, languages and weight files, and per file its Hugging Face URL pinned to a revision, size and SHA-256.
loader
Package loader opens speech.cpp's shared library, libspeech, at run time and checks that its C API is one this module was written against.
Package loader opens speech.cpp's shared library, libspeech, at run time and checks that its C API is one this module was written against.
speech
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.
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.

Jump to

Keyboard shortcuts

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