# Specification: Graphicizer

## 1. Overview & System Goals

**Graphicizer** is an end-to-end agentic motion graphics authoring, adversarial visual verification, and deterministic `30 FPS` video rendering pipeline. It transforms raw talking-head camera recordings into polished, data-driven short-form videos supporting both **`4:5` Portrait Feed (`1080×1350` for LinkedIn, X, Instagram)** and **`9:16` Vertical Reels / Shorts / TikTok (`1080×1920`)**.

### Core Philosophy & Engineering Principles
1. **Web-App-as-Video-Engine (React 19 + Vite 6 + Playwright + FFmpeg)**: Motion graphics, code blocks, vector diagrams, browser screenshots, and cover thumbnails are authored as standard React components (`src/App.tsx`) and rasterized directly in headless Playwright Chromium.
2. **100% Frame-Deterministic Animation Math (`30 FPS`)**: Headless frame capture exhibits variable wall-clock timing (`15ms–100ms/frame`). Therefore, CSS `transition`, `@keyframes`, `setInterval`, `setTimeout`, and wall-clock `requestAnimationFrame` are strictly forbidden. All spring settlements, Ken Burns scales, and reveals are pure mathematical functions of `currentFrame` and `sectionOffsetFrame`.
3. **Zero HTML5 `<video>` Seek Lag via Frame Sequences**: Seeking `<video>` in headless browsers produces decode lag and dropped frames. Speaker video and B-roll clips are pre-extracted to `30 FPS` image sequences (`frame_%05d.jpg`/`.png`) rendered via standard `<img>` tags, awaiting complete decoding on each tick.
4. **Self-Hosted Brand Assets & Zero External CDNs**: All webfonts (`.woff2`) and brand presets are self-hosted locally under `public/assets/brand/<brand>/` with `font-display: block` to eliminate First Contentful Paint text jitter and network dependencies.
5. **Dual Aspect Ratio Stage with Safe-Zone Guardrails**: A unified nested `1080×1350` `#graphicizer-stage` is centered within both `4:5` (`1080×1350`) and `9:16` (`1080×1920`, `stageOffsetY = 220`), strictly avoiding top player bars (`220px`), bottom metadata drawers (`350px–480px`), and right-hand action icon columns (`160px`).
6. **Adversarial 6-Prosecutor Verification Swarm**: Before rendering final MP4s, six cold-start LLM subagent prosecutors inspect keyframe snapshots and audit telemetry against 15 strict motion graphics laws, requiring scores of `≥ 9.8/10` with zero vetoes.

---

## 2. System Architecture & Pipeline Workflow

```mermaid
flowchart LR
    A["Raw Camera Video (.mp4/.mov)"] -->|"scripts/analyze_video.py (Gemini File API + Audio Extract)"| B["2-Column Markdown Script (projects/<ID>/<ID>.md + draft_script.json)"]
    B -->|"User Edits Graphics Notes, Brand & Aspect Ratio (4:5 | 9:16 | both)"| C["scripts/md_script_sync.py pull <ID>"]
    C --> D["projects/<ID>/storyboard.json + src/data/storyboard.json"]
    D -->|"scripts/fetch_assets.py + scripts/capture_url.ts + Image Generation"| E["scripts/generate_captions.py (Optional faster-whisper + DP Alignment)"]
    E -->|"projects/<ID>/Scenes.tsx -> src/scenes/Scenes.tsx"| F["Vite + React Dual-Aspect Web App (4:5 1080x1350 & 9:16 1080x1920)"]
    F -->|"scripts/audit_keyframes.ts + .agents/skills/graphicizer-swarm (6 Prosecutors)"| G["Verified Keyframes & Cover Thumbnail (>=9.8/10, 0 Vetoes)"]
    G -->|"scripts/render_mp4.ts (Playwright seekToFrame + ffmpeg)"| H["Final 30fps MP4(s) + Cover Thumbnail PNG(s) in out/"]
```

### Layout Modes & Stage Geometry
Every video section uses one of three layout modes over a single continuous background color (`palette.bg`):

