Skill: leothebravest/ponyflash (version 1.0.0)

--- name: ponyflash description: >- Generate images, videos, speech audio, and music using the PonyFlash Python SDK. Also handle local media editing with FFmpeg, including clip, concat, transcode, extract audio, frame capture, subtitle capability checks, and ASS subtitle prep. Use when the user asks to create, generate, produce, edit, trim, merge, concatenate, transcode, subtitle, or render AI-generated media content. license: MIT metadata: author: ponyflash version: "0.3.0" --- # PonyFlash Skill ## Step 0: Decide Which Capability Path Applies This skill now contains **two capability families**: 1. **Cloud generation via PonyFlash Python SDK** - image generation - video generation - speech synthesis - music generation - model listing - file management - account / credits - These tasks **require a valid PonyFlash API key**. 2. **Local media editing via FFmpeg toolchain** - ffmpeg / ffprobe detection - installation planning - clip / concat / transcode - extract audio / capture frame - subtitle capability checks - ASS subtitle generation and burn-in workflow - These tasks **do NOT require a PonyFlash API key**, but they **do require local `ffmpeg` / `ffprobe` support**. Before doing anything, classify the request: - If the user is asking to **generate** media with PonyFlash models, follow the SDK path and require API key setup. - If the user is asking to **edit or process local media**, follow the FFmpeg path and do dependency checks first. - If the user wants an **end-to-end production workflow**, you may use both: generate assets with PonyFlash, then assemble or export with FFmpeg. ## Step 1A: API Key Setup for PonyFlash SDK Tasks Only do this section when the request needs PonyFlash cloud capabilities. **The FIRST time this skill is activated for a cloud generation task**, tell the user the following in your own words: 1. PonyFlash skill is ready to use. 2. It can handle: - image generation - video generation - speech synthesis - music generation - local media editing with FFmpeg 3. For complex multi-step productions, there are **Creative Playbooks** in the `playbooks/` directory. 4. To use PonyFlash cloud generation, the user needs an API key: - Register / log in at **https://www.ponyflash.com** - Get API key at **https://www.ponyflash.com/api-key** (starts with `rk_`) - Check credits at **https://www.ponyflash.com/usage** - Paste the key back in the chat **On subsequent SDK activations**, check whether `PONYFLASH_API_KEY` is set in the environment. If not, ask the user for the key again. Once received, set it up: ```bash export PONYFLASH_API_KEY="rk_xxx" ``` Then install the SDK: ```bash pip install ponyflash ``` **Always verify the key works before any generation task:** ```python from ponyflash import PonyFlash pony_flash = PonyFlash(api_key="<key from user>") balance = pony_flash.account.credits() print(f"Balance: {balance.balance} {balance.currency}") ``` If verification fails: - **Key invalid or missing** → direct user to https://api.ponyflash.com/api-key - **Balance is zero** → direct user to https://api.ponyflash.com/usage to top up credits ## Step 1B: Local Dependency Setup for FFmpeg Tasks Only do this section when the request needs local editing, subtitle, or export work. 1. First check local dependencies: ```bash bash "{baseDir}/scripts/check_ffmpeg.sh" ``` 2. If the task involves subtitles, do **capability checks**, not just existence checks: ```bash bash "{baseDir}/scripts/check_ffmpeg.sh" --require-subtitles-filter ``` 3. If `ffmpeg` / `ffprobe` or required filters are missing: - Tell the user what is missing. - Ask whether the user wants platform-appropriate FFmpeg installation guidance. - After the user installs FFmpeg, rerun the dependency checks before continuing. ## What this Skill Can Do | Capability | Resource | Description | |---|---|---| | Image generation | `pony_flash.images` | Text-to-image, image editing with mask/reference images | | Video generation | `pony_flash.video` | Text-to-video, first-frame-to-video, OmniHuman, Motion Transfer | | Speech synthesis | `pony_flash.speech` | Text-to-speech with voice cloning, emotion control, speed, pitch | | Music generation | `pony_flash.music` | Text-to-music with lyrics, style, instrumental mode, continuation | | Model listing | `pony_flash.models` | List available models, get model details and supported modes | | File management | `pony_flash.files` | Upload, list, get, delete files | | Account | `pony_flash.account` | Check credit balance, get recharge link | | Local media editing | `scripts/media_ops.sh` | Clip, concat, transcode, extract audio, frame capture | | FFmpeg environment checks | `scripts/check_ffmpeg.sh` | Detect ffmpeg / ffprobe and subtitle capabilities | | Subtitle font prep | `scripts/ensure_subtitle_fonts.sh` | Keep a reusable local copy of the default subtitle font when explicitly requested | | ASS subtitle prep | `scripts/build_ass_subtitles.py` | Adaptive ASS subtitle generation with pre-wrapping | ## Creative Playbooks (production workflows) The `playbooks/` directory contains **Creative Playbooks** — step-by-step production workflow guides for specific content types. Playbooks act as a director layer: they tell you **what to create and in what order**, while this SKILL.md tells you **how to execute generation and editing**. ### When to use a playbook 1. **User explicitly requests a playbook by name** → Read the corresponding file from `playbooks/` and follow its workflow. 2. **User asks to see available playbooks** → Read [playbooks/INDEX.md](playbooks/INDEX.md) and display the full list. 3. **User's request is clearly a multi-step production task** → Suggest a matching playbook from [playbooks/INDEX.md](playbooks/INDEX.md) and ask whether to use it. 4. **User's request is a single-step generation or editing task** → Proceed directly with the relevant SDK or FFmpeg capability. No playbook needed. ### How to execute a playbook Once a playbook is loaded: - Follow its workflow (asset prep → content generation → voice / music → editing → output). - Use PonyFlash SDK for generation tasks and FFmpeg scripts for local assembly / export tasks. - Confirm key creative decisions with the user before expensive generation. - Adapt prompts, durations, output format, and export strategy to the user's actual goal. ### Creating custom playbooks When the user asks to create a new playbook, generate a markdown file in `playbooks/` following this template: ```markdown --- name: Playbook Name description: One-line summary of what this playbook produces tags: [keyword1, keyword2, keyword3] difficulty: beginner | intermediate | advanced estimated_credits: credit range estimate output_format: format description (e.g., "vertical 9:16 MP4") --- # Playbook Name ## Use Cases When to use this playbook. ## Workflow ### Step 1: Asset Preparation What the user needs to provide; how to generate missing assets. ### Step 2: Visual Content Generation Which models to use, recommended parameters, prompt guidance. ### Step 3: Voice / Music Speech synthesis + background music guidance. ### Step 4: Editing / Assembly How to assemble, trim, subtitle, transcode, and export with the local FFmpeg workflow. ### Step 5: Output / Optimization Render settings, format recommendations. ## Prompt Templates Reusable prompt examples for this content type. ## Notes Best practices, common pitfalls. ``` After creating the file, update [playbooks/INDEX.md](playbooks/INDEX.md) to include the new playbook. ## PonyFlash SDK Core Concepts ### Client initialization ```python from ponyflash import PonyFlash pony_flash = PonyFlash([REDACTED_SECRET]") ``` Reads `PONYFLASH_API_KEY` from environment if `api_key` is omitted. ### FileInput — zero-friction file handling All file parameters accept any of these types: | Input type | Example | Behavior | |---|---|---| | URL string | `"https://example.com/photo.jpg"` | Passed directly to API | | file_id string | `"file_abc123"` | Passed directly to API | | `Path` object | `Path("photo.jpg")` | Auto-uploaded via presigned URL | | `open()` file | `open("photo.jpg", "rb")` | Auto-uploaded via presigned URL | | `bytes` | `image_bytes` | Auto-uploaded via presigned URL | | `(filename, bytes)` tuple | `("photo.jpg", data)` | Auto-uploaded with filename | Temp uploads are cleaned up automatically after `generate()` completes. Plain local string paths such as `"./photo.jpg"` are not supported. For local files, always use `Path(...)` or `open(..., "rb")`. ### Generation result `Generation` object fields: `request_id`, `status`, `outputs`, `usage`, `error`. Convenience properties: - `gen.url` — first output URL (or `None`) - `gen.urls` — list of all output URLs - `gen.credits` — credits consumed ## Quick Examples (PonyFlash SDK) ### Image ```python gen = pony_flash.images.generate( model="nano-banana-pro", prompt="A sunset over mountains", resolution="2K", aspect_ratio="16:9", ) print(gen.url) ``` ### Video ```python gen = pony_flash.video.generate( model="veo-3.1-fast", prompt="A timelapse of a city at night", duration=4, resolution="720p", aspect_ratio="16:9", generate_audio=False, ) print(gen.url) ``` ### Speech ```python gen = pony_flash.speech.generate( model="speech-2.8-hd", input="Hello, welcome to PonyFlash!", voice="English_Graceful_Lady", ) print(gen.url) ``` ### Music ```python gen = pony_flash.music.generate( model="music-2.5", prompt="An upbeat electronic dance track", duration=30, ) print(gen.url) ``` ### List models ```python page = pony_flash.models.list() for model in page.items: print(f"{model.id} ({model.type})") ``` ### Check balance ```python balance = pony_flash.account.credits() print(f"Balance: {balance.balance} {balance.currency}") ``` ## Local Media Editing with FFmpeg > No PonyFlash API key is needed for local editing, but local FFmpeg capability checks are mandatory. ### When to use this path Use the local FFmpeg workflow when the user asks to: - trim or cut a video - merge or concatenate clips - transcode to a target format - extract audio - capture a frame / thumbnail - verify subtitle support - prepare adaptive ASS subtitles - export a final edited file after PonyFlash generation ### Preferred workflow 1. Check dependencies: ```bash bash "{baseDir}/scripts/check_ffmpeg.sh" ``` 2. If subtitle work is needed: ```bash bash "{baseDir}/scripts/check_ffmpeg.sh" --require-subtitles-filter ``` 3. Prefer the stable script entrypoint: ```bash bash "{baseDir}/scripts/media_ops.sh" help ``` 4. Before any multi-step editing task, create a temporary task workspace and keep **all** staged inputs and intermediate outputs inside it: ```bash taskDir="$(mktemp -d "${TMPDIR:-/tmp}/ponyflash-task.XXXXXX")" ``` Use this directory for: - downloaded source media; - generated `.srt` / `.ass` files; - intermediate clips; - intermediate subtitled renders; - reusable inspection outputs that were not explicitly requested as final deliverables. 5. Validate outputs after execution. 6. After the task finishes, delete the temporary task workspace unless the user explicitly asked to keep intermediate artifacts. ### Capability profiles - `basic`: requires `ffmpeg + ffprobe + libx264 + aac` - `full`: `basic` plus `subtitles` filter support ### Preferred commands #### Probe media ```bash bash "{baseDir}/scripts/media_ops.sh" probe --input "input.mp4" ``` #### Clip video ```bash bash "{baseDir}/scripts/media_ops.sh" clip --input "$taskDir/input.mp4" --output "$taskDir/clip.mp4" --start "00:00:05" --duration "8" ``` Fast copy mode only when the user explicitly wants speed / near-lossless slicing: ```bash bash "{baseDir}/scripts/media_ops.sh" clip --mode copy --input "$taskDir/input.mp4" --output "$taskDir/clip.mp4" --start "00:00:05" --duration "8" ``` #### Concat clips ```bash bash "{baseDir}/scripts/media_ops.sh" concat --input "$taskDir/part1.mp4" --input "$taskDir/part2.mp4" --output "$taskDir/merged.mp4" ``` Fallback to reencode if copy concat fails: ```bash bash "{baseDir}/scripts/media_ops.sh" concat --mode reencode --input "$taskDir/part1.mp4" --input "$taskDir/part2.mp4" --output "$taskDir/merged.mp4" ``` #### Extract audio ```bash bash "{baseDir}/scripts/media_ops.sh" extract-audio --input "$taskDir/input.mp4" --output "$taskDir/audio.m4a" ``` #### Transcode ```bash bash "{baseDir}/scripts/media_ops.sh" transcode --input "$taskDir/input.mov" --output "$taskDir/output.mp4" ``` #### Capture frame ```bash bash "{baseDir}/scripts/media_ops.sh" frame --input "$taskDir/input.mp4" --output "$taskDir/cover.jpg" --time "00:00:03" ``` ### Subtitle workflow For `.srt` / `.ass` burn-in: ```bash bash "{baseDir}/scripts/check_ffmpeg.sh" --require-subtitles-filter ``` If subtitle style is unspecified, the agent should use the default subtitle workflow, which stages its runtime font temporarily and cleans it up after export. Preferred stable entrypoint: ```bash bash "{baseDir}/scripts/media_ops.sh" subtitle-burn --input "$taskDir/input.mp4" --subtitle-file "$taskDir/subtitles.srt" --output "final-output.mp4" ``` If the task needs adaptive line wrapping or controlled subtitle layout, or if you need to understand the underlying steps: ```bash python3 "{baseDir}/scripts/build_ass_subtitles.py" --help ``` Default burn pattern: 1. Probe width and height: ```bash ffprobe -hide_banner -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0:s=x "input.mp4" ``` 2. Use the stable subtitle entrypoint when the user only wants the final rendered video: ```bash bash "{baseDir}/scripts/media_ops.sh" subtitle-burn --input "$taskDir/input.mp4" --subtitle-file "$taskDir/subtitles.srt" --output "final-output.mp4" ``` This path keeps only the final `final-output.mp4` by default and removes temporary ASS files and staged fonts. If the user did not explicitly request any staged files, the agent should also delete `$taskDir` after moving or confirming the final deliverable. 3. Build a default ASS subtitle file only when the user explicitly wants to keep or inspect it: ```bash bash "{baseDir}/scripts/ensure_subtitle_fonts.sh" python3 "{baseDir}/scripts/build_ass_subtitles.py" \ --subtitle-file "$taskDir/subtitles.srt" \ --output-ass "$taskDir/subtitles.ass" \ --video-width 1920 \ --video-height 1080 \ --latin-font-file "$HOME/.cache/ponyflash/fonts/NotoSansCJKsc-Regular.otf" \ --cjk-font-file "$HOME/.cache/ponyflash/fonts/NotoSansCJKsc-Regular.otf" ``` 4. Burn subtitles with the prepared runtime font: ```bash ffmpeg -i "$taskDir/input.mp4" \ -vf "subtitles=$taskDir/subtitles.ass:fontsdir=$HOME/.cache/ponyflash/fonts" \ -c:v libx264 -preset medium -crf 18 -c:a aac -b:a 192k -movflags +faststart "final-output.mp4" ``` Default subtitle references: - Font notes: `{baseDir}/assets/fonts.md` - Subtitle style: `{baseDir}/assets/subtitle-style.md` - Decision rules: `{baseDir}/reference/operations.md` - Examples: `{baseDir}/reference/examples.md` ### Decision rules - Clip tasks: default to `reencode`; use `copy` only when the user explicitly wants speed / minimal loss. - Concat tasks: default to `copy`; fallback to `reencode` if source parameters differ. - Audio extraction: default to AAC in `.m4a`. - Transcode: default to `mp4 + libx264 + aac`. - Subtitle tasks: if subtitle style is unspecified, use the default subtitle workflow, prepared runtime font, and default subtitle styling rules. - Subtitle tasks: prefer `subtitles`; use `drawtext` only as a plain text fallback. - Do not overwrite outputs unless the user explicitly allows it. - Unless the user explicitly asks to keep intermediate artifacts, remove temporary ASS files, temporary font directories, concat lists, and failed partial outputs after the task finishes. - Unless the user explicitly asks to keep intermediate artifacts, stage all non-final files inside `taskDir` and delete `taskDir` at the end of the task. ### Failure handling - If `ffmpeg` or `ffprobe` is missing, pause the task, help the user install FFmpeg if needed, and rerun the checks first. - If subtitle burn-in is requested but `subtitles` is missing, do not claim the machine can burn `.srt` / `.ass`. - If only `drawtext` exists, explain that this is text overlay fallback, not full subtitle burn-in. - If concat copy mode fails, retry with `reencode`. - If scripts do not cover the exact request, explain the limitation and fall back to a raw `ffmpeg` command. ## Delivering generated files to the user > **CRITICAL**: You MUST actually send generated files to the user — never just print a file path as text. ### File save location Always save generated files (rendered videos, downloaded media, etc.) to **your current working directory** (e.g., `./output.mp4`), NOT to `/tmp/` or other system directories. Many agent platforms restrict file-sending to the workspace directory only. Saving to `/tmp/` will cause file delivery to fail silently. ### Delivery rules 1. **API-generated content** — `gen.url` is already a downloadable URL. Send it to the user, and also use your platform's file-sending capability to send the file directly in the conversation. 2. **Locally rendered content** (e.g., `timeline.render("output.mp4")`) — save the output to your working directory, then use your platform's file-sending tool to send the actual file to the user as an attachment. Do NOT just send the file path as a text message. 3. **Multiple outputs** — send each file with a clear label describing what it is. ## Error Handling for PonyFlash SDK ```python from ponyflash import ( PonyFlash, InsufficientCreditsError, RateLimitError, GenerationFailedError, AuthenticationError, ) pony_flash = PonyFlash() try: gen = pony_flash.images.generate(model="nanobanana-pro", prompt="A cat") except AuthenticationError: print("Invalid or missing API key.") print("Get your API key at: https://api.ponyflash.com/api-key") except InsufficientCreditsError as e: print(f"Not enough credits. Balance: {e.balance}, required: {e.required}") print("Top up credits at: https://api.ponyflash.com/usage") except RateLimitError: print("Rate limited — wait and retry") except GenerationFailedError as e: print(f"Generation failed: {e.generation.error.code}") ``` ## More Examples For advanced PonyFlash SDK usage: See [examples/advanced.md](examples/advanced.md) For FFmpeg task patterns: - [reference/operations.md](reference/operations.md) - [reference/examples.md](reference/examples.md) ## API Reference For complete method signatures, parameter types, and return type fields: - **Image generation**: [reference/images.md](reference/images.md) - **Video generation**: [reference/video.md](reference/video.md) - **Speech synthesis**: [reference/speech.md](reference/speech.md) - **Music generation**: [reference/music.md](reference/music.md) - **Model listing**: [reference/models.md](reference/models.md) - **File management**: [reference/files.md](reference/files.md) - **Account / credits**: [reference/account.md](reference/account.md) - **FFmpeg operation strategy**: [reference/operations.md](reference/operations.md) - **FFmpeg examples**: [reference/examples.md](reference/examples.md) - **Subtitle fonts**: [assets/fonts.md](assets/fonts.md) - **Subtitle style**: [assets/subtitle-style.md](assets/subtitle-style.md) ## Model Catalog For all available models and their specific parameters, capabilities, and examples: See [reference/models/INDEX.md](reference/models/INDEX.md)

path: README.md
content: # PonyFlash — Agent Skill

