pipeline

package
v0.75.3 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: Apache-2.0 Imports: 20 Imported by: 0 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 pipeline is the composable capture-to-transcript engine of SpeechKit. It implements the contracts declared in the root speechkit package — speechkit.AudioRecorder, speechkit.SegmentCollector, speechkit.Transcriber, speechkit.TranscriptOutput — and wires them into three reusable building blocks:

Hosts that only need the ready-made dictation flow should use github.com/kombifyio/SpeechKit/pkg/speechkit/dictation; this package is for hosts that compose their own pipeline or replace one stage.

Stability: Beta — API-checked; may change with a changelog callout.

Index

Constants

View Source
const (
	DefaultDictationPause                  = 1500 * time.Millisecond
	DefaultDictationMinSegment             = 1200 * time.Millisecond
	DefaultDictationMinIntermediateSegment = 6 * time.Second
	DefaultDictationParagraphPause         = 4 * time.Second
	DefaultDictationPadding                = 480 * time.Millisecond
	DefaultDictationOverlap                = 200 * time.Millisecond
	// DefaultDictationMaxUtterance is the longest stretch of continuous speech
	// the segmenter lets accumulate before it closes the segment without
	// waiting for a pause. Zero disables the cap; hosts that stream segments
	// live (meeting capture) set one, because a call with no 1.5-second pause
	// otherwise yields one 13-minute transcript piece that no downstream
	// model window fits and that the notes cannot show until it ends.
	DefaultDictationMaxUtterance = 0 * time.Second
)

Segmenter tuning defaults, in audio time. DefaultDictationPause is the silence that closes an utterance; DefaultDictationMinSegment the shortest segment emitted (shorter audio is dropped); DefaultDictationMinIntermediateSegment how long an utterance must be before a pause may emit it ahead of Stop; DefaultDictationParagraphPause the silence after which the next segment starts a paragraph; DefaultDictationPadding the silence kept before and after speech; and DefaultDictationOverlap the tail of one segment repeated at the start of the next.

View Source
const (
	// LiveCommitImmediate pastes each provider-final as soon as it arrives.
	LiveCommitImmediate = "immediate"
	// LiveCommitPhrase waits for one sentence (or a short pause) before paste.
	LiveCommitPhrase = "phrase"
	// LiveCommitPassage waits for about two sentences (or a longer pause) so
	// live field injection reads as prose rather than breath-sized fragments.
	LiveCommitPassage = "passage"
	// LiveCommitSession holds every final until the recording stops and
	// commits the whole dictation once, like a full-capture dictation, while
	// the provider still transcribes live.
	LiveCommitSession = "session"
)

Variables

View Source
var (
	ErrMissingRunner      = errors.New("speechkit: transcription worker requires a runner")
	ErrMissingTranscriber = errors.New("speechkit: transcription runner requires a transcriber")
	ErrWorkerClosed       = errors.New("speechkit: transcription worker is closed")
	ErrWorkerQueueFull    = errors.New("speechkit: transcription worker queue is full")
)

Errors of the transcription worker. NewTranscriptionWorker returns ErrMissingRunner without a Runner and ErrMissingTranscriber when the runner has no transcriber; TranscriptionWorker.Submit returns ErrWorkerClosed after Close and ErrWorkerQueueFull when no queue slot is free.

Functions

func CountTerminalSentences

func CountTerminalSentences(text string) int

CountTerminalSentences counts fragments that already look like finished sentences so live commit can wait for a short paragraph instead of a breath.

func FallbackDictationSegments

func FallbackDictationSegments(fullPCM []byte) []speechkit.AudioSegment

FallbackDictationSegments wraps all of fullPCM in a single segment. Used when VAD-based segmentation is unavailable or produces no output.

func JoinTranscriptFragments

func JoinTranscriptFragments(parts ...string) string

JoinTranscriptFragments concatenates live transcript slices with a single separating space when the next slice would otherwise glue onto the previous word or sentence.

