hark

package module
v0.0.0-...-1d9bdd4 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 2 Imported by: 1 module, 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

hark

A real-time speech-to-text gateway. Clients stream audio; hark turns the output of any recognition engine into a live transcript with controlled rewrites and explicit finalization.

Features

  • Real-time use of batch-only models: models that can only recognize a whole utterance (SenseVoice, Whisper, file transcription APIs, ...) become streaming. hark segments sentences, re-recognizes while you speak, and finalizes (engine/batch)
  • Rewrites stay sane: changes are pushed as ops (replace characters i through j with this). Text before the commit watermark is guaranteed never to change; stable marks what upstream considers final (protocol)
  • Users can edit while speaking: the client merges recognition results with the user's edits, and edited text is never overwritten by recognition (draft)
  • Personal vocabulary: once a user keeps correcting a word to the same spelling, hark learns to replace it automatically (protocol)
  • Common backends built in: local SenseVoice (sherpa-onnx); Volcengine (Doubao) streaming recognition (volc); any OpenAI-compatible transcription API (OpenAI, Groq, SiliconFlow, self-hosted speaches, vLLM, whisper.cpp, ...) (openai)
  • Pluggable backends: plug in any batch (HTTP) or streaming (WebSocket) recognition service, written in any language, with a config change (http, ws, Python examples); or implement an engine in Go and compile it in (hark.go, harkcmd)
  • Multiple tracks: send the same audio to several engines to compare them, or recognize each channel separately
  • Works in the browser: a single HTML file that transcribes your microphone live; copy it to integrate (examples/browser)
  • Also a Go library: use it inside your own program without running a server, with the same semantics as the server (examples/embedded)
  • Local model included: start hark + SenseVoice with one Docker command, no cloud services needed (deploy)
  • No lost speech on shutdown: sessions in progress get 5 seconds to finish; those that run out are told explicitly that they can retry

Quick start

Start hark + local SenseVoice with Docker (the first build downloads the model):

docker compose -f deploy/docker/compose.yaml up -d --build

Then try it either way:

  • Browser: cd examples/browser && python3 -m http.server 8000, open http://localhost:8000, click Start, and speak into the microphone

  • Command line (requires Go 1.26+): prepare a 16 kHz / 16-bit / mono wav and stream it at real-time speed to watch live results

    ffmpeg -i any-audio-file -ar 16000 -ac 1 -sample_fmt s16 test.wav
    go run ./cmd/harkc test.wav
    

Without Docker, build it directly: go build ./cmd/hark && ./hark -config config.yaml. See docs/CONFIG.md for configuration and deploy/docker/hark.yaml for an example. The client protocol is in docs/PROTOCOL.md.

License

MIT

Documentation

Overview

Package hark defines the plugin contract for recognition engines (Engine).

Downstream, hark offers a single streaming recognition protocol (see package api and docs/PROTOCOL.md); upstream, it is backed by individual Engine implementations. Built-in and private engines follow the same contract: implement Engine / Stream, then either pass it straight to session.Open or register it with harkcmd.Engine as an engine type usable in the config file.

This package holds only the engine contract and the most basic types. It depends on no implementation and knows nothing about the config file.

Index

Constants

View Source
const (
	SampleRate     = 16000
	BytesPerSecond = SampleRate * 2
)

Audio format: v1 uses PCM s16le / 16kHz / mono throughout, and engines always receive this format.

Variables

This section is empty.

Functions

This section is empty.

Types

type AudioRange

type AudioRange struct {
	Start, End int64
}

AudioRange is a half-open interval [Start, End) on the input audio, in samples (at 16kHz, 1ms = 16 samples), counted from the session's first sample. The zero value means none.

type Engine

type Engine interface {
	// Open starts one streaming recognition. ctx is cancelled when the session ends or is aborted.
	Open(ctx context.Context, req Request, out Output) (Stream, error)
}

Engine is a configured recognition engine instance (e.g. one set of credentials, one model). The same instance is used by many sessions concurrently, so Open must be safe for concurrent use.

type Output

type Output interface {
	// Update reports a **full snapshot of all current segments** (not a delta).
	// hark works out which segments changed and pushes that downstream; the engine need not care.
	//
	// It may be called from any goroutine and never blocks. hark only guarantees to push the latest snapshot;
	// snapshots reported in quick succession may be coalesced.
	//
	// Ownership: after the call, the segments slice belongs to hark, which may modify segments in place
	// (e.g. personal vocabulary replacement). The engine must not read or write it afterwards, and should
	// build a new slice for every report.
	Update(segments []Segment)
}

Output is where an engine reports results. hark provides it.

type Request

type Request struct {
	SessionID string
	// Options is downstream's start.options, passed through as is; the engine interprets the fields.
	// Read-only: the same map may be handed to several tracks at once.
	Options map[string]any
	// Log is a logger already carrying fields such as session.
	Log *slog.Logger
}

Request holds the parameters of one session.

type Segment

type Segment struct {
	// Text: the full text is the segments' Text concatenated as is; hark never inserts spaces.
	// For languages that need spaces, such as English, the engine puts the spaces in Text (e.g. "Hello", " world.").
	Text string
	// Final means upstream considers this segment finalized (soft-final). It is only a hint; the segment may still be rewritten.
	// Whether and when to promise downstream that it will not change is decided by hark, per the session's commit policy.
	Final bool
	// Speaker is optional: a speaker label. A segment can have at most one speaker label; the engine should start a new
	// segment when the speaker changes. The label is scoped to this track of this session.
	Speaker string
	// Audio is optional: where this segment lies in the input audio. Upstream should provide it whenever it can:
	// besides being passed through to downstream, the freeze policy relies on it to reliably locate new content
	// when upstream rewrites frozen content.
	Audio AudioRange
}