Generate images, videos, speech audio, and music through the [PonyFlash](https://ponyflash.com) Python SDK, and handle local media editing with FFmpeg.

Compatible with the [Agent Skills](https://agentskills.io/specification) open standard. Works with **Claude Code, OpenClaw, Cursor, Codex, Gemini CLI, Windsurf, Cline** and 40+ other AI agents.

## Quick Install

### Git (all agents)

```bash
git clone https://github.com/ponyflash/ponyflash-skill.git ponyflash
```

Then move the `ponyflash` folder into your agent's skills directory.

### OpenClaw

```bash
# From ClawHub (if published)
clawhub install ponyflash

# Or manually
git clone https://github.com/ponyflash/ponyflash-skill.git ~/.openclaw/skills/ponyflash
```

### Claude Code

```bash
git clone https://github.com/ponyflash/ponyflash-skill.git .claude/skills/ponyflash
```

### Cursor

```bash
git clone https://github.com/ponyflash/ponyflash-skill.git .cursor/skills/ponyflash
```

### Skills Directory by Agent

| Agent | Project-level | Global |
|-------|--------------|--------|
| Claude Code | `.claude/skills/ponyflash/` | `~/.claude/skills/ponyflash/` |
| OpenClaw | `skills/ponyflash/` | `~/.openclaw/skills/ponyflash/` |
| Cursor | `.cursor/skills/ponyflash/` | `~/.cursor/skills/ponyflash/` |
| Codex | `.codex/skills/ponyflash/` | `~/.codex/skills/ponyflash/` |
| Windsurf | `.windsurf/skills/ponyflash/` | `~/.codeium/windsurf/skills/ponyflash/` |
| Cline | `.cline/skills/ponyflash/` | `~/.cline/skills/ponyflash/` |

## What This Skill Does

This skill now combines **PonyFlash cloud generation** and **local FFmpeg media processing**.

| Capability | Description |
|---|---|
| Image generation | Text-to-image, image editing with mask/reference images |
| Video generation | Text-to-video, first-frame-to-video, OmniHuman, Motion Transfer |
| Speech synthesis | Text-to-speech with voice cloning, emotion & speed control |
| Music generation | Text-to-music with lyrics, style, instrumental mode, continuation |
| Model listing | List available models, get model details and supported modes |
| File management | Upload, list, get, delete files |
| Account | Check credit balance, get recharge link |
| Local media editing | Clip, concat, transcode, extract audio, and frame capture through `scripts/media_ops.sh` |
| FFmpeg capability checks | Detect `ffmpeg` / `ffprobe`, subtitle filters, and editing profile support |
| Subtitle burn-in | Burn subtitles with `scripts/media_ops.sh subtitle-burn` using the default workflow and on-demand fonts |
| Subtitle prep | Build adaptive ASS subtitles with `scripts/build_ass_subtitles.py` |

## Prerequisites

### PonyFlash cloud generation

```bash
pip install ponyflash
export PONYFLASH_API_KEY="rk_xxx"
```

### Local FFmpeg editing

Local editing does not require a PonyFlash API key, but it does require working `ffmpeg` / `ffprobe` binaries on the machine.

Check with:

```bash
bash scripts/check_ffmpeg.sh
```

If you also need subtitle burn-in:

```bash
bash scripts/check_ffmpeg.sh --require-subtitles-filter
```

The default `subtitle-burn` workflow prepares and removes its temporary subtitle font automatically. Only run this command when you explicitly want to keep a reusable local copy:

```bash
bash scripts/ensure_subtitle_fonts.sh
```

## Quick Examples

### PonyFlash SDK

```python
from ponyflash import PonyFlash

pony_flash = PonyFlash()

gen = pony_flash.images.generate(
    model="nano-banana-pro",
    prompt="A sunset over mountains",
    resolution="2K",
)
print(gen.url)
```

### FFmpeg editing

```bash
taskDir="$(mktemp -d "${TMPDIR:-/tmp}/ponyflash-task.XXXXXX")"
bash scripts/media_ops.sh clip --input "$taskDir/input.mp4" --output "$taskDir/clip.mp4" --start "00:00:05" --duration "8"
```

### Default subtitle burn-in

```bash
taskDir="$(mktemp -d "${TMPDIR:-/tmp}/ponyflash-task.XXXXXX")"
bash scripts/media_ops.sh subtitle-burn --input "$taskDir/input.mp4" --subtitle-file "$taskDir/subtitles.srt" --output "final-output.mp4"
```

See [SKILL.md](SKILL.md) for full usage instructions.

Useful references:

- [reference/operations.md](reference/operations.md)
- [reference/examples.md](reference/examples.md)
- [assets/subtitle-style.md](assets/subtitle-style.md)
- [assets/fonts.md](assets/fonts.md)

## Directory Structure

```text
ponyflash/
├── SKILL.md
├── README.md
├── LICENSE
├── assets/
│   ├── fonts.md
│   └── subtitle-style.md
├── examples/
│   ├── quickstart.py
│   └── advanced.md
├── playbooks/
│   ├── INDEX.md
│   └── crepal-director.md
├── reference/
│   ├── account.md
│   ├── examples.md
│   ├── files.md
│   ├── images.md
│   ├── models.md
│   ├── music.md
│   ├── operations.md
│   ├── speech.md
│   ├── video.md
│   └── models/
│       ├── INDEX.md
│       └── (per-model docs)
└── scripts/
    ├── build_ass_subtitles.py
    ├── check_ffmpeg.sh
    ├── ensure_subtitle_fonts.sh
    └── media_ops.sh
```

## Notes on Fonts

The default subtitle workflow downloads `Noto Sans CJK SC` into a temporary directory, burns the subtitles, and removes the temporary font files when the task finishes. Only `scripts/ensure_subtitle_fonts.sh` keeps a reusable local copy under `~/.cache/ponyflash/fonts/`. You can override that cache directory with `PONYFLASH_FONT_DIR` or pass explicit font file paths to `scripts/media_ops.sh subtitle-burn`.

## Cleanup Policy

- By default, clip, concat, transcode, audio extraction, frame capture, and subtitle burn-in write to temporary paths first and only keep the final `--output` file on success.
- Temporary concat lists, temporary ASS files, staged font directories, and partial outputs are removed automatically.
- If you explicitly pass a path such as `--output` or `--ass-output`, that path is treated as a user-requested deliverable and is kept.
- For multi-step editing workflows, create a temporary task directory first and keep staged downloads, subtitle files, and intermediate renders inside it. Delete that directory after confirming the final deliverable unless the user explicitly asked to keep intermediates.

## Contributing

1. Fork this repo
2. Add or update skill content
3. Follow the [Agent Skills specification](https://agentskills.io/specification)
4. Submit a PR

## License

[MIT](LICENSE)


path: scripts/build_ass_subtitles.py
content: #!/usr/bin/env python3
"""Build ASS subtitles with adaptive sizing and pre-wrapping.

This script turns a subtitle source into an ASS subtitle file.
Supported source formats:
- JSON subtitle event list
- SRT subtitle file

It applies the default PonyFlash subtitle style, scales values to the
target output size, and pre-wraps text before ffmpeg/libass renders it.
"""

from __future__ import annotations

import argparse
import json
import re
import sys
import tempfile
from functools import lru_cache
from pathlib import Path
from typing import Any

try:
    from PIL import ImageFont  # type: ignore
except Exception:  # pragma: no cover - fallback path is intentional
    ImageFont = None


LATIN_FONT_NAME = "Noto Sans CJK SC"
CJK_FONT_NAME = "Noto Sans CJK SC"
DEFAULT_PRIMARY_COLOUR = "&H00FFFFFF"
DEFAULT_OUTLINE_COLOUR = "&H00000000"
DEFAULT_BACK_COLOUR = "&H00000000"


def is_cjk(char: str) -> bool:
    codepoint = ord(char)
    return (
        0x3400 <= codepoint <= 0x4DBF
        or 0x4E00 <= codepoint <= 0x9FFF
        or 0xF900 <= codepoint <= 0xFAFF
        or 0x3040 <= codepoint <= 0x30FF
        or 0xAC00 <= codepoint <= 0xD7AF
    )


def is_fullwidth_punctuation(char: str) -> bool:
    codepoint = ord(char)
    return (0x3000 <= codepoint <= 0x303F) or (0xFF00 <= codepoint <= 0xFFEF)


def load_font(font_path: Path, size: int) -> Any | None:
    if ImageFont is None:
        return None

    try:
        return ImageFont.truetype(str(font_path), size=size)
    except Exception:
        return None


class TextMeasurer:
    def __init__(self, latin_font_path: Path, cjk_font_path: Path, font_size: int):
        self.font_size = font_size
        self.latin_font = load_font(latin_font_path, font_size)
        self.cjk_font = load_font(cjk_font_path, font_size)

    def char_width(self, char: str) -> float:
        if not char:
            return 0.0

        if self.latin_font or self.cjk_font:
            font = self.cjk_font if is_cjk(char) or is_fullwidth_punctuation(char) else self.latin_font
            if font is None:
                font = self.cjk_font or self.latin_font
            if font is not None:
                try:
                    return float(font.getlength(char))
                except Exception:
                    bbox = font.getbbox(char)
                    return float(max(0, bbox[2] - bbox[0]))

        if char.isspace():
            return self.font_size * 0.33
        if is_cjk(char):
            return self.font_size * 1.0
        if is_fullwidth_punctuation(char):
            return self.font_size * 0.9
        if char.isascii() and char.isalnum():
            return self.font_size * 0.56
        if char.isascii():
            return self.font_size * 0.38
        return self.font_size * 0.8

    @lru_cache(maxsize=4096)
    def text_width(self, text: str) -> float:
        return sum(self.char_width(char) for char in text)


def tokenize(text: str) -> list[str]:
    tokens: list[str] = []
    index = 0
    while index < len(text):
        char = text[index]
        if char.isspace():
            start = index
            while index < len(text) and text[index].isspace():
                index += 1
            tokens.append(text[start:index])
            continue
        if char.isascii() and not char.isspace():
            start = index
            while index < len(text) and text[index].isascii() and not text[index].isspace():
                index += 1
            tokens.append(text[start:index])
            continue
        tokens.append(char)
        index += 1
    return tokens


def split_token_to_fit(token: str, max_width: float, measurer: TextMeasurer) -> list[str]:
    parts: list[str] = []
    current = ""
    for char in [REDACTED_SECRET] = f"{current}{char}"
        if current and measurer.text_width(proposal) > max_width:
            parts.append(current)
            current = char
        else:
            current = proposal
    if current:
        parts.append(current)
    return parts or [token]


def wrap_text(text: str, max_width: float, measurer: TextMeasurer) -> list[str]:
    wrapped_lines: list[str] = []
    for paragraph in text.splitlines():
        tokens = tokenize(paragraph)
        lines: list[str] = []
        current = ""

        def push_current() -> None:
            nonlocal current
            if current.strip():
                lines.append(current.rstrip())
            current = ""

        for token in tokens:
            if token.isspace():
                if current:
                    current += " "
                continue

            candidate = token if not current else f"{current}{token}"
            if measurer.text_width(candidate) <= max_width:
                current = candidate
                continue

            if current:
                push_current()

            [REDACTED_SECRET])
            if not [REDACTED_SECRET]

            if measurer.text_width(token) <= max_width:
                current = token
                continue

            for part in split_token_to_fit(token, max_width, measurer):
                if measurer.text_width(part) <= max_width:
                    if current:
                        push_current()
                    current = part
                else:
                    current = part

        push_current()
        if lines:
            wrapped_lines.extend(lines)
    return wrapped_lines


def ass_escape(text: str) -> str:
    return (
        text.replace("\\", r"\\")
        .replace("{", r"\{")
        .replace("}", r"\}")
    )


def font_name_for_char(char: str, previous_font: str | None = None) -> str:
    if char.isspace():
        return previous_font or LATIN_FONT_NAME
    if is_cjk(char) or is_fullwidth_punctuation(char):
        return CJK_FONT_NAME
    return LATIN_FONT_NAME


def stylize_line(line: str) -> str:
    if not line:
        return ""

    chunks: list[tuple[str, str]] = []
    current_font: str | None = None
    current_text = ""

    for char in line:
        target_font = font_name_for_char(char, current_font)
        if current_font is None or target_font == current_font:
            current_font = target_font
            current_text += char
            continue

        chunks.append((current_font, current_text))
        current_font = target_font
        current_text = char

    if current_font is not None and current_text:
        chunks.append((current_font, current_text))

    return "".join(r"{\fn" + font_name + "}" + ass_escape(text) for font_name, text in chunks)


def ratio_or_default(width: int, height: int) -> float:
    return 0.90


def build_style(args: argparse.Namespace) -> dict[str, int]:
    short_edge = min(args.video_width, args.video_height)
    font_size = args.font_size or round(short_edge * 0.0556)
    return {
        "font_size": font_size,
        "margin_v": args.margin_v or round(args.video_height * 0.0963),
        "margin_l": args.margin_l or round(args.video_width * 0.0625),
        "margin_r": args.margin_r or round(args.video_width * 0.0625),
        "outline": args.outline if args.outline is not None else max(1, round(font_size * 0.0167)),
        "shadow": args.shadow if args.shadow is not None else 1,
        "blur": args.blur if args.blur is not None else 1,
    }


def parse_srt_timestamp(timestamp: str) -> str:
    match = re.match(r"^(\d{2}):(\d{2}):(\d{2})[,.](\d{1,3})$", timestamp.strip())
    if not match:
        raise SystemExit(f"Invalid SRT timestamp: {timestamp}")

    hours, minutes, seconds, millis = match.groups()
    centiseconds = round(int(millis.ljust(3, "0")[:3]) / 10)
    if centiseconds == 100:
        centiseconds = 99
    return f"{int(hours)}:{minutes}:{seconds}.{centiseconds:02d}"


def read_events_from_json(events_json: Path) -> list[dict[str, Any]]:
    try:
        data = json.loads(events_json.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        raise SystemExit(f"Invalid JSON subtitle event file: {exc}") from exc

    if not isinstance(data, list):
        raise SystemExit("Subtitle event file must be a JSON array.")

    normalized: list[dict[str, Any]] = []
    for index, item in enumerate(data):
        if not isinstance(item, dict):
            raise SystemExit(f"Subtitle event #{index + 1} must be an object.")
        if "start" not in item or "end" not in item or "text" not in item:
            raise SystemExit(f"Subtitle event #{index + 1} must include start, end, and text.")
        normalized.append(item)
    return normalized


def read_events_from_srt(subtitle_file: Path) -> list[dict[str, Any]]:
    content = subtitle_file.read_text(encoding="utf-8-sig").replace("\r\n", "\n").strip()
    if not content:
        return []

    events: list[dict[str, Any]] = []
    blocks = re.split(r"\n\s*\n", content)
    for index, block in enumerate(blocks, start=1):
        lines = [line.rstrip() for line in block.split("\n") if line.strip() != ""]
        if not lines:
            continue

        if re.fullmatch(r"\d+", lines[0]):
            lines = lines[1:]

        if not lines or "-->" not in lines[0]:
            raise SystemExit(f"Invalid SRT block #{index}: missing timestamp line.")

        timestamp_line = lines[0]
        text_lines = lines[1:]
        if not text_lines:
            raise SystemExit(f"Invalid SRT block #{index}: missing subtitle text.")

        start_raw, end_raw = [part.strip() for part in timestamp_line.split("-->", 1)]
        events.append(
            {
                "start": parse_srt_timestamp(start_raw),
                "end": parse_srt_timestamp(end_raw),
                "text": "\n".join(text_lines),
            }
        )

    return events


def read_events(source_path: Path) -> list[dict[str, Any]]:
    suffix = source_path.suffix.lower()
    if suffix == ".json":
        return read_events_from_json(source_path)
    if suffix == ".srt":
        return read_events_from_srt(source_path)
    raise SystemExit(f"Unsupported subtitle source format: {source_path.suffix}")


def build_ass(args: argparse.Namespace) -> str:
    style = build_style(args)
    source_path = Path(args.subtitle_file or args.events_json)
    events = read_events(source_path)

    max_width_ratio = args.wrap_width_ratio or ratio_or_default(args.video_width, args.video_height)
    max_text_width = args.video_width * max_width_ratio

    measurer = TextMeasurer(
        Path(args.latin_font_file),
        Path(args.cjk_font_file),
        style["font_size"],
    )

    dialogue_lines: list[str] = []
    for event in events:
        raw_text = str(event["text"])
        wrapped_lines = wrap_text(raw_text, max_text_width, measurer)
        wrapped = r"\N".join(stylize_line(line) for line in wrapped_lines) or stylize_line(raw_text)

        event_blur = event.get("blur")
        if event_blur is not None and int(event_blur) != style["blur"]:
            wrapped = r"{\blur" + str(int(event_blur)) + "}" + wrapped

        dialogue_lines.append(
            "Dialogue: 0,{start},{end},Default,,0,0,0,,{text}".format(
                start=event["start"],
                end=event["end"],
                text=wrapped,
            )
        )

    return "\n".join(
        [
            "[Script Info]",
            "ScriptType: v4.00+",
            f"PlayResX: {args.video_width}",
            f"PlayResY: {args.video_height}",
            "WrapStyle: 2",
            "ScaledBorderAndShadow: yes",
            "",
            "[V4+ Styles]",
            "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
            (
                "Style: Default,{font_name},{font_size},{primary_colour},{primary_colour},"
                "{outline_colour},{back_colour},0,0,0,0,100,100,0,0,1,{outline},{shadow},2,{margin_l},{margin_r},{margin_v},1"
            ).format(
                font_name=LATIN_FONT_NAME,
                font_size=style["font_size"],
                primary_colour=DEFAULT_PRIMARY_COLOUR,
                outline_colour=DEFAULT_OUTLINE_COLOUR,
                back_colour=DEFAULT_BACK_COLOUR,
                outline=style["outline"],
                shadow=style["shadow"],
                margin_l=style["margin_l"],
                margin_r=style["margin_r"],
                margin_v=style["margin_v"],
            ),
            "",
            "[Events]",
            "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
            *dialogue_lines,
            "",
        ]
    )


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Build ASS subtitles with adaptive wrapping.")
    source_group = parser.add_mutually_exclusive_group(required=True)
    source_group.add_argument("--subtitle-file", help="Subtitle source file (.srt or .json).")
    source_group.add_argument("--events-json", help="Deprecated alias for JSON subtitle events.")
    parser.add_argument("--output-ass", required=True, help="Output ASS file path.")
    parser.add_argument("--video-width", type=int, required=True, help="Target output video width.")
    parser.add_argument("--video-height", type=int, required=True, help="Target output video height.")
    parser.add_argument("--latin-font-file", required=True, help="Primary latin font file path.")
    parser.add_argument("--cjk-font-file", required=True, help="CJK fallback font file path.")
    parser.add_argument("--wrap-width-ratio", type=float, help="Override max text width ratio.")
    parser.add_argument("--font-size", type=int, help="Override computed font size.")
    parser.add_argument("--margin-v", type=int, help="Override computed bottom margin.")
    parser.add_argument("--margin-l", type=int, help="Override computed left margin.")
    parser.add_argument("--margin-r", type=int, help="Override computed right margin.")
    parser.add_argument("--outline", type=int, help="Override computed outline width.")
    parser.add_argument("--shadow", type=int, help="Override computed shadow value.")
    parser.add_argument("--blur", type=int, help="Override default blur value.")
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    ass = build_ass(args)
    output_path = Path(args.output_ass)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(
        "w",
        encoding="utf-8",
        dir=output_path.parent,
        prefix=f".{output_path.stem}.",
        suffix=f"{output_path.suffix}.tmp",
        delete=False,
    ) as handle:
        handle.write(ass)
        temp_path = Path(handle.name)
    temp_path.replace(output_path)
    return 0


if __name__ == "__main__":
    sys.exit(main())


path: scripts/check_ffmpeg.sh
content: #!/usr/bin/env bash
# SECURITY MANIFEST:
#   Environment variables accessed: PATH
#   External endpoints called: none
#   Local files read: none
#   Local files written: none
set -euo pipefail

usage() {
  cat <<'EOF'
Usage:
  check_ffmpeg.sh [--quiet] [--profile basic|full] [--require-basic-editing] [--require-subtitle-support] [--require-subtitles-filter] [--require-drawtext-filter] [--help]

Options:
  --quiet                     Only print failure messages.
  --profile <name>            Capability profile: basic or full.
  --require-basic-editing     Fail unless ffprobe, libx264, and aac encoding are available.
  --require-subtitle-support  Fail unless subtitles or drawtext is available.
  --require-subtitles-filter  Fail unless the subtitles filter is available.
  --require-drawtext-filter   Fail unless the drawtext filter is available.
  --help                      Show this help message.
EOF
}

has_filter() {
  local ffmpeg_path="$1"
  local filter_name="$2"

  "$ffmpeg_path" -hide_banner -filters 2>/dev/null | awk -v name="$filter_name" '
    $2 == name { found=1 }
    END { exit(found ? 0 : 1) }
  '
}

has_encoder() {
  local ffmpeg_path="$1"
  local encoder_name="$2"

  "$ffmpeg_path" -hide_banner -encoders 2>/dev/null | awk -v name="$encoder_name" '
    $2 == name { found=1 }
    END { exit(found ? 0 : 1) }
  '
}

quiet=0
require_basic_editing=0
require_subtitle_support=0
require_subtitles_filter=0
require_drawtext_filter=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --quiet)
      quiet=1
      shift
      ;;
    --profile)
      case "${2:-}" in
        basic)
          require_basic_editing=1
          ;;
        full)
          require_basic_editing=1
          require_subtitles_filter=1
          ;;
        *)
          echo "Unsupported profile: ${2:-}" >&2
          usage >&2
          exit 2
          ;;
      esac
      shift 2
      ;;
    --require-basic-editing)
      require_basic_editing=1
      shift
      ;;
    --require-subtitle-support)
      require_subtitle_support=1
      shift
      ;;
    --require-subtitles-filter)
      require_subtitles_filter=1
      shift
      ;;
    --require-drawtext-filter)
      require_drawtext_filter=1
      shift
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

