tokenize

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: Apache-2.0 Imports: 12 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.

Documentation

Overview

Package tokenize provides the sentence, word, paragraph, and English hyphenation primitives used by streaming transcription and TTS.

Offsets returned by this package are UTF-8 byte offsets, matching Go's slice conventions. Streams are bounded and apply backpressure to PushText and Flush; one goroutine may send while another receives, and Close may run concurrently.

Index

Examples

Constants

View Source
const DefaultMaxBufferedBytes = 1 << 20

DefaultMaxBufferedBytes bounds text retained by an incremental tokenizer when hostile or malformed input never produces a complete token.

View Source
const Punctuations = `!"#$%&'()*+,-./:;<=>?@[\]^_` + "`" + `{|}~±—‘’“”…`

Punctuations is the punctuation vocabulary removed by the default word tokenizer. It intentionally matches livekit-agents 1.7.1.

Variables

View Source
var ErrBufferLimit = errors.New("tokenize: buffered text limit exceeded")

ErrBufferLimit means PushText rejected a chunk without consuming it because retaining it would exceed MaxBufferedBytes.

Functions

func HasUnclosedXMLTags

func HasUnclosedXMLTags(text string) bool

HasUnclosedXMLTags reports whether text ends inside a tag-shaped fragment or contains more opening than closing letter-named XML tags. Digit pseudo-tags and comparison operators are deliberately treated as prose.

func Hyphenate

func Hyphenate(word string) []string

Hyphenate is a concise compatibility alias.

func HyphenateWord

func HyphenateWord(word string) []string

HyphenateWord applies the Frank Liang English patterns used by the Python and TypeScript SDKs. Short and non-ASCII words are returned unchanged.

Example
package main

import (
	"fmt"

	"github.com/infinityscroll/livekit-agents-go/tokenize"
)

func main() {
	fmt.Println(tokenize.HyphenateWord("communication"))
}
Output:
[com mu ni ca tion]

func JoinTokens

func JoinTokens(tokens []TokenData) string

JoinTokens is a small convenience for tests and adapters that need to drain a finite stream while preserving the tokenizer's inter-token spacing.

func TokenizeParagraphs

func TokenizeParagraphs(text string) []string

TokenizeParagraphs returns paragraph text without offsets.

Types

type BufferedTokenStream

type BufferedTokenStream = TokenStream

BufferedTokenStream is the cross-language compatibility name.

type SentenceOptions

type SentenceOptions struct {
	Language            string
	MinSentenceLength   int
	StreamContextLength int
	RetainFormat        bool
	MaxTokenLength      int
	MinTokenLength      int
	FirstTokenLength    int
	XMLAware            bool
	OutputCapacity      int
	// MaxBufferedBytes bounds un-emitted streamed input. Zero selects the
	// production default; it does not affect batch Tokenize calls.
	MaxBufferedBytes int
}

SentenceOptions configures SentenceTokenizer. Zero values select the same defaults as the Python and TypeScript SDKs.

type SentenceStream

type SentenceStream struct{ *TokenStream }

SentenceStream is a TokenStream produced by SentenceTokenizer.

type SentenceTokenizer

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

SentenceTokenizer implements the LiveKit basic English sentence tokenizer. It is immutable and safe for concurrent Tokenize and Stream calls.

Example
package main

import (
	"fmt"

	"github.com/infinityscroll/livekit-agents-go/tokenize"
)

func main() {
	tokenizer := tokenize.NewSentenceTokenizer(tokenize.SentenceOptions{MinSentenceLength: 1})
	for _, sentence := range tokenizer.Tokenize("Hello! How are you?") {
		fmt.Println(sentence)
	}
}
Output:
Hello!
How are you?

func NewSentenceTokenizer

func NewSentenceTokenizer(options ...SentenceOptions) *SentenceTokenizer

NewSentenceTokenizer constructs a tokenizer. At most one options value is accepted; omitting it selects the cross-language defaults.

func (*SentenceTokenizer) Options

func (t *SentenceTokenizer) Options() SentenceOptions

Options returns the fully resolved configuration.

func (*SentenceTokenizer) Stream

func (t *SentenceTokenizer) Stream(_ ...string) *SentenceStream

Stream creates an independent incremental sentence stream.

func (*SentenceTokenizer) Tokenize

func (t *SentenceTokenizer) Tokenize(text string, _ ...string) []string

Tokenize splits text into sentence strings. The optional language is accepted for parity; the built-in tokenizer is deliberately English-only.

func (*SentenceTokenizer) TokenizeSpans

func (t *SentenceTokenizer) TokenizeSpans(text string) []Span

TokenizeSpans is Tokenize with source offsets.

type SentenceTokenizerOptions

type SentenceTokenizerOptions = SentenceOptions

SentenceTokenizerOptions is retained as a discoverable compatibility name.

type Span

type Span struct {
	Text       string
	Start, End int
}

Span is a token and its half-open UTF-8 byte range in the source text.

func SplitParagraphs

func SplitParagraphs(text string) []Span