func LiveInjectFragment

func LiveInjectFragment(previousSession uint64, previousTail, next string, session uint64) (fragment, tail string, nextSession uint64)

LiveInjectFragment returns the text that should be pasted for this fragment so consecutive live injects keep a word gap without rewriting earlier text.

func NeedsLiveInjectSpace

func NeedsLiveInjectSpace(prev, next string) bool

NeedsLiveInjectSpace reports whether two adjacent live fragments need a separating space when pasted one after the other.

Types

type DictationSegmenter

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

DictationSegmenter implements [SegmentCollector] using VAD-based pause detection to split continuous speech into discrete segments.

func NewDictationSegmenter

func NewDictationSegmenter(detector speechkit.VoiceActivityDetector, pauseThreshold time.Duration) *DictationSegmenter

NewDictationSegmenter builds a segmenter around detector with the DefaultDictation* tuning; pauseThreshold <= 0 selects DefaultDictationPause. It returns nil when detector is nil; a nil segmenter's methods are safe no-ops that fall back to whole-capture segments.

func (*DictationSegmenter) CollectStopSegments

func (s *DictationSegmenter) CollectStopSegments(fullPCM []byte) ([]speechkit.AudioSegment, error)

CollectStopSegments implements speechkit.SegmentCollector. It folds the part of fullPCM that was never fed into the open utterance, flushes that utterance as a final segment behind any segments still waiting to be drained, and resets the detector and session state for the next recording. When no segment was ever produced it returns FallbackDictationSegments of fullPCM; when earlier segments were drained and nothing remains it returns nil. A nil segmenter returns the fallback segment.

func (*DictationSegmenter) DrainReadySegments

func (s *DictationSegmenter) DrainReadySegments() []speechkit.AudioSegment

DrainReadySegments returns pause-bounded intermediate segments that were completed during FeedPCM calls. It leaves the active utterance in place so a later Stop() only flushes the remaining tail.

func (*DictationSegmenter) FeedPCM

func (s *DictationSegmenter) FeedPCM(pcm []byte) error

FeedPCM implements speechkit.SegmentCollector. It buffers pcm (16 kHz S16 mono), runs the detector over each 512-sample frame and keeps utterances closed by a pause for DictationSegmenter.DrainReadySegments and DictationSegmenter.CollectStopSegments. It returns the detector's error; nil receivers and empty input are no-ops. Safe for concurrent use with the Idle* methods.

func (*DictationSegmenter) IdleAudio

func (s *DictationSegmenter) IdleAudio() (time.Duration, time.Time)

IdleAudio reports silence measured in audio time rather than wall-clock time: the cumulative duration of processed silent frames since the last detected speech, plus the wall-clock time of the most recently processed PCM frame. While speech is in progress the silence duration is zero.

Audio-time anchoring makes silence-based auto-stop robust against CPU starvation: when frame delivery stalls, the silence counter freezes instead of counting real seconds against a stale timestamp.

Satisfies the [AudioIdleObserver] contract consumed by RecordingController; preferred over [IdleSince] when available.

func (*DictationSegmenter) IdleSince

func (s *DictationSegmenter) IdleSince() time.Time

IdleSince returns the wall-clock time at which the segmenter most recently transitioned out of speech (or, for a fresh session that has not yet seen speech, the construction time). Returns the zero value when speech is currently being captured — the poller treats zero as "user is actively speaking, silence timer should reset."

Satisfies the [IdleObserver] contract consumed by RecordingController to drive silence-based auto-stop.

func (*DictationSegmenter) SetMaxUtterance added in v0.68.6

func (s *DictationSegmenter) SetMaxUtterance(d time.Duration)

SetMaxUtterance caps how long continuous speech may run before the segmenter emits it as an intermediate segment even without a pause. <=0 disables the cap (the default).

func (*DictationSegmenter) SetMinIntermediateSegment

