Documentation
¶
Overview ¶
Package parakeet transcribes 16 kHz mono PCM using Parakeet TDT v3 and ONNX Runtime.
Example ¶
Transcribe a recording. The model files are downloads (see ASSETS.md); the vocabulary is built in. Long recordings are windowed automatically.
package main
import (
"context"
"fmt"
"log"
parakeet "github.com/androiddrew/go-parakeet"
)
// loadSamples stands in for the application's audio decoding. The engine
// requires 16 kHz mono float32 PCM and performs no resampling.
func loadSamples() []float32 { return make([]float32, parakeet.SampleRate) }
func main() {
engine, err := parakeet.New(parakeet.Config{
ORTLibrary: "libonnxruntime.so", // OS loader name or a path to the library
PreprocessorPath: "assets/parakeet/nemo128.onnx",
EncoderPath: "assets/parakeet/encoder-model.onnx",
DecoderPath: "assets/parakeet/decoder_joint-model.onnx",
})
if err != nil {
log.Fatal(err)
}
defer engine.Close()
result, err := engine.Transcribe(context.Background(), parakeet.Request{
Samples: loadSamples(), SampleRate: parakeet.SampleRate,
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Text)
}
Output:
Example (CallerOwnedEnvironment) ¶
An application that already initializes ONNX Runtime itself leaves ORTLibrary empty. The engine then uses that environment and never destroys it.
package main
import (
"fmt"
"log"
parakeet "github.com/androiddrew/go-parakeet"
ort "github.com/yalue/onnxruntime_go"
)
func main() {
ort.SetSharedLibraryPath("libonnxruntime.so")
if err := ort.InitializeEnvironment(); err != nil {
log.Fatal(err)
}
defer ort.DestroyEnvironment() // runs after engine.Close
engine, err := parakeet.New(parakeet.Config{
PreprocessorPath: "assets/parakeet/nemo128.onnx",
EncoderPath: "assets/parakeet/encoder-model.onnx",
DecoderPath: "assets/parakeet/decoder_joint-model.onnx",
Provider: parakeet.CUDA, // requires an ONNX Runtime build with CUDA
})
if err != nil {
log.Fatal(err)
}
defer engine.Close()
fmt.Println(engine.Initialization().RuntimeVersion)
}
Output:
Index ¶
- Constants
- Variables
- type ChunkOptions
- type ChunkResult
- type Config
- type Engine
- func (e *Engine) Close() error
- func (e *Engine) Initialization() Initialization
- func (e *Engine) ModelInfo() ModelInfo
- func (e *Engine) Transcribe(ctx context.Context, request Request) (Result, error)
- func (e *Engine) TranscribeStream(ctx context.Context, request Request, yield func(ChunkResult) error) (Summary, error)
- type GraphInfo
- type Initialization
- type ModelInfo
- type Provider
- type Request
- type Result
- type Seam
- type Summary
- type TensorInfo
- type Timings
- type Token
Examples ¶
Constants ¶
const ( DefaultWindow = 30 * time.Second DefaultOverlap = 4 * time.Second )
Default long-audio windowing, used when ChunkOptions durations are zero.
const MaxWindowSamples = 300 * SampleRate
MaxWindowSamples bounds each native pass, not the complete recording. It is not a memory guarantee on every GPU or an exact exported-model limit.
const SampleRate = 16000
SampleRate is the required input rate in Hz. Input is mono.
Variables ¶
var ( // ErrNotInitialized is returned by New when ORTLibrary is empty and the // caller has not initialized the ONNX Runtime environment. ErrNotInitialized = ortruntime.ErrNotInitialized // ErrClosed is returned by requests on a closed engine. ErrClosed = errors.New("parakeet engine is closed") // ErrInvalidAudio reports a wrong sample rate, too few samples or a // nonfinite sample. ErrInvalidAudio = errors.New("invalid audio") // ErrAudioTooLong is returned when SinglePass input exceeds MaxWindowSamples. ErrAudioTooLong = errors.New("audio exceeds the single-pass limit") // ErrInvalidChunking reports ChunkOptions outside their documented bounds. ErrInvalidChunking = errors.New("invalid chunking options") // ErrUnstableSeam is returned when an unbroken hypothesis cannot be // finalized within two windows' token budget. Delivered chunks remain valid. ErrUnstableSeam = errors.New("overlap cannot be finalized within bounded context") )
Functions ¶
This section is empty.
Types ¶
type ChunkOptions ¶
type ChunkOptions struct {
Window time.Duration `json:"window"`
Overlap time.Duration `json:"overlap"`
SinglePass bool `json:"single_pass"`
}
ChunkOptions controls complete-audio windowing. Zero values enable automatic chunking with 30-second windows and up to 4 seconds of overlap. Window is 2..300 seconds; Overlap is at most half the window. Durations round down to the 80 ms encoder grid. Zero Overlap selects min(4 seconds, Window/4). A positive overlap must round to at least one frame. SinglePass disables windowing and rejects audio beyond MaxWindowSamples; its durations must be zero.
type ChunkResult ¶
type ChunkResult struct {
Index int `json:"index"`
StartSample int `json:"start_sample"`
EndSample int `json:"end_sample"`
Text string `json:"text"`
Tokens []Token `json:"tokens"`
Seam Seam `json:"seam,omitempty"`
}
ChunkResult is finalized text and owned tokens. Text may start with a space; concatenate it verbatim. The half-open sample span records finalized source coverage, not precise word alignment or the encoder's overlapping window. Seam is empty for the first window.
type Config ¶
type Config struct {
// ORTLibrary is an ONNX Runtime library path or OS-loader name. When set, the
// engine initializes the environment through ortenv, which retains it until
// process exit. When empty, the caller owns the environment and must
// initialize it before New and destroy it only after Close.
ORTLibrary string
PreprocessorPath string // nemo128.onnx
EncoderPath string // encoder-model.onnx (with .onnx.data beside it) or encoder-model.int8.onnx
DecoderPath string // decoder_joint-model.onnx or decoder_joint-model.int8.onnx
// VocabPath overrides the embedded Parakeet TDT v3 vocabulary. Usually empty.
VocabPath string
Provider Provider // empty selects CPU
DeviceID int // CUDA device
Threads int // intra-op threads per session; zero selects 1
Verbose bool // write ORT node-placement diagnostics to stderr
}
Config locates the model assets and configures the sessions.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine owns three model sessions. Requests and Close are serialized. Construct with New; the zero value is not an initialized engine.
func New ¶
New validates assets and tensor metadata and eagerly creates the sessions. Close is mandatory. Concurrent calls on one engine are serialized, including Close.
func (*Engine) Close ¶
Close releases all owned native objects. It is idempotent. The ONNX Runtime environment stays initialized for other engines and later calls to New.
func (*Engine) Initialization ¶
func (e *Engine) Initialization() Initialization
Initialization returns how long New spent in each loading stage.
func (*Engine) ModelInfo ¶
ModelInfo returns an owned metadata copy. Negative dimensions are dynamic.
func (*Engine) Transcribe ¶
Transcribe collects finalized chunks into an owned aggregate result. Long recordings are windowed by default. On error it returns no partial transcript.
func (*Engine) TranscribeStream ¶
func (e *Engine) TranscribeStream(ctx context.Context, request Request, yield func(ChunkResult) error) (Summary, error)
TranscribeStream delivers finalized, caller-owned chunks to yield, in order. Text is final and concatenates verbatim to Transcribe's result. Empty text chunks can report progress through silence. The library retains no aggregate output.
A callback error stops inference; errors.Is/errors.As preserve its identity. Previously delivered chunks survive all errors and engine closure. Summary counts callbacks that returned nil, even if cancellation follows the last one. Callbacks must observe ctx themselves when blocking, and must not call this engine's inference methods or Close. Requests and Close stay serialized during callbacks. Native Run cannot be interrupted mid-call. The complete input audio is supplied up front and must remain unmodified until this method returns.
Example ¶
Stream finalized text into a bounded queue so a consumer can forward it while the next window is decoded.
package main
import (
"context"
"fmt"
"log"
parakeet "github.com/androiddrew/go-parakeet"
)
// loadSamples stands in for the application's audio decoding. The engine
// requires 16 kHz mono float32 PCM and performs no resampling.
func loadSamples() []float32 { return make([]float32, parakeet.SampleRate) }
func main() {
engine, err := parakeet.New(parakeet.Config{
ORTLibrary: "libonnxruntime.so",
PreprocessorPath: "assets/parakeet/nemo128.onnx",
EncoderPath: "assets/parakeet/encoder-model.int8.onnx",
DecoderPath: "assets/parakeet/decoder_joint-model.int8.onnx",
})
if err != nil {
log.Fatal(err)
}
defer engine.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
text := make(chan string, 2)
done := make(chan error, 1)
go func() {
_, err := engine.TranscribeStream(ctx, parakeet.Request{
Samples: loadSamples(), SampleRate: parakeet.SampleRate,
}, func(chunk parakeet.ChunkResult) error {
select {
case text <- chunk.Text:
return nil
case <-ctx.Done():
return ctx.Err()
}
})
close(text)
done <- err
}()
for t := range text {
// Forward to the application's display or transport. Text may begin
// with a space; concatenate chunks verbatim. On a consumer failure,
// cancel() and wait for done before closing the engine.
fmt.Print(t)
}
if err := <-done; err != nil {
log.Print(err) // earlier chunks may already have been delivered
}
}
Output:
type GraphInfo ¶
type GraphInfo struct {
Inputs []TensorInfo `json:"inputs"`
Outputs []TensorInfo `json:"outputs"`
}
GraphInfo describes one ONNX graph's inputs and outputs.
type Initialization ¶
type Initialization struct {
RuntimeVersion string `json:"runtime_version"`
RuntimeSeconds float64 `json:"runtime_initialization_seconds"`
VocabSeconds float64 `json:"vocabulary_loading_seconds"`
ModelSeconds float64 `json:"model_load_seconds"`
}
Initialization is a diagnostic breakdown of New's loading time. ModelSeconds includes metadata inspection, which loads temporary sessions with this binding version, as well as the retained inference sessions. RuntimeVersion is the loaded native ONNX Runtime version.
type ModelInfo ¶
type ModelInfo struct {
Preprocessor GraphInfo `json:"preprocessor"`
Encoder GraphInfo `json:"encoder"`
Decoder GraphInfo `json:"decoder"`
}
ModelInfo describes the three loaded graphs.
type Provider ¶
type Provider string
Provider selects the ONNX Runtime execution provider for the encoder and decoder. Preprocessing always runs on CPU.
type Request ¶
type Request struct {
Samples []float32 `json:"-"`
SampleRate int `json:"sample_rate"`
Chunking ChunkOptions `json:"chunking"`
}
Request supplies already-decoded mono PCM. Samples must remain unmodified until transcription returns. Values must be finite, conventionally in [-1, 1]. No implicit gain, clipping, channel conversion, or resampling is performed.
type Result ¶
type Result struct {
Text string `json:"text"`
Tokens []Token `json:"tokens"`
Chunks []ChunkResult `json:"chunks"`
Summary
}
Result collects the same finalized chunks emitted by TranscribeStream.
type Seam ¶
type Seam string
Seam reports how a chunk was joined to the previous window's hypothesis.
type Summary ¶
type Summary struct {
AudioSeconds float64 `json:"audio_seconds"`
ProcessedSeconds float64 `json:"processed_seconds"`
FinalizedSeconds float64 `json:"finalized_seconds"`
Windows int `json:"windows"`
DeliveredChunks int `json:"delivered_chunks"`
WindowSamples int `json:"window_samples"`
OverlapSamples int `json:"overlap_samples"`
Timings Timings `json:"timings"`
}
Summary has constant size. Windows counts completed decodes; DeliveredChunks counts callbacks that returned nil. On error it includes completed work and timings (including work in a failed window), excluding time in callbacks. ProcessedSeconds is the furthest decoded sample; FinalizedSeconds is the end of the last successfully delivered chunk. Neither implies recognition accuracy.
type TensorInfo ¶
type TensorInfo struct {
Name string `json:"name"`
Shape []int64 `json:"shape"`
Type string `json:"type"`
}
TensorInfo describes one model input or output.
type Timings ¶
type Timings struct {
ValidationSeconds float64 `json:"validation_seconds"`
PreprocessingSeconds float64 `json:"preprocessing_seconds"`
EncoderSeconds float64 `json:"encoder_seconds"`
DecoderSeconds float64 `json:"decoder_seconds"`
AssemblySeconds float64 `json:"assembly_seconds"`
}
Timings is a diagnostic breakdown of one request into disjoint stages, summed over all windows. TranscribeStream excludes time spent in the callback.
type Token ¶
type Token struct {
ID int `json:"id"`
Piece string `json:"piece"`
Frame int `json:"frame"`
StartSeconds float64 `json:"start_seconds"`
Advance int `json:"advance"` // predicted encoder-frame advance, not word duration
}
Token records a nonblank decoder emission. Piece is the raw SentencePiece entry. Frame and StartSeconds are recording-relative emission positions, not aligned word boundaries. Small backwards shifts at seams are clamped to keep the assembled sequence nondecreasing.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
inference-probe
command
inference-probe runs a local model on little-endian float32 mono PCM.
|
inference-probe runs a local model on little-endian float32 mono PCM. |
|
internal
|
|
|
assets
Package assets validates the supported Parakeet export's vocabulary.
|
Package assets validates the supported Parakeet export's vocabulary. |
|
chunking
Package chunking plans frame-aligned, overlapping PCM windows without retaining a per-recording list of windows.
|
Package chunking plans frame-aligned, overlapping PCM windows without retaining a per-recording list of windows. |
|
decoder
Package decoder implements Parakeet's greedy token-and-duration state machine.
|
Package decoder implements Parakeet's greedy token-and-duration state machine. |
|
ortruntime
Package ortruntime decides who owns the process-global ONNX Runtime environment.
|
Package ortruntime decides who owns the process-global ONNX Runtime environment. |