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 ¶
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.
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 ¶
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
}
Output:
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Language is "language" (recognition): "auto" or a BCP 47 tag of one of the model's languages.
func MaxSpeech ¶
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 ¶
MinSilence is "min_silence_duration_ms" (detection): how long the silence after speech lasts before the region ends.
func MinSpeech ¶
MinSpeech is "min_speech_duration_ms" (detection): the shortest a region may last, before its padding, to be kept.
func Prompt ¶
Prompt is "prompt" (recognition): what the model is told of the audio before it hears it, taken as context.
func SpeechPad ¶
SpeechPad is "speech_pad_ms" (detection): the padding added before and after each region.
func Threshold ¶
Threshold is "threshold" (detection): the speech probability, from 0 to 1, from which a chunk counts as speech.
func Timestamps ¶
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. |