func (s *DictationSegmenter) SetMinIntermediateSegment(d time.Duration)

SetMinIntermediateSegment configures the minimum active utterance duration that can be emitted before Stop(). Shorter utterances stay merged across natural pauses so dictation does not over-fragment; <=0 emits on every pause-bounded segment.

type LiveCommitFlusher

type LiveCommitFlusher interface {
	FlushLiveCommit(ctx context.Context) error
}

LiveCommitFlusher drains a grouped live-commit buffer. Recording stop calls this so a trailing sentence is not left behind when the stream ends.

type LiveCommitPolicy

type LiveCommitPolicy struct {
	Mode         string
	MinSentences int
	Hold         time.Duration
}

LiveCommitPolicy groups provider-native finals before they reach a sink. Overlay drafts still pass through immediately.

func NormalizeLiveCommitPolicy

func NormalizeLiveCommitPolicy(mode string) LiveCommitPolicy

NormalizeLiveCommitPolicy maps a host mode onto hold/sentence defaults. Empty or unknown modes disable grouping so existing hosts stay immediate.

type PooledPCMRecorder

type PooledPCMRecorder interface {
	SetPooledPCMHandler(func(buf []byte, release func()))
}

PooledPCMRecorder is optionally implemented by AudioRecorders whose backend leases per-frame buffers from a pool instead of allocating a fresh copy per frame (~33 allocations/sec during capture). When the recorder satisfies this interface the controller installs the pool-aware handler and releases each buffer as soon as the frame has been fed to the collector/stream — the controller never retains a frame. Structurally matches app/internal/audio's SetPooledPCMHandler.

type ReadySegmentCollector

type ReadySegmentCollector interface {
	speechkit.SegmentCollector
	DrainReadySegments() []speechkit.AudioSegment
}

ReadySegmentCollector is implemented by collectors that can hand completed pause-bounded segments to the transcription queue before recording stops.

type RecordingController

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

RecordingController manages the start/stop lifecycle of a single recording session and hands audio segments to the submission queue.

func NewRecordingController

func NewRecordingController(recorder speechkit.AudioRecorder, submitter speechkit.JobSubmitter, observer speechkit.RecordingObserver, segmenterFactory speechkit.SegmentCollectorFactory) *RecordingController

NewRecordingController wires a controller to its recorder, the queue that receives finished jobs, an optional observer for status and log lines, and an optional factory that builds a fresh speechkit.SegmentCollector for every Start. Defaults: full-capture submission (no fragmenting, streaming or provider stream), the speechkit.DefaultMinPCMBytes minimum, and a one-second idle poll.

func (*RecordingController) Cancel

Cancel stops the active recorder and discards the captured audio. Hosts use this when the user switches modes mid-capture; submitting the old buffer would deliver stale speech through the newly selected mode.

func (*RecordingController) IsCapturing

func (c *RecordingController) IsCapturing() bool

IsCapturing reports whether the microphone is physically open. Unlike [IsRecording] it excludes the stop/drain window, so hosts can distinguish "user is still dictating" (suppress post-capture UI states) from "capture ended, transcription in flight" (terminal states must display).

func (*RecordingController) IsRecording

func (c *RecordingController) IsRecording() bool

IsRecording reports whether a session is active or still stopping (tail delay and submission); see RecordingController.IsCapturing for the microphone-open state alone. A nil controller reports false.

func (*RecordingController) SetDictationStream

SetDictationStream configures the optional provider-native live dictation path. Hosts can leave this unset to keep the public full-capture default.

func (*RecordingController) SetFragmentSegments

func (c *RecordingController) SetFragmentSegments(enabled bool)

SetFragmentSegments controls whether Stop() submits the VAD-derived segments as the STT source (true) or the full captured audio as a single submission (false, default). The segmenter still drives silence-based auto-stop either way; this only changes what audio is sent to transcription.

func (*RecordingController) SetIdleWatchInterval

