# Pixel-Replica Loop — one-shot workflow for replicating a UI screenshot in code

> **PORTABILITY NOTE.** Published from Imperium's internal operating system. Paths starting
> with `~/.claude/`, `/Users/alex/...`, `<repo-root>/`, or `scripts/`, plus Drive/Telegram
> distribution steps and CLI wrappers, are the author's machine conveniences — substitute your
> own tooling. The prompts, model choices, parameters, and QA gates are the portable substance.

Proven 2026-07-27 on the Revenue Flow card (`Alex OS/assets/ui-lab/revenue-flow/`): reference →
pure HTML/CSS at 89.8% of pixels within 12/255 (mean diff 2.9%). The loop below is what got there;
run it start-to-finish in ONE session without asking the user between rounds. Budget ~6-10
render/compare rounds; the user sees only the final result.

## The method in one line

Never eyeball. Measure the reference numerically (PIL), build from the numbers, screenshot,
diff numerically, fix the worst region, repeat until the score plateaus.

## Step order

1. **Copy the reference** into the working dir as `reference.png`. Note exact WxH — the mockup
   page is that exact size, rendered at `--force-device-scale-factor=1`.
2. **Measure BEFORE writing any CSS** (PIL scripts, not eyes):
   - Element geometry: threshold-scan rows/columns for edges; bounding boxes for every text
     block (`bbox of pixels > luminance-threshold` in a crop). Record left/top/w/h per element.
   - Colors: sample flat fills at multiple interior points (single points lie — text AA, glow
     contamination). For text colors, average pixels above a color condition, not one pixel.
   - Watch for contaminated scans: glow/AA push thresholds — cross-check any measurement that
     disagrees with a clean neighbor (e.g. one bar measured 265px wide when its siblings are 190).
3. **Build the HTML** — single file, absolute positioning, page-exact dimensions.
   - PITFALL (cost a full round): if elements live inside an inset container, positions are
     container-relative. Measured page coords must have the container offset subtracted.
   - Fonts: Google-Sans-look references → bundle Roboto woff2 locally (`@font-face`); Google
     Fonts is not reachable from the sandboxed renderer, and system SF Pro is wider-per-cap-height
     than Google Sans (text bboxes won't converge). Fit font-size to the measured text bbox
     (width AND height), not to what looks right.
4. **Screenshot**: `scripts/shot.sh page.html render.png WxH` (chrome-headless-shell; full
   Chrome --headless writes the PNG but never exits on this machine).
5. **Compare**: `scripts/pixel-compare.py reference.png render.png` → global score, worst grid
   cells, `diff-heat.png` (mismatch amplified 4x), `side-by-side.png`. Read the heatmap:
   ghost/double text = position offset; halo around a shape = size/radius off; bright region =
   color/gradient off.
6. **Fix worst region, re-render, re-compare.** Numbers over impressions — one visually-driven
   "improvement" round regressed the score; the grid samples were already right.

## Complex gradients: FIT, don't hand-tune

Hand-layered radials plateau fast (~50% region accuracy on a beam-of-light background).
`scripts/fit-gradient.py` jumps past that (~80% same region) by least-squares fitting K rotated
elliptical Gaussian lobes to the reference background:

```bash
python3 fit-gradient.py reference.png \
  --region 36,36,1850,1290 \
  --exclude 85,80,560,345 --exclude 735,265,1495,725 ... (every UI element box) \
  --origin 30,30   # the card container's page offset
```

- Emits ready-to-paste CSS: a base `rgb()` + `.lobeN` divs (`mix-blend-mode:plus-lighter`
  = additive light, radial-gradient with Gaussian alpha stops, `transform:rotate`).
- Rotation is the unlock: axis-aligned CSS radials cannot express diagonal light shafts; the
  fitter recovers beam angles automatically (found -32°/-37°/55° shafts on the test card).
- Needs numpy (`python3 -m pip install --user numpy`).
- Layer order in HTML: biggest/dimmest lobe first, hottest core last; container has
  `overflow:hidden`.

On top of the fitted lobes, for "beams of light" styling add 2-3 thin rotated shaft divs
(width ~110-150px, height ~1800px, blur ~10px, plus-lighter, alpha .1-.2) at angles near the
fitted lobe angles, and a smoke layer for organic texture: SVG feTurbulence data-URI,
`mix-blend-mode:multiply; opacity:~.15`, masked to the lit area.

## Recurring physical details (check each explicitly)

- **Glass panels**: if a panel's interior tint shifts toward nearby bright content, it is
  translucent — `background:rgba(...,.75-.85)` + `backdrop-filter:blur(50px)`, not a solid fill.
- **Outer glow**: light "leaks" outside the container on the side OPPOSITE the light source
  (bottom/right for a top-left beam). Blurred warm strips behind the card, alpha ~.15.
- **Bars/charts**: gradients fade INTO the background at the bottom (last stop ≈ card bg);
  a colored feature bar often has a slightly different width/radius than its siblings — measure
  its cap curve column-by-column before assuming pill or flat.
- **Corner radius**: verify by checking whether a near-corner pixel is inside or outside the
  shape, don't trust appearances (glow makes radii look smaller).

## Accuracy expectations (say this to the user up front)

- 85-92% of pixels within 12/255 is the realistic ceiling for a faithful pure-code replica.
- The irreducible remainder: (a) stochastic textures (airbrush smoke/noise — the pattern can
  never align pixel-wise; reproduce the character, not the pixels), (b) proprietary fonts
  (Google Sans/Product Sans → Roboto is the closest free metric match), (c) AA edge differences.
- If the user needs >95% pixel parity, the honest options are embedding a fitted/blurred
  texture layer sampled from the reference, or accepting the visual (not pixel) match.
