formatter

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: BSD-2-Clause Imports: 11 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.

Documentation

Overview

Package formatter reads the expression tags an LLM writes, and formats them for a TTS service.

Part of expressive conversation (alpha). A TTS service with expressive conversation on is given its text a unit at a time: a sentence, or a token when it streams tokens. ExpressionFormatter handles each unit in three steps:

  1. ExpressionFormatter.Parse splits the unit into segments: the words to speak, with the delivery they are spoken in, and the sounds and pauses between them.
  2. ShownText gives the words without the tags, which clients are shown.
  3. ExpressionFormatter.Format builds the request the service is sent, in its provider's markup, and says what each stretch of the unit performs, for the spoken package to report as the words are spoken.

With ElevenLabs' audio tags, one sentence goes:

"<<warm>> It's [[laugh]] ^^back^^ up."    the unit, as the LLM wrote it
"It's back up."                           shown to clients
"[warmly] It's [laughs] BACK up."         sent to ElevenLabs

The tags are:

  • <<name>> sets the delivery the words after it are spoken in, until the next delivery tag replaces it or the response ends: <<warm>>. A name may be several words, as in <<soft tone>>. <<neutral>> returns to the voice's baseline. Delivery tags aren't segments of their own; the delivery travels with the Text it applies to.
  • <<name: words>> is a span: it speaks just those words in its delivery, added to the delivery around them, then goes back to it, as in <<slow: A B 7>>. <<neutral: words>> speaks them in the baseline. A span holds words and emphasis, and doesn't nest.
  • ^^words^^ stresses words. It is a span of emphasis, written short, and can stand within another span.
  • [[name]] is a Sound, a sound at one point ([[laugh]]), or a Pause, [[pause N]] for N milliseconds.

The brackets decide a tag's kind, except that a universal name, or one the TTS service declares, keeps its kind in the other kind's brackets: [[warm]] still sets a delivery. LLMs make that slip, so it is logged as a warning.

The formatter reads whole units: an aggregator such as text.SkipTagsAggregator, given ExpressionTags, keeps each tag in one unit as text streams. A tag left unfinished at the end of a unit is removed, never spoken.

The service's expression adapter says what it can perform and formats each piece in its provider's markup. A universal name, such as "warm" or "laugh", is sent as the name the service performs it by (expressive.ExpressionCapabilities.DeliveryName), such as ElevenLabs' "warmly"; everything else about the unit keeps the names as written. What the service can't perform is left out of the request, and kept in the unit's text for the context.

Alpha: the tag syntax and these types are likely to change between releases.

Index

Constants

This section is empty.

Variables

View Source
var ExpressionTagPattern = TagPattern{}

ExpressionTagPattern finds the delivery and sound tags in the LLM's text. See TagPattern.

Functions

func ExpressionTags

func ExpressionTags() []text.StartEndTags

ExpressionTags is the delimiters of the tags, for an aggregator such as text.SkipTagsAggregator to keep each tag in one unit.

func ShownText

func ShownText(segments []Segment, textType frames.TextType) string

ShownText is the words of a unit, without its tags, spaced as written, with one space where a tag stood between two. It is the unit's text as clients are shown it:

segments := f.Parse("<<warm>> It's [[laugh]] ^^back^^ up.", false)
formatter.ShownText(segments, frames.TextTypeSentence) // "It's back up."

A tag is removed as a word, with the space before it when punctuation follows it: "Hi [[laugh]], there." is shown as "Hi, there.", and so is "Hi <<calm>>, there.". A sentence's words are trimmed at both ends; a streamed token keeps its spacing.

func StripExpressionTags

func StripExpressionTags(unit string) string

StripExpressionTags returns text written with expression tags as its words alone, spaced as clients are shown them, as by ShownText:

formatter.StripExpressionTags("<<warm>> It's [[laugh]] ^^back^^ up.") // "It's back up."

Types

type ExpressionFormatter

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

ExpressionFormatter reads a TTS service's expression tags and formats its requests.

A TTS service has one formatter, which follows a response from unit to unit. A delivery set in one sentence carries on into the next, until the next delivery tag or ExpressionFormatter.Reset, which the service calls when the response ends or is interrupted. Call ExpressionFormatter.Parse on each unit in order, then ExpressionFormatter.Format to build its request. What the service can't perform is left out of the request, with one warning per tag.

f := formatter.NewExpressionFormatter(func() ttsadapter.ExpressionAdapter { return adapter }, "tts")

segments := f.Parse("<<warm>> It's [[laugh]] ^^back^^ up.", false)
// [Text{" It's ", ["warm"], 8, 14},
//  Sound{"laugh", 14, 23},
//  Text{" ", ["warm"], 23, 24},
//  Text{"back", ["warm", "emphasis"], 26, 30},
//  Text{" up.", ["warm"], 32, 36}]