func (c *RecordingController) SetIdleWatchInterval(d time.Duration)

SetIdleWatchInterval overrides the polling interval used by the silence-based auto-stop watcher. Tests use this to keep the unit tests fast (e.g. 5ms polling). Production should never touch this.

func (*RecordingController) SetStreamSegments

func (c *RecordingController) SetStreamSegments(enabled bool)

SetStreamSegments controls whether completed pause-bounded segments are submitted during recording instead of waiting until Stop(). The default is false. This is intended for live-ish dictation surfaces; hosts that need the strongest protection against VAD excision should keep the full-capture default.

func (*RecordingController) Start

Start begins a new session: it installs the PCM handler feeding the collector built by the segmenter factory (and, with opts.ProviderStream, the provider-native dictation stream), opens the recorder, and arms the silence watcher when opts.IdleTimeout and opts.OnIdleTimeoutCallback are set and the collector reports idle time. A stream that fails to start is logged and the session falls back to full capture. It reports "recording" (and opts.Label) to the observer on success and returns the recorder's error, leaving the controller idle, when the device fails to open; a nil controller returns an error.

func (*RecordingController) Stop

Stop ends the active session and queues its audio for transcription. After the optional opts.TailDelay it closes the recorder and drops captures that are too short, silent, or implausibly long for the wall-clock window (stale device buffer). A provider-native stream that produced finals completes the session itself; one that failed mid-session leaves the capture after its last committed word to a single job; otherwise one full-capture job is submitted (VAD segments when fragmenting or streaming is enabled) with opts.Label in the log. It returns the submitter's error and reports "processing" or "idle" to the observer, except after a drained provider stream: its sink's commits carry the session's terminal state, so Stop reports none of its own. A no-op while nothing is recording or a stop is in progress.

type TranscriptSessionLedger

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

TranscriptSessionLedger suppresses duplicate final commits for progressive transcription. It tracks both in-flight and completed segments so repeated Stop/Finalize/provider events cannot paste the same text twice.

func NewTranscriptSessionLedger

func NewTranscriptSessionLedger() *TranscriptSessionLedger

NewTranscriptSessionLedger returns an empty ledger. A nil *TranscriptSessionLedger is also usable: every call admits the segment.

func (*TranscriptSessionLedger) Begin

Begin reserves key for an in-flight commit and reports whether the caller may proceed. It returns false when the key was already committed or is being committed by another job. Zero keys (see speechkit.TranscriptSegmentKey.IsZero) and nil ledgers always admit.

func (*TranscriptSessionLedger) Commit

Commit marks key as committed and drops its in-flight reservation; later Begin calls for the key return false.

func (*TranscriptSessionLedger) EndRecordingSession

func (l *TranscriptSessionLedger) EndRecordingSession(recordingSessionID int64)

EndRecordingSession releases deduplication state once a durable recording session has ended. Controllers reconstructed while the recording is active still share the ledger; completed meetings cannot grow it without bound.

func (*TranscriptSessionLedger) Release

Release drops the in-flight reservation taken by Begin without committing, so a segment whose transcription failed can be retried.

type TranscriptionRunner

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

TranscriptionRunner transcribes audio submissions and persists results. Create one with NewTranscriptionRunner.

func NewTranscriptionRunner

func NewTranscriptionRunner(transcriber speechkit.Transcriber, store speechkit.Persistence) *TranscriptionRunner

NewTranscriptionRunner creates a TranscriptionRunner backed by the given transcriber and persistence store. Either argument may be nil.

func (*TranscriptionRunner) Commit

Commit finalizes a transcript: it trims the text, prepends submission.Prefix and persists the result. Quick-note submissions update the note named by QuickNoteID (as a new paragraph when Prefix is set) or create one; other submissions are saved as transcriptions, without audio for captures that name a channel (meetings). The observer is notified afterwards; a nil store skips persistence. It returns ErrMissingRunner on a nil receiver and wrapped store errors, in which case nothing is reported.

