workflow

package
v0.5.0-beta.5 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: AGPL-3.0 Imports: 13 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 workflow is WorkflowStudio's model (M6): a workflow is a graph of steps (nodes) with typed inputs and outputs joined by links (edges), run once per input item (a script, or an audio clip). The package is pure: the graph, its validation, the input items, the recipe keys that tell which results a run can keep, and the built-in templates. The services run workflows (internal/services/workflow*.go); the UI draws and edits them (workflow*.go).

Imports: lang (language codes), text (script splitting), i18n (texts of diagnostics).

Index

Constants

View Source
const (
	MaxNodes       = 100
	MaxScripts     = 50       // scripts (items) a Start step takes
	MaxScriptChars = 20000    // runes per script
	MaxClips       = 50       // audio clips a Source step takes
	MaxClipBytes   = 64 << 20 // per clip
	MaxName        = 120      // runes of a workflow's or a step's name
	MaxMatchText   = 200      // runes a condition looks for
	MaxTemplate    = 200      // runes of an export's file name template
)

Limits.

View Source
const (
	PortIn  = "in"
	PortOut = "out"
	PortYes = "yes"
	PortNo  = "no"
)

Port names.

View Source
const (
	MinZoom = 0.25
	MaxZoom = 2.0
)

Zoom limits.

View Source
const (
	LevelLoudness = "loudness" // integrated LUFS, true peak under −1 dBTP
	LevelPeak     = "peak"     // sample peak, dBFS
)

Normalize modes.

View Source
const (
	FormatWAV  = "wav"
	FormatM4A  = "m4a"
	FormatTXT  = "txt"
	FormatSRT  = "srt"
	FormatVTT  = "vtt"
	FormatJSON = "json"
)

Export formats.

View Source
const (
	DefaultLoudness = -16.0
	DefaultPeak     = -2.0
	MinLoudness     = -30.0
	MaxLoudness     = -10.0
	MinPeak         = -24.0
	MaxPeak         = -1.0
	MinSpeed        = 0.5
	MaxSpeed        = 2.0
)

Defaults of the normalize step.

View Source
const (
	SkipBranch   = "branch"   // the other branch of a condition
	SkipUpstream = "upstream" // a step before it failed
)

Skip codes (Step.Code of skipped steps).

View Source
const (
	GridX = 280
	GridY = 170
)

Column spacing of templates and new steps.

View Source
const (
	CodeEmpty         = "graph.empty"       // no steps
	CodeNoInput       = "graph.no_input"    // no Start or Source step
	CodeNoSteps       = "graph.no_steps"    // only the input step
	CodeExtraInput    = "node.extra_input"  // a second Start or Source step
	CodeUnconnected   = "node.unconnected"  // its input has no link
	CodeUnreachable   = "node.unreachable"  // no path from the input step
	CodeCycle         = "edge.cycle"        // the link closes a loop
	CodeType          = "edge.type"         // the link carries a type the input does not take (Arg: the type)
	CodeMergeTypes    = "edge.merge_types"  // links into one input carry different types
	CodeMerge         = "edge.merge"        // links into one input that are not alternative branches of a condition
	CodeStartEmpty    = "start.empty"       // no script
	CodeStartTooMany  = "start.too_many"    // more than MaxScripts items (Arg: the count)
	CodeStartTooLong  = "start.too_long"    // an item over MaxScriptChars (Arg: its number, 1-based)
	CodeSourceEmpty   = "source.empty"      // no clip
	CodeSourceTooMany = "source.too_many"   // more than MaxClips
	CodeSourceLarge   = "source.too_large"  // a clip over MaxClipBytes (Arg: its name)
	CodeSourceZero    = "source.empty_file" // a clip of 0 bytes (Arg: its name)
	CodeNoModel       = "speak.no_model"    // Speak/Convert without a model
	CodeNoTarget      = "translate.no_target"
	CodeSameLanguage  = "translate.same"
	CodeNoMatchText   = "condition.no_text"
	CodeFormat        = "export.format"    // the format does not suit the value (Arg: the format)
	CodeTemplate      = "export.template"  // the file name template is not a name
	CodeNoFolder      = "export.no_folder" // warning: the results stay in the app
)