os_name="$(uname -s 2>/dev/null | tr '[:upper:]' '[:lower:]')"
ffmpeg_bin="$(command -v ffmpeg || true)"
ffprobe_bin="$(command -v ffprobe || true)"

if [[ $quiet -eq 0 ]]; then
  echo "platform=${os_name:-unknown}"
  echo "path=$PATH"
fi

missing=0
capability_missing=0
subtitles_filter="missing"
drawtext_filter="missing"
subtitle_support="missing"
libx264_encoder="missing"
aac_encoder="missing"
basic_editing_support="missing"

if [[ -n "$ffmpeg_bin" ]]; then
  if has_encoder "$ffmpeg_bin" "libx264"; then
    libx264_encoder="available"
  fi

  if has_encoder "$ffmpeg_bin" "aac"; then
    aac_encoder="available"
  fi

  if [[ "$libx264_encoder" == "available" && "$aac_encoder" == "available" ]]; then
    basic_editing_support="available"
  fi

  if has_filter "$ffmpeg_bin" "subtitles"; then
    subtitles_filter="available"
  fi

  if has_filter "$ffmpeg_bin" "drawtext"; then
    drawtext_filter="available"
  fi

  if [[ "$subtitles_filter" == "available" && "$drawtext_filter" == "available" ]]; then
    subtitle_support="full"
  elif [[ "$subtitles_filter" == "available" ]]; then
    subtitle_support="subtitles_only"
  elif [[ "$drawtext_filter" == "available" ]]; then
    subtitle_support="drawtext_only"
  fi

  if [[ $quiet -eq 0 ]]; then
    ffmpeg_version="$("$ffmpeg_bin" -version 2>/dev/null | awk 'NR==1 { print $0 }')"
    echo "ffmpeg=installed"
    echo "ffmpeg_path=$ffmpeg_bin"
    echo "ffmpeg_version=${ffmpeg_version:-unknown}"
    echo "libx264_encoder=$libx264_encoder"
    echo "aac_encoder=$aac_encoder"
    echo "basic_editing_support=$basic_editing_support"
    echo "subtitles_filter=$subtitles_filter"
    echo "drawtext_filter=$drawtext_filter"
    echo "subtitle_support=$subtitle_support"
  fi
else
  echo "ffmpeg=missing"
  missing=1
fi

if [[ -n "$ffprobe_bin" ]]; then
  if [[ $quiet -eq 0 ]]; then
    ffprobe_version="$("$ffprobe_bin" -version 2>/dev/null | awk 'NR==1 { print $0 }')"
    echo "ffprobe=installed"
    echo "ffprobe_path=$ffprobe_bin"
    echo "ffprobe_version=${ffprobe_version:-unknown}"
  fi
else
  echo "ffprobe=missing"
  missing=1
fi

if [[ $missing -eq 0 ]]; then
  if [[ $require_basic_editing -eq 1 && "$basic_editing_support" != "available" ]]; then
    echo "Missing capability: basic editing support requires libx264 and aac encoders." >&2
    capability_missing=1
  fi

  if [[ $require_subtitle_support -eq 1 && "$subtitle_support" == "missing" ]]; then
    echo "Missing capability: subtitles or drawtext filter is required." >&2
    capability_missing=1
  fi

  if [[ $require_subtitles_filter -eq 1 && "$subtitles_filter" != "available" ]]; then
    echo "Missing capability: subtitles filter is required." >&2
    capability_missing=1
  fi

  if [[ $require_drawtext_filter -eq 1 && "$drawtext_filter" != "available" ]]; then
    echo "Missing capability: drawtext filter is required." >&2
    capability_missing=1
  fi
fi

if [[ $missing -ne 0 ]]; then
  [[ $quiet -eq 0 ]] && echo "status=missing_dependencies"
  exit 1
fi

if [[ $capability_missing -ne 0 ]]; then
  [[ $quiet -eq 0 ]] && echo "status=missing_capabilities"
  exit 3
fi

[[ $quiet -eq 0 ]] && echo "status=ready"
exit 0


path: scripts/ensure_subtitle_fonts.sh
content: #!/usr/bin/env bash
# SECURITY MANIFEST:
#   Environment variables accessed: HOME, PONYFLASH_FONT_DIR, PONYFLASH_NOTO_FONT_URL
#   External endpoints called:
#     - https://mirrors.aliyun.com/CTAN/fonts/notocjksc/NotoSansCJKsc-Regular.otf
#     - https://cdn.jsdelivr.net/gh/notofonts/noto-cjk@main/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Regular.otf
#   Local files read: downloaded font cache paths under the selected font directory
#   Local files written: downloaded font cache paths under the selected font directory
set -euo pipefail

usage() {
  cat <<'EOF'
Usage:
  ensure_subtitle_fonts.sh [--font-dir <dir>] [--quiet] [--help]

Options:
  --font-dir <dir>  Override the download/cache directory.
  --quiet           Print only the resolved font path.
  --help            Show this help message.
EOF
}

font_dir="${PONYFLASH_FONT_DIR:-$HOME/.cache/ponyflash/fonts}"
quiet=0
font_filename="NotoSansCJKsc-Regular.otf"
primary_url="${PONYFLASH_NOTO_FONT_URL:-https://mirrors.aliyun.com/CTAN/fonts/notocjksc/NotoSansCJKsc-Regular.otf}"
fallback_url="https://cdn.jsdelivr.net/gh/notofonts/noto-cjk@main/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Regular.otf"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --font-dir)
      font_dir="${2:-}"
      [[ -n "$font_dir" ]] || { echo "Missing value for --font-dir" >&2; exit 2; }
      shift 2
      ;;
    --quiet)
      quiet=1
      shift
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

font_dir="${font_dir/#\~/$HOME}"
font_path="$font_dir/$font_filename"

download_font() {
  local url="$1"
  local tmp_path="$font_path.tmp"

  if command -v curl >/dev/null 2>&1; then
    curl --fail --location --silent --show-error "$url" --output "$tmp_path"
  elif command -v wget >/dev/null 2>&1; then
    wget -q -O "$tmp_path" "$url"
  else
    echo "Missing downloader: need curl or wget to fetch subtitle fonts." >&2
    return 2
  fi

  mv "$tmp_path" "$font_path"
}

mkdir -p "$font_dir"

if [[ ! -s "$font_path" ]]; then
  rm -f "$font_path.tmp"
  if ! download_font "$primary_url"; then
    rm -f "$font_path.tmp"
    download_font "$fallback_url"
  fi
fi

if [[ ! -s "$font_path" ]]; then
  echo "Failed to prepare subtitle font: $font_path" >&2
  exit 1
fi

if [[ $quiet -eq 1 ]]; then
  printf '%s\n' "$font_path"
else
  echo "font_name=Noto Sans CJK SC"
  echo "font_dir=$font_dir"
  echo "font_file=$font_path"
fi


path: scripts/media_ops.sh
content: #!/usr/bin/env bash
# SECURITY MANIFEST:
#   Environment variables accessed: HOME, PATH, PONYFLASH_FONT_DIR, PONYFLASH_NOTO_FONT_URL
#   External endpoints called:
#     - https://mirrors.aliyun.com/CTAN/fonts/notocjksc/NotoSansCJKsc-Regular.otf
#     - https://cdn.jsdelivr.net/gh/notofonts/noto-cjk@main/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Regular.otf
#   Local files read: input media/subtitle files, generated ASS files, downloaded font files
#   Local files written: output media files, temporary concat/ASS files, temporary font directories
set -euo pipefail

usage() {
  cat <<'EOF'
Usage:
  media_ops.sh <command> [options]

Commands:
  help
  fonts-prepare [--font-dir <dir>]
  probe --input <file>
  clip --input <file> --output <file> --start <time> --duration <time> [--mode reencode|copy] [--overwrite]
  concat --input <file> --input <file> --output <file> [--mode copy|reencode] [--overwrite]
  extract-audio --input <file> --output <file> [--audio-codec <codec>] [--bitrate <rate>] [--overwrite]
  transcode --input <file> --output <file> [--video-codec <codec>] [--audio-codec <codec>] [--crf <value>] [--preset <name>] [--bitrate <rate>] [--overwrite]
  frame --input <file> --output <file> --time <time> [--overwrite]
  subtitle-burn --input <video> --subtitle-file <file> --output <file> [--ass-output <file>] [--latin-font-file <file>] [--cjk-font-file <file>] [--wrap-width-ratio <ratio>] [--font-size <px>] [--margin-v <px>] [--margin-l <px>] [--margin-r <px>] [--outline <px>] [--shadow <px>] [--blur <px>] [--overwrite]
EOF
}

ensure_deps() {
  if ! command -v ffmpeg >/dev/null 2>&1; then
    echo "Missing dependency: ffmpeg" >&2
    exit 1
  fi

  if ! command -v ffprobe >/dev/null 2>&1; then
    echo "Missing dependency: ffprobe" >&2
    exit 1
  fi
}

require_file() {
  local path="$1"
  if [[ ! -f "$path" ]]; then
    echo "Input file not found: $path" >&2
    exit 1
  fi
}

require_output_target() {
  local path="$1"
  local overwrite="$2"
  local parent_dir

  parent_dir="$(dirname "$path")"
  if [[ ! -d "$parent_dir" ]]; then
    echo "Output directory does not exist: $parent_dir" >&2
    exit 1
  fi

  if [[ -e "$path" && "$overwrite" -ne 1 ]]; then
    echo "Output already exists: $path" >&2
    echo "Use --overwrite to replace it." >&2
    exit 1
  fi
}

overwrite_flag() {
  if [[ "${1:-0}" -eq 1 ]]; then
    echo "-y"
  else
    echo "-n"
  fi
}

run_command_to_output() {
  local output_path="$1"
  local overwrite="$2"
  shift 2

  local output_dir
  local output_name
  local temp_dir
  local temp_output

  require_output_target "$output_path" "$overwrite"

  output_dir="$(dirname "$output_path")"
  output_name="$(basename "$output_path")"
  temp_dir="$(mktemp -d "$output_dir/.ponyflash-output.XXXXXX")"
  temp_output="$temp_dir/$output_name"

  cleanup_temp_output() {
    rm -f "$temp_output"
    rmdir "$temp_dir" 2>/dev/null || true
  }

  if "$@" "$temp_output"; then
    if [[ -e "$output_path" ]]; then
      rm -f "$output_path"
    fi
    mv "$temp_output" "$output_path"
    rmdir "$temp_dir"
    return 0
  fi

  cleanup_temp_output
  return 1
}

require_command() {
  local command_name="$1"
  if ! command -v "$command_name" >/dev/null 2>&1; then
    echo "Missing dependency: $command_name" >&2
    exit 1
  fi
}

prepare_default_font_dir() {
  local font_dir="$1"
  bash "$script_dir/ensure_subtitle_fonts.sh" --font-dir "$font_dir" --quiet
}

probe_video_dimensions() {
  local input_path="$1"
  ffprobe -hide_banner -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0:s=x "$input_path"
}

escape_filter_path() {
  local value="$1"
  value="${value//\\/\\\\}"
  value="${value//:/\\:}"
  value="${value//,/\\,}"
  value="${value//[/\\[}"
  value="${value//]/\\]}"
  printf '%s' "$value"
}

script_dir="$(cd "$(dirname "$0")" && pwd)"
default_font="__PONYFLASH_DEFAULT_FONT__"
default_latin_font="$default_font"
default_cjk_font="$default_font"

