repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/scripts/demo.py

Raw
File outline
#!/usr/bin/env python3
"""Record interactive Pi extension demos."""

from __future__ import annotations

import argparse
import importlib.util
import shutil
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from types import ModuleType

try:
    import pexpect
except ImportError as e:
    raise SystemExit("missing Python package: pexpect") from e

ROOT = Path(__file__).resolve().parents[1]
DRIVERS = ROOT / "drivers"
EXTENSIONS = ROOT / "agent" / "extensions"
OUT = ROOT / ".demo"

CAST_IDLE_LIMIT = "4.0"
AGG_ARGS = [
    "--theme", "asciinema",
    "--text-font-family", "JetBrains Mono",
    "--font-size", "14",
    "--line-height", "1.25",
    "--idle-time-limit", "4.0",
    "--last-frame-duration", "5",
    "--fps-cap", "24",
]


@dataclass(frozen=True)
class Driver:
    name: str
    title: str
    extensions: list[str]
    targets: list[str]
    cols: int
    rows: int
    cwd: Path
    steps: list[tuple]


def load_module(name: str) -> ModuleType:
    path = DRIVERS / f"{name}.py"
    if not path.exists():
        raise SystemExit(f"driver not found: {path}")
    spec = importlib.util.spec_from_file_location(f"driver_{name}", path)
    if spec is None or spec.loader is None:
        raise SystemExit(f"cannot load driver: {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def str_list(module: ModuleType, attr: str) -> list[str]:
    value = getattr(module, attr, None)
    if not isinstance(value, list) or not all(isinstance(x, str) and x for x in value):
        raise SystemExit(f"driver {module.__name__}: {attr} must be non-empty string list")
    return value


def load_driver(name: str) -> Driver:
    module = load_module(name)
    title = getattr(module, "title", name.replace("_", " ").title())
    if not isinstance(title, str) or not title:
        raise SystemExit("title must be string")

    cols = getattr(module, "cols", 100)
    rows = getattr(module, "rows", 28)
    if not isinstance(cols, int) or not isinstance(rows, int) or cols < 40 or rows < 12:
        raise SystemExit("cols/rows must be reasonable ints")

    cwd_raw = getattr(module, "cwd", ".")
    if not isinstance(cwd_raw, str):
        raise SystemExit("cwd must be string")
    cwd = (ROOT / cwd_raw).resolve()
    if not cwd.is_dir():
        raise SystemExit(f"cwd missing: {cwd}")

    steps = getattr(module, "steps", None)
    if not isinstance(steps, list):
        raise SystemExit("steps must be list")
    for step in steps:
        validate_step(step)

    driver = Driver(
        name=name,
        title=title,
        extensions=str_list(module, "extensions"),
        targets=str_list(module, "targets"),
        cols=cols,
        rows=rows,
        cwd=cwd,
        steps=steps,
    )
    validate_driver(driver)
    return driver


def validate_step(step: object) -> None:
    if not isinstance(step, tuple) or not step:
        raise SystemExit(f"invalid step: {step!r}")
    op = step[0]
    if op not in {"wait", "type", "send", "command", "prompt", "ctrl", "quit"}:
        raise SystemExit(f"unknown step op: {op!r}")
    if op == "wait" and not (len(step) == 2 and isinstance(step[1], int)):
        raise SystemExit(f"wait step must be ('wait', ms): {step!r}")
    if op in {"type", "send"} and not (len(step) in {2, 3} and isinstance(step[1], str)):
        raise SystemExit(f"{op} step must include text: {step!r}")
    if op in {"command", "prompt"} and not (len(step) in {2, 3} and isinstance(step[1], str)):
        raise SystemExit(f"{op} step must include text: {step!r}")
    if op == "ctrl" and not (len(step) == 2 and isinstance(step[1], str) and len(step[1]) == 1):
        raise SystemExit(f"ctrl step must be ('ctrl', key): {step!r}")
    if op == "quit" and len(step) != 1:
        raise SystemExit(f"quit step takes no args: {step!r}")


def validate_driver(driver: Driver) -> None:
    for name in driver.extensions:
        if not (EXTENSIONS / name / "index.ts").exists():
            raise SystemExit(f"extension missing index.ts: {name}")
    for name in driver.targets:
        ext = EXTENSIONS / name
        if not ext.is_dir():
            raise SystemExit(f"target extension missing: {name}")
        if not (ext / "README.md").exists():
            raise SystemExit(f"target README missing: {ext / 'README.md'}")


def pi_command(driver: Driver) -> str:
    parts = [
        "pi",
        "--no-session",
        "--no-context-files",
        "--no-skills",
        "--no-prompt-templates",
        "--no-extensions",
    ]
    for name in driver.extensions:
        parts.extend(["-e", str(EXTENSIONS / name)])
    return " ".join(shlex_quote(part) for part in parts)


def shlex_quote(value: str) -> str:
    import shlex
    return shlex.quote(value)


def pump(child: pexpect.spawn, seconds: float) -> None:
    end = time.time() + seconds
    while time.time() < end and child.isalive():
        try:
            data = child.read_nonblocking(size=8192, timeout=0.03)
            if data:
                sys.stdout.write(data)
                sys.stdout.flush()
        except pexpect.TIMEOUT:
            pass
        except pexpect.EOF:
            break


def type_text(child: pexpect.spawn, text: str, delay: float) -> None:
    for ch in text:
        child.send(ch)
        pump(child, delay)


def run_step(child: pexpect.spawn, step: tuple) -> bool:
    op = step[0]
    if op == "wait":
        pump(child, step[1] / 1000)
    elif op == "type":
        delay = (step[2] if len(step) > 2 else 55) / 1000
        type_text(child, step[1], delay)
    elif op == "send":
        child.send(step[1])
        pump(child, (step[2] if len(step) > 2 else 500) / 1000)
    elif op == "command":
        type_text(child, step[1], 0.055)
        pump(child, 0.35)
        child.send("\r")
        pump(child, (step[2] if len(step) > 2 else 1000) / 1000)
    elif op == "prompt":
        type_text(child, step[1], 0.035)
        pump(child, 0.45)
        child.send("\r")
        pump(child, (step[2] if len(step) > 2 else 12000) / 1000)
    elif op == "ctrl":
        child.sendcontrol(step[1])
        pump(child, 0.5)
    elif op == "quit":
        return True
    return False


def drive(driver: Driver) -> int:
    child = pexpect.spawn(
        pi_command(driver),
        cwd=str(driver.cwd),
        encoding="utf-8",
        timeout=90,
        dimensions=(driver.rows, driver.cols),
    )
    try:
        for step in driver.steps:
            if run_step(child, step):
                break
    finally:
        try:
            child.sendcontrol("c")
            pump(child, 1.0)
        except Exception:
            pass
        child.terminate(force=True)
    return 0


def ensure_tools() -> None:
    missing = [tool for tool in ["asciinema", "agg"] if not shutil.which(tool)]
    if missing:
        raise SystemExit(f"missing tool(s): {', '.join(missing)}")


def record(driver: Driver) -> tuple[Path, Path, Path]:
    ensure_tools()
    OUT.mkdir(exist_ok=True)
    cast = OUT / f"{driver.name}.cast"
    gif = OUT / f"{driver.name}.gif"
    txt = OUT / f"{driver.name}.txt"

    cmd = [
        "asciinema", "rec",
        "--headless",
        "--overwrite",
        "--capture-input",
        "--window-size", f"{driver.cols}x{driver.rows}",
        "-i", CAST_IDLE_LIMIT,
        "-c", f"python3 {shlex_quote(str(Path(__file__).resolve()))} --drive {shlex_quote(driver.name)}",
        str(cast),
    ]
    subprocess.run(cmd, cwd=ROOT, check=True)

    subprocess.run([
        "agg",
        "--cols", str(driver.cols),
        "--rows", str(driver.rows),
        *AGG_ARGS,
        str(cast),
        str(gif),
    ], cwd=ROOT, check=True)

    subprocess.run([
        "asciinema", "convert", "-f", "txt", str(cast), str(txt), "--overwrite",
    ], cwd=ROOT, check=True, stdout=subprocess.DEVNULL)

    return cast, gif, txt


def readme_block(driver: Driver) -> str:
    return (
        f"<!-- demo:{driver.name}:start -->\n"
        f"![{driver.title}](assets/{driver.name}.gif)\n"
        f"<!-- demo:{driver.name}:end -->"
    )


def update_readme(readme: Path, driver: Driver) -> None:
    text = readme.read_text()
    start = f"<!-- demo:{driver.name}:start -->"
    end = f"<!-- demo:{driver.name}:end -->"
    block = readme_block(driver)

    if start in text and end in text:
        before, rest = text.split(start, 1)
        _, after = rest.split(end, 1)
        readme.write_text(before + block + after)
        return

    addition = f"\n\n## Demo\n\n{block}\n"
    readme.write_text(text.rstrip() + addition)


def install_assets(driver: Driver, gif: Path) -> None:
    for name in driver.targets:
        ext = EXTENSIONS / name
        assets = ext / "assets"
        assets.mkdir(exist_ok=True)
        shutil.copy2(gif, assets / f"{driver.name}.gif")
        update_readme(ext / "README.md", driver)
        print(f"OK asset {name}/assets/{driver.name}.gif")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("name", nargs="?")
    parser.add_argument("--drive", dest="drive_name")
    parser.add_argument("--no-install", action="store_true")
    args = parser.parse_args()

    if args.drive_name:
        return drive(load_driver(args.drive_name))
    if not args.name:
        raise SystemExit("usage: scripts/demo.py <driver>")

    driver = load_driver(args.name)
    cast, gif, txt = record(driver)
    print(f"OK cast {cast}")
    print(f"OK gif  {gif}")
    print(f"OK txt  {txt}")
    if not args.no_install:
        install_assets(driver, gif)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())