Diagnostic codes.

View Source
const DefaultTemplate = "{workflow}-{n}-{item}"

DefaultTemplate is an export's file name template.

View Source
const Version = 1

Version is the document version Normalize writes.

Variables

Kinds lists the step kinds in the palette's order.

Matches lists the comparisons in the inspector's order.

View Source
var TemplateTokens = []string{"{workflow}", "{n}", "{item}", "{step}", "{date}", "{lang}"}

TemplateTokens are the tokens a file name template may use.

View Source
var Templates = []Template{
	{ID: "narration", Name: "Batch narration", About: "Scripts → speech, one file each.", /* contains filtered or unexported fields */},
	{ID: "narration-normalize", Name: "Narration + normalize", About: "Scripts → speech at an even loudness.", /* contains filtered or unexported fields */},
	{ID: "transcript", Name: "Audio to transcript", About: "Recordings → text files.", /* contains filtered or unexported fields */},
	{ID: "change-voice", Name: "Change the voice", About: "Recordings → the same words in another voice.", /* contains filtered or unexported fields */},
	{ID: "translate-narrate", Name: "Translate and narrate", About: "Recordings → transcribed, translated and spoken.", /* contains filtered or unexported fields */},
	{ID: "subtitles", Name: "Transcript → subtitles", About: "Recordings → SubRip subtitles.", /* contains filtered or unexported fields */},
}

Templates are AudioSmith's templates, in the library's order.

Functions

func CopyName

func CopyName(base string, taken []string) string

CopyName is the first of "base (2)", "base (3)"… not in taken.

func Evaluate

func Evaluate(m Match, want, text string) bool

Evaluate reports whether a condition matches text: trimmed, ignoring case.

func Excerpt

func Excerpt(s string, n int) string

Excerpt is the start of a text on one line, at most n runes (with "…").

func ExportFormat

func ExportFormat(format string, t Type) string

ExportFormat is the format an export writes for type t: its own, or the type's first.

func FileName

func FileName(template string, v NameVars) string

FileName fills a template and makes it a safe file name (without its extension): characters files cannot have become "_", at most 120 runes.

func FormatsFor

func FormatsFor(t Type) []string

FormatsFor are the export formats of a value type.

func ItemFile

func ItemFile(key string) string

ItemFile is where a run keeps a script item's text, in its folder.

func PortLabel

func PortLabel(port string) string

PortLabel names an output port ("yes", "no"); "" for the others.

func RunSignature

func RunSignature(keys map[string]map[string]string, items []Item) string

RunSignature sums up the keys of every step for every item.

func SafeName

func SafeName(s string) string

SafeName replaces what file names cannot hold and caps the length.

func SplitScript

func SplitScript(s string) []string

SplitScript cuts a script at lines of "---" into its parts, trimmed, without empty ones.

func StepKeys

func StepKeys(w *Workflow, rep *Report, items []Item, salt Salt) map[string]map[string]string

StepKeys are the recipe keys of every step reachable from the input, for every item: a hash of the step's kind and settings, salt, and the keys of the steps feeding it (the input step's: the item's content). A result whose key is unchanged was made from the same recipe.

func TemplateAbout

func TemplateAbout(id string) string

func TemplateName

func TemplateName(id string) string

TemplateName and TemplateAbout translate a template's texts.

func ValidTemplate

func ValidTemplate(s string) bool

ValidTemplate reports whether a file name template makes names: not empty, no folders.

Types

type Check

type Check func(n *Node, in Type) []Diagnostic

Check adds the diagnostics only the app can make about a step (a model not downloaded, a saved voice deleted, no translator set up), given the type its input receives ("" when unknown).

type Clip