cmd="${1:-help}"
if [[ $# -gt 0 ]]; then
  shift
fi

case "$cmd" in
  help|-h|--help)
    usage
    exit 0
    ;;
  fonts-prepare)
    bash "$script_dir/ensure_subtitle_fonts.sh" "$@"
    ;;
  probe)
    ensure_deps
    input=""

    while [[ $# -gt 0 ]]; do
      case "$1" in
        --input)
          input="$2"
          shift 2
          ;;
        *)
          echo "Unknown option for probe: $1" >&2
          exit 2
          ;;
      esac
    done

    [[ -n "$input" ]] || { echo "probe requires --input" >&2; exit 2; }
    require_file "$input"

    ffprobe -hide_banner -v error -show_format -show_streams "$input"
    ;;
  clip)
    ensure_deps
    input=""
    output=""
    start=""
    duration=""
    mode="reencode"
    overwrite=0

    while [[ $# -gt 0 ]]; do
      case "$1" in
        --input)
          input="$2"
          shift 2
          ;;
        --output)
          output="$2"
          shift 2
          ;;
        --start)
          start="$2"
          shift 2
          ;;
        --duration)
          duration="$2"
          shift 2
          ;;
        --mode)
          mode="$2"
          shift 2
          ;;
        --overwrite)
          overwrite=1
          shift
          ;;
        *)
          echo "Unknown option for clip: $1" >&2
          exit 2
          ;;
      esac
    done

    [[ -n "$input" ]] || { echo "clip requires --input" >&2; exit 2; }
    [[ -n "$output" ]] || { echo "clip requires --output" >&2; exit 2; }
    [[ -n "$start" ]] || { echo "clip requires --start" >&2; exit 2; }
    [[ -n "$duration" ]] || { echo "clip requires --duration" >&2; exit 2; }
    require_file "$input"

    if [[ "$mode" == "copy" ]]; then
      run_command_to_output "$output" "$overwrite" \
        ffmpeg -y -hide_banner -ss "$start" -i "$input" -t "$duration" -c copy
    elif [[ "$mode" == "reencode" ]]; then
      run_command_to_output "$output" "$overwrite" \
        ffmpeg -y -hide_banner -i "$input" -ss "$start" -t "$duration" -c:v libx264 -preset medium -crf 18 -c:a aac -b:a 192k -movflags +faststart
    else
      echo "Unsupported clip mode: $mode" >&2
      exit 2
    fi
    ;;
  concat)
    ensure_deps
    inputs=()
    output=""
    mode="copy"
    overwrite=0
    list_file=""

    cleanup() {
      [[ -n "$list_file" && -f "$list_file" ]] && rm -f "$list_file"
    }
    trap cleanup EXIT

    while [[ $# -gt 0 ]]; do
      case "$1" in
        --input)
          inputs+=("$2")
          shift 2
          ;;
        --output)
          output="$2"
          shift 2
          ;;
        --mode)
          mode="$2"
          shift 2
          ;;
        --overwrite)
          overwrite=1
          shift
          ;;
        *)
          echo "Unknown option for concat: $1" >&2
          exit 2
          ;;
      esac
    done

    [[ ${#inputs[@]} -ge 2 ]] || { echo "concat requires at least two --input values" >&2; exit 2; }
    [[ -n "$output" ]] || { echo "concat requires --output" >&2; exit 2; }

    list_file="$(mktemp)"
    for input in "${inputs[@]}"; do
      require_file "$input"
      escaped_path="${input//\'/\'\\\'\'}"
      printf "file '%s'\n" "$escaped_path" >>"$list_file"
    done

    if [[ "$mode" == "copy" ]]; then
      run_command_to_output "$output" "$overwrite" \
        ffmpeg -y -hide_banner -f concat -safe 0 -i "$list_file" -c copy
    elif [[ "$mode" == "reencode" ]]; then
      run_command_to_output "$output" "$overwrite" \
        ffmpeg -y -hide_banner -f concat -safe 0 -i "$list_file" -c:v libx264 -preset medium -crf 18 -c:a aac -b:a 192k -movflags +faststart
    else
      echo "Unsupported concat mode: $mode" >&2
      exit 2
    fi
    ;;
  extract-audio)
    ensure_deps
    input=""
    output=""
    audio_codec="aac"
    bitrate="192k"
    overwrite=0

    while [[ $# -gt 0 ]]; do
      case "$1" in
        --input)
          input="$2"
          shift 2
          ;;
        --output)
          output="$2"
          shift 2
          ;;
        --audio-codec)
          audio_codec="$2"
          shift 2
          ;;
        --bitrate)
          bitrate="$2"
          shift 2
          ;;
        --overwrite)
          overwrite=1
          shift
          ;;
        *)
          echo "Unknown option for extract-audio: $1" >&2
          exit 2
          ;;
      esac
    done

    [[ -n "$input" ]] || { echo "extract-audio requires --input" >&2; exit 2; }
    [[ -n "$output" ]] || { echo "extract-audio requires --output" >&2; exit 2; }
    require_file "$input"

    if [[ "$audio_codec" == "copy" ]]; then
      run_command_to_output "$output" "$overwrite" \
        ffmpeg -y -hide_banner -i "$input" -vn -c:a copy
    else
      run_command_to_output "$output" "$overwrite" \
        ffmpeg -y -hide_banner -i "$input" -vn -c:a "$audio_codec" -b:a "$bitrate"
    fi
    ;;
  transcode)
    ensure_deps
    input=""
    output=""
    video_codec="libx264"
    audio_codec="aac"
    crf="18"
    preset="medium"
    bitrate="192k"
    overwrite=0

    while [[ $# -gt 0 ]]; do
      case "$1" in
        --input)
          input="$2"
          shift 2
          ;;
        --output)
          output="$2"
          shift 2
          ;;
        --video-codec)
          video_codec="$2"
          shift 2
          ;;
        --audio-codec)
          audio_codec="$2"
          shift 2
          ;;
        --crf)
          crf="$2"
          shift 2
          ;;
        --preset)
          preset="$2"
          shift 2
          ;;
        --bitrate)
          bitrate="$2"
          shift 2
          ;;
        --overwrite)
          overwrite=1
          shift
          ;;
        *)
          echo "Unknown option for transcode: $1" >&2
          exit 2
          ;;
      esac
    done

    [[ -n "$input" ]] || { echo "transcode requires --input" >&2; exit 2; }
    [[ -n "$output" ]] || { echo "transcode requires --output" >&2; exit 2; }
    require_file "$input"

    run_command_to_output "$output" "$overwrite" \
      ffmpeg -y -hide_banner -i "$input" -c:v "$video_codec" -preset "$preset" -crf "$crf" -c:a "$audio_codec" -b:a "$bitrate" -movflags +faststart
    ;;
  frame)
    ensure_deps
    input=""
    output=""
    time_value=""
    overwrite=0

    while [[ $# -gt 0 ]]; do
      case "$1" in
        --input)
          input="$2"
          shift 2
          ;;
        --output)
          output="$2"
          shift 2
          ;;
        --time)
          time_value="$2"
          shift 2
          ;;
        --overwrite)
          overwrite=1
          shift
          ;;
        *)
          echo "Unknown option for frame: $1" >&2
          exit 2
          ;;
      esac
    done

    [[ -n "$input" ]] || { echo "frame requires --input" >&2; exit 2; }
    [[ -n "$output" ]] || { echo "frame requires --output" >&2; exit 2; }
    [[ -n "$time_value" ]] || { echo "frame requires --time" >&2; exit 2; }
    require_file "$input"

    run_command_to_output "$output" "$overwrite" \
      ffmpeg -y -hide_banner -ss "$time_value" -i "$input" -frames:v 1
    ;;
  subtitle-burn)
    ensure_deps
    require_command python3

    input=""
    subtitle_file=""
    output=""
    ass_output=""
    latin_font_file="$default_latin_font"
    cjk_font_file="$default_cjk_font"
    wrap_width_ratio=""
    font_size=""
    margin_v=""
    margin_l=""
    margin_r=""
    outline=""
    shadow=""
    blur=""
    overwrite=0
    temp_ass_output=""
    temp_fonts_dir=""
    fonts_dir=""

    cleanup_subtitle_burn() {
      [[ -n "$temp_ass_output" && -f "$temp_ass_output" ]] && rm -f "$temp_ass_output"
      [[ -n "$temp_fonts_dir" && -d "$temp_fonts_dir" ]] && rm -rf "$temp_fonts_dir"
    }
    trap cleanup_subtitle_burn EXIT

    while [[ $# -gt 0 ]]; do
      case "$1" in
        --input)
          input="$2"
          shift 2
          ;;
        --subtitle-file)
          subtitle_file="$2"
          shift 2
          ;;
        --output)
          output="$2"
          shift 2
          ;;
        --ass-output)
          ass_output="$2"
          shift 2
          ;;
        --latin-font-file)
          latin_font_file="$2"
          shift 2
          ;;
        --cjk-font-file)
          cjk_font_file="$2"
          shift 2
          ;;
        --wrap-width-ratio)
          wrap_width_ratio="$2"
          shift 2
          ;;
        --font-size)
          font_size="$2"
          shift 2
          ;;
        --margin-v)
          margin_v="$2"
          shift 2
          ;;
        --margin-l)
          margin_l="$2"
          shift 2
          ;;
        --margin-r)
          margin_r="$2"
          shift 2
          ;;
        --outline)
          outline="$2"
          shift 2
          ;;
        --shadow)
          shadow="$2"
          shift 2
          ;;
        --blur)
          blur="$2"
          shift 2
          ;;
        --overwrite)
          overwrite=1
          shift
          ;;
        *)
          echo "Unknown option for subtitle-burn: $1" >&2
          exit 2
          ;;
      esac
    done

    [[ -n "$input" ]] || { echo "subtitle-burn requires --input" >&2; exit 2; }
    [[ -n "$subtitle_file" ]] || { echo "subtitle-burn requires --subtitle-file" >&2; exit 2; }
    [[ -n "$output" ]] || { echo "subtitle-burn requires --output" >&2; exit 2; }
    require_file "$input"
    require_file "$subtitle_file"

    bash "$script_dir/check_ffmpeg.sh" --require-subtitles-filter >/dev/null

    using_default_fonts=0
    if [[ "$latin_font_file" == "$default_latin_font" && "$cjk_font_file" == "$default_cjk_font" ]]; then
      using_default_fonts=1
      temp_fonts_dir="$(mktemp -d "${TMPDIR:-/tmp}/ponyflash-fonts.XXXXXX")"
      latin_font_file="$(prepare_default_font_dir "$temp_fonts_dir")"
      cjk_font_file="$latin_font_file"
      fonts_dir="$temp_fonts_dir"
    else
      require_file "$latin_font_file"
      require_file "$cjk_font_file"
      latin_font_dir="$(cd "$(dirname "$latin_font_file")" && pwd)"
      cjk_font_dir="$(cd "$(dirname "$cjk_font_file")" && pwd)"
      if [[ "$latin_font_dir" == "$cjk_font_dir" ]]; then
        fonts_dir="$latin_font_dir"
      else
        temp_fonts_dir="$(mktemp -d "${TMPDIR:-/tmp}/ponyflash-fonts.XXXXXX")"
        cp "$latin_font_file" "$temp_fonts_dir/"
        cp "$cjk_font_file" "$temp_fonts_dir/"
        fonts_dir="$temp_fonts_dir"
      fi
    fi

    subtitle_ext="$(printf '%s' "${subtitle_file##*.}" | tr '[:upper:]' '[:lower:]')"
    video_dims="$(probe_video_dimensions "$input")"
    [[ -n "$video_dims" ]] || { echo "Could not probe input video dimensions." >&2; exit 1; }
    video_width="${video_dims%x*}"
    video_height="${video_dims#*x}"
    [[ -n "$video_width" && -n "$video_height" && "$video_width" != "$video_dims" ]] || {
      echo "Could not parse probed video dimensions: $video_dims" >&2
      exit 1
    }

    ass_source="$subtitle_file"
    if [[ "$subtitle_ext" != "ass" ]]; then
      if [[ -n "$ass_output" ]]; then
        ass_source="$ass_output"
      else
        temp_ass_output="$(mktemp "${TMPDIR:-/tmp}/ponyflash-subtitles.XXXXXX.ass")"
        ass_source="$temp_ass_output"
      fi

      build_args=(
        "$script_dir/build_ass_subtitles.py"
        --subtitle-file "$subtitle_file"
        --output-ass "$ass_source"
        --video-width "$video_width"
        --video-height "$video_height"
        --latin-font-file "$latin_font_file"
        --cjk-font-file "$cjk_font_file"
      )

      [[ -n "$wrap_width_ratio" ]] && build_args+=(--wrap-width-ratio "$wrap_width_ratio")
      [[ -n "$font_size" ]] && build_args+=(--font-size "$font_size")
      [[ -n "$margin_v" ]] && build_args+=(--margin-v "$margin_v")
      [[ -n "$margin_l" ]] && build_args+=(--margin-l "$margin_l")
      [[ -n "$margin_r" ]] && build_args+=(--margin-r "$margin_r")
      [[ -n "$outline" ]] && build_args+=(--outline "$outline")
      [[ -n "$shadow" ]] && build_args+=(--shadow "$shadow")
      [[ -n "$blur" ]] && build_args+=(--blur "$blur")

      python3 "${build_args[@]}"
    fi

    run_command_to_output "$output" "$overwrite" \
      ffmpeg -y -hide_banner -i "$input" \
      -vf "subtitles=$(escape_filter_path "$ass_source"):fontsdir=$(escape_filter_path "$fonts_dir")" \
      -c:v libx264 -preset medium -crf 18 -c:a aac -b:a 192k -movflags +faststart
    ;;
  *)
    echo "Unknown command: $cmd" >&2
    usage >&2
    exit 2
    ;;
esac


path: reference/account.md
content: # Account API Reference

## Methods

### `pony_flash.account.credits() -> CreditBalance`

Get current credit balance.

### `pony_flash.account.recharge(*, amount=NOT_GIVEN, redirect_url=NOT_GIVEN) -> RechargeResponse`

Get a recharge payment link.

## Parameters

### recharge()

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `amount` | `int` | No | — | Amount of credits to recharge |
| `redirect_url` | `str` | No | — | URL to redirect after payment |

## Return types

### CreditBalance

| Field | Type | Description |
|---|---|---|
| `balance` | `int` | Current credit balance |
| `currency` | `str` | Currency unit (default `"credits"`) |
| `updated_at` | `str \| None` | Last update timestamp |

### RechargeResponse

| Field | Type | Description |
|---|---|---|
| `recharge_url` | `str` | Payment page URL |
| `expires_at` | `str \| None` | Link expiration |

## Example

```python
bal = pony_flash.account.credits()
print(f"Balance: {bal.balance} {bal.currency}")

if bal.balance < 50:
    resp = pony_flash.account.recharge(amount=100)
    print(f"Recharge at: {resp.recharge_url}")
```


path: reference/examples.md
content: # Examples

These examples help an agent map user requests to the stable script entrypoints.

## Example 1: Check whether FFmpeg is available

User intent:

> Check whether this machine can run ffmpeg directly

Recommended command:

```bash
bash scripts/check_ffmpeg.sh
```

If only basic editing support is required:

```bash
bash scripts/check_ffmpeg.sh --profile basic
```

If dependencies are missing, explain what is missing, offer installation guidance, and rerun the check after installation.

If subtitle burn-in may be needed later, run an extra check:

```bash
bash scripts/check_ffmpeg.sh --require-subtitles-filter
```

## Example 2: Keep 8 seconds starting at 00:00:05

User intent:

> Cut an 8-second clip starting from 00:00:05 in `input.mp4`

Recommended command:

```bash
taskDir="$(mktemp -d "${TMPDIR:-/tmp}/ponyflash-task.XXXXXX")"
bash scripts/media_ops.sh clip --input "$taskDir/input.mp4" --output "$taskDir/clip.mp4" --start "00:00:05" --duration "8"
```

## Example 3: Fast near-lossless trimming

User intent:

> I only care about speed and I can tolerate keyframe-boundary inaccuracies

Recommended command:

```bash
bash scripts/media_ops.sh clip --mode copy --input "$taskDir/input.mp4" --output "$taskDir/clip.mp4" --start "00:00:05" --duration "8"
```

## Example 4: Concatenate two clips

User intent:

> Merge `part1.mp4` and `part2.mp4` into one output file

Recommended command:

```bash
bash scripts/media_ops.sh concat --input "$taskDir/part1.mp4" --input "$taskDir/part2.mp4" --output "$taskDir/merged.mp4"
```

If that fails, retry with re-encoding:

```bash
bash scripts/media_ops.sh concat --mode reencode --input "$taskDir/part1.mp4" --input "$taskDir/part2.mp4" --output "$taskDir/merged.mp4"
```

## Example 5: Extract audio

User intent:

> Export the audio track from the video

Recommended command:

```bash
bash scripts/media_ops.sh extract-audio --input "$taskDir/input.mp4" --output "$taskDir/audio.m4a"
```

## Example 6: Convert MOV to a more compatible MP4

User intent:

> Convert this MOV file into a more standard MP4

Recommended command:

```bash
bash scripts/media_ops.sh transcode --input "$taskDir/input.mov" --output "$taskDir/output.mp4"
```

## Example 7: Export a cover frame

User intent:

> Grab a cover image at the 3-second mark

Recommended command:

```bash
bash scripts/media_ops.sh frame --input "$taskDir/input.mp4" --output "$taskDir/cover.jpg" --time "00:00:03"
```

## Example 8: Inspect media before deciding what to do

User intent:

> Check the codec and duration of this video first

Recommended command:

```bash
bash scripts/media_ops.sh probe --input "input.mp4"
```

## Example 9: Allow overwriting existing output

User intent:

> Overwrite the existing output file directly

Add:

```bash
--overwrite
```

For example:

```bash
bash scripts/media_ops.sh transcode --input "input.mov" --output "output.mp4" --overwrite
```

## Example 10: Verify whether subtitle burn-in is supported

User intent:

> Confirm whether this machine can burn in SRT subtitles directly with ffmpeg

Recommended command:

```bash
bash scripts/check_ffmpeg.sh --require-subtitles-filter
```

If that fails, explain that a full FFmpeg build with `libass` support is required and ask the user to install it manually.

## Example 11: Check whether simple text overlays are possible

User intent:

> I do not necessarily need SRT support. I just need to place a few lines of text at the bottom.

Recommended command:

```bash
bash scripts/check_ffmpeg.sh --require-subtitle-support
```

## Example 12: Prepare the default subtitle font

User intent:

> Keep a reusable local copy of the default subtitle font

Recommended command:

```bash
bash scripts/ensure_subtitle_fonts.sh
```

## Example 13: Use a custom subtitle font cache directory

User intent:

> Download the default subtitle font into a project-specific cache directory

Recommended command:

```bash
bash scripts/ensure_subtitle_fonts.sh --font-dir "./.cache/subtitle-fonts"
```

## Example 14: Generate adaptive ASS subtitles for 9:16 output

User intent:

> Burn subtitles into a portrait video and keep long lines from overflowing the frame

Recommended command:

```bash
bash scripts/ensure_subtitle_fonts.sh

python3 scripts/build_ass_subtitles.py \
  --events-json "events.json" \
  --output-ass "subtitles.ass" \
  --video-width 1080 \
  --video-height 1920 \
  --latin-font-file "$HOME/.cache/ponyflash/fonts/NotoSansCJKsc-Regular.otf" \
  --cjk-font-file "$HOME/.cache/ponyflash/fonts/NotoSansCJKsc-Regular.otf"
```

## Example 15: Burn subtitles with the default workflow

User intent:

> Add subtitles to this video. Use the default style.

Recommended command:

```bash
taskDir="$(mktemp -d "${TMPDIR:-/tmp}/ponyflash-task.XXXXXX")"
bash scripts/media_ops.sh subtitle-burn --input "$taskDir/input.mp4" --subtitle-file "$taskDir/subtitles.srt" --output "final-output.mp4"
```

What it does by default:

- probes the input video width and height with `ffprobe`
- builds an adaptive `.ass` file with `scripts/build_ass_subtitles.py`
- prepares the default runtime font in a temporary directory
- burns subtitles with `ffmpeg subtitles=...:fontsdir=...`
- removes temporary subtitle and font files after the final output is written
- deletes `taskDir` afterwards unless you explicitly asked to keep staged files

## Example 16: Expanded default subtitle burn pattern

User intent:

> Show me the full default subtitle burn flow

Recommended workflow:

```bash
taskDir="$(mktemp -d "${TMPDIR:-/tmp}/ponyflash-task.XXXXXX")"
ffprobe -hide_banner -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0:s=x "$taskDir/input.mp4"
```

```bash
bash scripts/media_ops.sh subtitle-burn --input "$taskDir/input.mp4" --subtitle-file "$taskDir/subtitles.srt" --output "final-output.mp4"
```

Notes:

- the command stages fonts and temporary subtitle files automatically
- only the final `final-output.mp4` is kept unless you explicitly request another deliverable such as `--ass-output`
- staged downloads, subtitle sources, and intermediate renders should stay inside `taskDir`


path: reference/files.md
content: # Files API Reference

## Methods

### `pony_flash.files.upload(file: FileInput) -> str`

Upload a file via presigned URL. Returns `file_id`.

Most users don't need to call this directly — `generate()` auto-uploads `FileInput` values.

### `pony_flash.files.presign(*, filename, content_type, size) -> PresignResponse`

Get a presigned upload URL. Low-level; prefer `upload()`.

### `pony_flash.files.resolve(inp: FileInput) -> dict`

Resolve a `FileInput` to API JSON (`{"type": "url", "url": ...}` or `{"type": "file_id", "file_id": ...}`). Auto-uploads if needed.

### `pony_flash.files.resolve_many(inputs: Sequence[FileInput]) -> list[dict]`

Resolve multiple `FileInput` values.

### `pony_flash.files.get(file_id: str) -> FileObject`

Get file metadata.

### `pony_flash.files.list() -> list[FileObject]`

List all uploaded files.

### `pony_flash.files.delete(file_id: str) -> None`

Delete a file.

### `pony_flash.files.cleanup(file_ids: Sequence[str]) -> None`

Best-effort delete of temporary files. Errors are logged, never raised.

## Return types

### PresignResponse

| Field | Type | Description |
|---|---|---|
| `file_id` | `str` | Assigned file ID |
| `upload_url` | `str` | Presigned PUT URL |
| `expires_at` | `str` | Expiration timestamp |
| `method` | `str` | HTTP method (default `"PUT"`) |
| `headers` | `Dict[str, str]` | Headers to include in upload |

### FileObject

| Field | Type | Description |
|---|---|---|
| `file_id` | `str` | File identifier |
| `filename` | `str` | Original filename |
| `content_type` | `str` | MIME type |
| `size` | `int` | File size in bytes |
| `status` | `str` | Upload status |
| `created_at` | `str` | Creation timestamp |
| `expires_at` | `str \| None` | Expiration timestamp |

## Example

```python
file_id = pony_flash.files.upload(open("photo.jpg", "rb"))
print(f"Uploaded: {file_id}")

files = pony_flash.files.list()
for f in files:
    print(f"{f.file_id}: {f.filename} ({f.size} bytes)")

pony_flash.files.delete(file_id)
```


path: reference/images.md
content: # Images API Reference

## Method

### `pony_flash.images.generate(**kwargs) -> Generation`

Generate images and wait for completion. Returns `Generation` with output URLs.

## Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `model` | `str` | Yes | — | Model ID (e.g. `"nanobanana-pro"`, `"nanobanana"`) |
| `prompt` | `str` | Yes | — | Text description of the image to generate |
| `size` | `str` | No | — | Output size (e.g. `"1K"`, `"2K"`, `"4K"`) |
| `n` | `int` | No | — | Number of images to generate |
| `quality` | `str` | No | — | Quality level |
| `output_format` | `str` | No | — | Output format |
| `images` | `List[FileInput]` | No | — | Reference/input images for editing |
| `mask` | `FileInput` | No | — | Mask image for inpainting |
| `context` | `str` | No | — | Additional context for the generation |

## Return type: Generation

| Field | Type | Description |
|---|---|---|
| `request_id` | `str` | Request ID |
| `status` | `"queued" \| "running" \| "succeeded" \| "failed"` | Current status |
| `outputs` | `List[GenerationOutput]` | Output items |
| `usage` | `GenerationUsage \| None` | Credit usage |
| `error` | `GenerationError \| None` | Error details if failed |

**Convenience properties:** `gen.url` (first URL), `gen.urls` (all URLs), `gen.credits` (credits used).

## Example

```python
gen = pony_flash.images.generate(
    model="nanobanana-pro",
    prompt="A cyberpunk cityscape at night",
    size="2K",
    n=2,
)
for url in gen.urls:
    print(url)
```

## Available models

- [nanobanana-pro / nanobanana](models/nanobanana-pro.md) — sizes (1K/2K/4K), aspect ratios, credit costs, image-to-image

For the full model list, see [models/INDEX.md](models/INDEX.md).


path: reference/models.md
content: # Models API Reference

## Methods

### `pony_flash.models.list(**kwargs) -> SyncPage[ModelInfo]`

List available models. Supports pagination and filtering by type.

### `pony_flash.models.get(model_id: str) -> ModelDetail`

Get detailed information about a specific model.

## list() Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `cursor` | `str` | No | — | Pagination cursor |
| `limit` | `int` | No | — | Max items per page |
| `type` | `str` | No | — | Filter by type (e.g. `"image"`, `"video"`, `"speech"`, `"music"`) |

## Return types

### ModelInfo

| Field | Type | Description |
|---|---|---|
| `id` | `str` | Model identifier |
| `type` | `str` | Model type |
| `input` | `List[str]` | Supported input types |
| `output` | `List[str]` | Supported output types |
| `supported_sizes` | `List[str]` | Available output sizes |
| `supported_durations` | `List[int]` | Available durations |
| `supported_qualities` | `List[str]` | Quality options |
| `supported_output_formats` | `List[str]` | Output format options |
| `pricing` | `ModelPricing \| None` | Pricing info |

### ModelDetail (extends ModelInfo)

Additional fields:

| Field | Type | Description |
|---|---|---|
| `name` | `str \| None` | Display name |
| `description` | `str \| None` | Model description |
| `supported_modes` | `List[SupportedMode]` | Available generation modes |
| `limits` | `ModelLimits \| None` | Input constraints |

### SupportedMode

