Real portraits for the four new advisors, and portraits built into /newroaster

- Naval, Codie Sanchez, Leila Hormozi, and Sara Blakely now have cartoon
  portraits made the same way as the original seven: a real photo of each
  person, the original Seedream prompts, the Buffett cartoon as the style
  reference, two candidates picked by likeness, and open, mid, and blink
  talking frames aligned and keyed by build_portraits.py.
- /newroaster Step 8 (Portrait) does this for every new seat, with
  scripts/portrait.mjs (photo, base, pick, frames), scripts/build_portraits.py
  (sheet, build), and assets/style-reference.jpg. "/newroaster portrait <name>"
  redoes one. Without a kie.ai key the seat still works with a placeholder.
- .env.example gains KIE_AI_API_KEY; README explains the portrait step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Nate HerkandClaude Opus 5.5 committed 2026-10-21 09:34:59 -05:00
1 parent 60e7b0c80b
commit 576c6f35d5
22 files changed
+359 -11

No files matched your search

@@ -0,0 +1,184 @@
"""Turn a seat's portrait renders into the talking-head frames the Roast Room uses.
The same processing the original seven went through (OtherWorlds art/build_portraits.py in
the source workspace): each edit (open, mid, blink) is aligned back onto the base with ORB
features and a similarity transform, and only the changed region (mouth or eyes) is feathered
onto the base. Every frame is then pixel-identical outside the mouth or eyes, which keeps the
swap from jittering. The green screen is keyed to alpha, every head is cropped to the same
scale, and the frames land in <out>/<key>-<shape>.webp.
python build_portraits.py sheet <dir> photo next to every candidate, for picking
python build_portraits.py build <dir> <key> --out <dir> base/open/mid/blink.png -> <key>-*.webp
<dir> is the seat's portrait folder (photo.jpg, cand*.png, base.png, open.png, mid.png, blink.png).
Needs opencv-python and numpy (pip install opencv-python numpy).
"""
import sys
from pathlib import Path
import cv2
import numpy as np
W = 1024 # working size
SIZE = 560 # output size (square)
HEAD_W = 375 # target head width (px at W) a little under the crown
# region each shape is allowed to touch, as a fraction box (x0, y0, x1, y1) of the frame
REGION = {"open": (0.30, 0.47, 0.70, 0.82), "mid": (0.30, 0.47, 0.70, 0.82), "blink": (0.24, 0.20, 0.76, 0.52)}
def load(p):
im = cv2.imread(str(p), cv2.IMREAD_COLOR)
return cv2.resize(im, (W, W), interpolation=cv2.INTER_AREA)
def align(base, var, region):
"""Similarity-align var onto base using features outside the region that changed."""
orb = cv2.ORB_create(6000)
mask = np.full(base.shape[:2], 255, np.uint8)
x0, y0, x1, y1 = (np.array(region) * W).astype(int)
mask[y0:y1, x0:x1] = 0
g1, g2 = cv2.cvtColor(base, cv2.COLOR_BGR2GRAY), cv2.cvtColor(var, cv2.COLOR_BGR2GRAY)
k1, d1 = orb.detectAndCompute(g1, mask)
k2, d2 = orb.detectAndCompute(g2, mask)
m = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True).match(d1, d2)
m = sorted(m, key=lambda x: x.distance)[:800]
src = np.float32([k2[x.trainIdx].pt for x in m])
dst = np.float32([k1[x.queryIdx].pt for x in m])
M, inl = cv2.estimateAffinePartial2D(src, dst, method=cv2.RANSAC, ransacReprojThreshold=3)
warped = cv2.warpAffine(var, M, (W, W), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
return warped, M, int(inl.sum())
def patch_mask(base, warped, region):
"""Feathered ellipse around where the edit actually differs, clipped to the region."""
d = cv2.absdiff(base, warped).max(axis=2).astype(np.float32)
d = cv2.GaussianBlur(d, (0, 0), 6)
x0, y0, x1, y1 = (np.array(region) * W).astype(int)
roi = np.zeros_like(d)
roi[y0:y1, x0:x1] = d[y0:y1, x0:x1]
ys, xs = np.where(roi > 28)
if len(xs) < 50:
cx, cy, rx, ry = (x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0) / 3, (y1 - y0) / 3
else:
lo, hi = np.percentile(xs, [2, 98]), np.percentile(ys, [2, 98])
cx, cy = lo.mean(), hi.mean()
rx, ry = (lo[1] - lo[0]) / 2 + 26, (hi[1] - hi[0]) / 2 + 26
m = np.zeros((W, W), np.float32)
cv2.ellipse(m, (int(cx), int(cy)), (int(rx), int(ry)), 0, 0, 360, 1.0, -1)
m = cv2.GaussianBlur(m, (0, 0), 14)
clip = np.zeros_like(m)
clip[y0:y1, x0:x1] = 1
clip = cv2.GaussianBlur(clip, (0, 0), 10)
return (m * clip)[..., None]
def figure(base, warped):
"""Soft mask of pixels that are the figure (not green screen) in both frames, so a
patch never drags background into the face or tints it while matching skin tone."""
def fg(img):
f = img.astype(np.float32)
return (f[..., 1] - np.maximum(f[..., 0], f[..., 2])) < 20
both = (fg(base) & fg(warped)).astype(np.uint8)
both = cv2.erode(both, np.ones((9, 9), np.uint8))
return cv2.GaussianBlur(both.astype(np.float32), (0, 0), 3)[..., None]
def key_green(img):
"""Green screen to straight alpha, with despill on the edges."""
f = img.astype(np.float32)
b, g, r = f[..., 0], f[..., 1], f[..., 2]
spill = g - np.maximum(r, b)
a = 1.0 - np.clip((spill - 40) / 70, 0, 1)
a = cv2.GaussianBlur(a, (0, 0), 0.8)
# despill: clamp green to the max of red and blue where it leads
g2 = np.where(spill > 0, np.maximum(r, b), g)
out = np.dstack([b, g2, r, a * 255]).clip(0, 255).astype(np.uint8)
return out
def crop_box(alpha, zoom=1.0):
"""Square crop that puts every head at about the same size: the figure's width a
little under the crown is scaled toward HEAD_W, with a little headroom on top.
A crop larger than the frame is padded with transparency; the table hides it."""
solid = alpha > 40
ys = np.where(solid.any(1))[0]
top = int(ys.min())
xs = np.where(solid[min(top + 120, W - 1)])[0]
head = xs.max() - xs.min()
side = int(W * (head / HEAD_W) ** 0.85 * zoom)
cx = int((xs.max() + xs.min()) / 2)
y0 = top - int(side * 0.07)
return cx - side // 2, y0, cx - side // 2 + side, y0 + side
def cut(img, box):
"""Crop with transparent padding where the box leaves the frame."""
x0, y0, x1, y1 = box
out = np.zeros((y1 - y0, x1 - x0, img.shape[2]), img.dtype)
sx0, sy0, sx1, sy1 = max(x0, 0), max(y0, 0), min(x1, W), min(y1, W)
out[sy0 - y0:sy1 - y0, sx0 - x0:sx1 - x0] = img[sy0:sy1, sx0:sx1]
return out
def build(d, key, out, zoom=1.0):
base = load(d / "base.png")
frames = {"base": base}
report = []
for shape, region in REGION.items():
p = d / f"{shape}.png"
if not p.exists():
print(f" no {p.name}; {shape} will reuse the base frame")
continue
warped, M, inliers = align(base, load(p), region)
scale = float(np.hypot(M[0, 0], M[1, 0]))
m = patch_mask(base, warped, region)
# AI edits shift skin tone; match the patch to the base on its feathered rim
ring = (m[..., 0] > 0.15) & (m[..., 0] < 0.6)
if ring.sum() > 200:
warped = np.clip(warped.astype(np.float32) + (base[ring].mean(0) - warped[ring].mean(0)), 0, 255)
frames[shape] = (base * (1 - m) + warped * m).astype(np.uint8)
report.append(f"{shape}: {inliers} inliers, scale {scale:.3f}")
keyed = {k: key_green(v) for k, v in frames.items()}
box = crop_box(keyed["base"][..., 3], zoom)
out.mkdir(parents=True, exist_ok=True)
tiles = []
for k, v in keyed.items():
c = cv2.resize(cut(v, box), (SIZE, SIZE), interpolation=cv2.INTER_AREA)
cv2.imwrite(str(out / f"{key}-{k}.webp"), c, [cv2.IMWRITE_WEBP_QUALITY, 88])
bg = np.full((SIZE, SIZE, 3), (34, 26, 18), np.float32)
a = c[..., 3:4] / 255.0
tiles.append((c[..., :3] * a + bg * (1 - a)).astype(np.uint8))
cv2.imwrite(str(d / "review.jpg"), np.hstack(tiles), [cv2.IMWRITE_JPEG_QUALITY, 82])
print(key, "|", "; ".join(report), f"| frames in {out}, review sheet {d / 'review.jpg'}")
def sheet(d):
"""photo.jpg, then every candidate, side by side at the same height."""
files = [d / "photo.jpg"] + sorted(d.glob("cand*.png"))
tiles = []
for f in files:
im = cv2.imread(str(f), cv2.IMREAD_COLOR)
if im is None:
continue
h, w = im.shape[:2]
s = min(h, w)
im = im[0:s, (w - s) // 2:(w - s) // 2 + s]
im = cv2.resize(im, (420, 420), interpolation=cv2.INTER_AREA)
cv2.putText(im, f.stem, (12, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2, cv2.LINE_AA)
tiles.append(im)
cv2.imwrite(str(d / "candidates.jpg"), np.hstack(tiles), [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f"sheet: {d / 'candidates.jpg'}")
if __name__ == "__main__":
a = sys.argv[1:]
if len(a) >= 2 and a[0] == "sheet":
sheet(Path(a[1]))
elif len(a) >= 3 and a[0] == "build":
out = Path(a[a.index("--out") + 1]) if "--out" in a else Path("app/public/portraits")
zoom = float(a[a.index("--zoom") + 1]) if "--zoom" in a else 1.0
build(Path(a[1]), a[2], out, zoom)
else:
print(__doc__)
sys.exit(1)
@@ -0,0 +1,142 @@
#!/usr/bin/env node
// Make a new seat's cartoon portrait the same way the original seven were made: a real photo
// of the person plus a style reference (one of the existing cartoons) go to Seedream 5 Pro
// image-to-image, which returns a 3D animated-film bust on a green screen. Then three edits of
// the chosen bust give the talking frames (mouth open, mouth "oh", eyes closed).
// build_portraits.py turns those into the room's aligned, keyed frames.
//
// node .claude/skills/newroaster/scripts/portrait.mjs photo <dir> <image url or file>
// node .claude/skills/newroaster/scripts/portrait.mjs base <dir> "<who and what they wear>" [--n 2]
// node .claude/skills/newroaster/scripts/portrait.mjs pick <dir> <candidate number>
// node .claude/skills/newroaster/scripts/portrait.mjs frames <dir>
// node .claude/skills/newroaster/scripts/portrait.mjs probe
//
// <dir> is the seat's portrait folder, <build>/portrait/. It holds photo.jpg, cand1.png...,
// base.png, open.png, mid.png, and blink.png. Needs KIE_AI_API_KEY (kie.ai) in the
// environment or the project .env. A base candidate or edit costs a few credits.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const STYLE_REF = path.join(HERE, "..", "assets", "style-reference.jpg");
const API = "https://api.kie.ai";
const UPLOAD = "https://kieai.redpandaai.co/api/file-base64-upload";
const UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36";
// The exact prompts the original seven were built with. Change them and new seats stop matching.
const STYLE = "Turn the real person in the first image into a stylized 3D animated-film cartoon caricature drawn in exactly the same art style, rendering, lighting, and framing as the cartoon in the second image: head and upper chest bust, facing the camera straight on, centered, eyes looking at the viewer, mouth closed in a relaxed friendly smile. Keep the real person's likeness from the first image exactly: face shape, nose, eyes, eyebrows, hairline, and facial hair. Plain flat solid pure green (#00ff00) background, nothing else in the frame, no text except on the clothing.";
const KEEP = "Keep everything else exactly identical: same character, same face, same head position and size, same pose, same clothes, same lighting, same framing, same green background.";
const EDITS = {
open: `Edit this image: the character is mid-sentence talking, mouth open wide in an 'ah' shape, teeth and tongue visible. ${KEEP} Only the mouth changes.`,
mid: `Edit this image: the character is talking, mouth half open saying 'oh', lips slightly rounded. ${KEEP} Only the mouth changes.`,
blink: `Edit this image: the character blinks, both eyes fully closed with relaxed eyelids. ${KEEP} Only the eyes change.`,
};
function key() {
if (process.env.KIE_AI_API_KEY) return process.env.KIE_AI_API_KEY;
let dir = process.cwd();
for (let i = 0; i < 8; i++) {
const p = path.join(dir, ".env");
if (fs.existsSync(p)) {
const m = fs.readFileSync(p, "utf8").match(/^\s*KIE_AI_API_KEY\s*=\s*["']?([^"'\r\n]+)/m);
if (m && m[1].trim()) return m[1].trim();
}
const up = path.dirname(dir);
if (up === dir) break;
dir = up;
}
console.error("portrait: no KIE_AI_API_KEY. Get a key at https://kie.ai/api-key and add KIE_AI_API_KEY=... to the project .env.");
process.exit(3);
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let H;
async function upload(file) {
const ext = path.extname(file).slice(1).toLowerCase();
const mime = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : `image/${ext}`;
const r = await fetch(UPLOAD, {
method: "POST", headers: H,
body: JSON.stringify({ base64Data: `data:${mime};base64,${fs.readFileSync(file).toString("base64")}`, uploadPath: "roast-room", fileName: path.basename(file) }),
});
const j = await r.json();
const url = j?.data?.downloadUrl || j?.data?.fileUrl || j?.data?.url;
if (!url) throw new Error("upload failed: " + JSON.stringify(j));
return url;
}
/** One Seedream 5 Pro image-to-image job, saved to `out`. */
async function still(prompt, refs, out) {
const image_urls = await Promise.all(refs.map(upload));
const r = await fetch(`${API}/api/v1/jobs/createTask`, {
method: "POST", headers: H,
body: JSON.stringify({ model: "seedream/5-pro-image-to-image", input: { prompt, image_urls, aspect_ratio: "1:1", quality: "high", output_format: "png", nsfw_checker: false } }),
});
const j = await r.json();
const id = j?.data?.taskId;
if (!id) throw new Error(`createTask: ${JSON.stringify(j)}`);
const t0 = Date.now();
for (let delay = 4000; ; delay = Math.min(delay * 1.25, 15000)) {
if (Date.now() - t0 > 15 * 60 * 1000) throw new Error(`${path.basename(out)}: timed out`);
await sleep(delay);
const d = (await (await fetch(`${API}/api/v1/jobs/recordInfo?taskId=${id}`, { headers: H })).json())?.data || {};
const state = d.state || d.status;
if (state === "fail" || state === "failed") throw new Error(`${path.basename(out)}: ${d.failMsg || d.failCode || "failed"}`);
if (state !== "success") continue;
let res = d.resultJson;
if (typeof res === "string") res = JSON.parse(res);
const url = (res?.resultUrls || res?.urls || [])[0];
if (!url) throw new Error(`${path.basename(out)}: no result url`);
fs.writeFileSync(out, Buffer.from(await (await fetch(url)).arrayBuffer()));
return out;
}
}
/** Run jobs in parallel; a failed job is retried once. */
async function all(jobs) {
const results = await Promise.allSettled(jobs.map(async ([prompt, refs, out]) => {
try { return await still(prompt, refs, out); } catch (e) {
console.error(`retrying ${path.basename(out)} (${e.message})`);
return still(prompt, refs, out);
}
}));
for (const r of results) console.log(r.status === "fulfilled" ? `ok ${r.value}` : `fail ${r.reason.message}`);
if (results.some((r) => r.status === "rejected")) process.exitCode = 1;
}
const [cmd, dirArg, arg, ...rest] = process.argv.slice(2);
const dir = dirArg && path.resolve(dirArg);
const need = (f) => { if (!fs.existsSync(f)) { console.error(`portrait: missing ${f}`); process.exit(2); } return f; };
if (cmd === "photo") {
if (!arg) throw new Error("usage: portrait.mjs photo <dir> <image url or file>");
fs.mkdirSync(dir, { recursive: true });
const out = path.join(dir, "photo.jpg");
if (/^https?:/i.test(arg)) {
const r = await fetch(arg, { headers: { "user-agent": UA } });
if (!r.ok) throw new Error(`download ${r.status}`);
fs.writeFileSync(out, Buffer.from(await r.arrayBuffer()));
} else fs.copyFileSync(arg, out);
fs.writeFileSync(path.join(dir, "photo-source.txt"), arg + "\n");
console.log(`saved ${out}. Look at it before going on: one real person, face clear and toward the camera.`);
} else if (cmd === "probe") {
H = { "Content-Type": "application/json", Authorization: `Bearer ${key()}` };
console.log("kie.ai credit:", (await (await fetch(`${API}/api/v1/chat/credit`, { headers: H })).json()).data);
} else if (cmd === "base") {
if (!arg) throw new Error('usage: portrait.mjs base <dir> "<who and what they wear>" [--n 2]');
H = { "Content-Type": "application/json", Authorization: `Bearer ${key()}` };
const n = Number(rest[rest.indexOf("--n") + 1]) || 2;
const refs = [need(path.join(dir, "photo.jpg")), need(STYLE_REF)];
await all(Array.from({ length: n }, (_, i) => [`${STYLE} Person: ${arg}`, refs, path.join(dir, `cand${i + 1}.png`)]));
} else if (cmd === "pick") {
fs.copyFileSync(need(path.join(dir, `cand${arg}.png`)), path.join(dir, "base.png"));
console.log(`base.png = cand${arg}.png`);
} else if (cmd === "frames") {
H = { "Content-Type": "application/json", Authorization: `Bearer ${key()}` };
const base = need(path.join(dir, "base.png"));
await all(Object.entries(EDITS).map(([shape, prompt]) => [prompt, [base], path.join(dir, `${shape}.png`)]));
} else {
console.error("usage: portrait.mjs photo|base|pick|frames <dir> ... | probe");
process.exit(1);
}