type Clip struct {
	Name string `json:"name"`
	Path string `json:"path"` // absolute
	Size int64  `json:"size"`
	// Mod is the file's modification time when it was added: a changed
	// file is a new item.
	Mod time.Time `json:"mod"`
}

Clip is one audio file of a Source step.

type Diagnostic

type Diagnostic struct {
	Severity Severity `json:"severity"`
	Code     string   `json:"code"`
	Node     string   `json:"node,omitempty"`
	Edge     string   `json:"edge,omitempty"`
	Arg      string   `json:"arg,omitempty"`
}

Diagnostic is a finding about the workflow, a step or a link.

func (Diagnostic) Text

func (d Diagnostic) Text() string

Text is the diagnostic's message in the interface's language. Codes the app adds (Check) are not known here: their Arg is the message.

type Edge

type Edge struct {
	ID       string `json:"id"`
	From     string `json:"from"`
	FromPort string `json:"fromPort"`
	To       string `json:"to"`
	ToPort   string `json:"toPort"`
}

Edge links an output of one step to the input of another.

type Item

type Item struct {
	// Key identifies the item by its content: an edited script is a new
	// item, a script moved in the list is the same one.
	Key  string `json:"key"`
	Name string `json:"name"`
	Text string `json:"text,omitempty"` // a script
	// Path, Size: a clip.
	Path string `json:"path,omitempty"`
	Size int64  `json:"size,omitempty"`
	// Source is the script or clip it comes from (0-based), Part its
	// part when the script holds several ("---").
	Source int `json:"source"`
	Part   int `json:"part,omitempty"`
}

Item is one input of a run: a script, or an audio clip. The workflow runs once per item.

type Kind

type Kind string

Kind is a step's kind.

const (
	KindStart      Kind = "start"      // scripts → text
	KindSource     Kind = "source"     // audio clips → audio
	KindSpeak      Kind = "speak"      // text → audio (the render pipeline)
	KindTranscribe Kind = "transcribe" // audio → transcript
	KindTranslate  Kind = "translate"  // text → text, transcript → transcript
	KindConvert    Kind = "convert"    // audio → audio in another voice
	KindNormalize  Kind = "normalize"  // audio → audio at a loudness or peak level
	KindCondition  Kind = "condition"  // text → yes / no (the same text)
	KindExport     Kind = "export"     // anything → files in a folder
)

func (Kind) About

func (k Kind) About() string

About says what a kind does.

func (Kind) IsInput

func (k Kind) IsInput() bool

IsInput reports whether a kind brings the items (Start, Source).

func (Kind) Label

func (k Kind) Label() string

Label is a kind's name in the interface's language.

type Match

type Match string

Match is how a condition compares.

const (
	MatchContains Match = "contains"
	MatchEquals   Match = "equals"
	MatchPrefix   Match = "prefix"
	MatchSuffix   Match = "suffix"
)

func (Match) Label

func (m Match) Label() string

Label names a comparison.

type NameVars

type NameVars struct {
	Workflow string
	N        int // the item's number, 1-based
	Item     string
	Step     string
	Date     time.Time
	Lang     string
}

NameVars are the values of a file name template's tokens.

type Node

type Node struct {
	ID   string `json:"id"`
	Kind Kind   `json:"kind"`
	// Name is the user's name for the step ("" = the kind's).
	Name string  `json:"name,omitempty"`
	X    float64 `json:"x"`
	Y    float64 `json:"y"`
	P    Params  `json:"params"`
}

Node is a step.

func (*Node) StepName

func (n *Node) StepName(label string) string

StepName is a step's display name: its own, or label (the kind's, translated by the caller).

type Params