| Layout Mode | Description | Active Stage Zone (`#graphicizer-stage`) | Speaker Zone |
| :--- | :--- | :--- | :--- |
| **`FULL_GRAPHIC`** | Full-screen motion graphics with no visible speaker. | `x: 64..1016` (`952px` wide)<br>• **With captions (`bottomOffsetPx: 160`)**: `y_stage: 90..1065` (`height: 975px`)<br>• **Without captions**: `y_stage: 90..1190` (`height: 1100px`) | Hidden |
| **`FULL_SPEAKER`** | Fully visible speaker with zero graphics overlays. | None (zero overlays) | Full-bleed `1080×1350` (`4:5`) or `1080×1920` (`9:16`) center-crop |
| **`PIP_TOP_GRAPHIC`** | Widescreen speaker across lower half; graphics on top. | **Top Half**: `x: 64..1016`, `y_stage: 48..660`<br>*Continuous `palette.bg` background; zero divider line.* | **Lower Half (Widescreen PIP)**: `x: 64..1016`, `y_stage: 684..1302` (`height: 618px`) |
| **`SPEAKER_OVERLAY`** *(Thumbnail)* | Full-bleed speaker frame with containerless hook typography & vector accents. | **Lower Torso**: `x: 64..916`, `y_stage: 850..1270`<br>*Face Clearance Rule: Graphics must strictly clear `y_stage <= 845`.* | Full-bleed speaker frame with soft contrast vignette |

---

## 3. Target Repository Structure

```text
graphicizer/
├── .agents/skills/
│   ├── graphicizer-brand-customizer/
│   │   └── SKILL.md                  # Interactive guide for customizing themes, fonts, motifs, captions & archetypes
│   └── graphicizer-swarm/
│       ├── SKILL.md                  # 5-Stage workflow & 6-Prosecutor adversarial verification engine
│       └── references/
│           └── platform-safe-zones.md # Empirical 4:5 and 9:16 social platform UI exclusion zones
├── .env.example                      # Template environment variables (GEMINI_API_KEY, GEMINI_MODEL, PROJECT_PREFIX)
├── .gitignore                        # Ignores secrets, caches, projects/*, episode assets, active storyboard/Scenes
├── GEMINI.md                         # Workspace rules & end-to-end 5-stage workflow instructions for coding agents
├── README.md                         # Overview, copy-paste onboarding prompt, and dependency reference
├── docs/
│   └── architecture.md               # Comprehensive architectural specification & CLI reference
├── index.html                        # 1080px viewport HTML entry point
├── package.json                      # React 19, Vite 6, Playwright, TypeScript, tsx scripts
├── projects/
│   └── .gitkeep                      # Episode-specific scripts & scenes (projects/* gitignored except .gitkeep)
├── public/
│   └── assets/
│       └── brand/                    # Shared first-class brand presets (checked into Git)
│           ├── default/              # Built-in default ("modern-tech") brand
│           │   ├── BRAND.md          # Canonical brand specification
│           │   ├── fonts/            # Self-hosted WOFF2 fonts (inter-normal.woff2, jetbrains-mono-normal.woff2)
│           │   └── reference-images/
│           │       └── .gitkeep
│           └── editorial/            # Built-in secondary ("editorial-serif") brand preset
│               ├── BRAND.md          # Canonical brand specification
│               ├── fonts/            # Self-hosted WOFF2 fonts (eb-garamond-normal.woff2, eb-garamond-italic.woff2, jetbrains-mono-normal.woff2)
│               └── reference-images/
│                   └── .gitkeep
├── scripts/
│   ├── verify_setup.py               # Stage 0 environment, binary, API, font & read-only upstream git checker
│   ├── analyze_video.py              # Stage 1 Gemini multimodal video analyzer with geometric backoff
│   ├── md_script_sync.py             # Stage 2 two-column Markdown <-> storyboard.json compiler
│   ├── capture_url.ts                # Stage 3 Retina (1280x1216 @ 2x) URL screenshot capture
│   ├── fetch_assets.py               # Stage 3 YouTube/Drive/local clip download & 30 FPS ffmpeg frame extraction
│   ├── generate_captions.py          # Stage 5 faster-whisper + Needleman-Wunsch DP word-level caption aligner
│   ├── audit_keyframes.ts            # Stage 5 Playwright keyframe, thumbnail face-clearance & safe-zone geometry auditor
│   └── render_mp4.ts                 # Stage 5 deterministic 30 FPS Playwright -> ffmpeg MP4 & cover thumbnail renderer
├── src/
│   ├── App.tsx                       # Dual-aspect stage, standby fallback, seekToFrame(), setThumbnailMode(), safe-zone overlay & studio scrubber
│   ├── components/
│   │   └── GraphicPrimitives.tsx     # Composable theme-driven archetypes (TitleCard, ScreenshotCard, CaptionOverlay, etc.)
│   ├── data/
│   │   └── .gitkeep                  # Active storyboard.json is synced here (gitignored)
│   ├── main.tsx                      # React DOM root mount
│   ├── scenes/
│   │   └── .gitkeep                  # Active Scenes.tsx is synced here (gitignored)
│   ├── styles.css                    # Self-hosted @font-face rules (font-display: block) & reset
│   └── theme.ts                      # Brand presets, semantic tokens, safe-zone geometry & frame-deterministic math
├── tsconfig.json                     # Strict TypeScript bundler config covering src/ and scripts/
└── vite.config.ts                    # Vite server on port 5173 (copyPublicDir: false)
```