Segment is one piece of recognition result, usually a sentence. A segment's index is its position in the snapshot.

type Stream

type Stream interface {
	// Write pushes a chunk of PCM audio of any length (an even number of bytes).
	// It may block to feed upstream at real-time speed; blocking propagates to downstream as TCP backpressure.
	// But it must return promptly when ctx is cancelled or Close is called.
	//
	// Ownership: pcm is valid only for the duration of the call; the caller may reuse the memory after it returns.
	// An engine that needs to keep it must copy it.
	Write(pcm []byte) error
	// Finish signals the end of audio and blocks until upstream finalizes.
	// The final snapshot must have been reported through Output.Update before it returns.
	// It should return promptly when ctx expires (finalize timeout).
	Finish(ctx context.Context) error
	// Close releases resources and aborts the session if it has not finished.
	Close() error
}

Stream is one streaming recognition session.

Calling conventions:

  • Write and Finish are never called concurrently; Finish is called at most once, and Write is not called after it
  • Close may be called at any time from another goroutine (to abort the session), and may be called more than once
  • After Close, there may still be one Write or Finish call; it should return an error rather than panic
  • If upstream fails midway, the error is returned from the next Write or Finish

Directories

Path Synopsis
Package api is hark's downstream wire protocol (see docs/PROTOCOL.md).
Package api is hark's downstream wire protocol (see docs/PROTOCOL.md).
cmd
hark command
Command hark is the official binary: it includes only the built-in engines.
Command hark is the official binary: it includes only the built-in engines.
harkc command
Command harkc is a command-line client for integration testing: it streams a wav file to hark at real-time speed and prints each track's live results.
Command harkc is a command-line client for integration testing: it streams a wav file to hark at real-time speed and prints each track's live results.
Package draft merges client-side edits: the user can edit text while recognition is still running, and edited places are not overwritten by recognition results.
Package draft merges client-side edits: the user can edit text while recognition is still running, and edited places are not overwritten by recognition results.
engine
batch
Package batch turns a non-streaming recognizer (whole audio in, text out) into a streaming engine.
Package batch turns a non-streaming recognizer (whole audio in, text out) into a streaming engine.
httpasr
Package httpasr is a generic HTTP recognizer: it connects any "whole audio in, text out" HTTP service as a hark backend, through configuration alone, with no Go code.
Package httpasr is a generic HTTP recognizer: it connects any "whole audio in, text out" HTTP service as a hark backend, through configuration alone, with no Go code.
mock
Package mock is a fake engine that needs no network: it advances through a preset script according to the duration of audio received.
Package mock is a fake engine that needs no network: it advances through a preset script according to the duration of audio received.
openai
Package openai connects to OpenAI-compatible transcription APIs (POST {base_url}/audio/transcriptions).
Package openai connects to OpenAI-compatible transcription APIs (POST {base_url}/audio/transcriptions).
sherpa
Package sherpa supports local models: it connects to a sherpa-onnx non-streaming recognition server (sherpa-onnx-offline-websocket-server, e.g.
Package sherpa supports local models: it connects to a sherpa-onnx non-streaming recognition server (sherpa-onnx-offline-websocket-server, e.g.
volc
Package volc implements Volcengine (Doubao) large-model streaming speech recognition: wss://openspeech.bytedance.com/api/v3/sauc/bigmodel_async.
Package volc implements Volcengine (Doubao) large-model streaming speech recognition: wss://openspeech.bytedance.com/api/v3/sauc/bigmodel_async.
wsasr
Package wsasr is a generic WebSocket streaming engine: it connects any service that emits text while listening as a hark backend, through configuration alone, with no Go code.
Package wsasr is a generic WebSocket streaming engine: it connects any service that emits text while listening as a hark backend, through configuration alone, with no Go code.
examples
embedded command
Command embedded recognizes a wav file in its own process, without running a hark server: it drives the engine with the session package, and the results are exactly the same as the server's.
Command embedded recognizes a wav file in its own process, without running a hark server: it drives the engine with the session package, and the results are exactly the same as the server's.
Package harkcmd is a reusable hark entry point: it reads the config, registers engines, and starts the server.
Package harkcmd is a reusable hark entry point: it reads the config, registers engines, and starts the server.
internal
server
Package server implements the WebSocket service described in docs/PROTOCOL.md, connecting downstream sessions to hark.Engine.
Package server implements the WebSocket service described in docs/PROTOCOL.md, connecting downstream sessions to hark.Engine.
wav
Package wav reads 16kHz / 16-bit PCM wav files (used by the command-line client and examples).
Package wav reads 16kHz / 16-bit PCM wav files (used by the command-line client and examples).
Package session uses hark inside your own process: instead of starting an HTTP/WebSocket server, it drives an engine directly, with the same semantics as the server: updates in the same format (rev, OT ops, stable, commit), the same normalization, and the same commit policies (strict / freeze).
Package session uses hark inside your own process: instead of starting an HTTP/WebSocket server, it drives an engine directly, with the same semantics as the server: updates in the same format (rev, OT ops, stable, commit), the same normalization, and the same commit policies (strict / freeze).
Package vocab implements the personal vocabulary: it learns, from the user's corrections, the words the recognizer keeps getting wrong, and replaces them automatically from then on.
Package vocab implements the personal vocabulary: it learns, from the user's corrections, the words the recognizer keeps getting wrong, and replaces them automatically from then on.

Jump to

Keyboard shortcuts

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