Python API
The canonical public entry point is compile_document, which compiles one SSMD
document or explicitly configured plain-text document and returns a CompileResult.
Its plan is the immutable, round-trippable renderer-facing FlowPlan; its
diagnostics describe compilation, and an optional PreparationTrace holds compiler
provenance separately. UtterancePlanner.plan is also supported and returns the
same current FlowPlan directly.
The Python defaults are repair-first with best-effort spaCy enrichment: PlannerConfig uses text_preparation="auto" and renderability_mode="repair"; auto resolves to SSMD-authoritative preparation for SSMD input and TTSReady/Spokenform for plain text. Explicit spokenform on SSMD is a warned legacy mode. Pause-activation policy is not a PlannerConfig field, and LinguisticsConfig uses local-model auto. Auto prefers installed compatible models sm, md, lg, trf, then falls back safely if spaCy or models are unavailable. No model is downloaded.
To require a specific installed model, set require_spacy=True and configure its model or tier. The plan records final pass-B token provenance in linguistic_runs; provider documents are not retained. Set use_spacy=False for deterministic opt-out.
V7 token.span, pos, tag, lemma, and morph are the authoritative linguistic context for the exact prepared segment text. Consumers should not retokenize or rerun spaCy. Optional replacement spans are local to final prepared segment.text; original spellings are stored as provenance strings, while complete source offsets and preparation maps belong in the optional trace sidecar.
Sentence segmentation and private topology
PhraseSplit is an advisory sentence-boundary provider, not an owner of compiler topology. UtterPlan validates each whole proposal batch, maps accepted run-local offsets once into prepared spoken-text coordinates, then recomputes paragraph and sentence indices from parser paragraph events and accepted boundaries. If PhraseSplit fails or returns malformed/incomplete coverage, deterministic conservative fallback preserves the text and emits diagnostics. Automatic cuts that divide provider-aware lexical content are discarded or merged; the final flow-projection token-edge check remains active.
Semicolon and context-safe colon separators, plus optional trusted clause/parenthetical candidates, form private sentence parts. Language, directive, authored-pause, marker, and media cuts subdivide those parts without changing their indices. Exact surface and non-whitespace coverage validation runs in strict and repair renderability modes alike. Parts are not public fields: the compact ordered v7 flow serializes canonical boundary kinds at segment edges; FlowUnit grouping is fixed paragraph-local and independent of renderer chunk choices.
Canonical single-document compiler
compile_document is the shared semantic interpretation boundary for independent
consumers. It does not load books, traverse chapters, or manage consumer workspaces.
SSMD header language takes precedence over a fallback; the explicit
fallback_language keyword is a per-call fallback override, never a forced language.
PlannerConfig.language remains required for compatibility and supplies the fallback
when fallback_language is omitted. Plain input must have a language fallback.
from utterplan import PlannerConfig, compile_document
result = compile_document(
ssmd_source,
input_format="ssmd",
config=PlannerConfig(language="en-us"),
trace=True,
)
plan = result.plan
assert result.plan is plan
assert result.trace is not None
Use input_format="plain" only for explicitly configured plain text. A trace
contains explanatory per-unit preparation information but is not serialized into
the plan, is not renderer input, and does not change plan.plan_id. Its source
ranges index SSMD-clean structural text; transformation output ranges index prepared
spoken text, using Python string character offsets.
Build and replan a RenderPlan
build_render_plan is the shared schema-v7-only projection API. It consumes an
already compiled FlowPlan and a shared renderplan.RenderProfile; it does not
prepare text again or depend on renderer, G2P, or audio packages. Replanning passes
the exact prior RenderPlan and its matching preflight report together:
from renderplan.codec import load_plan, load_preflight, load_profile, save_plan
from utterplan import FlowPlan, build_render_plan
source = FlowPlan.load("chapter.utterplan.toml")
profile = load_profile("voice.renderprofile.toml")
plan = build_render_plan(source, profile)
save_plan(plan, "chapter.renderplan.toml")
previous = load_plan("chapter.renderplan.toml")
preflight = load_preflight("chapter.preflight.toml")
next_plan = build_render_plan(
source,
profile,
previous_plan=previous,
preflight=preflight,
)
save_plan(next_plan, "chapter.next.renderplan.toml")
The previous plan and preflight are a required pair. UtterPlan preserves successful
prior partitions and replaces only exact failed speech occurrences. Backend metrics
remain diagnostics supplied by preflight; UtterPlan does not estimate them. Use
utterplan render-plan --explain to format the already-built decisions.
Inspect logical role coverage
The public role-coverage helpers expose source inventory independently of projection or renderer bindings. logical_role_inventory() counts explicit role references and speech using the profile default; profile_role_coverage() compares those requirements with one complete RenderProfile, preserving first-occurrence order for required roles and deterministic sorting for available roles. The returned LogicalRoleInventory and ProfileRoleCoverage types separate source inventory from profile coverage. Both functions are available from the package root:
from renderplan.codec import load_profile
from utterplan import (
FlowPlan,
logical_role_inventory,
profile_role_coverage,
assert_profile_role_coverage,
)
source = FlowPlan.load("chapter.utterplan.toml")
inventory = logical_role_inventory(source)
profile = load_profile("cast.renderprofile.toml")
coverage = assert_profile_role_coverage(source, profile)
print(inventory.explicit_roles, inventory.explicit_occurrences)
print(coverage.required_roles, coverage.available_roles, coverage.missing_roles)
Empty and audio-only segments do not require a role. assert_profile_role_coverage() raises the normal renderplan.role.missing projection error with all missing role names; build_render_plan() performs this check before grouping or replanning.
Persistable planning attempts
compile_attempt and UtterancePlanner.compile_attempt expose a finalized planning
outcome without raising solely because a segment is not renderable. They still raise
for input, configuration, and planning failures. The existing compile_document,
UtterancePlanner.compile, and plan APIs remain strict and continue raising
PlanRenderabilityError when renderability blocks completion.
Attempts are separate from canonical plans. A blocked attempt retains an inspect-only
candidate draft; it is not a valid FlowPlan and cannot be loaded by
FlowPlan.load(). Persist it with PlanningAttempt.save() and restore it with
PlanningAttempt.load(); the attempt TOML schema is
utterplan.planning-attempt.v1, independent of canonical plan schema v7.
from utterplan import PlannerConfig, compile_attempt
attempt = compile_attempt(
"Hello.\n\n.\n\nWorld.",
input_format="plain",
config=PlannerConfig(
language="en-us",
renderability_mode="strict",
),
)
assert attempt.status == "blocked"
attempt.save("chapter.attempt.toml")
for issue in attempt.renderability.issues:
assessment = issue.repair_assessment
if assessment is not None:
print(issue.segment_id, assessment.safe, assessment.action)
print(assessment.blockers)
Repair assessments report the existing conservative options; they do not rewrite
text speculatively. In repair mode, only the planner’s established safe repairs are
applied. utterplan inspect-attempt chapter.attempt.toml --issues shows issues,
source locations, and repair assessments; --segment and --unit select candidate
topology, and --json emits the complete attempt as JSON for inspection.
TOML persistence
Schema v7 is the current semantic contract, while .utterplan.toml is the canonical persisted format. FlowPlan.to_toml() and FlowPlan.from_toml() round-trip the current executable plan; save() writes atomically, and load() accepts TOML only. All normal decode/load and execution paths reject non-v7 plans with schema.version_unsupported; they never migrate implicitly. Historical inputs retain a separate sequential data-only migration path through v6, but v6-to-v7 refuses with migration.recompile_required because omitted boundary opportunities cannot be recovered; recompile the original source.
from utterplan import FlowPlan
toml_text = plan.to_toml()
restored = FlowPlan.from_toml(toml_text)
assert restored == plan
plan.save("chapter.utterplan.toml")
assert FlowPlan.load("chapter.utterplan.toml") == plan
FlowPlan.to_dict() and FlowPlan.from_dict() expose the current v7 executable mapping. Normal decoding accepts v7 only; versioned v5/v6 codecs are reachable solely through explicit serialized-data migration. Promotion to v7 requires source recompilation and does not invent boundaries. utterplan migrate reports that requirement; SSMD source migration remains a separate operation.
Incremental batch compilation
The public batch API compiles independent requests one at a time, atomically commits each successful plan, and yields an outcome without retaining the plan object. Ordinary per-document read, planning, validation, serialization, and write failures become failed outcomes and processing continues by default. Set fail_fast=True to skip later requests after the first failure. Existing files are protected unless force=True is explicit. An optional TOML operational report is refreshed after each outcome.
from pathlib import Path
from utterplan import CompileRequest, PlannerConfig, compile_to_files
requests = [
CompileRequest(
id="chapter-1",
source=Path("chapters/one.ssmd"),
output=Path("plans/one.utterplan.toml"),
input_format="auto",
),
CompileRequest(
id="chapter-2",
source=Path("chapters/two.ssmd"),
output=Path("plans/two.utterplan.toml"),
input_format="auto",
),
]
for outcome in compile_to_files(
requests,
config=PlannerConfig(language="en-us"),
report_path="plans/compile-report.toml",
):
print(outcome.status, outcome.source_label, outcome.output)
The report is operational data, not a semantic plan, and must not be passed to FlowPlan.load(). Unexpected programming and progress-callback errors propagate rather than being converted to document failures.
RenderPlan batch projection
The shared RenderPlan set contract is owned by renderplan. Import its types and codecs from that package; use UtterPlan’s batch module only for UtterPlan-specific request, outcome, set-construction, and projection orchestration APIs. Although utterplan.renderplan_batch retains compatibility re-exports, new consumers should not depend on them.
from renderplan import (
RenderPlanSet,
RenderPlanSetChapter,
RenderPlanSetError,
RenderProfile,
load_renderplan_set,
save_renderplan_set,
)
from utterplan.renderplan_batch import RenderRequest, new_renderplan_set, render_to_files
render_to_files() projects schema-v7 FlowPlan inputs; grouping, source mapping, export, and replan logic remain UtterPlan-owned.
Unified bundle services
compile_bundle(), render_bundle(), and replan_bundle() are the public Python counterparts of utterplan bundle compile|render|replan. They accept a canonical <name>.ssmd-bundle/ path and dispatch book or document behavior from its manifest. The CLI delegates to these services, so selection and path-safety rules are shared.
from utterplan import compile_bundle, replan_bundle, render_bundle
compiled = compile_bundle("novel.ssmd-bundle", chapters="5-17")
projected = render_bundle(
"novel.ssmd-bundle",
profile="narration.renderprofile.toml",
chapters="5-17",
)
refined = replan_bundle(
"novel.ssmd-bundle",
variant=projected.variant,
chapters="5",
)
assert compiled.exit_code == projected.exit_code == refined.exit_code == 0
The compile and render services accept paths and keyword options. chapters defaults to "all"; book bundles select manifest source numbers, while document bundles accept only "all". Rendering requires an explicit profile; replanning requires the exact active variant. Options include output/report paths, force and fail-fast behavior, compile planning settings, and optional progress/start callbacks. Services do not print.
BundleCompileResult, BundleRenderResult, and BundleReplanResult expose the resolved bundle, manifest-declared kind, selected item IDs, per-item outcomes, generated paths, reports, and exit status. Their start records provide resolved configuration to optional callbacks. Invalid or unsafe shared requests raise BundleServiceError or BundleReplanError; item-level failures are reported in result outcomes. The package also exports manifest loader, selector, item-path, result, start, and callback types for integrations that need to inspect dispatch results.
Planner progress callbacks
UtterancePlanner.plan, UtterancePlanner.compile, and compile_document accept an optional keyword-only on_progress callback. It receives typed PlannerProgressEvent objects synchronously in the planner thread. Progress is operational only: it is not added to PlannerConfig or the plan, and enabling a callback does not change plan identity or serialization.
from utterplan import PlannerConfig, PlannerProgressEvent, UtterancePlanner
def report(event: PlannerProgressEvent) -> None:
if event.kind == "run.started":
print(
event.phase,
event.pass_index,
event.language,
event.provider,
event.model,
)
planner = UtterancePlanner(PlannerConfig(language="en-us"))
plan = planner.plan(text, on_progress=report)
The phase events cover parsing, source analysis, preparation, spoken analysis, segmentation, and finalization. Each provider run reports run.started and run.completed; completed counts fully completed runs and total is the number of runs in that phase. When a local spaCy model is actually loaded, model.started and model.completed identify its language, provider, and resolved model. Cached models produce no load events. Events contain primitive metadata only, never spaCy pipelines or documents.
Callbacks should be lightweight. An exception raised by a callback propagates to the caller and can be used to stop planning. A provider invocation such as pipeline(text) is one opaque work unit: events report its start and completion but do not claim smooth percentages or internal progress. If spoken-text preparation leaves the linguistic input unchanged, the planner can reuse source analysis; the spoken_analysis phase events expose details["reused"] = True and no provider-run events are emitted for that reuse. Identity preparation also reports source_analysis as skipped (details["skipped"] = True) because it does not use source analyses; the single actual provider pass runs as logical pass 2.
SSMD input and semantic plan
The SSMD parser accepts dialect 0.9 only. Select SSMD explicitly for unversioned canonical fragments with PlannerConfig(document_format="ssmd"). Older SSMD source must be migrated with ssmd migrate FILE --to 0.9; migrate_plan_data operates on serialized plan mappings, while utterplan migrate imports legacy plans, not source documents.
PlannerConfig.document_format defaults to "plain", so SSMD syntax is never inferred for an ordinary Python string. Set it to "ssmd" for SSMD documents or fragments. There is no compile-time pause activation setting: authored SSMD breaks are represented as PauseIntent, while automatic safe boundaries remain separate boundary_before / boundary_after values. Consumers choose how to realize either fact without changing plan identity.
from utterplan import PlannerConfig, compile_document
ssmd_source = """---
ssmd_version: "0.9"
title: API example
language: en-us
---
Hello [world]{emphasis="strong"}.
"""
result = compile_document(
ssmd_source,
input_format="ssmd",
config=PlannerConfig(language="en-us"),
trace=True,
)
plan = result.plan
segment = plan.flow[0].segments[0]
assert plan.document.ssmd_version == "0.9"
assert result.trace is not None # source spans/diagnostics are sidecar data
print(segment.directives.emphasis)
The document record retains compact portable document information. Effective directives and pause intents live on their owning flow segments. Compiler-only source spans and preparation coordinate maps remain in the optional trace. See the coordinate-space contract and consumer guide for renderer responsibilities.
Flow segments and local tokens
A FlowPlan stores ordered FlowUnit objects. Each unit owns its ordered segments, so consumers do not join plan-global IDs. Token offsets use Python-character coordinates local to segment.text:
FlowUnit grouping is always paragraph-local; it is not a renderer-chunk selection. Each FlowSegment carries boundary_before and boundary_after tuples of canonical BoundaryKind values (clause, sentence, paragraph, parenthetical, voice_change). These are safe downstream cut opportunities, not commands or pause durations. Authored SSMD breaks live independently in pause_before / pause_after, so both may coexist at one edge. A segment is not necessarily one TTS request.
for unit in plan.flow:
for segment in unit.segments:
for token in segment.tokens:
surface = segment.text[token.start : token.end]
print(segment.language, surface, token.lemma, token.pos)
Authored pause intent is local to the segment edge: it is an authored strength or exact timed break (including explicit none), not an automatic sentence/parenthetical boundary. Downstream consumers choose whether to realize authored pauses natively, automatically, or manually. Heading levels and marker names are already localized to the segments and units that own them. Linguistic token views do not expose engine-token IDs or token counts.
Audio/media segments
AudioDirective is already part of the public API. Inspect it on the segment; its
src is an opaque renderer input, and segment.text is optional spoken fallback:
segment = plan.flow[0].segments[0]
audio = segment.directives.audio
if audio is not None:
print(audio.src) # Resolve externally; do not parse SFX URI syntax here.
fallback_text = segment.text # May be "" when no spoken fallback exists.
else:
spoken_text = segment.text
Each SSMD audio annotation is represented by one audio-bearing segment. Separate
occurrences may have the same src; segment.text is not the media identity and
consumers do not need to inspect raw SSMD annotations to find media.
Planner configuration
Planning and plan records
UtterancePlan, PlanSegment, and PlanUnit remain legacy compiler/migration models. Fresh compilation returns FlowPlan; renderers should use only the v7 flow contract.
Renderer-neutral SSMD directives
The v7 public model exposes FlowPlan.flow, compact document and linguistics records, and local segment fields for text, language, canonical boundary opportunities, authored pause intent, directives, markers, headings, and linguistic tokens. FlowSegment.directives contains typed semantics after scope and voice-default resolution. TokenView offsets address only its owning segment’s text; provider documents are not retained. See the consumer guide for renderer responsibilities.
TokenView carries optional lemma, POS, tag, and morph facts. LinguisticProvenance identifies the analysis provider and model without retaining provider state. Exact raw source is stored in the optional FlowPlan.source record, introduced in v6 and retained in v7, which may be absent on migrated v5 plans. Source spans and preparation coordinate maps remain available only in an optional PreparationTrace sidecar.
Errors
Planning and loading failures derive from utterplan.UtterPlanError. Important
public subclasses include ConfigurationError, PlanningError,
PlanFormatError, PlanValidationError, and UnsupportedSchemaError.
PlanMigrationError and MigrationPathError report migration-specific failures. UnsupportedSchemaError remains reserved for a schema newer than the installed package understands.
PlanRenderabilityError presents the same actionable source and spoken context as the CLI, including safe repair opportunities, semantic blockers, and a next action. Safe punctuation-only repair is the default; choose PlannerConfig(renderability_mode="strict") when a caller needs to reject every repair opportunity. Symbols are never assigned guessed pronunciations.
Schema migration API
from utterplan import (
FlowPlan,
CURRENT_SCHEMA_VERSION,
MigrationResult,
MigrationStep,
SUPPORTED_SCHEMA_VERSIONS,
migrate_plan_data,
)
result: MigrationResult = migrate_plan_data(serialized_mapping)
assert result.target_version == CURRENT_SCHEMA_VERSION
plan = FlowPlan.from_dict(result.data)
Migration functions operate on plain JSON-compatible mappings and never mutate their input. MigrationResult records source and target versions, sequential steps, and source and target plan IDs. Current-schema migration is an exact no-op.