| Field | Type | Description |
|---|---|---|
| `name` | `str` | Mode name |
| `description` | `str \| None` | Mode description |
| `required_fields` | `List[str]` | Required parameters for this mode |
| `optional_fields` | `List[str]` | Optional parameters for this mode |

### ModelLimits

| Field | Type |
|---|---|
| `max_prompt_length` | `int \| None` |
| `max_images` | `int \| None` |
| `max_file_size_mb` | `int \| None` |

### ModelPricing

| Field | Type |
|---|---|
| `unit` | `str` |
| `credits` | `int` |

## SyncPage

| Field | Type | Description |
|---|---|---|
| `items` | `List[T]` | Current page items |
| `has_more` | `bool` | More pages available |
| `next_cursor` | `str \| None` | Cursor for next page |

Iterable: `for model in page.items:`.

## Example

```python
page = pony_flash.models.list(type="video")
for m in page.items:
    print(f"{m.id}: sizes={m.supported_sizes}, durations={m.supported_durations}")

detail = pony_flash.models.get("omnihuman-1.5")
for mode in detail.supported_modes:
    print(f"  {mode.name}: required={mode.required_fields}")
```


path: reference/music.md
content: # Music API Reference

## Method

### `pony_flash.music.generate(**kwargs) -> Generation`

Generate music and wait for completion.

## Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `model` | `str` | Yes | — | Model ID (e.g. `"music-2.5"`) |
| `prompt` | `str` | Yes | — | Description of the music to generate |
| `lyrics` | `str` | No | — | Song lyrics (supports structure tags like `[Verse]`, `[Chorus]`) |
| `title` | `str` | No | — | Song title |
| `style` | `str` | No | — | Music style (e.g. `"pop ballad"`, `"electronic"`) |
| `duration` | `int` | No | — | Duration in seconds |
| `instrumental` | `bool` | No | — | If `True`, generate without vocals |
| `reference_audio` | `FileInput` | No | — | Reference audio for style/continuation |
| `continue_at` | `float` | No | — | Timestamp (seconds) to continue from |
| `format` | `str` | No | — | Output format |
| `quality` | `str` | No | — | Quality level |

## Example

```python
gen = pony_flash.music.generate(
    model="music-2.5",
    prompt="A chill lo-fi hip hop beat for studying",
    instrumental=True,
    duration=60,
)
print(gen.url)
```

## Available models

- [music-2.5](models/music-2.5.md) — lyrics structure tags, instrumental mode, song continuation

For the full model list, see [models/INDEX.md](models/INDEX.md).


path: reference/operations.md
content: # Operation Strategy

This document explains how an agent should make decisions when using this skill across different FFmpeg-related tasks.

## General Flow

1. Run `scripts/check_ffmpeg.sh` first.
2. If the task involves subtitles, run an additional subtitle capability check.
3. If dependencies or required filters are missing, explain what is missing, offer installation guidance, and rerun the checks after installation.
4. Confirm input files, output path, time parameters, and overwrite policy.
5. Prefer `scripts/media_ops.sh` over ad-hoc shell commands.
6. After execution, verify that the output file was actually created.
7. Unless the user explicitly asks to keep intermediate files, remove temporary files and caches after the task finishes.
8. For multi-step edits, create a temporary task directory first and keep every non-final file inside it.

Example:

```bash
taskDir="$(mktemp -d "${TMPDIR:-/tmp}/ponyflash-task.XXXXXX")"
```

## Capability Profiles

### `basic`

Used to guarantee that the basic editing path is available. Requires at least:

- `ffmpeg`
- `ffprobe`
- `libx264`
- `aac`

Recommended command:

```bash
bash scripts/check_ffmpeg.sh --profile basic
```

### `full`

Used to guarantee that both subtitle burn-in and basic editing are available. Requires:

- everything in `basic`
- the `subtitles` filter

Recommended command:

```bash
bash scripts/check_ffmpeg.sh --profile full
```

## Subtitle Capability Checks

### Basic check

If the user only asks whether FFmpeg is installed and usable, run:

```bash
bash scripts/check_ffmpeg.sh
```

### Subtitle-specific checks

If the user wants to burn in `.srt` or `.ass` subtitles, run:

```bash
bash scripts/check_ffmpeg.sh --require-subtitles-filter
```

If the user only needs basic editing support, run:

```bash
bash scripts/check_ffmpeg.sh --profile basic
```

If the user only needs simple text overlay support, run:

```bash
bash scripts/check_ffmpeg.sh --require-subtitle-support
```

### Result interpretation

- `subtitles_filter=available`: standard subtitle burn-in is supported
- `drawtext_filter=available`: plain text overlay is supported
- `basic_editing_support=available`: basic editing and common transcoding are supported
- `subtitle_support=full`: both subtitle burn-in and text overlay are available
- `subtitle_support=subtitles_only`: subtitle burn-in is available, but `drawtext` may not be
- `subtitle_support=drawtext_only`: plain text overlay is available, but direct `.srt` / `.ass` burn-in is not
- `subtitle_support=missing`: the current FFmpeg build lacks subtitle-related support

## Media Probe

Useful for:

- checking duration, codec, and resolution first
- deciding whether media is suitable for lossless concat
- confirming input parameters before transcoding

Recommended command:

```bash
bash scripts/media_ops.sh probe --input "input.mp4"
```

## Video Trimming

### Default strategy

Use `reencode` by default, because it is less sensitive to keyframe boundaries and produces more predictable results.

```bash
bash scripts/media_ops.sh clip --input "$taskDir/input.mp4" --output "$taskDir/clip.mp4" --start "00:00:05" --duration "8"
```

### When to use `copy`

Prefer `copy` only when the user explicitly wants:

- higher speed
- minimal or no re-encoding loss
- acceptance of keyframe-boundary inaccuracies

```bash
bash scripts/media_ops.sh clip --mode copy --input "$taskDir/input.mp4" --output "$taskDir/clip.mp4" --start "00:00:05" --duration "8"
```

## Video Concat

### Default strategy

If clips share the same codec, container, and resolution, prefer `concat + copy`.

```bash
bash scripts/media_ops.sh concat --input "$taskDir/part1.mp4" --input "$taskDir/part2.mp4" --output "$taskDir/merged.mp4"
```

### Fallback strategy

If lossless concat fails, the inputs usually differ in one of these ways:

- different video codec
- different audio codec
- different time base or container parameters

In that case, switch to re-encoding:

```bash
bash scripts/media_ops.sh concat --mode reencode --input "$taskDir/part1.mp4" --input "$taskDir/part2.mp4" --output "$taskDir/merged.mp4"
```

## Audio Extraction

### Default strategy

Use `aac` by default and prefer `.m4a` as the output format.

```bash
bash scripts/media_ops.sh extract-audio --input "$taskDir/input.mp4" --output "$taskDir/audio.m4a"
```

### When to use `copy`

Use `copy` only when the user explicitly wants to preserve the original audio codec and the target container supports it.

```bash
bash scripts/media_ops.sh extract-audio --input "$taskDir/input.mp4" --output "$taskDir/audio.aac" --audio-codec copy
```

## Transcoding

### Default strategy

Prefer broadly compatible Web / app output:

- container: `mp4`
- video codec: `libx264`
- audio codec: `aac`

```bash
bash scripts/media_ops.sh transcode --input "$taskDir/input.mov" --output "$taskDir/output.mp4"
```

### When to customize encoding

Override defaults only when the user explicitly asks for:

- a specific codec
- a specific compression level
- a target bitrate
- a delivery format for a downstream platform

## Frame Capture

Useful for cover images, screenshots at a specific timestamp, and preview frames.

```bash
bash scripts/media_ops.sh frame --input "$taskDir/input.mp4" --output "$taskDir/cover.jpg" --time "00:00:03"
```

## Subtitle Burn-in

### Default strategy

Check whether the current FFmpeg build supports the required filters first.

If subtitle style is unspecified, use the default subtitle workflow, which stages its runtime font in a temporary directory, keeps subtitle sources inside `taskDir`, and cleans them up afterwards.

Preferred stable entrypoint:

```bash
bash scripts/media_ops.sh subtitle-burn --input "$taskDir/input.mp4" --subtitle-file "$taskDir/subtitles.srt" --output "final-output.mp4"
```

If the task has explicit requirements for long-line wrapping, portrait / landscape adaptation, or subtitle safe margins, generate `.ass` first and then burn it in with `ffmpeg subtitles`.

Recommended entry point:

```bash
python3 scripts/build_ass_subtitles.py --help
```

Default burn pattern:

1. Probe output dimensions with `ffprobe`
2. Stage the runtime font in a temporary directory
3. Build `.ass` with `scripts/build_ass_subtitles.py`
4. Burn it in with `ffmpeg subtitles=...:fontsdir=...`
5. Delete temporary font files and temporary subtitle files, keeping only explicit deliverables

The default subtitle style should use `1920x1080` as the reference baseline, but scale dynamically at runtime:

- `shortEdge = min(videoWidth, videoHeight)`
- `fontSize = round(shortEdge * 0.0556)`
- `marginV = round(videoHeight * 0.0963)`
- `marginL = marginR = round(videoWidth * 0.0625)`
- `outline = max(1, round(fontSize * 0.0167))`
- `shadow = 1`
- `blur = 1`

Wrapping rules:

- landscape or wide aspect ratio: keep max text width around `videoWidth * 0.90`
- portrait or narrow aspect ratio: keep max text width around `videoWidth * 0.90`
- pre-wrap `.ass` / `.srt` content before rendering whenever possible instead of relying fully on player or filter auto-wrapping
- `scripts/build_ass_subtitles.py` measures text width before deciding where to break lines

### Prerequisite for subtitle tasks

Standard subtitle burn-in requires the `subtitles` filter.

```bash
bash scripts/check_ffmpeg.sh --require-subtitles-filter
```

### Fallback when subtitle filters are missing

If `subtitles` is missing but `drawtext` is available:

- plain text overlays are still possible
- do not claim support for direct `.srt` / `.ass` burn-in

If both are missing:

- stop the subtitle task
- direct the user to install an FFmpeg build with `libass` / `freetype` support

## Overwrite Policy

Do not overwrite outputs by default. Only append `--overwrite` when the user explicitly allows it.

## Cleanup Policy

- Keep only the final deliverables the user explicitly requested, such as `--output` or `--ass-output`.
- Delete temporary concat lists, temporary ASS files, temporary font directories, and failed partial outputs automatically.
- Delete the temporary task directory after moving or confirming the final deliverable.
- If the user explicitly asks to keep reusable fonts, a local copy may be prepared with `scripts/ensure_subtitle_fonts.sh`.

## Out-of-Scope Tasks

The current stable script interface is not a good fit for:

- complex filter chains
- watermark compositing
- picture-in-picture
- multi-track audio/video rearrangement

Subtitle burn-in now has a stable default entrypoint through `media_ops.sh subtitle-burn`.
For more complex subtitle tasks beyond the default workflow, it is acceptable to fall back to raw `ffmpeg` commands after clearly explaining that they are outside the stable skill interface.


path: reference/speech.md
content: # Speech API Reference

## Method

### `pony_flash.speech.generate(**kwargs) -> Generation`

Generate speech audio and wait for completion.

## Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `model` | `str` | Yes | — | Model ID (e.g. `"speech-2.8-hd"`) |
| `input` | `str` | Yes | — | Text to synthesize |
| `voice` | `str` | Yes | — | Voice ID (e.g. `"English_Graceful_Lady"`, `"English_Insightful_Speaker"`) |
| `language` | `str` | No | — | Language code |
| `speed` | `float` | No | — | Playback speed multiplier |
| `pitch` | `int` | No | — | Pitch adjustment |
| `emotion` | `str` | No | — | Emotion (e.g. `"happy"`, `"sad"`, `"calm"`, `"angry"`, `"surprised"`) |
| `instructions` | `str` | No | — | Style instructions |
| `voice_settings` | `VoiceSettings` | No | — | Fine-grained voice control |
| `sample_rate` | `int` | No | — | Audio sample rate in Hz |
| `format` | `str` | No | — | Output format (e.g. `"mp3"`, `"wav"`) |

### VoiceSettings (TypedDict)

| Field | Type | Description |
|---|---|---|
| `stability` | `float` | Voice stability (0.0-1.0) |
| `similarity_boost` | `float` | Voice similarity (0.0-1.0) |
| `style` | `float` | Style exaggeration (0.0-1.0) |
| `use_speaker_boost` | `bool` | Enable speaker boost |

## Example

```python
gen = pony_flash.speech.generate(
    model="speech-2.8-hd",
    input="Hello, welcome to PonyFlash!",
    voice="English_Graceful_Lady",
    speed=1.0,
    format="mp3",
)
print(gen.url)
```

## Available models

- [speech-2.8-hd](models/speech-2.8-hd.md) — 40+ languages, 300+ voices, interjection tags, emotion control

For the full model list, see [models/INDEX.md](models/INDEX.md).


path: reference/video.md
content: # Video API Reference

## Method

### `pony_flash.video.generate(**kwargs) -> Generation`

Generate video and wait for completion.

## Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `model` | `str` | Yes | — | Model ID (e.g. `"seedance-1.5-pro"`, `"veo-3.1"`, `"omnihuman-1.5"`, `"motion-transfer-1"`) |
| `prompt` | `str` | No | — | Text description |
| `size` | `str` | No | — | Output size (e.g. `"1920x1080"`) |
| `duration` | `int` | No | — | Duration in seconds |
| `quality` | `str` | No | — | Quality level |
| `first_frame` | `FileInput` | No | — | Starting frame image |
| `last_frame` | `FileInput` | No | — | Ending frame image |
| `video` | `FileInput` | No | — | Input video |
| `audio` | `FileInput` | No | — | Audio track (for OmniHuman) |
| `reference_images` | `List[FileInput]` | No | — | Reference images |
| `motion_video` | `FileInput` | No | — | Motion source video (for Motion Transfer) |

## Generation modes

| Mode | Required params | Model example |
|---|---|---|
| Text-to-video | `model`, `prompt` | `seedance-1.5-pro`, `veo-3.1` |
| First-frame to video | `model`, `first_frame`, `prompt` | `seedance-1.5-pro`, `veo-3.1` |
| OmniHuman | `model`, `first_frame`, `audio` | `omnihuman-1.5` |
| Motion Transfer | `model`, `first_frame`, `motion_video` | `motion-transfer-1` |

## Example

```python
gen = pony_flash.video.generate(
    model="seedance-1.5-pro",
    prompt="Ocean waves crashing on a beach",
    duration=5,
)
print(gen.url)
print(f"Credits: {gen.credits}")
```

## Available models

- [seedance-1.5-pro](models/seedance-1.5-pro.md) — 720p, 2-12s, auto-generated audio, multi-language
- [veo-3.1](models/veo-3.1.md) — 720p/1080p, 4/6/8s, reference images, English only

For the full model list, see [models/INDEX.md](models/INDEX.md).


path: reference/models/INDEX.md
content: # Available Models

All models accessible via `pony_flash.models.list()` and `pony_flash.models.get(model_id)`.

## Quick Reference

| Model | Type | Pricing | Doc |
|---|---|---|---|
| `nano-banana-pro` | image | 7/10/15 credits (1K/2K/4K) | [nano-banana-pro.md](nano-banana-pro.md) |
| `nano-banana-2` | image | 7/10/15 credits (1K/2K/4K) | [nano-banana-2.md](nano-banana-2.md) |
| `seedream-5-lite` | image | 4 credits/image | [seedream-5-lite.md](seedream-5-lite.md) |
| `image-pro-1` | image | 20 credits/request | *(placeholder, not yet connected)* |
| `seedance-1.5-pro` | video | 1-12 c/s (by resolution+audio) | [seedance-1.5-pro.md](seedance-1.5-pro.md) |
| `veo-3.1` | video | 20-40 c/s (by audio) | [veo-3.1.md](veo-3.1.md) |
| `veo-3.1-fast` | video | 10-15 c/s (by audio) | [veo-3.1-fast.md](veo-3.1-fast.md) |
| `omnihuman-1.5` | video | 16 credits/second | *(see SKILL.md for usage)* |
| `speech-2.8-hd` | speech | 1 credit/request | [speech-2.8-hd.md](speech-2.8-hd.md) |
| `speech-2.8-turbo` | speech | 1 credit/request | [speech-2.8-turbo.md](speech-2.8-turbo.md) |

---

## Image Models

### nano-banana-pro

Google DeepMind's highest-quality image generation model (Gemini 3 Pro). Accurate text rendering, multi-image blending (up to 14 refs), professional creative controls.

| Field | Values |
|---|---|
| **resolution** | `1K`, `2K` (default), `4K` |
| **aspect_ratio** | `match_input_image`, `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9` |
| **output_format** | `jpg` (default), `png` |
| **reference_images** | Up to 14 images (FileInput[]) |
| **Pricing** | 1K = 7 credits, 2K = 10 credits, 4K = 15 credits |

```python
gen = pony_flash.images.generate(
    model="nano-banana-pro",
    prompt="A minimalist logo for a coffee shop",
    resolution="2K",
    aspect_ratio="1:1",
)
```

Extra parameters via `**extra_body`: `safety_filter_level` (`block_low_and_above` / `block_medium_and_above` / `block_only_high`)

---

### nano-banana-2

Google's fast image model (Gemini 3.1 Flash). Same quality as Pro with faster generation. Supports Google Search grounding for real-time info in images.

| Field | Values |
|---|---|
| **resolution** | `1K` (default), `2K`, `4K` |
| **aspect_ratio** | `match_input_image`, `1:1`, `1:4`, `1:8`, `2:3`, `3:2`, `3:4`, `4:1`, `4:3`, `4:5`, `5:4`, `8:1`, `9:16`, `16:9`, `21:9` |
| **output_format** | `jpg` (default), `png` |
| **reference_images** | Up to 14 images (FileInput[]) |
| **Pricing** | 1K = 7 credits, 2K = 10 credits, 4K = 15 credits |

```python
gen = pony_flash.images.generate(
    model="nano-banana-2",
    prompt="Current weather forecast for Tokyo as an infographic",
    resolution="2K",
    aspect_ratio="9:16",
)
```

Extra parameters via `**extra_body`: `google_search` (bool, default true), `image_search` (bool, default true)

---

### seedream-5-lite

ByteDance's image model with built-in reasoning, example-based editing, and batch generation. Lowest cost per image.