func (*TranscriptionRunner) WithObserver

WithObserver sets the speechkit.CommitObserver notified after each successful Commit and returns the runner for chaining (nil for a nil receiver).

type TranscriptionWorker

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

TranscriptionWorker processes [TranscriptionJob] values from an internal queue on a single goroutine. Start it with TranscriptionWorker.Start and submit work with TranscriptionWorker.Submit.

func NewTranscriptionWorker

func NewTranscriptionWorker(cfg TranscriptionWorkerConfig) (*TranscriptionWorker, error)

NewTranscriptionWorker validates cfg and builds a worker that is not yet running; call TranscriptionWorker.Start. It returns ErrMissingRunner or ErrMissingTranscriber for an unusable runner. Defaults: Timeout 30s (the base of the per-segment transcription deadline, which grows with audio length), QueueSize 4, and a private TranscriptSessionLedger when none is shared.

func (*TranscriptionWorker) Close

func (w *TranscriptionWorker) Close()

Close stops accepting jobs and closes the queue so the worker goroutine exits once queued jobs are processed. It does not wait; see TranscriptionWorker.Wait. Idempotent.

func (*TranscriptionWorker) EndDictationStreamSession added in v0.75.1

func (w *TranscriptionWorker) EndDictationStreamSession(ctx context.Context, sessionID uint64, _ speechkit.DictationStreamSinkOptions)

EndDictationStreamSession implements speechkit.DictationStreamSessionEnder. When a delivery was blocked during the session, the held text is inserted once, like a full-capture dictation inserts at the end. If the target still refuses it, the text stays in history as one entry.

func (*TranscriptionWorker) EndRecordingSession

func (w *TranscriptionWorker) EndRecordingSession(recordingSessionID int64)

EndRecordingSession releases deduplication history for a durable recording after its capture lifecycle has ended.

func (*TranscriptionWorker) HandleDictationStreamEvent

HandleDictationStreamEvent routes provider-native dictation events through the same final-commit path as batch transcription. Interim/draft events are UI/status-only and must never call output or persistence.

func (*TranscriptionWorker) Start

func (w *TranscriptionWorker) Start(ctx context.Context)

Start launches the single goroutine that drains the queue. It returns immediately and is idempotent. The goroutine exits when ctx is done or the queue was closed by TranscriptionWorker.Close and drained; a panic in a job is recovered and logged.

func (*TranscriptionWorker) Submit

Submit implements speechkit.JobSubmitter. It stores a copy of job with QueuedAt stamped on the job and its segments and enqueues it without blocking. It returns ErrWorkerClosed after Close and ErrWorkerQueueFull when the queue is full; the caller decides whether to drop or retry.

func (*TranscriptionWorker) Wait

func (w *TranscriptionWorker) Wait()

Wait blocks until the worker goroutine has exited (after Close or context cancellation) and every asynchronous history write has finished. It only returns for a worker that was started.

type TranscriptionWorkerConfig

type TranscriptionWorkerConfig struct {
	Timeout     time.Duration
	QueueSize   int
	Runner      *TranscriptionRunner
	Output      speechkit.TranscriptOutput
	Interceptor speechkit.TranscriptInterceptor
	Transformer speechkit.TranscriptTransformer
	Observer    speechkit.TranscriptionObserver
	Ledger      *TranscriptSessionLedger
	// LowConfidenceThreshold flags recognized words below this acoustic
	// confidence (0..1) so the host can surface likely-misrecognized terms.
	// <= 0 disables the check. Only providers that expose per-word confidence
	// (Deepgram, AssemblyAI) produce data here.
	LowConfidenceThreshold float64
	// Logger receives the worker's diagnostics. Nil falls back to
	// slog.Default() at log time.
	Logger *slog.Logger
}

TranscriptionWorkerConfig configures a TranscriptionWorker. Runner is required; all other fields are optional.

Jump to

Keyboard shortcuts

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