type Params struct {
	// Start.
	Scripts []Script `json:"scripts,omitempty"`
	// Source.
	Clips []Clip `json:"clips,omitempty"`
	// Speak, Convert: the TTS model (repo), the voice (a saved voice's
	// id, "speaker:<id>" for the model's own, "preset:<id>"…; "" = the
	// model's default), the language (BCP-47; "" = auto) and the speed.
	Model    string  `json:"model,omitempty"`
	Voice    string  `json:"voice,omitempty"`
	Language string  `json:"language,omitempty"`
	Speed    float64 `json:"speed,omitempty"`
	// Convert: keep the source's length (the model's duration control,
	// else time-stretching).
	MatchDuration bool `json:"matchDuration,omitempty"`
	// Transcribe: the language spoken (""= detect). Translate: From
	// ("" = detect) and To.
	From string `json:"from,omitempty"`
	To   string `json:"to,omitempty"`
	// Translate: "" = the language model of Settings; "deepl", "google",
	// "microsoft".
	Translator string `json:"translator,omitempty"`
	// Normalize.
	Level  string  `json:"level,omitempty"` // LevelLoudness | LevelPeak
	Target float64 `json:"target,omitempty"`
	// Condition.
	Match Match  `json:"match,omitempty"`
	Text  string `json:"text,omitempty"`
	// Export: the folder ("" = none: the results stay in the app), the
	// file name template and the format ("" = the first for the type).
	Folder   string `json:"folder,omitempty"`
	Template string `json:"template,omitempty"`
	Format   string `json:"format,omitempty"`
}

Params are a step's settings; each kind reads its own.

func DefaultParams

func DefaultParams(k Kind) Params

DefaultParams are a new step's settings.

type Port

type Port struct {
	Name string
	// Type is an output's type (TypeSame: the input's).
	Type Type
	// Accepts are the types an input takes.
	Accepts []Type
}

Port is an input or output of a step.

type Report

type Report struct {
	Diags []Diagnostic
	// Input is the input step's id ("" without one).
	Input string
	// Order lists the steps reachable from the input in an order that
	// runs every step after the steps feeding it (without cycles).
	Order []string
	// In and Out are the types of each step's input and outputs, where
	// they are known.
	In, Out map[string]Type
	// Items counts the input's items.
	Items int
}

Report is what Validate found.

func Validate

func Validate(w *Workflow, check Check) *Report

Validate checks the graph: one input step, every other step fed and reachable from it, no loops, links of types the inputs take, inputs fed by several links only from alternative branches of conditions, and each step's settings; check (optional) adds the app's own findings.

func (*Report) Errors

func (r *Report) Errors() int

Errors counts the errors.

func (*Report) For

func (r *Report) For(node string) []Diagnostic

For lists the diagnostics of a step (and of the links into it).

func (*Report) ForEdge

func (r *Report) ForEdge(edge string) []Diagnostic

ForEdge lists the diagnostics of a link.

func (*Report) OK

func (r *Report) OK() bool

OK reports whether nothing stops a run.

type Run

type Run struct {
	ID string `json:"id"`
	// Signature sums up what the run was asked to make (RunSignature):
	// a workflow whose signature differs has changed since.
	Signature string    `json:"signature"`
	State     RunState  `json:"state"`
	StartedAt time.Time `json:"startedAt,omitzero"`
	EndedAt   time.Time `json:"endedAt,omitzero"`
	Items     []RunItem `json:"items"`
	// Steps are the step ids the run made jobs for.
	Steps []string `json:"steps,omitempty"`
	// Code and Err say why the run stopped before its end (a model not
	// downloaded, the engine gone…).
	Code string `json:"code,omitempty"`
	Err  string `json:"err,omitempty"`
}

Run is a workflow's last run, with every item's checkpoints.

func Plan

func Plan(w *Workflow, rep *Report, items []Item, keys map[string]map[string]string, prev *Run, force bool, exists func(*Value) bool) (*Run, []string)

Plan makes the next run from the last one: an item per input item, in order, keeping each step whose result is still good (finished, same key, its file still there, and nothing before it running again) and resetting the others. force starts over. It returns the run and, in run order, the steps that have work.

func (*Run) Clone

func (r *Run) Clone() *Run

Clone deep-copies the run.

func (*Run) Counts

func (r *Run) Counts() (done, failed, total int)

Counts are how many items are done and failed, of all.

func (*Run) Item

