Metadata-Version: 2.5
Name: framedown
Version: 0.1.0
Summary: Write Markdown, render video.
License-Expression: Apache-2.0
License-File: LICENSE
Requires-Python: >=3.14
Requires-Dist: jinja2>=3.1.6
Requires-Dist: markdown-it-py>=4.0
Requires-Dist: mdit-py-plugins>=0.5
Requires-Dist: playwright>=1.55
Requires-Dist: pydantic>=2.12
Requires-Dist: pygments>=2.19
Requires-Dist: pyyaml>=6.0.3
Requires-Dist: rich>=14.0
Requires-Dist: typer>=0.20
Provides-Extra: all
Requires-Dist: faster-whisper>=1.2; extra == 'all'
Requires-Dist: fastmcp<5,>=4.2; extra == 'all'
Requires-Dist: imageio-ffmpeg>=0.6; extra == 'all'
Requires-Dist: starlette>=0.48; extra == 'all'
Requires-Dist: textual>=6.0; extra == 'all'
Requires-Dist: uvicorn>=0.38; extra == 'all'
Requires-Dist: watchfiles>=1.1; extra == 'all'
Provides-Extra: captions
Requires-Dist: faster-whisper>=1.2; extra == 'captions'
Provides-Extra: ffmpeg
Requires-Dist: imageio-ffmpeg>=0.6; extra == 'ffmpeg'
Provides-Extra: mcp
Requires-Dist: fastmcp<5,>=4.2; extra == 'mcp'
Provides-Extra: preview
Requires-Dist: starlette>=0.48; extra == 'preview'
Requires-Dist: uvicorn>=0.38; extra == 'preview'
Requires-Dist: watchfiles>=1.1; extra == 'preview'
Provides-Extra: tui
Requires-Dist: textual>=6.0; extra == 'tui'
Description-Content-Type: text/markdown

# framedown

Write Markdown, render video. Marp-style scenes become MP4/WebM/GIF with animation, TTS narration and multilingual subtitles. Python, with an MCP server and agent skill.

> **Status:** 0.1.0, the first public release (`pip install framedown`; see the [changelog](CHANGELOG.md)). All phases (0–7: render pipeline, agents, MCP server and its container, audio,
> multilingual, quality, rich content, user guide and examples) are done; the table below says what each one added. Specs
> live in [`specs/`](specs/) and are the source of truth.

**New here?** Read the [user guide](docs/guide.md) — install, write, check, render, narration,
captions and languages, step by step — and browse the [examples](examples/), starting with a
narrated tour of framedown made by framedown. AI agents: see [`skills/`](skills/).

## Implementation status

| Phase | Scope | State |
| --- | --- | --- |
| 0 | Packaging, quality tooling, CI, license gate, traceability | ✅ done |
| 1 | Markdown → MP4: parser, timeline, layouts, `midnight` theme, WAAPI runtime, Chromium capture, ffmpeg encode, CLI + Python API | ✅ done |
| 2 | Agents: MCP server, agent skill, `check`, `export` (HyperFrames, HTML player), `init`, `list` | ✅ done |
| 2b | Container: Dockerfile and docker-compose for the MCP server | ✅ done |
| 3 | Audio: TTS plugins (`tone` built in, `framedown-kokoro` package), `duration: auto`, music with ducking, SRT/VTT and burned captions | ✅ done |
| 4 | Multilingual: `i18n/<lang>.yaml` catalogs, translator plugins, `translate`, per-language files or audio/subtitle tracks, `sync: longest` | ✅ done |
| 5 | Quality: deterministic BeginFrame capture, parallel workers, live preview, `framedown tui`, pinned Docker image | ✅ done |
| 6 | Content: code steps, Mermaid flowcharts, `line`/`donut`/`mermaid`/`quote`/`split` layouts, embedded video clips, Ken Burns, Marp import/export, plugin guide | ✅ done |
| 7 | Docs: user guide (`docs/guide.md`), example videos (`examples/`), agent skills for Claude Code, Claude Desktop and other agents (`skills/`) | ✅ done |

## Requirements