---

## 4. Theme System & Brand Presets

### Semantic Tokens (`src/theme.ts`)
- **`ThemePalette`**: `bg`, `surface`, `surfaceAlt`, `codeBg`, `border`, `borderSubtle`, `textPrimary`, `textMuted`, `accentPrimary`, `accentSecondary`, `accentTertiary`.
- **`ThemeFonts`**: `display`, `sans`, `mono` (all backed by self-hosted local `.woff2` files).
- **`ThemeCaptionConfig`**: Font slot, size (`56px`), weight (`600`/`700` uniform), color tokens, single-line phrase packing (`max_words = 4`, `max_chars = 22`), and bottom offset (`160px` -> `y_stage: 1102..1190`).
- **Brand Presets**:
  1. **`default` (`modern-tech`)**: Rounded `16px` cards, `Inter` typography, `JetBrains Mono` telemetry, `geometric-orbit` SVG motif, clean blue/teal/amber accents.
  2. **`editorial` (`editorial-serif`)**: Archival unbleached paper palette (`#fbf9f4` / `#151413`), `2px` corners, `EB Garamond` display serif, `flying-books` SVG motif, terracotta/slate-teal accents.

### Frame-Deterministic Math (`src/theme.ts`)
- **`springValue(frameOffset, fps, { damping, stiffness, mass })`**: Analytical second-order harmonic oscillator without non-deterministic timers.
- **`getSpringSettleUp(offsetFrame, fps, maxOffsetPx = 14)`**: Guarantees `opacity = 1` immediately at `offsetFrame = 0` (preventing blank-card flash) and locks to `{ translateY: 0, opacity: 1 }` after 14 frames.
- **`getKenBurnsScale(offsetFrame, durationFrames, startScale, endScale)`**: Linear subtle zoom (`1.0 -> 1.04`).
- **`getStaggeredLineReveal(offsetFrame, startFrame, endFrame)`**: Staggered opacity and translation reveals for code and bullet points.

---

## 5. Composable Graphic Primitives (`src/components/GraphicPrimitives.tsx`)

Each primitive exposes data attributes for Playwright audit inspection:
- **`LowerHalfSpeakerPip`**: Positioned at `y_stage: 684..1302, x: 64..1016` (`952×618px`), framing the pre-extracted speaker frame sequence.
- **`TitleCard`**: Centered display headline (`116px` or `76px`), uppercase status badge with beacon dot, optional subtitle, and optional architectural corner marks.
- **`ScreenshotCard`**: Browser-chrome header bar with three semantic traffic dots, URL pill, and padded viewport with subtle Ken Burns scale.
- **`IllustrationCard`**: Full-bleed framed artwork with inner hairline border.
- **`VideoClipCard`**: Deterministically steps through frame sequences (`frame_%05d.png`) using `sectionOffsetFrame + 1`.
- **`CodeDisplay`**: Dark code container with per-line staggered opacity reveals.
- **`BrandEmblemCanvas`**: Harmonic orbiting SVG motifs centered around the brand emblem card.
- **`CaptionOverlay`**: Color-only active word highlighting with uniform font weights to ensure zero horizontal text jitter.