SplitParagraphs splits at runs containing two or more newlines with only whitespace between them.

func SplitSentences

func SplitSentences(text string, minLength int, retainFormat ...bool) []Span

SplitSentences implements the basic LiveKit sentence splitter. Short spans are merged forward until their combined length is strictly greater than minLength, matching the Python/TypeScript semantics.

func SplitWords

func SplitWords(text string, ignorePunctuation ...bool) []Span

SplitWords splits text on Unicode whitespace. Offsets always refer to the unmodified source, even when punctuation is removed from Span.Text.

func SplitWordsWithOptions

func SplitWordsWithOptions(text string, opts WordOptions) []Span

SplitWordsWithOptions exposes Python-compatible character splitting and formatting. Stream-only WordOptions fields are ignored.

type StreamOptions

type StreamOptions struct {
	MinTokenLength   int
	MinContextLength int
	MaxTokenLength   int
	FirstTokenLength int
	XMLAware         bool
	OutputCapacity   int
	// MaxBufferedBytes caps in-progress input plus a batched output token. Zero
	// selects DefaultMaxBufferedBytes.
	MaxBufferedBytes int
}

StreamOptions controls incremental buffering. Lengths are Unicode code-point counts; source Span offsets remain UTF-8 byte offsets.

type TokenData

type TokenData struct {
	SegmentID string
	Token     string
}

TokenData is one streamed token. SegmentID changes after each Flush, allowing downstream consumers to retain segment boundaries without sentinel values.

type TokenStream

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

TokenStream incrementally applies a tokenizer with bounded output buffering. PushText and Flush may block on downstream backpressure and therefore accept a context. One sender and one receiver may operate concurrently.

func NewBufferedTokenStream

func NewBufferedTokenStream(fn func(string) []Span, opts StreamOptions) *TokenStream

NewBufferedTokenStream builds a stream around a custom span tokenizer.

func (*TokenStream) Abort

func (s *TokenStream) Abort(err error) error

Abort closes the stream with a terminal receive error.

func (*TokenStream) Close

func (s *TokenStream) Close() error

Close closes the stream without flushing, matching the JS/Python close contract. Call EndInput to retain pending text.

func (*TokenStream) Closed

func (s *TokenStream) Closed() bool

Closed reports whether Close or Abort has run.

func (*TokenStream) EndInput

func (s *TokenStream) EndInput(ctx context.Context) error

EndInput flushes pending text and closes the receive side with io.EOF.

func (*TokenStream) Flush

func (s *TokenStream) Flush(ctx context.Context) error

Flush emits all buffered text and starts a new segment.

func (*TokenStream) PushText

func (s *TokenStream) PushText(ctx context.Context, text string) error

PushText adds text and emits every token that is provably complete.

func (*TokenStream) Range

Range adapts Recv to Go's range-over-function iteration.

func (*TokenStream) Recv

func (s *TokenStream) Recv(ctx context.Context) (TokenData, error)

Recv receives the next token. io.EOF is returned after a clean close.

type WordOptions

type WordOptions struct {
	// KeepPunctuation opts out of the default punctuation stripping.
	KeepPunctuation bool
	// SplitCharacter emits CJK, Japanese, and Thai code points separately,
	// matching the Python tokenizer's non-spaced-language mode.
	SplitCharacter bool
	// RetainFormat attaches original inter-word whitespace to the next token.
	RetainFormat bool
	// DropEmptyTokens selects Python's behavior for punctuation-only spans. The
	// JS tokenizer retains those spans as empty tokens by default.
	DropEmptyTokens  bool
	OutputCapacity   int
	MaxBufferedBytes int
}

WordOptions configures WordTokenizer.

type WordStream

type WordStream struct{ *TokenStream }

WordStream is a TokenStream produced by WordTokenizer.

type WordTokenizer

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

WordTokenizer splits on Unicode whitespace and optionally removes the shared punctuation vocabulary from each word.

func NewWordTokenizer

func NewWordTokenizer(ignorePunctuation ...bool) *WordTokenizer

NewWordTokenizer constructs a word tokenizer. Punctuation is ignored by default; pass false to retain it, matching new WordTokenizer(false) in JS.

func NewWordTokenizerWithOptions

func NewWordTokenizerWithOptions(opts WordOptions) *WordTokenizer

NewWordTokenizerWithOptions is the struct-options constructor.

func (*WordTokenizer) FormatWords

func (t *WordTokenizer) FormatWords(words []string) string

FormatWords joins already-tokenized words using the cross-language default.

func (*WordTokenizer) Stream

func (t *WordTokenizer) Stream(_ ...string) *WordStream

Stream creates an independent incremental word stream.

func (*WordTokenizer) Tokenize

func (t *WordTokenizer) Tokenize(text string, _ ...string) []string

Tokenize splits text into words. The optional language is accepted for parity.

func (*WordTokenizer) TokenizeSpans

func (t *WordTokenizer) TokenizeSpans(text string) []Span

TokenizeSpans is Tokenize with source offsets.

Jump to

Keyboard shortcuts

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