- Python ≥ 3.14
- ffmpeg on `PATH` (or `pip install "framedown[ffmpeg]"`, or `FRAMEDOWN_FFMPEG=/path/to/ffmpeg`)
- Chromium headless shell, installed once with `framedown install`

## Install (from source)

```bash
git clone <repo> framedown && cd framedown
uv sync
uv run framedown install     # downloads the Chromium headless shell
uv run framedown doctor      # chromium: ok · ffmpeg: ok · fonts: ok
```

## Quick start

`video.md`:

```markdown
---
framedown: 1
title: Hello
size: 1920x1080        # or 16:9, 9:16, 1:1
fps: 30
theme: midnight
transition: fade 0.6
duration: 4
---

<!-- layout: title, enter: blur -->
## Demo
# Markdown → video
One scene per `---`.

---

<!-- layout: list, duration: 5, transition: slide 0.8 -->
# How it works
- Front matter sets size, fps, theme and defaults
- HTML comments carry scene directives
- Each frame is a seek of a paused animation timeline
```

```bash
framedown validate video.md          # diagnostics: file:line: error[FD-E004]: …
framedown plan video.md              # scenes, starts, durations, transitions (--json)
framedown snapshot video.md --at s2.mid,s2.in
framedown render video.md -o video.mp4 --quality draft   # half resolution, fast
framedown render video.md            # final quality → video.mp4
```

More complete examples, ready to render, live in [`examples/`](examples/); the
[user guide](docs/guide.md) walks through every step.

## Example videos

Every video below was written in Markdown and rendered by framedown with Kokoro voices; click a
cover to watch it. The sources and the command that renders each one are in
[`examples/`](examples/).