formatter.ShownText(segments, frames.TextTypeSentence)
// "It's back up."

request := f.Format(segments, frames.TextTypeSentence, transform, trim)
// With ElevenLabs' audio tags, request.Text is "[warmly] It's [laughs] BACK up."

f.Parse("Bye.", false)
// [Text{"Bye.", ["warm"], 0, 4}]: still warm

It is not safe for concurrent use: the service calls it from its frame goroutine.

func NewExpressionFormatter

func NewExpressionFormatter(adapter func() ttsadapter.ExpressionAdapter, owner string) *ExpressionFormatter

NewExpressionFormatter builds a formatter. adapter returns the service's adapter, which may depend on its settings, such as its model; owner names the service in warnings.

func (*ExpressionFormatter) Capabilities

Capabilities is the expression the service can perform now: its adapter's capabilities, or nil when it performs none.

func (*ExpressionFormatter) Format

func (f *ExpressionFormatter) Format(
	segments []Segment, textType frames.TextType, transform Transform, trim Trim,
) FormattedRequest

Format builds the request for a unit: its text, its spans, and the settings the adapter asks for the delivery its first words are spoken in.

Each run of words goes through transform first, so text transforms such as markdown stripping never see markup, and is then formatted by the adapter in the delivery the service can perform. Sounds and pauses are formatted at their places, except that punctuation written after one stays with the words before it, where the service reports it: "Hi [[laugh]], there." asks ElevenLabs for "Hi, [laughs] there.". A sentence's request is trimmed at both ends; a streamed token keeps its spacing.

Cartesia names warm and laugh its own way, has no emphasis, and changes emotion only between sentences:

segments := f.Parse("<<warm>> It's [[laugh]] ^^back^^ up.", false)
request := f.Format(segments, frames.TextTypeSentence, transform, trim)
// text:  `<emotion value="content"/> It's [laughter] back up.`
// spans: {8, 14, ["warm"]}, {14, 23, laugh}, {23, 24, ["warm"]},
//        {26, 30, ["warm"]} (no emphasis), {32, 36, ["warm"]}

func (*ExpressionFormatter) Parse

func (f *ExpressionFormatter) Parse(unit string, whole bool) []Segment

Parse splits a unit of text, with each of its tags whole, into segments, in order. Spacing alone between two tags is a Text of its own, so the request keeps it.

Words take the delivery in effect where they are written, which may have been set by an earlier unit of the response:

f.Parse("<<calm>> All set.", false) // [Text{" All set.", ["calm"], 8, 17}]
f.Parse(" Bye.", false)             // [Text{" Bye.", ["calm"], 0, 5}]

Text that stands on its own, such as a TTSSpeakFrame's spoken in the middle of a response, is parsed with whole set: it starts in the voice's baseline, and the response's delivery carries on after it:

f.Parse("<<excited>> One moment.", true) // [Text{" One moment.", ["excited"], 11, 23}]
f.Parse(" Back.", false)                 // [Text{" Back.", ["calm"], 0, 6}]

func (*ExpressionFormatter) Reset

func (f *ExpressionFormatter) Reset()

Reset returns to the baseline, as at the end of a response or an interruption.

func (*ExpressionFormatter) RestateDelivery

func (f *ExpressionFormatter) RestateDelivery()

RestateDelivery has the next request state its delivery from its start.

Markup marks only where the delivery changes, so a request continuing the one before it doesn't repeat them. Text spoken in an audio context of its own, such as a TTSSpeakFrame's, follows no earlier request there, nor does the response's next request follow it, so the service calls this before and after it.

type ExpressionSpan

type ExpressionSpan struct {
	// Start is where the stretch starts in the unit.
	Start int
	// End is where it ends.
	End int
	// Delivery is the delivery its words are spoken in, empty for the voice's
	// baseline, or nil for a sound.
	Delivery []string
	// Sound is the sound or pause, as reported to clients, or nil for words.
	Sound *ReportedSound
}

ExpressionSpan is what a stretch of a unit performs: words in their delivery, or a sound.

ExpressionFormatter.Format returns one for each segment the service performs, with what it actually performs: a delivery or emphasis the service can't perform is left out of Delivery, and a sound it can't perform has no span. Offsets are into the unit as the LLM wrote it, so the spoken package can find which spans the text of each word the service reports covers.

For "<<calm>> Hi [[laugh]]" on a service that performs both:

ExpressionSpan{Start: 8, End: 12, Delivery: []string{"calm"}}
ExpressionSpan{Start: 12, End: 21, Sound: &ReportedSound{TextTypeExpressionSound, "laugh"}}

type FormattedRequest

type FormattedRequest struct {
	// Text is the text to send to the service, empty when nothing is left to
	// say.
	Text string
	// Spans has a span for each stretch of the unit the service performs.
	Spans []ExpressionSpan
	// Settings is what the adapter asks to send beside the text, from its
	// RequestSettings.
	Settings map[string]any
}

FormattedRequest is a unit's request, as ExpressionFormatter.Format builds it.

type Pause

type Pause struct {
	// DurationMS is how long, in milliseconds.
	DurationMS int
	// Start is where its tag starts in the unit.
	Start int
	// End is where it ends.
	End int
}

Pause is a silence at one point, written [[pause N]] for N milliseconds.

func (Pause) Bounds

func (p Pause) Bounds() (start, end int)

Bounds implements Segment.

func (Pause) DurationWithin

func (p Pause) DurationWithin(c *expressive.ExpressionCapabilities) int

DurationWithin is how long the pause is, in milliseconds, within the service's range.

func (Pause) PerformedBy

func (p Pause) PerformedBy(c *expressive.ExpressionCapabilities) bool

PerformedBy reports whether a service with these capabilities pauses.

func (Pause) Reported

Reported is the pause as reported to clients: its milliseconds.

func (Pause) Tag

func (p Pause) Tag() string

Tag is the pause written as a tag.

type ReportedSound

type ReportedSound struct {
	TextType frames.TextType
	Text     string
}

ReportedSound is a sound or pause as reported to clients: its text type, frames.TextTypeExpressionSound or frames.TextTypeExpressionPause, and its text, the sound's name or the pause's milliseconds.

type Segment

type Segment interface {
	// Bounds is where the segment was written in the unit: its start and end
	// offsets, tags included.
	Bounds() (start, end int)
	// contains filtered or unexported methods
}

Segment is a piece of a unit: a Text, a Sound or a Pause.

type Sound

type Sound struct {
	// Name is the sound, as written between the brackets.
	Name string
	// Start is where its tag starts in the unit.
	Start int
	// End is where it ends.
	End int
}

Sound is a sound made at one point, such as a laugh. In "Hi [[laugh]]", the sound is Sound{"laugh", 3, 12}.

func (Sound) Bounds

func (s Sound) Bounds() (start, end int)

Bounds implements Segment.

func (Sound) PerformedBy

func (s Sound) PerformedBy(c *expressive.ExpressionCapabilities) bool

PerformedBy reports whether a service with these capabilities makes the sound.

func (Sound) Reported

Reported is the sound as reported to clients.

func (Sound) Tag

func (s Sound) Tag() string

Tag is the sound written as a tag.

type TagPattern

type TagPattern struct{}

TagPattern finds the delivery and sound tags in the LLM's text, which word tracking passes over so their names aren't matched against spoken words: a span's opening and its closing ">>", not the words between them, then whole delivery and sound tags. Emphasis has no letters in its delimiters, so it needs none.

It reads as a regular expression would whose span opening looks ahead for the ">>" closing it, which Go's regular expressions can't write.

func (TagPattern) FindAllStringIndex

func (TagPattern) FindAllStringIndex(s string, n int) [][]int

FindAllStringIndex reports where each tag is in s, as regexp.Regexp does: at most n of them, or all when n is negative.

func (TagPattern) ReplaceAllString

func (p TagPattern) ReplaceAllString(s, repl string) string

ReplaceAllString returns s with each tag replaced by repl.

type Text

type Text struct {
	// Text is the words, with the spacing around them.
	Text string
	// Delivery is the delivery the words are spoken in, empty for the voice's
	// baseline.
	Delivery []string
	// Start is where the words start in the unit.
	Start int
	// End is where they end.
	End int
	// Span is the delivery a span such as <<slow: A B 7>> or ^^B^^ adds for
	// just these words, empty for words outside one.
	Span []string
}

Text is words to speak, and the delivery to speak them in.

Start and End are byte offsets into the unit as the LLM wrote it, tags included. In "<<calm>> Hi.", the words are Text{" Hi.", ["calm"], 8, 12}.

func (Text) Bounds

func (t Text) Bounds() (start, end int)

Bounds implements Segment.

type Transform

type Transform func(words string, textType frames.TextType) (string, bool)

Transform rewrites a run of words for the service, and reports false when nothing is left of it.

type Trim

type Trim func(words string) (string, bool)

Trim trims a unit's first words as the service trims a unit's text, and reports false when nothing is left of them.

Jump to

Keyboard shortcuts

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