| Field | Values |
|---|---|
| **resolution** | `2K` (default), `3K` |
| **aspect_ratio** | `match_input_image`, `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `9:16`, `16:9`, `21:9` |
| **output_format** | `png` (default), `jpg` |
| **reference_images** | Up to 14 images (FileInput[]) |
| **n** | 1-15, number of images to generate (maps to `max_images`) |
| **Pricing** | 4 credits/image (all resolutions) |

```python
gen = pony_flash.images.generate(
    model="seedream-5-lite",
    prompt="A photorealistic interior rendering from this floor plan sketch",
    reference_images=[open("floor_plan.jpg", "rb")],
    resolution="3K",
    aspect_ratio="16:9",
)
```

Extra parameters via `**extra_body`: `sequential_image_generation` (`disabled` (default) / `auto`)

---

## Video Models

### seedance-1.5-pro

ByteDance's cinema-quality video model. Synchronized audio+video, lip-sync, multilingual.

| Field | Values |
|---|---|
| **duration** | 2-12 (any integer) |
| **resolution** | `480p`, `720p` (default), `1080p` |
| **aspect_ratio** | `16:9`, `4:3`, `1:1`, `3:4`, `9:16`, `21:9`, `9:21` |
| **generate_audio** | bool (default false) |
| **first_frame** | Starting image (FileInput) |
| **last_frame** | Ending image (FileInput) |
| **Pricing** | 480p: 3/1 c/s, 720p: 5/3 c/s, 1080p: 12/6 c/s (audio/silent) |

Extra via `**extra_body`: `camera_fixed` (bool)

### veo-3.1

Google's SOTA video model. Synchronized audio, reference images, first/last frame, 720p/1080p.

| Field | Values |
|---|---|
| **duration** | `4`, `6`, `8` |
| **resolution** | `720p`, `1080p` (default) |
| **aspect_ratio** | `16:9` (default), `9:16` |
| **generate_audio** | bool (default true) |
| **first_frame** | Starting image (FileInput) |
| **last_frame** | Ending image (FileInput) |
| **reference_images** | Up to 3 images (FileInput[]) |
| **negative_prompt** | What to exclude |
| **Pricing** | with_audio: 40 c/s, without: 20 c/s |

Extra via `**extra_body`: `seed` (int)

### veo-3.1-fast

Faster Veo 3.1. Same params, lower cost. Best for iteration.

| Field | Values |
|---|---|
| Same as veo-3.1 | All params identical |
| **Pricing** | with_audio: 15 c/s, without: 10 c/s |

### omnihuman-1.5

ByteDance OmniHuman. Portrait image + audio to talking-head video with lip-sync.

| Field | Values |
|---|---|
| **first_frame** | Human portrait image (required, FileInput) |
| **audio** | Speech/music audio, max 35s (required, FileInput) |
| **prompt** | Scene/action description (optional) |
| **Pricing** | 16 credits/second (duration = audio length) |

Extra parameters via `**extra_body`: `seed` (int), `fast_mode` (bool)

---

## Speech Models

### speech-2.8-hd

MiniMax Speech 2.8 HD. Ranked #1 on TTS benchmarks. Studio-grade quality, 330+ voices, 40+ languages, interjection tags, emotion control.

| Field | Values |
|---|---|
| **input** | Text to synthesize, max 10000 chars |
| **voice** | Voice ID (required). See voice list below |
| **emotion** | `auto` (default), `happy`, `calm`, `sad`, `angry`, `fearful`, `disgusted`, `surprised` |
| **speed** | `0.5` - `2.0` (default `1.0`) |
| **pitch** | `-12` to `+12` semitones (default `0`) |
| **format** | `mp3` (default), `wav`, `flac`, `pcm` |
| **sample_rate** | `8000`, `16000`, `22050`, `24000`, `32000` (default), `44100` |
| **language** | Language hint or `auto`. See language list below |
| **Pricing** | 1 credit/request (provisional) |

```python
gen = pony_flash.speech.generate(
    model="speech-2.8-hd",
    input="Hello (laughs), welcome to PonyFlash!",
    voice="English_Graceful_Lady",
    emotion="happy",
)
```

Extra parameters via `**extra_body`: `volume` (0-10), `bitrate` (int), `channel` (`mono`/`stereo`), `english_normalization` (bool)

#### Preset Voices (17)

`Wise_Woman`, `Friendly_Person`, `Inspirational_girl`, `Deep_Voice_Man`, `Calm_Woman`, `Casual_Guy`, `Lively_Girl`, `Patient_Man`, `Young_Knight`, `Determined_Man`, `Lovely_Girl`, `Decent_Boy`, `Imposing_Manner`, `Elegant_Man`, `Abbess`, `Sweet_Girl_2`, `Exuberant_Girl`

#### Extended Voice IDs (330+)

Also accepts MiniMax official voice IDs by language prefix:

| Language | Example Voice IDs |
|---|---|
| English (45) | `English_Graceful_Lady`, `English_radiant_girl`, `English_magnetic_voiced_man`, `English_Trustworth_Man`, `English_CalmWoman`, `English_PlayfulGirl`, `English_ManWithDeepVoice` |
| Chinese (34) | `Chinese (Mandarin)_Sweet_Lady`, `Chinese (Mandarin)_Gentleman`, `Chinese (Mandarin)_Radio_Host`, `Chinese (Mandarin)_Lyrical_Voice` |
| Japanese (15) | `Japanese_GentleButler`, `Japanese_KindLady`, `Japanese_CalmLady`, `Japanese_GracefulMaiden` |
| Korean (38) | `Korean_CalmGentleman`, `Korean_SweetGirl`, `Korean_CheerfulBoyfriend` |
| Spanish (39) | `Spanish_SereneWoman`, `Spanish_CaptivatingStoryteller`, `Spanish_Narrator` |
| Portuguese (72) | `Portuguese_SentimentalLady`, `Portuguese_Narrator`, `Portuguese_Comedian` |
| French (6) | `French_CasualMan`, `French_MovieLeadFemale`, `French_FemaleAnchor` |
| Others | Indonesian (9), German (3), Russian (8), Italian (4), Dutch (2), Arabic (2), Turkish (2), Ukrainian (2), Thai (4), Polish (4), Romanian (4), Greek (3), Czech (3), Finnish (3), Hindi (2) |

Custom cloned voice IDs (from MiniMax Voice Clone) are also accepted.

#### Supported Languages (40+)

`auto`, Chinese, English, Arabic, Russian, Spanish, French, Portuguese, German, Turkish, Dutch, Ukrainian, Vietnamese, Indonesian, Japanese, Italian, Korean, Thai, Polish, Romanian, Greek, Czech, Finnish, Hindi, Bulgarian, Danish, Hebrew, Malay, Persian, Slovak, Swedish, Croatian, Filipino, Hungarian, Norwegian, Slovenian, Catalan, Nynorsk, Tamil, Afrikaans

#### Interjection Tags

Place inline in text: `(laughs)`, `(chuckle)`, `(coughs)`, `(clear-throat)`, `(groans)`, `(breath)`, `(pant)`, `(inhale)`, `(exhale)`, `(gasps)`, `(sniffs)`, `(sighs)`, `(snorts)`, `(burps)`, `(lip-smacking)`, `(humming)`, `(hissing)`, `(emm)`, `(sneezes)`

#### Pause Control

Insert `<#x#>` for custom pauses (x = 0.01-99.99 seconds): `"First sentence.<#2.5#>Second sentence."`

---

### speech-2.8-turbo

MiniMax Speech 2.8 Turbo. Same parameters as HD, faster generation, slightly lower quality.

| Field | Values |
|---|---|
| Same as speech-2.8-hd | All parameters identical |
| **Pricing** | 1 credit/request (provisional) |

```python
gen = pony_flash.speech.generate(
    model="speech-2.8-turbo",
    input="Quick draft narration for review",
    voice="Casual_Guy",
)
```

---

## API Usage

```python
# List all models
page = pony_flash.models.list()
for m in page.items:
    print(f"{m.id} ({m.type})")

# Filter by type
images = pony_flash.models.list(type="image")

# Get model details
detail = pony_flash.models.get("nano-banana-pro")
print(detail.supported_resolutions)
print(detail.supported_aspect_ratios)
print(detail.pricing)
```


path: reference/models/music-2.5.md
content: # music-2.5 — Music Generation (MiniMax)

Full-song generation with vocals, lyrics structure control, and instrumental mode. Masters every genre with complete song structures, expressive melodies, and hi-fi audio.

## Supported parameters via PonyFlash SDK

```python
gen = pony_flash.music.generate(
    model="music-2.5",
    prompt="Soulful Blues, Rainy Night, Melancholy, Male Vocals, Slow Tempo",
    lyrics="[Verse]\nThe sky is cryin', Lord\nI can hear it on the roof\n\n[Chorus]\nMidnight rain, fallin' down on me\nLike tears I can't cry",
    duration=60,
)
```

## Prompt guidelines

The `prompt` parameter describes music style, mood, and scenario (0–2000 characters). Use comma-separated descriptors:

```
"Soulful Blues, Rainy Night, Melancholy, Male Vocals, Slow Tempo"
"Upbeat Pop, Summer Vibes, Female Vocals, 120 BPM"
"Lo-fi Hip Hop, Chill, Study Music, Mellow"
```

## Lyrics structure tags

14+ structure tags to control song arrangement:

| Tag | Purpose |
|---|---|
| `[Intro]` | Opening section |
| `[Verse]` | Verse section |
| `[Pre Chorus]` | Build-up before chorus |
| `[Chorus]` | Main hook |
| `[Hook]` | Catchy repeated phrase |
| `[Bridge]` | Contrasting section |
| `[Interlude]` | Instrumental break |
| `[Break]` | Pause/break |
| `[Transition]` | Section transition |
| `[Outro]` | Ending section |
| `[Post Chorus]` | After chorus section |
| `[Build Up]` | Energy build |
| `[Inst]` | Instrumental section |
| `[Solo]` | Solo section |

Lines within lyrics separated by `\n`. Max 3500 characters.

## Modes

| Mode | How to use |
|---|---|
| Vocal song | `prompt` + `lyrics` |
| Instrumental | `prompt` + `instrumental=True` |
| Auto-lyrics | `prompt` only (model generates lyrics from prompt) |
| Continue/extend | `prompt` + `reference_audio` + `continue_at` |

## Audio output settings

| Parameter | Supported values |
|---|---|
| `sample_rate` | 16000, 24000, 32000, 44100 |
| `format` | mp3, wav, pcm |

## Example: full song with structure

```python
gen = pony_flash.music.generate(
    model="music-2.5",
    prompt="Upbeat Pop, Summer Vibes, Female Vocals, 120 BPM",
    lyrics=(
        "[Intro]\n(Oh yeah, here we go)\n\n"
        "[Verse]\nSunshine on my face today\n"
        "Dancing through the light\n"
        "Every worry fades away\n"
        "Everything feels right\n\n"
        "[Chorus]\nThis is our summer song\n"
        "Singing all night long\n"
        "Turn the music up\n"
        "We'll never stop\n\n"
        "[Bridge]\nWhen the stars come out tonight\n"
        "We'll keep the fire burning bright\n\n"
        "[Outro]\n(Fade out...)"
    ),
    title="Summer Song",
    style="pop",
)
print(gen.url)
```

## Example: instrumental

```python
gen = pony_flash.music.generate(
    model="music-2.5",
    prompt="Cinematic Orchestral, Epic, Dramatic, Strings, Brass",
    instrumental=True,
    duration=90,
)
```

## Example: continue a song from timestamp

```python
gen = pony_flash.music.generate(
    model="music-2.5",
    prompt="Continue with an electric guitar solo, blues style",
    reference_audio=open("my_track.mp3", "rb"),
    continue_at=60.0,
)
```


path: reference/models/nano-banana-2.md
content: # nano-banana-2 — Image Generation (Google)

Google's fast image model built on Gemini 3.1 Flash. High-quality generation with Google Search grounding for real-time info, multi-image fusion, and 14 aspect ratios. Faster than Pro.

## Parameters

```python
gen = pony_flash.images.generate(
    model="nano-banana-2",
    prompt="Current weather forecast for Tokyo as an infographic",
    resolution="2K",
    aspect_ratio="9:16",
)
```

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `prompt` | str | Yes | — | Text description of the image |
| `resolution` | str | No | `"1K"` | `"1K"`, `"2K"`, `"4K"` |
| `aspect_ratio` | str | No | `"match_input_image"` | See values below |
| `output_format` | str | No | `"jpg"` | `"jpg"`, `"png"` |
| `reference_images` | List[FileInput] | No | — | Up to 14 reference images |

### aspect_ratio values

`match_input_image`, `1:1`, `1:4`, `1:8`, `2:3`, `3:2`, `3:4`, `4:1`, `4:3`, `4:5`, `5:4`, `8:1`, `9:16`, `16:9`, `21:9`

### Extra parameters (via **extra_body)

| Parameter | Type | Default | Description |
|---|---|---|---|
| `google_search` | bool | `true` | Use Google Web Search for real-time info (weather, sports, events) |
| `image_search` | bool | `true` | Use Google Image Search for visual context |

## Pricing

| Resolution | Credits |
|---|---|
| 1K | 7 |
| 2K | 10 |
| 4K | 15 |

## Examples

```python
# Real-time info grounding
gen = pony_flash.images.generate(
    model="nano-banana-2",
    prompt="Today's NBA scores as a sports infographic",
    resolution="2K",
    google_search=True,
)

# Multi-image blending
gen = pony_flash.images.generate(
    model="nano-banana-2",
    prompt="Combine these photos into a collage with consistent lighting",
    reference_images=[open("photo1.jpg", "rb"), open("photo2.jpg", "rb")],
    resolution="4K",
    aspect_ratio="16:9",
)
```


path: reference/models/nano-banana-pro.md
content: # nano-banana-pro — Image Generation (Google)

Google DeepMind's highest-quality image generation model built on Gemini 3 Pro. Accurate text rendering in multiple languages, multi-image blending (up to 14 references), professional creative controls.

## Parameters

```python
gen = pony_flash.images.generate(
    model="nano-banana-pro",
    prompt="A minimalist logo for a coffee shop with the text 'BREW'",
    resolution="2K",
    aspect_ratio="1:1",
    output_format="png",
)
```

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `prompt` | str | Yes | — | Text description of the image |
| `resolution` | str | No | `"2K"` | `"1K"`, `"2K"`, `"4K"` |
| `aspect_ratio` | str | No | `"match_input_image"` | See values below |
| `output_format` | str | No | `"jpg"` | `"jpg"`, `"png"` |
| `reference_images` | List[FileInput] | No | — | Up to 14 reference images |

### aspect_ratio values

`match_input_image`, `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9`

### Extra parameters (via **extra_body)

| Parameter | Type | Default | Description |
|---|---|---|---|
| `safety_filter_level` | str | `"block_only_high"` | `"block_low_and_above"`, `"block_medium_and_above"`, `"block_only_high"` |

## Pricing

| Resolution | Credits |
|---|---|
| 1K | 7 |
| 2K | 10 |
| 4K | 15 |

## Examples

```python
# Text-to-image, 4K panoramic
gen = pony_flash.images.generate(
    model="nano-banana-pro",
    prompt="Panoramic view of Tokyo skyline at dusk, cinematic",
    resolution="4K",
    aspect_ratio="21:9",
)

# Image editing with reference
gen = pony_flash.images.generate(
    model="nano-banana-pro",
    prompt="Same scene but in winter with snow",
    reference_images=[open("summer_photo.jpg", "rb")],
    resolution="2K",
)
```


path: reference/models/nanobanana-pro.md
content: # nanobanana-pro — Image Generation

High-quality AI image generation model. Also available as `nanobanana` (standard quality, lower cost).

## Supported parameters via PonyFlash SDK

```python
gen = pony_flash.images.generate(
    model="nanobanana-pro",   # or "nanobanana"
    prompt="A sunset over mountains",
    size="2K",                # "1K", "2K", "4K"
    n=1,
    output_format="png",
)
```

## Model variants and credits

| Model | Credits (1K) | Credits (2K) | Credits (4K) |
|---|---|---|---|
| `nanobanana` | 10 | — | — |
| `nanobanana-pro` | 20 | 20 | 20 |

Other variants: `nanobanana-fast` (5 credits), `nanobanana-vip` (30), `nanobanana-pro-vip` (40/50 at 4K), `nanobanana-2` (20/30/50).

## Resolution / size

| Value | Pixel dimensions (1:1) |
|---|---|
| `1K` | 1024x1024 |
| `2K` | 2048x2048 |
| `4K` | 4096x4096 |

Actual pixels scale proportionally with aspect ratio. For example, `16:9` at `4K` produces 4096x2304.

## Aspect ratios

Supported values: `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9`, `auto`.

Default is `1:1` if not specified.

## Modes

| Mode | Description | How to use |
|---|---|---|
| Text-to-image | Generate from text prompt | `prompt` only |
| Image-to-image | Transform with reference images | `prompt` + `images=[...]` |

Supports up to 8 reference images for image-to-image.

## Example: high-res wide image

```python
gen = pony_flash.images.generate(
    model="nanobanana-pro",
    prompt="Panoramic view of Tokyo skyline at dusk, cinematic",
    size="4K",
)
print(gen.url)
```

## Example: image-to-image with reference

```python
from pathlib import Path

gen = pony_flash.images.generate(
    model="nanobanana-pro",
    prompt="Same scene but in winter with snow",
    images=[Path("summer_photo.jpg")],
    size="2K",
)
print(gen.url)
```


path: reference/models/seedance-1.5-pro.md
content: # seedance-1.5-pro — Video Generation (ByteDance)

Cinema-quality video with synchronized audio, lip-sync, multilingual support. Dual-branch architecture generates audio+video simultaneously.

## Parameters

| Parameter | Type | Required | Default | Values |
|---|---|---|---|---|
| `prompt` | str | Yes* | — | Text description (*or first_frame required) |
| `duration` | int | No | 8 | 2-12 (any integer) |
| `resolution` | str | No | "720p" | `"480p"`, `"720p"`, `"1080p"` |
| `aspect_ratio` | str | No | "16:9" | `"16:9"`, `"4:3"`, `"1:1"`, `"3:4"`, `"9:16"`, `"21:9"`, `"9:21"` |
| `generate_audio` | bool | No | false | Synchronized audio generation |
| `first_frame` | FileInput | No | — | Starting image for image-to-video |
| `last_frame` | FileInput | No | — | Ending image |

Extra via `**extra_body`: `camera_fixed` (bool, lock camera to reduce motion blur)

## Pricing

| resolution | with_audio | without_audio |
|---|---|---|
| 480p | 3 credits/s | 1 credit/s |
| 720p | 5 credits/s | 3 credits/s |
| 1080p | 12 credits/s | 6 credits/s |

Example: 8s 720p with audio = 5 * 8 = 40 credits

## Examples

```python
# Text-to-video
gen = pony_flash.video.generate(
    model="seedance-1.5-pro",
    prompt="A cinematic sunrise over mountains, slow camera pan",
    duration=5,
    resolution="720p",
    aspect_ratio="16:9",
)

# Image-to-video with audio
gen = pony_flash.video.generate(
    model="seedance-1.5-pro",
    prompt="Person starts talking to the camera",
    first_frame=open("portrait.jpg", "rb"),
    duration=8,
    resolution="1080p",
    generate_audio=True,
)

# Budget mode: 480p, short, no audio
gen = pony_flash.video.generate(
    model="seedance-1.5-pro",
    prompt="Quick product demo",
    duration=3,
    resolution="480p",
    generate_audio=False,
)
```


path: reference/models/seedream-5-lite.md
content: # seedream-5-lite — Image Generation (ByteDance)

ByteDance's image model with built-in reasoning, example-based editing, and batch generation. Lowest cost per image. Supports up to 3K resolution.

## Parameters

```python
gen = pony_flash.images.generate(
    model="seedream-5-lite",
    prompt="A color film portrait with shallow depth of field",
    resolution="2K",
    aspect_ratio="3:2",
)
```

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `prompt` | str | Yes | — | Text description of the image |
| `resolution` | str | No | `"2K"` | `"2K"`, `"3K"` |
| `aspect_ratio` | str | No | `"match_input_image"` | See values below |
| `output_format` | str | No | `"png"` | `"png"`, `"jpg"` |
| `reference_images` | List[FileInput] | No | — | Up to 14 reference images |
| `n` | int | No | `1` | Number of images to generate (1-15) |

### aspect_ratio values

`match_input_image`, `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `9:16`, `16:9`, `21:9`

### Extra parameters (via **extra_body)

| Parameter | Type | Default | Description |
|---|---|---|---|
| `sequential_image_generation` | str | `"disabled"` | `"disabled"` or `"auto"` — auto lets model generate multiple related images (storyboards, character sheets) |

## Pricing

4 credits/image (all resolutions)

## Examples

```python
# Example-based editing: show before/after pair, apply to new image
gen = pony_flash.images.generate(
    model="seedream-5-lite",
    prompt="Apply the same color grading transformation",
    reference_images=[
        open("before.jpg", "rb"),
        open("after.jpg", "rb"),
        open("new_photo.jpg", "rb"),
    ],
    resolution="2K",
)