func (r *Run) Item(key string) *RunItem

Item returns the run's item with key, or nil.

type RunItem

type RunItem struct {
	Key  string `json:"key"`
	Name string `json:"name"`
	// Path is a clip's file (Source).
	Path  string           `json:"path,omitempty"`
	Steps map[string]*Step `json:"steps"`
}

RunItem is an item's state in a run.

func (*RunItem) State

func (it *RunItem) State() StepStatus

ItemState sums up an item: running, failed, done, or pending ("").

type RunState

type RunState string

RunState is a run's state.

const (
	RunIdle      RunState = ""          // never ran
	RunRunning   RunState = "running"   // jobs are queued or running
	RunDone      RunState = "done"      // every item went through
	RunFailed    RunState = "failed"    // some items failed
	RunCancelled RunState = "cancelled" // stopped by the user
)

type Salt

type Salt func(n *Node) string

Salt adds what else a step's result depends on, besides its settings and inputs (the speech-to-text model of Settings, the translator…).

type Script

type Script struct {
	Name string `json:"name,omitempty"` // the imported file's name, or ""
	Text string `json:"text"`
}

Script is one script of a Start step. Its text may hold several scripts separated by lines of "---".

type Severity

type Severity int

Severity is how bad a diagnostic is: errors stop a run, warnings don't.

const (
	Error Severity = iota
	Warning
)

type Spec

type Spec struct {
	Kind Kind
	In   []Port // none (Start, Source) or one
	Out  []Port // none (Export), one, or yes and no (Condition)
}

Spec describes a kind of step.

func SpecOf

func SpecOf(k Kind) (Spec, bool)

SpecOf describes a kind; ok is false for unknown kinds.

func (Spec) Input

func (s Spec) Input(name string) (Port, bool)

Input returns the spec's input port name, or false.

func (Spec) Output

func (s Spec) Output(name string) (Port, bool)

Output returns the spec's output port name, or false.

type Step

type Step struct {
	Status StepStatus `json:"status"`
	// Key is the recipe of the result (StepKeys): a result whose key
	// still matches is reused by the next run.
	Key string `json:"key"`
	Out *Value `json:"out,omitempty"`
	// Branch is the branch a condition took ("yes"/"no").
	Branch string `json:"branch,omitempty"`
	// Code and Err say why it failed (or was skipped: Code).
	Code     string    `json:"code,omitempty"`
	Err      string    `json:"err,omitempty"`
	Warnings []string  `json:"warnings,omitempty"`
	Seconds  float64   `json:"seconds,omitempty"` // how long it took
	At       time.Time `json:"at,omitzero"`
}

Step is one step's state for one item: the checkpoint a run keeps.

func (*Step) Finished

func (s *Step) Finished() bool

Finished reports whether the step needs no more work.

type StepStatus

type StepStatus string

StepStatus is where one step is for one item.

const (
	StepPending StepStatus = ""
	StepRunning StepStatus = "running"
	StepDone    StepStatus = "done"
	StepFailed  StepStatus = "failed"
	// StepSkipped: the item did not reach the step (the other branch of
	// a condition, or a step before it failed: Code says which).
	StepSkipped StepStatus = "skipped"
)

type Template

type Template struct {
	ID string
	// Name and About are English; the UI translates them (i18n.T).
	Name, About string
	// contains filtered or unexported fields
}

Template is a ready-made workflow.

func TemplateByID

func TemplateByID(id string) (Template, bool)

TemplateByID returns a template, or false.

func (Template) Make

func (t Template) Make(id, name string, now time.Time, o TemplateOptions) *Workflow

Make builds a workflow from the template.

type TemplateOptions

type TemplateOptions struct {
	Model    string // the TTS model of Speak and Convert steps
	Voice    string // their voice ("" = the model's default)
	Language string // their language ("" = auto)
}

TemplateOptions fill in what a template leaves to the app.

type Type

type Type string

Type is the type of the value a port carries.