| Video | What it shows |
| --- | --- |
| [![framedown tour, English](https://raw.githubusercontent.com/ecrespo/framedown/main/docs/videos/tour.en.jpg)](https://github.com/ecrespo/framedown/blob/main/docs/videos/tour.en.mp4) | **[framedown tour](https://github.com/ecrespo/framedown/blob/main/docs/videos/tour.en.mp4)** (2:08, English) — install, write, check, render, narration, captions, languages, and asking Claude Code or Claude Desktop for a video with the framedown skill. |
| [![framedown tour, Spanish](https://raw.githubusercontent.com/ecrespo/framedown/main/docs/videos/tour.es.jpg)](https://github.com/ecrespo/framedown/blob/main/docs/videos/tour.es.mp4) | **[Recorrido por framedown](https://github.com/ecrespo/framedown/blob/main/docs/videos/tour.es.mp4)** (2:08, español) — the same tour from the Spanish catalog `i18n/es.yaml`: one source, one video per language. |
| [![Feature showcase](https://raw.githubusercontent.com/ecrespo/framedown/main/docs/videos/showcase.jpg)](https://github.com/ecrespo/framedown/blob/main/docs/videos/showcase.mp4) | **[Feature showcase](https://github.com/ecrespo/framedown/blob/main/docs/videos/showcase.mp4)** (2:34) — every layout: code steps, charts, Mermaid, quote, split, an image with Ken Burns, an embedded clip; captions burned in. |
| [![The water cycle](https://raw.githubusercontent.com/ecrespo/framedown/main/docs/videos/water.jpg)](https://github.com/ecrespo/framedown/blob/main/docs/videos/water.mp4) | **[The water cycle](https://github.com/ecrespo/framedown/blob/main/docs/videos/water.mp4)** (1:29) — Spanish source with English and French catalogs, rendered as one MP4 with three audio and subtitle tracks (`--mode tracks`). |
| [![Marp deck](https://raw.githubusercontent.com/ecrespo/framedown/main/docs/videos/deck.jpg)](https://github.com/ecrespo/framedown/blob/main/docs/videos/deck.mp4) | **[From slides to video](https://github.com/ecrespo/framedown/blob/main/docs/videos/deck.mp4)** (1:36) — a Marp deck imported with `framedown import marp`; presenter notes become the narration. |

## Format

- **Front matter** (YAML): `framedown`, `title`, `lang`, `size`, `fps`, `theme`, `transition`,
  `duration`, `enter`, `style` (colors, background, fonts, `font_scale`). Unknown keys warn (`FD-W100`).
- **Scenes** are separated by `---`. Directives go in an HTML comment at the top of the scene:
  `<!-- layout: stat, duration: 4, transition: wipe 0.9, enter: zoom -->`.
- **Transitions:** `cut`, `fade`, `slide`, `wipe`, `zoom` — they occupy the first *d* seconds of
  the incoming scene, so the total duration is the sum of scene durations.
- **Enter effects:** `rise`, `blur`, `zoom`, `wipe`, `none`, staggered per element.
- **Layouts:** `title`, `list`, `stat`, `code` (Pygments highlighting), `media` (full-bleed image
  or clip), `bars` (animated bar chart from a `label | value` table), `line` (1–3 series),
  `donut`, `mermaid`, `quote` (quote + attribution) and `split` (text beside a visual,
  `class: reverse` swaps). Inferred when not given.
- **Code steps:** ```` ```python {steps="1-3,4-6"} ```` highlights each line range in turn and
  dims the rest (`FD-E007` for ranges outside the block).
- **Mermaid:** ```` ```mermaid ```` flowcharts (`graph`/`flowchart`, `TD`/`LR`/`RL`/`BT`, node
  shapes `[]`, `()`, `{}`, `(())`, `([])`, links `-->`, `---`, `-.->`, `==>`, labels) are drawn as SVG
  by framedown itself; nodes appear in order and links draw after them. Anything else is `FD-E008`.
- **Images and video:** `![alt](photo.jpg){kenburns=in|out|left|right}` zooms or pans a picture
  over its scene. `![alt](clip.mp4){start=2 duration=4 muted loop}` embeds a clip (MP4, MOV,
  WebM): its frames are extracted once with ffmpeg (cached in `.framedown/cache/video`) so
  renders stay deterministic, and its sound is mixed in unless `muted`.
- **Narration:** `> [!SAY] text` (or `> [!SAY:es]`) in a scene is spoken, never shown.
  `<!-- duration: auto -->` sizes the scene to its narration (audio + 0.8 s).
- **Music:** `music: assets/bed.mp3` or `music: {src: …, volume: 0.25}` — looped or trimmed,
  faded out over the last second, ducked under narration.
- **Captions:** `captions: on` (default: `<out>.<lang>.srt`/`.vtt` next to the video), `burn`
  (drawn into the frames too) or `off`.
- **Elements:** headings (`##` kicker, `#` headline), paragraphs, lists, code blocks, tables, images,
  raw HTML (scripts stripped, `FD-W105`); trailing `{#id .class key=value}` attributes.

The JSON Schema of the model: `framedown schema`.

## CLI

| Command | What it does |
| --- | --- |
| `validate FILE [--json]` | Parse and report diagnostics; exit 1 on errors |
| `plan FILE [--json]` | Timeline table or plan JSON |
| `render FILE [-o OUT] [--quality draft\|final] [--fps N] [--size S] [--lang L[,L…]] [--mode files\|tracks] [--tts ENGINE] [--allow-cloud] [--workers N] [--json]` | Render `.mp4`, `.mkv`, `.webm` or `.gif` (+ SRT/VTT when narrated) |
| `translate FILE --to L[,L…] [--engine E] [--json]` | Fill `i18n/<lang>.yaml` with machine translations |
| `snapshot FILE --at T[,T…] [--out-dir D] [--lang L]` | PNG frames at seconds or aliases `sN`, `sN.mid`, `sN.in`, `sN.end` |
| `preview FILE [--port P] [--host H] [--lang L]` | Live preview with a scrubber; reloads on save (extra `framedown[preview]`) |
| `tui FILE` | Terminal UI: scenes, diagnostics, validate / snapshot / render (extra `framedown[tui]`) |
| `schema [--out FILE]` | JSON Schema of the video model |
| `install` | Install the Chromium headless shell |
| `doctor [--json]` | Check Chromium, ffmpeg and fonts |
| `check FILE [--strict] [--render] [--json]` | Content checks: ≤ 12 on-screen words (`FD-W102`), narration rate (`FD-W103`), missing files (`FD-E012`), overflow with `--render` (`FD-W104`) |
| `export FILE --format hyperframes\|html\|marp [-o DIR]` | HyperFrames composition (one clip per scene), a standalone HTML player, or a Marp deck (narration as presenter notes) |
| `import marp FILE [-o OUT] [--force]` | Convert a Marp deck: directives → scene directives, presenter notes → narration (`duration: auto`); writes `<stem>.framedown.md` |
| `init [DIR] [--template explainer] [--force]` | New project: `video.md` + `framedown.toml` |
| `list layouts\|themes\|voices [--json]` | Installed plugins |
| `voices preview --text T [--voice V] [--lang L] [--tts E] [-o WAV]` | Audition a voice; prints path and duration |
| `skills install [--dest DIR] [--force]` | Install the agent skill (default `~/.claude/skills/framedown`) |
| `mcp [--http --host H --port P] [--root DIR]` | Run the MCP server (extra `framedown[mcp]`) |
| `--version` | Print the version |

`render --quality draft` renders at half resolution for fast iteration.
Output is styled with Rich on a terminal and plain otherwise (`NO_COLOR` respected).
Exit codes: `0` ok · `1` invalid input · `2` usage · `3` missing dependency · `4` render/encode
failure · `5` security · `130` interrupted. Runtime error codes: `FD-E600` missing dependency,
`FD-E601` render failure, `FD-E602` cancelled, `FD-E603` unknown job.

## Python API

```python
import framedown

video = framedown.load("video.md")            # or framedown.loads(text)
problems = framedown.validate("video.md")     # list[Diagnostic]
timeline = framedown.plan(video)              # scenes, frames, transitions
framedown.snapshot(video, ["s1.mid"], out_dir="shots")
result = framedown.render(video, output="video.mp4", quality="final",
                          progress=lambda e: print(e.stage, e.frame, e.frames))
print(result.outputs, result.duration, result.frames)
```

Several languages: `framedown.render(video, langs=["es", "en"], mode="files"|"tracks")`;
`framedown.translate(video, ["en"])` fills the catalogs.
Also `framedown.check(path, render=False)`, `framedown.export(video, "hyperframes"|"html"|"marp")`,
`framedown.import_marp("deck.md")`
and `framedown.init(dir)`. Background renders: `framedown.jobs.JobManager().submit(video)` with
`status`, `cancel` (stops within 2 s and deletes the partial file) and `wait`.

Layouts, themes, TTS engines, translators and adapters are plugins (entry points
`framedown.layouts`, `framedown.themes`, `framedown.tts`, `framedown.translators`,
`framedown.adapters`); [`docs/plugins.md`](docs/plugins.md) shows how to write one. `framedown.render(video, tts="tone")` picks the engine; `framedown.tts_preview(text, output=Path("hi.wav"))`
auditions one. `RenderResult.outputs` lists the video and its subtitle files; `.diagnostics` holds `FD-W301`/`W302`.

## Narration, music and captions

```bash
framedown render video.md --tts tone      # built-in deterministic engine: drafts, CI, timing
pip install framedown-kokoro              # real voices (separate package, see below)
framedown render video.md                 # tts: auto → highest-priority installed engine
framedown voices preview --text "Hola" --lang es -o hola.wav
```

- **Engines** are plugins (`framedown.tts` entry points). `tone` ships with framedown;
  [`framedown-kokoro`](plugins/framedown-kokoro/) is a **separate package** because Kokoro's
  dependencies include espeak-ng (GPL-3.0) and, with default torch wheels on Linux, proprietary
  NVIDIA libraries — framedown itself stays GPL-free. Without an engine, narrated renders exit 3
  (`FD-E600`). Cloud engines need `allow_cloud = true` under `[security]` or `--allow-cloud` (`FD-E502`).
- Speech is cached in `.framedown/cache/tts/` (SHA-256 of engine, version, voice, language, text).
- Narration starts 0.3 s into its scene; one AAC 48 kHz track (Opus for WebM) is muxed, its
  duration within one frame of the video. GIF output has no audio.
- Caption cues: ≤ 2 lines × 42 characters, ≤ 7 s, timed from word timings. Engines without
  timings are aligned with faster-whisper (`framedown[captions]`) or estimated (`FD-W301`).
  `check` warns on cues faster than 17 characters/s (`FD-W302`).
- Defaults go in `framedown.toml`: `[tts] engine = "auto"`.

## Languages

```yaml
lang: es                    # source language
languages: [es, en]         # output languages
voices: {en: af_heart}      # voice per language
sync: longest               # every language gets the longest duration of each scene
```

```bash
framedown translate video.md --to en                 # fills i18n/en.yaml via [translate] command
framedown render video.md --lang es,en               # video.es.mp4, video.en.mp4 (+ .srt/.vtt each)
framedown render video.md --lang es,en --mode tracks # one MP4: audio + subtitles per language
```

- `i18n/<lang>.yaml` holds one entry per heading, paragraph, list item, table label and narration
  (`id`, `source`, `source_hash`, `text`, `origin`, `machine_hash`). Edit `text` freely: entries
  with `origin: human` or edited by hand are never overwritten; machine entries whose source
  changed are re-translated; removed ids move under `stale:`.
- Translators are plugins (`framedown.translators`). The built-in `command` translator runs
  `[translate] command = ["python", "translate.py"]`, sending `{"source", "target", "texts"}` as
  JSON on stdin and reading `{"texts": [...]}` from stdout (`FD-E402` on failure, exit 4).
  Through MCP the connected agent translates (`translate` → `apply_translations`), no API keys.
- Rendering a language uses its catalog on screen and in narration; empty entries use the
  source text (`FD-W401`). An inline `> [!SAY:en]` wins over the catalog.
- `--mode tracks` (MP4 `mov_text` or MKV `subrip` subtitles, ISO 639-2 tags) needs `sync: longest`
  with several languages (`FD-E401`); the frames use the source language.

## Agents: MCP server and skill

```bash
uv sync --extra mcp --extra preview --extra tui
framedown mcp --root ./my-video                 # stdio (for Claude Code, Claude Desktop, …)
framedown mcp --http --port 8000 --root ./my-video   # streamable HTTP on 127.0.0.1:8000/mcp
framedown skills install                        # ~/.claude/skills/framedown
```

Claude Code: `claude mcp add framedown -- framedown mcp --root /path/to/project`.

**Tools:** `validate`, `plan`, `check`, `snapshot` (returns the PNGs as images), `render`
(returns a `job_id` at once; progress notifications; poll `render_status`), `render_status`,
`cancel_render`, `export`, `init`, `list_layouts`, `list_themes`, `list_voices`, `tts_preview`
(WAV path + duration), `translate` (returns the pending entries for the agent to translate) and
`apply_translations` (writes them). `render` takes `lang` as one language or a list, and `mode`.
**Resources:** `framedown://spec`, `framedown://layouts/{name}`, `framedown://themes/{name}`,
`framedown://examples/{reference_demo|explainer|narrated|multilingual}`.
**Prompts:** `video_from_topic`, `video_from_document`, `video_from_marp`.
Every path is confined to `--root` (`FD-E500`); tool errors start with their code
(`FD-E004: unknown transition 'spin' (video.md:7)`).

The skill teaches agents the loop *validate → plan → check → snapshot → draft render → final
render* and the limits (≤ 12 on-screen words per scene, ~2.5 narration words/s).
Ready-to-use variants for Claude Code, Claude Desktop (a `framedown.zip` to upload) and any
other agent live in [`skills/`](skills/), with set-up steps for each.

## Preview, terminal UI and speed

```bash
uv sync --extra preview --extra tui
uv run framedown preview video.md        # http://127.0.0.1:8765/ — reloads within a second of each save
uv run framedown tui video.md            # v validate · s snapshot the selected scene · r render · q quit
uv run framedown render video.md --workers 4
```

- **Preview** serves only `/` (the player) and `/events` (server-sent `reload`), with media
  embedded, so it never serves files from disk. It answers loopback `Host` headers only; bind to
  another interface with `--host` only on a network you trust (there is no authentication).
- **Deterministic frames.** On Linux every frame is captured with Chromium's BeginFrame
  control (`HeadlessExperimental.beginFrame`): two renders of the same file give byte-identical
  PNGs. Elsewhere, or if the probe fails, framedown falls back to screenshots.
  `FRAMEDOWN_CAPTURE=beginframe|screenshot` forces a method.
- **Workers.** `--workers N` (also the MCP `render` tool) splits the frames into N contiguous
  shards, each in its own Chromium, writes lossless segments and encodes them once: the output
  has exactly the frames of a single-worker render. On the 840-frame reference demo, 4 workers
  take 44 % of the single-worker time.

## Docker (MCP server)

The image bundles `framedown[mcp]`, the Chromium headless shell and ffmpeg, and runs as a
non-root user in `/work`. The base image is pinned by digest and Chromium by the locked
Playwright version, so builds are reproducible.

```bash
mkdir -p work                                   # your project folder (video.md, assets/)
FRAMEDOWN_UID=$(id -u) FRAMEDOWN_GID=$(id -g) docker compose up -d --build
# MCP endpoint: http://127.0.0.1:8000/mcp
claude mcp add --transport http framedown http://127.0.0.1:8000/mcp
```

| Variable | Default | Meaning |
| --- | --- | --- |
| `FRAMEDOWN_WORKDIR` | `./work` | Host folder mounted at `/work` (the server's root) |
| `FRAMEDOWN_PORT` | `8000` | Host port, published on `127.0.0.1` only |
| `FRAMEDOWN_UID` / `FRAMEDOWN_GID` | `1000` | Build args `UID`/`GID`: files written by the server belong to this user |

The HTTP transport has **no authentication**; keep it on localhost or put an authenticating
proxy in front of it. It rejects requests whose `Host` or `Origin` is not loopback (or the
`--host` name), so web pages cannot reach it through DNS rebinding. The service has a healthcheck (`docker compose ps` shows `healthy`).

Stdio, without compose (for clients that launch the server themselves):

```bash
docker build -t framedown:local --build-arg UID=$(id -u) --build-arg GID=$(id -g) .
docker run -i --rm -v "$PWD:/work" framedown:local framedown mcp --root /work
```

CLI commands work too: `docker run --rm -v "$PWD:/work" framedown:local framedown render video.md`.

## How it works

Markdown → Pydantic model → timeline (frame-quantized) → HTML page with every scene, the theme
fonts embedded and a small runtime (`window.__fd.seek(t)`) over **paused Web Animations** →
headless Chromium seeks each frame and captures it (BeginFrame on Linux, optionally in parallel
workers) → ffmpeg encodes. The runtime never reads
the clock or random numbers, and the render blocks all network requests.

## Security

Media and output paths are confined to the project root (`framedown.toml` sets the root and
limits such as `max_duration`); violations exit with code 5 (`FD-E500`, `FD-E501`). Renders block
every request except the page itself and inline `data:`/`blob:` URLs. The preview and the MCP
HTTP server accept loopback `Host`/`Origin` headers only. Video clips are read by ffmpeg with the
demuxer chosen from the file extension and the `file` protocol only, so a playlist disguised as a
clip is never followed; Mermaid diagrams are capped at 100 nodes, and every label is escaped.

## Development

```bash
uv sync --extra mcp
uv run pre-commit install
uv run pytest                     # fast suite (< 60 s)
uv run pytest -m "(slow or e2e) and not docker"   # gates and performance
uv run pytest -m docker                           # container gate (builds the image)
uv run python tools/traceability.py --phase 7
uv run python tools/licenses.py
```

Development is spec-driven and test-driven: see [`specs/constitution.md`](specs/constitution.md),
the task files in [`specs/tasks/`](specs/tasks/) and [`CLAUDE.md`](CLAUDE.md). Golden frames
(SSIM ≥ 0.98) live in `tests/fixtures/golden`; regenerate them with
`FRAMEDOWN_UPDATE_GOLDEN=1 uv run pytest tests/golden` after an intended visual change.

## License

Apache-2.0. Bundled fonts (Inter, Fira Code) are under the SIL Open Font License; see [`NOTICE`](NOTICE).