# Batch generation: storyboard
gen = pony_flash.images.generate(
    model="seedream-5-lite",
    prompt="A series of 4 illustrations of a courtyard across four seasons",
    n=4,
    resolution="2K",
    aspect_ratio="16:9",
    sequential_image_generation="auto",
)
```


path: reference/models/speech-2.8-hd.md
content: # speech-2.8-hd — Text-to-Speech (MiniMax)

MiniMax's highest-quality speech synthesis model. Supports 40+ languages, interjection tags, emotion control, voice modification, and pronunciation dictionaries.

## Supported parameters via PonyFlash SDK

```python
gen = pony_flash.speech.generate(
    model="speech-2.8-hd",
    input="Hello (laughs), welcome to PonyFlash!",
    voice="English_Graceful_Lady",
    language="English",
    speed=1.0,
    pitch=0,
    emotion="happy",
    format="mp3",
)
```

## Voice IDs (selection)

### English
- `English_Graceful_Lady`
- `English_Insightful_Speaker`
- `English_radiant_girl`
- `English_Persuasive_Man`
- `English_Lucky_Robot`

### Chinese
- `Chinese (Mandarin)_Lyrical_Voice`
- `Chinese (Mandarin)_HK_Flight_Attendant`

### Japanese
- `Japanese_Whisper_Belle`

### Other system voices
300+ system voices available. Custom cloned voices and AI-generated voices also supported.

## Emotion control

Supported values: `happy`, `sad`, `angry`, `fearful`, `disgusted`, `surprised`, `calm`, `fluent`.

By default the model auto-selects the most natural emotion. Manual specification only when explicitly needed.

Note: `whisper` is NOT supported on speech-2.8-hd (only on speech-2.6 series).

## Interjection tags

Only supported on speech-2.8-hd and speech-2.8-turbo:

`(laughs)`, `(chuckle)`, `(coughs)`, `(clear-throat)`, `(groans)`, `(breath)`, `(pant)`, `(inhale)`, `(exhale)`, `(gasps)`, `(sniffs)`, `(sighs)`, `(snorts)`, `(burps)`, `(lip-smacking)`, `(humming)`, `(hissing)`, `(emm)`, `(sneezes)`.

Place them inline: `"Hello (laughs), that's amazing (gasps)!"`.

## Voice settings

| Parameter | Range | Default | Description |
|---|---|---|---|
| `speed` | 0.5–2.0 | 1.0 | Speech speed |
| `pitch` | -12 to 12 | 0 | Pitch adjustment |

## Audio output settings

| Parameter | Supported values |
|---|---|
| `sample_rate` | 8000, 16000, 22050, 24000, 32000, 44100 |
| `format` | mp3, pcm, flac, wav (wav only in non-streaming) |

## Pause control

Insert `<#x#>` in text for custom pauses (x = 0.01–99.99 seconds):

`"First sentence.<#2.5#>Second sentence after 2.5s pause."`

## Supported languages (40+)

Chinese, English, Arabic, Russian, Spanish, French, Portuguese, German, Turkish, Dutch, Ukrainian, Vietnamese, Indonesian, Japanese, Italian, Korean, Thai, Polish, Romanian, Greek, Czech, Finnish, Hindi, Bulgarian, Danish, Hebrew, Malay, Persian, Slovak, Swedish, Croatian, Filipino, Hungarian, Norwegian, Slovenian, Catalan, Nynorsk, Tamil, Afrikaans, `auto` (auto-detect).

## Example: expressive narration

```python
gen = pony_flash.speech.generate(
    model="speech-2.8-hd",
    input="(sighs) The real danger is not that computers start thinking like people (gasps), but that people start thinking like computers.",
    voice="English_Insightful_Speaker",
    language="English",
    speed=0.9,
    pitch=-2,
    emotion="calm",
    sample_rate=44100,
    format="mp3",
)
print(gen.url)
```

## Example: multilingual with auto-detect

```python
gen = pony_flash.speech.generate(
    model="speech-2.8-hd",
    input="Hello World! Welcome to PonyFlash!",
    voice="English_Graceful_Lady",
    language="auto",
)
```

## Related model

`speech-2.8-turbo` — faster generation, slightly lower quality. Same parameter set.


path: reference/models/speech-2.8-turbo.md
content: # speech-2.8-turbo — Text-to-Speech (MiniMax)

MiniMax Speech 2.8 Turbo. Same voice quality and parameter set as HD, with faster generation and lower latency (<250ms). Best for real-time applications, drafts, and high-volume use.

## Parameters

Same as [speech-2.8-hd.md](speech-2.8-hd.md). All voices, emotions, interjection tags, languages, and audio settings are identical.

```python
gen = pony_flash.speech.generate(
    model="speech-2.8-turbo",
    input="Quick draft narration for review",
    voice="Casual_Guy",
    emotion="calm",
)
```

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `input` | str | Yes | — | Text to synthesize, max 10000 chars |
| `voice` | str | Yes | — | Voice ID (see speech-2.8-hd.md for full list) |
| `emotion` | str | No | `"auto"` | `auto`, `happy`, `calm`, `sad`, `angry`, `fearful`, `disgusted`, `surprised` |
| `speed` | float | No | `1.0` | 0.5 - 2.0 |
| `pitch` | int | No | `0` | -12 to +12 semitones |
| `format` | str | No | `"mp3"` | `mp3`, `wav`, `flac`, `pcm` |
| `sample_rate` | int | No | `32000` | 8000, 16000, 22050, 24000, 32000, 44100 |
| `language` | str | No | — | Language hint or `auto` |

## Pricing

1 credit/request (provisional — actual cost is $0.06/thousand input tokens)

## When to use Turbo vs HD

| | HD | Turbo |
|---|---|---|
| Quality | Highest | Very high |
| Latency | Standard | <250ms |
| Best for | Final production, audiobooks | Real-time apps, drafts, high volume |
| Cost | $0.10/1K tokens | $0.06/1K tokens |


path: reference/models/veo-3.1-fast.md
content: # veo-3.1-fast — Video Generation (Google)

Faster version of Veo 3.1. Same quality level with faster generation. Best for rapid iteration.

## Parameters

Same as [veo-3.1.md](veo-3.1.md). All parameters identical.

## Pricing

| | with_audio | without_audio |
|---|---|---|
| Per second | 15 credits | 10 credits |
| 4s video | 60 credits | 40 credits |
| 6s video | 90 credits | 60 credits |
| 8s video | 120 credits | 80 credits |

## Example

```python
gen = pony_flash.video.generate(
    model="veo-3.1-fast",
    prompt="A timelapse of clouds over a cityscape",
    duration=4,
    resolution="720p",
    generate_audio=False,
)
```


path: reference/models/veo-3.1.md
content: # veo-3.1 — Video Generation (Google)

Google's state-of-the-art video model. Synchronized audio, reference images, first/last frame control, 720p/1080p.

## Parameters

| Parameter | Type | Required | Default | Values |
|---|---|---|---|---|
| `prompt` | str | Yes | — | Text description |
| `duration` | int | No | 8 | `4`, `6`, `8` |
| `resolution` | str | No | "1080p" | `"720p"`, `"1080p"` |
| `aspect_ratio` | str | No | "16:9" | `"16:9"`, `"9:16"` |
| `generate_audio` | bool | No | true | Synchronized audio generation |
| `first_frame` | FileInput | No | — | Starting image |
| `last_frame` | FileInput | No | — | Ending image (smooth transition) |
| `reference_images` | List[FileInput] | No | — | Up to 3 reference images |
| `negative_prompt` | str | No | — | What to exclude |

Extra via `**extra_body`: `seed` (int)

## Pricing

| | with_audio | without_audio |
|---|---|---|
| Per second | 40 credits | 20 credits |
| 4s video | 160 credits | 80 credits |
| 6s video | 240 credits | 120 credits |
| 8s video | 320 credits | 160 credits |

## Examples

```python
# Text-to-video with audio
gen = pony_flash.video.generate(
    model="veo-3.1",
    prompt="A woman sings in a recording studio, warm lighting, close-up shot",
    duration=6,
    resolution="1080p",
    aspect_ratio="16:9",
)

# Image-to-video without audio
gen = pony_flash.video.generate(
    model="veo-3.1",
    prompt="Camera slowly zooms into the scene",
    first_frame=open("photo.jpg", "rb"),
    duration=4,
    generate_audio=False,
)

# Frame-to-frame transition
gen = pony_flash.video.generate(
    model="veo-3.1",
    prompt="Smooth transition from day to night",
    first_frame=open("day.jpg", "rb"),
    last_frame=open("night.jpg", "rb"),
    duration=8,
)
```

## Related

`veo-3.1-fast` — faster, cheaper. Same parameters. See [veo-3.1-fast.md](veo-3.1-fast.md).


path: playbooks/crepal-director.md
content: ---
name: crepal-director
description: Plans and produces end-to-end videos across general-purpose agent environments. Use when the user wants to create ads, promos, explainers, social videos, brand films, story videos, talking-avatar videos, or any multi-shot video that requires requirement intake, technical method selection, storyboard creation, image generation, clip generation, voice, music, ffmpeg-based editing, and final delivery.
tags: [video, director, ad, promo, explainer, social, brand, film, story, talking-avatar, multi-shot, storyboard, production, 视频, 导演, 广告, 宣传片, 短片, 故事, 数字人, 分镜]
difficulty: intermediate
estimated_credits: 50-300
output_format: Configurable (16:9, 9:16, 1:1, etc.)
---

# CrePal Director Playbook

This playbook provides a complete creative workflow for planning and directing video productions — from concept and storyboard to shot-by-shot creative direction. It focuses on **what to create** (narrative, visual style, composition, pacing) while the base PonyFlash SKILL.md handles **how to create** (API calls, model parameters, and FFmpeg editing workflow).

## Core Operating Rules

1. Start with discovery. Do not generate assets before understanding the goal.
2. Ask from multiple angles: business goal, format, visuals, editing, audio, references, constraints, and delivery.
3. Confirm major checkpoints before expensive generation.
4. Choose the simplest production method that still gives enough creative control.
5. Keep one stable visual identity per recurring character.
6. Keep one stable voice ID per speaking character unless the user approves a change.
7. Visually inspect generated images and clips instead of trusting prompts alone.
8. State assumptions clearly when the user has not answered something.
9. Keep all written communication concise, structured, and in English.

## When To Use

Use this playbook when the user wants to:

- create a complete video from an idea, script, brief, or references;
- make a short ad, promo, explainer, trailer, story video, or social clip;
- turn static images into video clips;
- produce a talking-avatar or digital-human video;
- create a multi-shot video with music, voice-over, and editing.

## Workflow Overview

1. Requirement intake
2. Technical approach selection
3. Pre-production and storyboard
4. Image and keyframe generation
5. Music direction
6. Shot-level video generation (creative direction and prompt design)
7. Voice direction and dialogue planning

## Phase 1: Requirement Intake

### Goal

Collect enough detail to design the right video workflow before generating anything.

### Intake Rules

- Ask grouped questions instead of one long unstructured paragraph.
- If the user already provided part of the brief, do not ask for it again.
- If the user is unsure, offer defaults and mark them as assumptions.
- Prioritize the questions that affect method choice, cost, and consistency.

### Required Discovery Topics

Ask the user about all of the following:

| Topic | What to ask |
|---|---|
| Video goal | What is the video trying to achieve: sales, branding, education, announcement, storytelling, or internal communication? |
| Audience | Who will watch it? What should they feel or do after watching? |
| Duration | Desired total runtime and whether a strict length limit exists |
| Format | Aspect ratio, platform, resolution, and whether horizontal, vertical, or square output is needed |
| Video type | Ad, promo, explainer, testimonial, cinematic montage, tutorial, character story, talking avatar, or other |
| Story content | Main message, narrative arc, must-show products, people, scenes, or claims |
| Visual style | Realistic, cinematic, anime, stylized 3D, motion graphic, documentary, luxury, playful, minimal, dark, bright, or other |
| Editing style | Fast-cut, smooth cinematic, rhythmic, energetic, elegant, documentary, meme-like, or platform-native |
| Character design | Whether the video includes people, recurring characters, products, mascots, or a host |
| Audio plan | Music mood, whether voice-over is needed, whether on-screen dialogue is needed, and whether sound effects matter |
| References | Reference videos, frames, screenshots, moodboards, brand guides, logos, character sheets, or product photos |
| Language | Spoken language, subtitle language, text language, and target market |
| Constraints | Budget sensitivity, realism limits, brand restrictions, legal claims, deadlines, or tool limitations |
| Deliverables | Final render, separate clips, captions, subtitles, thumbnails, key art, or alternate aspect ratios |

### Recommended Intake Question Block

Use this structure and adapt it to the request:

```markdown
To design the right workflow, please confirm:

1. What is the goal of the video, and who is the target audience?
2. How long should it be?
3. What format do you need: 16:9, 9:16, 1:1, or multiple?
4. What type of video is it: ad, explainer, cinematic montage, social clip, talking avatar, or something else?
5. What visual style do you want?
6. What editing style do you want?
7. Do you need people, characters, products, or a digital host on screen?
8. Do you want voice-over, dialogue, subtitles, music, and sound effects?
9. Do you have any reference videos, images, logos, or brand guidelines?
10. Are there any hard constraints or must-include elements?
```

### Intake Output

After the user replies, return a brief in this format before moving on:

```markdown
VIDEO BRIEF SUMMARY

- Goal:
- Audience:
- Duration:
- Format:
- Video type:
- Visual style:
- Editing style:
- Characters or subjects:
- Audio requirements:
- References provided:
- Constraints:
- Deliverables:

Open questions:
- ...

Assumptions:
- ...
```

Do not start production until the brief is clear enough to choose a method.

## Phase 2: Technical Approach Selection

### Goal

Select the most suitable generation method for the whole video and for each shot.

### Available Production Methods

#### 1. First-Frame Video

Use one starting image to generate a clip.

- Best for: simple shots, object motion, camera drift, atmosphere, reveal shots, mood shots
- Strengths: lowest cost, fastest iteration, simple setup
- Limitations: weaker ending control, more drift across shots
- Default use case: non-speaking shots with modest motion

#### 2. First-Last-Frame Video

Use a starting image and an ending image to control both clip endpoints.

- Best for: transformation shots, before-and-after shots, clean transitions, precise opening and ending composition
- Strengths: stronger endpoint control, useful for morphs and reveals
- Limitations: more setup, higher generation cost than first-frame
- Default use case: shots where the ending composition matters as much as the start

#### 3. Multi-Reference Video

Use multiple references such as character, wardrobe, prop, scene, and style images.

- Best for: recurring characters, continuity across shots, branded scenes, consistent environments
- Strengths: highest consistency for identity and scene control
- Limitations: higher setup cost, more reference management, can slow iteration
- Default use case: any project where consistency matters more than speed

#### 4. Digital Human

Use a face or character image plus generated audio to create a speaking video.

- Best for: hosts, presenters, founders, spokespersons, teachers, talking avatars
- Strengths: direct lip sync workflow, efficient for speaking scenes
- Limitations: depends on clean face reference and strong audio quality; less flexible for complex body action
- Default use case: any shot where a visible character must speak clearly to camera

### Method Selection Logic

Choose the method with this priority:

1. If a visible character must speak on camera, prefer `digital_human`.
2. If a shot needs exact start and end control, prefer `first_last_frame`.
3. If consistency across character or scene identity is critical, prefer `multi_reference`.
4. If the shot is simple and cost-sensitive, prefer `first_frame`.

### Method Comparison Table

| Method | Cost | Control | Consistency | Best for |
|---|---|---|---|---|
| `first_frame` | Low | Medium | Medium-Low | Quick non-speaking shots |
| `first_last_frame` | Medium | High on endpoints | Medium | Transformations and reveals |
| `multi_reference` | Medium-High | High | High | Recurring character and scene continuity |
| `digital_human` | Medium-High | High for talking shots | High for host identity | Presenter or avatar scenes |

### Hybrid Planning Rule

Do not force one method on the entire video. Use the best method per shot.

Typical hybrid examples:

- Open with `first_last_frame` for a reveal, use `first_frame` for cinematic inserts, use `multi_reference` for recurring character shots.
- Use `digital_human` only for speaking scenes and another method for b-roll.
- Use `multi_reference` for all hero shots if brand identity must remain stable.

### Technical Proposal Output

After reviewing the brief, return a technical proposal in this format:

```markdown
TECHNICAL PROPOSAL

Recommended overall approach:
- Primary method:
- Secondary methods:
- Why this is the best fit:

Method by shot type:
- Intro or hook:
- Character continuity shots:
- Transition or transformation shots:
- Speaking shots:
- Product or environment inserts:

Tradeoffs:
- Cost:
- Speed:
- Consistency:
- Creative flexibility:

Approval request:
- Confirm this production approach before storyboard and asset generation.
```

Do not generate storyboard assets until the user approves the production approach.

## Phase 3: Pre-Production And Storyboard

### Goal

Turn the approved brief and method selection into a production-ready plan.

### Required Outputs

Create the following before image generation:

- creative brief;
- subject and character registry;
- scene registry;
- asset checklist;
- shot list;
- storyboard;
- approval gate.

### Subject And Character Registry

For each recurring subject, record:

| Field | Description |
|---|---|
| `subject_id` | Stable identifier |
| `type` | Human, product, mascot, environment, prop, logo, text card |
| `role` | Host, hero product, supporting object, background, etc. |
| `appearance` | Face, hair, clothing, color palette, materials, silhouette |
| `consistency_rule` | What must never drift across shots |
| `voice_id` | Only for speaking characters; one character must keep one voice ID |

### Scene Registry

For each environment, record:

| Field | Description |
|---|---|
| `scene_id` | Stable scene identifier |
| `location` | Studio, street, office, fantasy world, room, etc. |
| `time_of_day` | Day, sunset, night, unspecified |
| `lighting` | Soft daylight, hard sunlight, moody rim light, neon, etc. |
| `style_rule` | Visual consistency rules for that scene |

### Storyboard Rules

Build the storyboard shot by shot. Every shot must include:

| Field | Description |
|---|---|
| `shot_no` | Sequential number |
| `duration` | Planned clip length |
| `goal` | What the shot must communicate |
| `method` | `first_frame`, `first_last_frame`, `multi_reference`, or `digital_human` |
| `subjects` | Character, product, environment, or props used |
| `visual` | What appears on screen |
| `motion` | Object, camera, and atmosphere motion |
| `camera` | Angle, lens feel, framing, movement |
| `dialogue` | Spoken line if any |
| `voice_id` | Required for speaking shots |
| `music_note` | Energy or mood guidance |
| `sfx_note` | Sound effects guidance |
| `references_needed` | Which images, logos, or clips are required |
| `approval_status` | Pending or approved |

### Storyboard Output Template

```markdown
STORYBOARD

Shot 1
- Duration:
- Goal:
- Method:
- Subjects:
- Visual:
- Motion:
- Camera:
- Dialogue:
- Music note:
- SFX note:
- References needed:

Shot 2
- ...
```

### Approval Gate

After writing the storyboard, ask the user to confirm:

- shot flow;
- tone and pacing;
- character design direction;
- speaking lines;
- any must-change shots before generation begins.

Do not move to Phase 4 until the storyboard is approved.

## Phase 4: Image And Keyframe Generation

### Goal

Generate all images needed to support clip generation and keep visual identity stable.

### Generation Order

1. Generate or collect hero references first.
2. Generate scene references second.
3. Generate shot keyframes third.
4. Review each image before moving to video generation.

### Required Image Types

Generate whichever of these are needed:

| Image type | Purpose |
|---|---|
| Character reference | Locks face, wardrobe, expression, and silhouette |
| Product reference | Locks product shape, materials, and brand details |
| Scene reference | Locks environment, palette, and lighting |
| Prop reference | Locks recurring objects |
| Start keyframe | For `first_frame` or `first_last_frame` shots |
| End keyframe | For `first_last_frame` shots |
| Style board | Optional style anchor for look and mood |
| Thumbnail frame | Optional approval frame before full clip generation |

### Visual Review Checklist

Inspect every image against this checklist:

- anatomy and proportions are correct;
- identity matches the intended character or product;
- clothing, props, and brand details are accurate;
- background and lighting fit the approved style;
- no extra limbs, artifacts, warped text, or broken objects;
- the image is strong enough to be used as a keyframe;
- recurring subjects still look like the same subject.

### Image Confirmation Loop

Return images to the user in manageable batches, usually by shot or by subject set.

Use this format:

```markdown
IMAGE REVIEW

Assets ready for approval:
- Character reference:
- Scene reference:
- Shot 1 keyframe(s):
- Shot 2 keyframe(s):

Please confirm:
- keep as is;
- revise specific assets;
- replace style direction.
```

If the user requests revisions, update only the affected assets and keep approved ones unchanged.

## Phase 5: Music Generation

### Goal

Create background music that fits the approved narrative and editing rhythm.

### Music Planning Rules

- Generate music only after the storyboard and core image direction are approved.
- Match the music to audience, pace, emotional arc, and platform.
- If the user wants heavy dialogue clarity, avoid music that competes with speech.
- If the user wants multiple edits, prefer loopable or stem-friendly music.

### Music Brief Fields

| Field | Description |
|---|---|
| `mood` | Inspirational, intense, playful, elegant, emotional, suspenseful, etc. |
| `tempo` | Slow, medium, fast, or BPM target |
| `genre` | Cinematic, electronic, ambient, orchestral, pop, lo-fi, corporate, etc. |
| `structure` | Intro, build, peak, outro |
| `edit_notes` | Beat drop, transitions, pauses for dialogue |
| `duration` | Match or slightly exceed final runtime |

### Music Approval Output

```markdown
MUSIC REVIEW

- Direction:
- Tempo:
- Genre:
- Structure:
- Intended use on timeline:

Please confirm whether this music direction works before final shot generation and edit assembly.
```

## Phase 6: Shot-Level Video Generation

### Goal

Generate each video clip with the most suitable method and the right prompt structure.

### General Rules

- Produce clips shot by shot.
- Keep all clip filenames and versions stable.
- Use approved images only.
- Use the selected method per shot, not a one-method shortcut.
- If a shot fails, revise that shot instead of restarting the whole project.

### Prompt Structure For Non-Speaking Shots

For each non-speaking shot, build prompts with these parts:

| Prompt section | What to include |
|---|---|
| Subject | Who or what is in frame |
| Environment | Background, weather, lighting, and atmosphere |
| Composition | Framing and camera position |
| Motion | Subject motion and camera motion |
| Style | Approved visual style and realism level |
| Continuity anchors | Character, product, wardrobe, scene, and color constraints |
| Restrictions | What must not change or appear |

### Prompt Structure For Speaking Shots

For a speaking shot, include:

- character identity;
- framing suitable for lip sync;
- facial expression and tone;
- speaking energy;
- exact dialogue or attached audio;
- subtitle requirement if needed;
- strict continuity with approved character image.

### Shot Production Record

Maintain a record like this:

```markdown
SHOT PRODUCTION RECORD

Shot:
- Method:
- Duration:
- Source references:
- Prompt summary:
- Audio dependency:
- Status:
- Revision notes:
```

### Shot Review Loop

After generating clips, return them for review in batches.

Use this format:

```markdown
SHOT REVIEW

Completed shots:
- Shot 1:
- Shot 2:
- Shot 3:

Please confirm for each shot:
- approve;
- revise motion;
- revise framing;
- revise style;
- revise continuity.
```

Do not finalize the timeline until all critical shots are approved.

## Phase 7: Voice Generation And Dialogue

### Goal

Generate voice-over or character dialogue that matches the approved creative direction.

### Voice Rules

1. Voice generation is optional unless the project requires narration or speaking characters.
2. Each recurring character must keep one voice ID through the whole project.
3. The narrator should also keep one stable voice ID.
4. Only change a voice ID if the user explicitly approves it.
5. If the project uses a digital human, generate or confirm the dialogue audio before or during shot generation for those speaking clips.

### Voice Planning Fields

| Field | Description |
|---|---|
| `character_name` | Speaker name |
| `voice_id` | Stable voice identifier |
| `voice_type` | Narrator, host, character, announcer |
| `tone` | Warm, authoritative, friendly, energetic, calm, luxury, etc. |
| `pace` | Slow, medium, fast |
| `accent_or_locale` | Optional locale requirement |
| `script` | Exact spoken text |

### Voice Output Template

```markdown
VOICE REVIEW

Speakers:
- Narrator:
- Character A:
- Character B:

Voice assignments:
- Narrator -> voice_id:
- Character A -> voice_id:
- Character B -> voice_id:

Scripts ready:
- ...

Please confirm voice choice and script before final FFmpeg assembly and export.
```

## Fallbacks And Recovery Rules

### If references are missing

- Ask the user for them first.
- If unavailable, propose a reference-free path and warn that consistency may drop.
- Mark every inferred design choice as an assumption.

### If image consistency breaks

- Regenerate the affected asset using the approved hero reference set.
- Reduce style variation and strengthen continuity constraints.
- Do not regenerate unrelated approved assets.

### If the clip drifts from the storyboard

- Tighten the prompt around composition, motion, and restrictions.
- If endpoint control matters, switch from `first_frame` to `first_last_frame`.
- If identity control matters, switch to `multi_reference`.

### If a speaking shot looks wrong

- Verify the face reference first.
- Verify the audio quality and pacing second.
- Shorten the dialogue if needed.
- If the body motion is too complex, simplify the framing to head-and-shoulders or bust shot.

### If the user requests late changes

- Isolate the impact first: script, images, clips, audio, or timeline.
- Rework the smallest affected layer.
- Tell the user which approved assets remain reusable.

## Minimal Execution Policy

Use this order unless the project has a strong reason not to:

1. Brief
2. Technical proposal
3. Storyboard
4. Hero references
5. Shot keyframes
6. Music direction
7. Shot generation
8. Voice generation

Exception: for digital-human shots, dialogue audio may need to be created before the corresponding clip. Once all creative assets are approved, hand off to the base SKILL.md for FFmpeg assembly, subtitle handling, and final export.

## Reusable Agent Templates

### Template A: Discovery

```markdown
To plan the video correctly, please confirm:

1. Goal and audience
2. Desired runtime
3. Output format and platform
4. Video type
5. Visual style
6. Editing style
7. Subjects or characters on screen
8. Music, voice-over, dialogue, and subtitles
9. Reference videos, images, or brand materials
10. Hard constraints and deliverables
```

### Template B: Technical Proposal

```markdown
Based on your brief, I recommend this production setup:

- Primary method:
- Additional methods:
- Why:
- Best method for speaking shots:
- Best method for continuity-heavy shots:
- Best method for transformation shots:
- Cost and speed tradeoff:

Please confirm this approach before I build the storyboard.
```

### Template C: Storyboard Delivery

```markdown
I have prepared the storyboard.

Please review:
- shot order;
- pacing;
- visual direction;
- dialogue;
- any scenes that need changes.

Once approved, I will generate the key images for each shot.
```

### Template D: Asset Review

```markdown
The first image batch is ready for review.

Please tell me for each asset whether to:
- approve;
- revise;
- replace.
```

### Template E: Music Review

```markdown
The music direction is ready.

Please confirm:
- mood;
- tempo;
- genre;
- whether it leaves enough room for dialogue.
```

### Template F: Clip Review

```markdown
The first video clips are ready.

Please review each shot for:
- motion;
- framing;
- continuity;
- style;
- overall fit with the storyboard.
```

## Success Criteria

This playbook is successful when the agent:

- asks the right requirement questions first;
- selects the correct creative method per shot;
- creates a coherent storyboard before generation;
- gets user approval at major checkpoints;
- keeps visual and voice consistency across the project;
- delivers a complete set of approved creative assets ready for final assembly.


path: playbooks/INDEX.md
content: # Creative Playbooks

Pre-built production workflows for common content types. Each playbook guides you through a complete creation process using PonyFlash SDK capabilities.

## Available Playbooks

| Playbook | Description | Tags | Difficulty | Est. Credits |
|---|---|---|---|---|
| [CrePal Director](crepal-director.md) | End-to-end video production: requirement intake, storyboard, image/clip generation, voice, music, ffmpeg-based editing, and final export. Works for ads, promos, explainers, social videos, brand films, story videos, and talking-avatar videos. | `video`, `director`, `ad`, `promo`, `explainer`, `social`, `brand`, `film`, `story`, `talking-avatar`, `multi-shot`, `storyboard`, `production`, `视频`, `导演`, `广告`, `宣传片`, `短片`, `故事`, `数字人`, `分镜` | Intermediate | 50-300 |

## How Playbooks Work

1. Each playbook is a step-by-step markdown guide (not code).
2. The agent reads the playbook and follows the workflow, calling PonyFlash SDK as instructed in SKILL.md.
3. Playbooks include prompt templates, recommended models/parameters, and best practices for the content type.

## Custom Playbooks

Users can ask the agent to create new playbooks. Custom playbooks are saved to this directory and added to this index.


path: examples/advanced.md
content: # Advanced Usage Examples

More examples beyond the basics in SKILL.md. For model-specific parameters and capabilities, see [reference/models/INDEX.md](../reference/models/INDEX.md).

## Image editing with reference images

```python
from pathlib import Path

gen = pony_flash.images.generate(
    model="nanobanana",
    prompt="Remove the background",
    images=[Path("photo.jpg")],
    mask=open("mask.png", "rb"),
)
print(gen.url)
```

## Multiple images

```python
gen = pony_flash.images.generate(
    model="nanobanana-pro",
    prompt="A cat in space",
    n=4,
    size="1K",
)
for url in gen.urls:
    print(url)
```

## Text-to-video (Veo 3.1)

```python
gen = pony_flash.video.generate(
    model="veo-3.1",
    prompt="Ocean waves crashing on a rocky coastline at sunset",
    size="1920x1080",
    duration=8,
)
print(gen.url)
```

## First-frame to video (local file)

```python
with open("my_photo.jpg", "rb") as f:
    gen = pony_flash.video.generate(
        model="seedance-1.5-pro",
        first_frame=f,
        prompt="Camera slowly zooms in",
    )
```

## First-frame to video (URL)

```python
gen = pony_flash.video.generate(
    model="seedance-1.5-pro",
    first_frame="https://example.com/photo.jpg",
    prompt="Camera slowly zooms in",
)
```

## OmniHuman — portrait + audio to talking video

```python
with open("portrait.jpg", "rb") as img, open("speech.wav", "rb") as audio:
    gen = pony_flash.video.generate(
        model="omnihuman-1.5",
        first_frame=img,
        audio=audio,
        size="1280x720",
    )
```

## Motion Transfer — person image + dance video

```python
with open("avatar.jpg", "rb") as img, open("dance.mp4", "rb") as vid:
    gen = pony_flash.video.generate(
        model="motion-transfer-1",
        first_frame=img,
        motion_video=vid,
        size="1280x720",
    )
```

## Speech with full voice control

```python
gen = pony_flash.speech.generate(
    model="speech-2.8-hd",
    input="Breaking news (gasps): AI can now compose music.",
    voice="English_Insightful_Speaker",
    language="English",
    speed=1.2,
    pitch=2,
    emotion="happy",
    voice_settings={
        "stability": 0.8,
        "similarity_boost": 0.9,
        "style": 0.5,
        "use_speaker_boost": True,
    },
    sample_rate=44100,
    format="mp3",
)
```

## Music with lyrics and structure tags

```python
gen = pony_flash.music.generate(
    model="music-2.5",
    prompt="Soulful Blues, Rainy Night, Melancholy, Male Vocals, Slow Tempo",
    lyrics="[Verse]\nWaves crash upon the shore\nWhispering forevermore\n\n[Chorus]\nOcean whispers call my name\nNothing here will be the same",
    title="Ocean Whispers",
    style="pop ballad",
    duration=60,
)
```

## Instrumental music

```python
gen = pony_flash.music.generate(
    model="music-2.5",
    prompt="Lo-fi hip hop study beats",
    instrumental=True,
    duration=120,
)
```

## Continue / extend a song

```python
gen = pony_flash.music.generate(
    model="music-2.5",
    prompt="Continue with a guitar solo",
    reference_audio=open("my_song.mp3", "rb"),
    continue_at=45.0,
)
```

## Get model details

```python
detail = pony_flash.models.get("nanobanana-pro")
print(detail.supported_sizes)
print(detail.supported_modes)
```

## Get recharge link

```python
resp = pony_flash.account.recharge(amount=100)
print(resp.recharge_url)
```


path: examples/quickstart.py
content: """PonyFlash SDK — end-to-end quickstart.

Run:
    pip install ponyflash
    export PONYFLASH_API_KEY="rk_xxx"
    python quickstart.py
"""

from ponyflash import PonyFlash, InsufficientCreditsError

pony_flash = PonyFlash()

# ── Check balance ──
balance = pony_flash.account.credits()
print(f"Credit balance: {balance.balance} {balance.currency}")

# ── List models ──
page = pony_flash.models.list()
for m in page.items:
    print(f"  {m.id} ({m.type})")

# ── Generate an image ──
try:
    gen = pony_flash.images.generate(
        model="nanobanana-pro",
        prompt="A magical forest with glowing mushrooms",
        size="2K",
    )
    print(f"Image URL: {gen.url}")
    print(f"Credits used: {gen.credits}")
except InsufficientCreditsError as e:
    print(f"Not enough credits (balance={e.balance}, required={e.required})")
    link = pony_flash.account.recharge()
    print(f"Recharge at: {link.recharge_url}")

# ── Generate a video ──
try:
    gen = pony_flash.video.generate(
        model="seedance-1.5-pro",
        prompt="A timelapse of clouds moving over a mountain",
        duration=5,
    )
    print(f"Video URL: {gen.url}")
    print(f"Credits used: {gen.credits}")
except InsufficientCreditsError as e:
    print(f"Not enough credits: {e}")

# ── Generate speech ──
try:
    gen = pony_flash.speech.generate(
        model="speech-2.8-hd",
        input="Welcome to PonyFlash, the AI media generation platform.",
        voice="English_Graceful_Lady",
    )
    print(f"Speech URL: {gen.url}")
except InsufficientCreditsError as e:
    print(f"Not enough credits: {e}")

# ── Generate music ──
try:
    gen = pony_flash.music.generate(
        model="music-2.5",
        prompt="A calm acoustic guitar melody",
        instrumental=True,
        duration=30,
    )
    print(f"Music URL: {gen.url}")
except InsufficientCreditsError as e:
    print(f"Not enough credits: {e}")


path: assets/fonts.md
content: # Subtitle Fonts

The repository no longer ships binary font files. Subtitle fonts are prepared on demand at runtime.

## Default Font Strategy

- Use `Noto Sans CJK SC` for both Latin text and Simplified Chinese subtitles.
- Keep a reusable downloaded font under `~/.cache/ponyflash/fonts/` only when the user explicitly runs the font preparation script.
- Allow overriding the cache directory with `PONYFLASH_FONT_DIR`.

## Explicit Keep Command

```bash
bash scripts/ensure_subtitle_fonts.sh
```

Quiet mode prints only the resolved font file path:

```bash
bash scripts/ensure_subtitle_fonts.sh --quiet
```

## Download Sources

The default script tries these sources in order:

1. `https://mirrors.aliyun.com/CTAN/fonts/notocjksc/NotoSansCJKsc-Regular.otf`
2. `https://cdn.jsdelivr.net/gh/notofonts/noto-cjk@main/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Regular.otf`

You can override the primary URL with `PONYFLASH_NOTO_FONT_URL`.

## Intended Usage

In the default workflow:

1. Run `scripts/media_ops.sh subtitle-burn`
2. Let the script create a temporary font directory automatically
3. Keep only the final requested output and remove temporary font files afterwards

## Notes

- `Noto Sans CJK SC` covers Simplified Chinese and common Latin text, which keeps the upload package text-only while preserving stable subtitle rendering.
- `scripts/ensure_subtitle_fonts.sh` is the opt-in path for keeping a reusable font copy on disk.
- `fontsdir` should point to a directory that contains only font files when possible.
- If you want to use custom fonts instead, pass `--latin-font-file` and `--cjk-font-file` explicitly.


path: assets/subtitle-style.md
content: # Default Subtitle Style

This style sheet serves as the default subtitle rendering reference for the skill, using a `1920x1080` landscape render as the baseline.

## Fonts

- Default subtitle font: `Noto Sans CJK SC`
- Default runtime behavior:
  - `scripts/media_ops.sh subtitle-burn` stages the font in a temporary directory and deletes it after export
- Explicit keep command:
  - `bash scripts/ensure_subtitle_fonts.sh`

## Baseline Style

The following values correspond to the approved default look for `1920x1080` output:

- font size: `60`
- text color: `#ffffff`
- outline color: `#000000`
- outline width: `1`
- outline join: `round`
- outline cap: `round`
- shadow offset: `1`
- `blur`: `1`
- shadow color: `rgba(0,0,0,0.25)`
- bottom margin: `104`
- left / right safe margin: `120`
- no background box by default

## Adaptive Rules

The default subtitle style should not rely on hardcoded pixel values. It should scale with the output dimensions:

- `shortEdge = min(videoWidth, videoHeight)`
- `fontSize = round(shortEdge * 0.0556)`
- `marginV = round(videoHeight * 0.0963)`
- `marginL = marginR = round(videoWidth * 0.0625)`
- `outline = max(1, round(fontSize * 0.0167))`
- `shadow = 1`
- `blur = 1`

Notes:

- These formulas are derived from the approved `1920x1080` baseline and keep visual density roughly consistent across resolutions.
- Tying font size to `shortEdge` works well across landscape, portrait, and square outputs.
- Tying bottom margin to `videoHeight` helps keep subtitles in the lower-middle area instead of too low on tall screens.
- Tying left / right margins to `videoWidth` helps prevent edge collisions on narrow frames.

## Wrapping and Layout

- For landscape or wide outputs (`videoWidth >= videoHeight`), keep max text width around `90%` of frame width
- For portrait or narrow outputs (`videoWidth < videoHeight`), keep max text width around `90%` of frame width
- Prefer explicit pre-wrapping for long lines instead of relying entirely on subtitle-engine auto-wrap
- Keep multiline subtitles center-aligned so that lines of different lengths still feel visually balanced

## Suggested ASS Mapping

- `PrimaryColour`: white
- `OutlineColour`: black
- `Outline`: `outline`
- `Shadow`: `shadow`
- `Blur`: `blur`
- `MarginV`: `marginV`
- `MarginL` / `MarginR`: `marginL` / `marginR`
- no background box

Notes:

- If you render subtitles with Canvas, Pillow, or a frontend renderer, you can implement the same baseline values and scaling formulas directly.
- If you render with `ffmpeg subtitles` / ASS, map to the closest ASS parameters and insert manual line breaks for long text when needed.

## Usage Notes

- This parameter set works well as a default subtitle reference, especially for light, warm, or medium-contrast video backgrounds.
- On high-contrast scenes, white text with a light outline is usually stable enough. Keep shadow subtle rather than heavy.
- For `9:16` short-video output, prefer reusing the same formulas instead of maintaining a separate fixed portrait preset.


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)