const (
	TypeText       Type = "text"
	TypeAudio      Type = "audio"
	TypeTranscript Type = "transcript" // text with times (segments, words)
	// TypeSame, as an output's type, is the type of the step's input
	// (Translate, Condition).
	TypeSame Type = "same"
)

func (Type) Label

func (t Type) Label() string

Label names a value type.

type Value

type Value struct {
	Type Type `json:"type"`
	// File holds the value: audio (WAV), text (UTF-8) or a transcript
	// (JSON, core.Transcript); relative to the run's folder, or absolute
	// for files exported elsewhere.
	File string `json:"file,omitempty"`
	// Text is the start of a text or transcript, to show.
	Text    string  `json:"text,omitempty"`
	Chars   int     `json:"chars,omitempty"`
	Seconds float64 `json:"seconds,omitempty"` // audio, transcripts
	Lang    string  `json:"lang,omitempty"`
}

Value is a step's result for an item.

type View

type View struct {
	X    float64 `json:"x"`
	Y    float64 `json:"y"`
	Zoom float64 `json:"zoom"`
}

View is a canvas's pan and zoom: the content point at the canvas's top-left corner, and the scale.

type Workflow

type Workflow struct {
	Version   int       `json:"version"`
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
	Nodes     []Node    `json:"nodes"`
	Edges     []Edge    `json:"edges"`
	// View is where the canvas looked last.
	View View `json:"view"`
	// Seq numbers new nodes and edges ("n7", "e12").
	Seq int `json:"seq"`
}

Workflow is a saved workflow: its graph and its inputs.

func New

func New(id, name string, now time.Time) *Workflow

New makes an empty workflow: Start → Speak → Export.

func (*Workflow) AddNode

func (w *Workflow) AddNode(k Kind, x, y float64) string

AddNode adds a step of kind k at x, y with its default settings and returns its id ("" past MaxNodes).

func (*Workflow) Clone

func (w *Workflow) Clone() *Workflow

Clone deep-copies the workflow.

func (*Workflow) Connect

func (w *Workflow) Connect(from, fromPort, to, toPort string) (string, error)

Connect links from's output port to to's input port and returns the link's id. It refuses ("" and why) links to the step itself, between ports that do not exist, and duplicates. Types are checked by Validate, so that a link can be made before the step feeding it is set up.

func (*Workflow) Duplicate

func (w *Workflow) Duplicate(id, name string, now time.Time) *Workflow

Duplicate copies a workflow under a new id and name.

func (*Workflow) Edge

func (w *Workflow) Edge(id string) *Edge

Edge returns the edge id, or nil.

func (*Workflow) FreeSpot

func (w *Workflow) FreeSpot() (float64, float64)

FreeSpot is where a new step goes: the first cell of a three-column grid that no step covers.

func (*Workflow) Incoming

func (w *Workflow) Incoming(id string) []Edge

Incoming are the links into node id, in order.

func (*Workflow) InputNode

func (w *Workflow) InputNode() *Node

InputNode is the workflow's Start or Source step (the first), or nil.

func (*Workflow) Items

func (w *Workflow) Items() []Item

Items are the items of the workflow's input step, in order (nil without one). Duplicates of a content get distinct keys by occurrence.

func (*Workflow) Node

func (w *Workflow) Node(id string) *Node

Node returns the node id, or nil.

func (*Workflow) Normalize

func (w *Workflow) Normalize()

Normalize makes a document read from storage safe to use: unknown kinds, links to missing steps or ports and duplicates go; strings, numbers and lists are clamped to their limits; missing defaults are filled. It never fails.

func (*Workflow) Outgoing

func (w *Workflow) Outgoing(id string) []Edge

Outgoing are the links out of node id, in order.

func (*Workflow) RemoveEdge

func (w *Workflow) RemoveEdge(id string)

RemoveEdge removes a link.

func (*Workflow) RemoveNode

func (w *Workflow) RemoveNode(id string)

RemoveNode removes a step and its links.

Jump to

Keyboard shortcuts

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