#!/usr/bin/env python3 """Confere um render sem abrir imagens: resume o log e mede cada quadro de inspeção. Economiza tokens: o agente lê ~10 linhas de texto e só abre UMA imagem (a folha de 480 px) quando o veredito pede; um quadro solto só quando a linha dele vier marcada. Mede em cada `inspect/t*.png`: - luminância média (0–1): ESCURO < 0,08, ESTOURADO > 0,92; - contraste (desvio padrão da luminância): CHAPADO < 0,04 (céu/chão liso, câmera no vazio); - movimento em relação ao quadro anterior: PARADO quando nada muda entre os instantes; - enquadramento: caixa e centro do "detalhe" (bordas). FORA quando o centro do detalhe foge mais de 30% do centro, ou quando a caixa encosta numa borda e ocupa < 15% da altura. Uso: python .claude/skills/cenaforge/scripts/frame_check.py output/runs/ python .claude/skills/cenaforge/scripts/frame_check.py --config data/tmp/-teste.json (renderiza o perfil preview e confere em seguida; --profile para outro perfil) python .claude/skills/cenaforge/scripts/frame_check.py --last (último render do disco) """ from __future__ import annotations import argparse import os import re import subprocess from pathlib import Path from _common import REPO_ROOT, RUNS_DIR, load_json, rel, utf8_stdout DARK, BRIGHT, FLAT, STILL, OFF_CENTER = 0.08, 0.92, 0.04, 0.004, 0.30 LOG_TAIL = 15 def run_render(config: str, profile: str) -> tuple[Path | None, int]: """Roda o lançador e devolve a pasta da execução. Só imprime o fim do log se falhar.""" pnpm = "pnpm.cmd" if os.name == "nt" else "pnpm" cmd = [pnpm, "render", "--", "--config", config, "--profile", profile] proc = subprocess.run(cmd, cwd=REPO_ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace") output = (proc.stdout or "") + (proc.stderr or "") match = re.search(r"->\s*(output[\\/]runs[\\/][^\s]+)", output) run_dir = (REPO_ROOT / match.group(1)).resolve() if match else None if proc.returncode != 0: lines = [l for l in output.splitlines() if l.strip()] print(f"render FALHOU (código {proc.returncode}). Últimas {LOG_TAIL} linhas do log:") for line in lines[-LOG_TAIL:]: print(" " + line[:220]) return run_dir, proc.returncode def summarize_report(run_dir: Path) -> bool: report_path = run_dir / "report.json" if not report_path.is_file(): print("sem report.json em", rel(run_dir)) return False report = load_json(report_path) timings = report.get("timingsSeconds") or {} video = report.get("video") or report.get("output") or {} size = f"{video.get('width', '?')}x{video.get('height', '?')}" if isinstance(video, dict) else "?" print(f"status {report.get('status')} · {rel(run_dir)} · {size} · total {timings.get('total', '?')} s" f" (godot {timings.get('godotRender', '-')} s)") failed = [c for c in report.get("checks") or [] if not c.get("ok")] for check in failed[:8]: print(f" FALHA {check.get('name')} — {check.get('detail')}") for warning in (report.get("warnings") or [])[:5]: print(f" AVISO {warning}") if report.get("error"): print(f" erro na etapa {report.get('failedStage')}: {str(report['error'])[:300]}") return report.get("status") == "success" def frame_stats(image, previous): from PIL import ImageChops, ImageFilter, ImageStat gray = image.convert("L") stat = ImageStat.Stat(gray) mean, std = stat.mean[0] / 255, stat.stddev[0] / 255 edges = gray.filter(ImageFilter.FIND_EDGES).point(lambda v: 255 if v > 40 else 0) # Ignora 2 px da borda (o filtro marca a moldura). w, h = edges.size edges = edges.crop((2, 2, w - 2, h - 2)) box = edges.getbbox() centroid = None if box: small = edges.resize((64, 64)) data = small.tobytes() total = sum(data) or 1 cx = sum((i % 64) * v for i, v in enumerate(data)) / total / 63 cy = sum((i // 64) * v for i, v in enumerate(data)) / total / 63 centroid = (cx, cy) motion = None if previous is not None: diff = ImageChops.difference(gray.resize((135, 240)), previous.resize((135, 240))) motion = ImageStat.Stat(diff).mean[0] / 255 return gray, mean, std, box, (w - 4, h - 4), centroid, motion def check_frames(run_dir: Path) -> int: try: from PIL import Image except ImportError: print("PIL não instalado: sem métricas de quadro. Abra só inspect/contact-sheet.png.") return 0 frames = sorted((run_dir / "inspect").glob("t*.png")) if not frames: print("sem quadros em inspect/ (render falhou antes da etapa 6?)") return 1 flagged: list[str] = [] previous = None for frame in frames: with Image.open(frame) as img: gray, mean, std, box, (w, h), centroid, motion = frame_stats(img, previous) previous = gray tags = [] if mean < DARK: tags.append("ESCURO") if mean > BRIGHT: tags.append("ESTOURADO") if std < FLAT: tags.append("CHAPADO") if motion is not None and motion < STILL: tags.append("PARADO") framing = "sem detalhe" if box and centroid: x0, y0, x1, y1 = box framing = (f"detalhe x {x0 / w:.0%}–{x1 / w:.0%} y {y0 / h:.0%}–{y1 / h:.0%}" f" centro ({centroid[0]:.2f},{centroid[1]:.2f})") touches = x0 <= 1 or y0 <= 1 or x1 >= w - 1 or y1 >= h - 1 if max(abs(centroid[0] - 0.5), abs(centroid[1] - 0.5)) > OFF_CENTER or (touches and (y1 - y0) / h < 0.15): tags.append("FORA") elif std >= FLAT: tags.append("FORA") move = f" mov {motion:.3f}" if motion is not None else "" verdict = " ".join(tags) or "ok" print(f" {frame.stem:>7}: luz {mean:.2f} contraste {std:.2f}{move} · {framing} · {verdict}") if tags: flagged.append(frame.name) sheet = run_dir / "inspect" / "contact-sheet.png" if flagged: print(f"ATENÇÃO em {len(flagged)} quadro(s). Abra só: {rel(run_dir / 'inspect' / flagged[0])}" + (f" (e os demais marcados se precisar: {', '.join(flagged[1:])})" if len(flagged) > 1 else "")) return 2 print(f"métricas ok. Para a revisão visual abra só UMA imagem: {rel(sheet) if sheet.is_file() else rel(frames[0])}") return 0 def main() -> int: utf8_stdout() ap = argparse.ArgumentParser(description="Resumo do render e métricas dos quadros, sem LLM.") ap.add_argument("run", nargs="?", help="pasta da execução (output/runs/)") ap.add_argument("--config", help="renderiza esta cena antes de conferir") ap.add_argument("--profile", default="preview") ap.add_argument("--last", action="store_true", help="usa a execução mais recente de output/runs/") args = ap.parse_args() if args.config: run_dir, code = run_render(args.config, args.profile) if run_dir is None: print("não achei a pasta da execução na saída do render") return code or 1 elif args.last: runs = sorted((p for p in RUNS_DIR.iterdir() if p.is_dir()), key=lambda p: p.name) if RUNS_DIR.is_dir() else [] if not runs: print("nenhuma execução em", rel(RUNS_DIR)) return 1 run_dir = runs[-1] elif args.run: run_dir = Path(args.run).resolve() else: ap.error("informe a pasta da execução, --config ou --last") return 1 ok = summarize_report(run_dir) result = check_frames(run_dir) return result if ok else 1 if __name__ == "__main__": raise SystemExit(main())