---

## 6. End-to-End CLI Pipeline

All Python utilities use PEP 723 inline script metadata (`# /// script`) for zero-config `uv run` execution:
1. **`verify_setup.py`**: Pre-flight validation of git upstream status, system binaries (`ffmpeg`, `ffprobe`, `node`, `npx`), Node modules, Playwright Chromium, Gemini API key, and brand fonts.
2. **`analyze_video.py`**: Multimodal video analysis via Gemini File API with geometric backoff (`5s, 10s, 20s, ... up to 300s`) producing `projects/<ID>/<ID>.md` and `draft_script.json`.
3. **`md_script_sync.py`**: Bidirectional synchronization between the user's 2-column Markdown script (`projects/<ID>/<ID>.md`) and `storyboard.json`.
4. **`fetch_assets.py`**: Automatic extraction of speaker video frames (`fps=30 -q:v 2`) and download/clipping of referenced YouTube, Google Drive, or local media clips.
5. **`capture_url.ts`**: Playwright Retina (`1280×1216 @ 2x`) screenshot capture matching `ScreenshotCard` proportions.
6. **`generate_captions.py`**: Speech alignment via `faster-whisper` and Needleman-Wunsch dynamic programming with single-line packing and natural pause preservation.
7. **`audit_keyframes.ts`**: Headless Playwright verification of stage bounding boxes, PIP bounds (`y_stage <= 660`), caption clearance, and thumbnail speaker face clearance (`y_stage >= 850`).
8. **`render_mp4.ts`**: Frame-by-frame Playwright render piping lossless PNG buffers into `ffmpeg` (`-c:v libx264 -crf 16 -pix_fmt yuv420p`) muxing speaker audio into `out/<projectId>.mp4`.

---

## 7. Adversarial 6-Prosecutor Swarm & Quality Laws

Before rendering, six autonomous LLM prosecutors independently audit the keyframes and telemetry:
- **Subagent A**: Script, Timestamp Sync & Editorial Pacing
- **Subagent B**: Brand Theme & Token Compliance
- **Subagent C**: Viewport Geometry, Safe-Zones & Frame Determinism
- **Subagent D**: Asset Integrity, Screenshot Fidelity & Media Sync
- **Subagent E**: Adversarial QA, Transition & Frame-Boundary Glitch Breaker
- **Subagent F**: Generated Graphics, Viewer Optimization & Cognitive Load

### Key Instant Veto Triggers
- **Law 1**: Graphics intruding into lower-half PIP zone (`y_stage > 660px`).
- **Law 2**: Non-deterministic wall-clock CSS animations or timers.
- **Law 3**: HTML5 `<video>` seek lag (must use pre-extracted frame sequences).
- **Law 4**: External CDN webfonts or off-brand colors.
- **Law 5**: Mobile illegibility (body `< 22px`, code `< 18px`, captions `< 52px`).
- **Law 9**: Frame 0 opacity flash or layout overflow.
- **Law 12**: Wall of text (headlines `> 8` words, hold time `> 2.5` words/sec).
- **Law 15**: Superimposed graphics obscuring the speaker's face on cover thumbnails (`minGraphicStageTopY < 850`).

---

## 8. Definition of Done & Acceptance Criteria

A Graphicizer implementation is complete when:
- [ ] `uv run scripts/verify_setup.py` reports `PASS` across all system tools, Node packages, and brand font files.
- [ ] `npm run typecheck` (`tsc --noEmit`) passes with `0` errors.
- [ ] Dual-aspect stage renders both `1080×1350` (`4:5`) and `1080×1920` (`9:16`, `stageOffsetY = 220`) correctly.
- [ ] `npm run audit:keyframes -- --aspect both` passes with `0` safe-zone, PIP bound, image, or console errors.
- [ ] `npm run render:thumbnail` outputs `out/<projectId>-thumbnail.png` verifying speaker face clearance.
- [ ] `npm run render:mp4` outputs 30 FPS MP4 video with frame-perfect audio sync and zero dropped frames.
