CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
"""Utilidades compartilhadas pelos scripts da skill cenaforge (só biblioteca padrão)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# .claude/skills/cenaforge/scripts/<arquivo> -> raiz do repositório
|
||||
REPO_ROOT = Path(__file__).resolve().parents[4]
|
||||
RUNS_DIR = REPO_ROOT / "output" / "runs"
|
||||
LAST_SUCCESS = REPO_ROOT / "output" / "last-success.json"
|
||||
|
||||
|
||||
def utf8_stdout() -> None:
|
||||
"""Console do Windows pode vir em cp1252; acentos e '—' quebrariam."""
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except (AttributeError, ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def rel(path: Path) -> str:
|
||||
try:
|
||||
return path.resolve().relative_to(REPO_ROOT).as_posix()
|
||||
except ValueError:
|
||||
return str(path)
|
||||
|
||||
|
||||
def load_json(path: Path) -> dict:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def find_tool(name: str) -> str | None:
|
||||
"""Mesma ordem do lançador: variável de ambiente -> PATH -> .tools/ (só Godot)."""
|
||||
env = {"godot": "GODOT_BIN", "ffmpeg": "FFMPEG_BIN", "ffprobe": "FFPROBE_BIN"}[name]
|
||||
if os.environ.get(env):
|
||||
return os.environ[env] if Path(os.environ[env]).is_file() else None
|
||||
for candidate in ([name, "godot4"] if name == "godot" else [name]):
|
||||
found = shutil.which(candidate)
|
||||
if found:
|
||||
return found
|
||||
if name == "godot":
|
||||
pattern = "Godot_v*-stable_win64.exe" if os.name == "nt" else "Godot_v*-stable_linux.x86_64"
|
||||
for exe in sorted((REPO_ROOT / ".tools").glob(f"godot-*/{pattern}"), reverse=True):
|
||||
return str(exe)
|
||||
return None
|
||||
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Confere um roteiro (.md) e os JSON da história sem LLM: duração, narração, trechos e campos.
|
||||
|
||||
Mesmas regras do leitor de roteiro do painel (panel/src/lib/script-doc.ts):
|
||||
- duração alvo = linha de metadados "Duração: 60 s" (antes do primeiro "##");
|
||||
- trechos = primeira tabela cuja 1ª coluna é o tempo ("t (s)" / "Tempo");
|
||||
- narração lida a 2,5 palavras por segundo (doc/roteiro/comum.md).
|
||||
|
||||
Confere também, na pasta da história: meta.json (title ≤ 60, logline) e *.choices.json
|
||||
(opções ≤ 60 caracteres, distintas).
|
||||
|
||||
Uso:
|
||||
python .claude/skills/cenaforge/scripts/check_script.py stories/<história>/ep01.md
|
||||
python .claude/skills/cenaforge/scripts/check_script.py stories/<história> (todos os ep*.md)
|
||||
Saída: poucas linhas; código 0 = ok, 2 = há avisos, 1 = erro de leitura.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from _common import rel, utf8_stdout
|
||||
|
||||
WORDS_PER_SECOND = 2.5
|
||||
TOLERANCE = 0.15
|
||||
MAX_LABEL = 60
|
||||
WORD = re.compile(r"[^\W_][\w'’-]*", re.UNICODE)
|
||||
|
||||
|
||||
def count_words(text: str) -> int:
|
||||
return len(WORD.findall(re.sub(r"[*_`\"“”]", " ", text)))
|
||||
|
||||
|
||||
def split_row(line: str) -> list[str]:
|
||||
return [c.strip() for c in line.strip().strip("|").split("|")]
|
||||
|
||||
|
||||
def is_separator(line: str) -> bool:
|
||||
return bool(re.match(r"^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$", line))
|
||||
|
||||
|
||||
def parse(markdown: str):
|
||||
lines = markdown.replace("\r\n", "\n").split("\n")
|
||||
meta, body, seen_h2 = [], [], False
|
||||
for line in lines:
|
||||
if line.startswith("## "):
|
||||
seen_h2 = True
|
||||
if not seen_h2 and line.strip() and not line.startswith("# "):
|
||||
meta.append(line.strip())
|
||||
if seen_h2:
|
||||
body.append(line)
|
||||
target = None
|
||||
for part in (p for m in meta for p in re.split(r"\s+·\s+", m)):
|
||||
m = re.match(r"^([^:]{2,40}):\s*(.+)$", part)
|
||||
if m and re.search(r"dura[cç][aã]o", m.group(1), re.I):
|
||||
num = re.search(r"\d+", m.group(2))
|
||||
target = int(num.group()) if num else None
|
||||
shots = []
|
||||
for i, line in enumerate(body):
|
||||
if line.strip().startswith("|") and i + 1 < len(body) and is_separator(body[i + 1]):
|
||||
header = split_row(line)
|
||||
if not re.match(r"^t\b|tempo", header[0] if header else "", re.I):
|
||||
continue
|
||||
col = lambda pattern: next((k for k, h in enumerate(header) if re.search(pattern, h, re.I)), -1)
|
||||
narr, visual = col(r"narra|di[aá]logo|fala"), col(r"imagem|b-?roll|visual")
|
||||
j = i + 2
|
||||
while j < len(body) and body[j].strip().startswith("|"):
|
||||
row = split_row(body[j])
|
||||
nums = [float(n.replace(",", ".")) for n in re.findall(r"\d+(?:[.,]\d+)?", row[0] if row else "")]
|
||||
shots.append({
|
||||
"time": row[0] if row else "",
|
||||
"start": nums[0] if nums else None,
|
||||
"end": nums[1] if len(nums) > 1 else None,
|
||||
"narration": row[narr] if 0 <= narr < len(row) else "",
|
||||
"visual": row[visual] if 0 <= visual < len(row) else "",
|
||||
"has_visual_col": visual >= 0,
|
||||
})
|
||||
j += 1
|
||||
break
|
||||
return target, shots
|
||||
|
||||
|
||||
def check_episode(path: Path) -> list[str]:
|
||||
target, shots = parse(path.read_text(encoding="utf-8"))
|
||||
words = sum(count_words(s["narration"]) for s in shots)
|
||||
spoken = words / WORDS_PER_SECOND
|
||||
warnings: list[str] = []
|
||||
head = f"{rel(path)}: {len(shots)} trechos · narração {words} palavras ≈ {spoken:.0f} s"
|
||||
head += f" · alvo {target} s" if target else " · SEM duração alvo"
|
||||
print(head)
|
||||
if not target:
|
||||
warnings.append("falta a linha 'Duração: <n> s' antes do primeiro '##'")
|
||||
elif abs(spoken - target) > TOLERANCE * target:
|
||||
warnings.append(f"narração ({spoken:.0f} s) foge mais de {TOLERANCE:.0%} do alvo ({target} s)")
|
||||
if not shots:
|
||||
warnings.append("sem tabela de trechos (1ª coluna 't (s)')")
|
||||
previous_end = None
|
||||
for n, shot in enumerate(shots, 1):
|
||||
if shot["start"] is not None and previous_end is not None and abs(shot["start"] - previous_end) > 0.05:
|
||||
warnings.append(f"trecho {n} ({shot['time']}): começa em {shot['start']:g}, o anterior terminou em {previous_end:g}")
|
||||
if shot["start"] is not None and shot["end"] is not None:
|
||||
length = shot["end"] - shot["start"]
|
||||
need = count_words(shot["narration"]) / WORDS_PER_SECOND
|
||||
if length <= 0:
|
||||
warnings.append(f"trecho {n} ({shot['time']}): tempo inválido")
|
||||
elif need > length + 0.5:
|
||||
warnings.append(f"trecho {n} ({shot['time']}): narração pede {need:.1f} s em {length:g} s")
|
||||
if shot["has_visual_col"] and not shot["visual"]:
|
||||
warnings.append(f"trecho {n} ({shot['time']}): coluna Imagem vazia")
|
||||
previous_end = shot["end"] if shot["end"] is not None else previous_end
|
||||
if shots and target and previous_end is not None and abs(previous_end - target) > 1:
|
||||
warnings.append(f"último trecho termina em {previous_end:g} s; alvo {target} s")
|
||||
return warnings
|
||||
|
||||
|
||||
def check_story_json(story_dir: Path) -> list[str]:
|
||||
warnings: list[str] = []
|
||||
meta = story_dir / "meta.json"
|
||||
if meta.is_file():
|
||||
try:
|
||||
data = json.loads(meta.read_text(encoding="utf-8"))
|
||||
title = str(data.get("title") or "")
|
||||
if not title or len(title) > MAX_LABEL:
|
||||
warnings.append(f"meta.json: title vazio ou com mais de {MAX_LABEL} caracteres ({len(title)})")
|
||||
if not str(data.get("logline") or "").strip():
|
||||
warnings.append("meta.json: logline vazia")
|
||||
except json.JSONDecodeError as error:
|
||||
warnings.append(f"meta.json inválido: {error}")
|
||||
for choices in sorted(story_dir.glob("*.choices.json")):
|
||||
try:
|
||||
data = json.loads(choices.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError as error:
|
||||
warnings.append(f"{choices.name} inválido: {error}")
|
||||
continue
|
||||
labels = [str(v).strip() for v in data.values()] if isinstance(data, dict) else []
|
||||
if not labels:
|
||||
warnings.append(f"{choices.name}: esperado objeto {{\"A\": \"...\", \"B\": \"...\"}}")
|
||||
for letter, label in (data.items() if isinstance(data, dict) else []):
|
||||
if not str(label).strip() or len(str(label)) > MAX_LABEL:
|
||||
warnings.append(f"{choices.name}: opção {letter} vazia ou com mais de {MAX_LABEL} caracteres")
|
||||
if len({l.lower() for l in labels}) < len(labels):
|
||||
warnings.append(f"{choices.name}: opções repetidas")
|
||||
return warnings
|
||||
|
||||
|
||||
def main() -> int:
|
||||
utf8_stdout()
|
||||
ap = argparse.ArgumentParser(description="Confere roteiro e JSON da história, sem LLM.")
|
||||
ap.add_argument("target", help="episódio .md ou pasta da história")
|
||||
args = ap.parse_args()
|
||||
target = Path(args.target).resolve()
|
||||
if target.is_dir():
|
||||
story_dir, episodes = target, sorted(target.glob("ep*.md"))
|
||||
elif target.is_file():
|
||||
story_dir, episodes = target.parent, [target]
|
||||
else:
|
||||
print("não encontrado:", args.target)
|
||||
return 1
|
||||
warnings: list[str] = []
|
||||
for episode in episodes:
|
||||
warnings += check_episode(episode)
|
||||
warnings += check_story_json(story_dir)
|
||||
for w in warnings[:20]:
|
||||
print(" AVISO " + w)
|
||||
if len(warnings) > 20:
|
||||
print(f" ... e mais {len(warnings) - 20} avisos")
|
||||
print("ok" if not warnings else f"{len(warnings)} aviso(s)")
|
||||
return 2 if warnings else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Autoverificação da skill cenaforge: caminhos citados existem, comandos pnpm existem e a
|
||||
versão do SKILL.md bate com o topo do CHANGELOG. Sai com 1 se houver problema.
|
||||
|
||||
Uso: python .claude/skills/cenaforge/scripts/check_skill.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from _common import REPO_ROOT, load_json, utf8_stdout
|
||||
|
||||
SKILL = REPO_ROOT / ".claude" / "skills" / "cenaforge"
|
||||
TEMPORARY = {"godot/override.cfg"}
|
||||
ROOTS = ("godot/", "scripts/", "config/", "doc/", ".claude/")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
utf8_stdout()
|
||||
files = [*SKILL.rglob("*.md"), *(REPO_ROOT / ".claude" / "agents").glob("cenaforge-*.md"), REPO_ROOT / "CLAUDE.md"]
|
||||
scripts = load_json(REPO_ROOT / "package.json")["scripts"]
|
||||
problems: list[str] = []
|
||||
for f in files:
|
||||
name = f.relative_to(REPO_ROOT).as_posix()
|
||||
text = f.read_text(encoding="utf-8")
|
||||
for p in re.findall(r"`([^`\s]+)`", text):
|
||||
if not p.startswith(ROOTS) or any(c in p for c in "<*{") or p in TEMPORARY:
|
||||
continue
|
||||
if not (REPO_ROOT / p.split(":")[0]).exists():
|
||||
problems.append(f"{name}: caminho inexistente `{p}`")
|
||||
for link in re.findall(r"\]\(([^)#\s]+)\)", text):
|
||||
if not link.startswith("http") and not (f.parent / link).exists():
|
||||
problems.append(f"{name}: link quebrado ({link})")
|
||||
for cmd in re.findall(r"`pnpm (?:run )?([a-z][a-z:-]*)", text):
|
||||
if cmd not in scripts and cmd not in {"install", "exec"}:
|
||||
problems.append(f"{name}: comando inexistente `pnpm {cmd}`")
|
||||
skill_text = (SKILL / "SKILL.md").read_text(encoding="utf-8")
|
||||
version = re.search(r"Versão da skill: ([\d.]+)", skill_text)
|
||||
top = re.search(r"^## ([\d.]+)", (SKILL / "CHANGELOG.md").read_text(encoding="utf-8"), re.M)
|
||||
if not version or not top or version.group(1) != top.group(1):
|
||||
problems.append(f"versão do SKILL.md ({version and version.group(1)}) diferente do topo do CHANGELOG ({top and top.group(1)})")
|
||||
lines = len(skill_text.splitlines())
|
||||
if lines > 220:
|
||||
problems.append(f"SKILL.md com {lines} linhas (meta: até ~200)")
|
||||
if problems:
|
||||
print("\n".join(problems))
|
||||
return 1
|
||||
print(f"skill ok (versão {version.group(1)}, SKILL.md com {lines} linhas, {len(files)} arquivos conferidos)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Limpa output/runs/: remove execuções com falha ou canceladas e sucessos antigos, mantendo os
|
||||
N mais recentes por (configuração, perfil). Nunca remove a execução de last-success.json.
|
||||
|
||||
Por padrão só MOSTRA o que removeria. Use --apply para apagar.
|
||||
Uso: python .claude/skills/cenaforge/scripts/clean_runs.py [--keep 2] [--apply]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import shutil
|
||||
from collections import defaultdict
|
||||
|
||||
from _common import LAST_SUCCESS, RUNS_DIR, load_json, rel, utf8_stdout
|
||||
|
||||
|
||||
def main() -> int:
|
||||
utf8_stdout()
|
||||
ap = argparse.ArgumentParser(description="Limpa execuções antigas de output/runs/.")
|
||||
ap.add_argument("--keep", type=int, default=2, help="sucessos mantidos por configuração e perfil")
|
||||
ap.add_argument("--apply", action="store_true", help="apaga de fato (sem isto, só simula)")
|
||||
args = ap.parse_args()
|
||||
|
||||
protected = load_json(LAST_SUCCESS).get("runDir") if LAST_SUCCESS.is_file() else None
|
||||
kept: dict[tuple, int] = defaultdict(int)
|
||||
remove: list[tuple] = []
|
||||
for run in sorted((p for p in RUNS_DIR.glob("*") if p.is_dir()), reverse=True):
|
||||
if rel(run) == protected:
|
||||
continue
|
||||
report = run / "report.json"
|
||||
r = load_json(report) if report.is_file() else {}
|
||||
if r.get("status") != "success":
|
||||
remove.append((run, r.get("status", "sem report.json")))
|
||||
continue
|
||||
key = (r.get("configSource"), r.get("profile"))
|
||||
kept[key] += 1
|
||||
if kept[key] > args.keep:
|
||||
remove.append((run, "sucesso antigo"))
|
||||
if not remove:
|
||||
print("nada a remover")
|
||||
return 0
|
||||
for run, why in remove:
|
||||
print(f"{'removido' if args.apply else 'removeria'}: {run.name} ({why})")
|
||||
if args.apply:
|
||||
shutil.rmtree(run)
|
||||
if not args.apply:
|
||||
print("(simulação; use --apply para apagar)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,178 @@
|
||||
#!/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/<execução>
|
||||
python .claude/skills/cenaforge/scripts/frame_check.py --config data/tmp/<id>-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/<execução>)")
|
||||
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())
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Gera doc/godot/api.md: o resumo das peças (godot/kits/) e das cenas da biblioteca (godot/library/).
|
||||
|
||||
Para o agente que constrói cenas ler ~100 linhas de assinaturas em vez de ~1.700 de GDScript.
|
||||
Extrai de cada .gd o cabeçalho "##" do topo e as funções públicas (sem "_") com os "##" logo acima;
|
||||
de cada manifest.json, o rótulo, a descrição e os parâmetros.
|
||||
|
||||
Uso (na raiz do repositório): python .claude/skills/cenaforge/scripts/godot_api.py
|
||||
Rode de novo sempre que uma peça ou cena mudar (o agente da tarefa "Cena no Godot" também roda).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[4]
|
||||
OUT = ROOT / "doc" / "godot" / "api.md"
|
||||
FUNC = re.compile(r"^(static\s+)?func\s+([A-Za-z]\w*)\s*\((.*?)\)\s*(->\s*[\w\[\], ]+)?\s*:")
|
||||
|
||||
|
||||
def summarize_gd(path: Path) -> list[str]:
|
||||
lines = path.read_text(encoding="utf-8").splitlines()
|
||||
out: list[str] = []
|
||||
# Cabeçalho: os "##" do topo (depois de extends/class_name).
|
||||
header: list[str] = []
|
||||
for line in lines[:40]:
|
||||
s = line.strip()
|
||||
if s.startswith("##"):
|
||||
header.append(s[2:].strip())
|
||||
elif header and not s:
|
||||
break
|
||||
elif s and not s.startswith(("extends", "class_name", "@")):
|
||||
if header:
|
||||
break
|
||||
if header:
|
||||
out.append("> " + "\n> ".join(h for h in header if h))
|
||||
funcs: list[str] = []
|
||||
for i, line in enumerate(lines):
|
||||
m = FUNC.match(line)
|
||||
if not m or m.group(2).startswith("_"):
|
||||
continue
|
||||
doc: list[str] = []
|
||||
j = i - 1
|
||||
while j >= 0 and lines[j].strip().startswith("##"):
|
||||
doc.insert(0, lines[j].strip()[2:].strip())
|
||||
j -= 1
|
||||
sig = f"{'static ' if m.group(1) else ''}{m.group(2)}({m.group(3)}){(' ' + m.group(4).strip()) if m.group(4) else ''}"
|
||||
funcs.append(f"- `{sig}`" + (f": {' '.join(doc)}" if doc else ""))
|
||||
if funcs:
|
||||
out.append("")
|
||||
out.extend(funcs)
|
||||
return out
|
||||
|
||||
|
||||
def summarize_manifest(path: Path) -> list[str]:
|
||||
try:
|
||||
m = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as e:
|
||||
return [f"- manifest.json ilegível: {e}"]
|
||||
out = [f"**{m.get('label', path.parent.name)}** ({m.get('kind', 'doc3d')}): {m.get('description', '')}"]
|
||||
for p in m.get("params", []):
|
||||
if p.get("type") == "select":
|
||||
opts = ", ".join(str(o.get("value")) for o in p.get("options", []))
|
||||
out.append(f"- param `{p.get('name')}` (select: {opts}; padrão {p.get('default')!r})")
|
||||
else:
|
||||
out.append(f"- param `{p.get('name')}` ({p.get('type')}; padrão {p.get('default')!r})")
|
||||
return out
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parts = [
|
||||
"# API das peças e cenas do Godot (gerado)",
|
||||
"",
|
||||
"Gerado por `python .claude/skills/cenaforge/scripts/godot_api.py`. Não edite à mão: rode de novo",
|
||||
"quando uma peça ou cena mudar. Use estas funções sem abrir os .gd inteiros.",
|
||||
"",
|
||||
"## Peças (`godot/kits/`, use com `preload(\"res://kits/<arquivo>.gd\")`)",
|
||||
]
|
||||
for gd in sorted((ROOT / "godot" / "kits").glob("*.gd")):
|
||||
parts += ["", f"### `{gd.relative_to(ROOT).as_posix()}`", *summarize_gd(gd)]
|
||||
parts += ["", "## Cenas da biblioteca (`godot/library/<id>/`)"]
|
||||
for scene in sorted(p for p in (ROOT / "godot" / "library").iterdir() if p.is_dir()):
|
||||
parts += ["", f"### `{scene.name}`"]
|
||||
manifest = scene / "manifest.json"
|
||||
if manifest.exists():
|
||||
parts += summarize_manifest(manifest)
|
||||
for gd in sorted(scene.glob("*.gd")):
|
||||
summary = summarize_gd(gd)
|
||||
if summary:
|
||||
parts += ["", f"`{gd.relative_to(ROOT).as_posix()}`", *summary]
|
||||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
OUT.write_text("\n".join(parts) + "\n", encoding="utf-8")
|
||||
print(f"{OUT.relative_to(ROOT).as_posix()}: {len(parts)} linhas")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Gera uma tira com 1 quadro por segundo de um MP4 (qualquer FPS e duração).
|
||||
|
||||
Economiza tokens: o agente lê UMA imagem em vez de vários quadros soltos.
|
||||
Saída: <pasta da execução>/inspect/strip.png (ou ao lado do MP4).
|
||||
|
||||
Uso:
|
||||
python .claude/skills/cenaforge/scripts/inspect_strip.py output/runs/<execução>
|
||||
python .claude/skills/cenaforge/scripts/inspect_strip.py video.mp4 --width 160
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from _common import find_tool, rel, utf8_stdout
|
||||
|
||||
|
||||
def main() -> int:
|
||||
utf8_stdout()
|
||||
ap = argparse.ArgumentParser(description="Tira de 1 quadro por segundo de um MP4.")
|
||||
ap.add_argument("target", help="pasta de execução ou arquivo .mp4")
|
||||
ap.add_argument("--width", type=int, default=180, help="largura de cada quadro na tira")
|
||||
ap.add_argument("--cols", type=int, default=7)
|
||||
args = ap.parse_args()
|
||||
|
||||
target = Path(args.target).resolve()
|
||||
if target.is_dir():
|
||||
mp4s = sorted(target.glob("*.mp4"))
|
||||
if not mp4s:
|
||||
print("nenhum .mp4 em", rel(target))
|
||||
return 1
|
||||
mp4, out_dir = mp4s[0], target / "inspect"
|
||||
else:
|
||||
mp4, out_dir = target, target.parent
|
||||
ffmpeg, ffprobe = find_tool("ffmpeg"), find_tool("ffprobe")
|
||||
if not ffmpeg or not ffprobe:
|
||||
print("ffmpeg/ffprobe não encontrados (PATH ou FFMPEG_BIN/FFPROBE_BIN)")
|
||||
return 1
|
||||
|
||||
probe = subprocess.run(
|
||||
[ffprobe, "-v", "error", "-select_streams", "v:0", "-count_frames",
|
||||
"-show_entries", "stream=r_frame_rate,nb_read_frames", "-of", "json", str(mp4)],
|
||||
capture_output=True, text=True)
|
||||
if probe.returncode != 0:
|
||||
print("ffprobe falhou:", probe.stderr.strip()[-300:])
|
||||
return 1
|
||||
stream = json.loads(probe.stdout)["streams"][0]
|
||||
num, den = (int(x) for x in stream["r_frame_rate"].split("/"))
|
||||
fps = round(num / den)
|
||||
count = math.ceil(int(stream["nb_read_frames"]) / fps)
|
||||
cols = min(args.cols, count)
|
||||
rows = math.ceil(count / cols)
|
||||
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
out = out_dir / "strip.png"
|
||||
vf = f"select='not(mod(n\\,{fps}))',scale={args.width}:-1,tile={cols}x{rows}"
|
||||
r = subprocess.run([ffmpeg, "-hide_banner", "-loglevel", "error", "-y", "-i", str(mp4),
|
||||
"-vf", vf, "-frames:v", "1", "-fps_mode", "vfr", str(out)],
|
||||
capture_output=True, text=True)
|
||||
if r.returncode != 0:
|
||||
print("ffmpeg falhou:", r.stderr.strip()[-300:])
|
||||
return 1
|
||||
print(f"{rel(out)} ({count} quadros, 0..{count - 1} s, grade {cols}x{rows}, {fps} FPS)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Cria config/<id>.json a partir de uma cena base, com alterações por caminho, e valida na Godot.
|
||||
|
||||
Economiza tokens: o agente não lê nem reescreve o JSON inteiro para mudar poucos campos.
|
||||
|
||||
Uso:
|
||||
python .claude/skills/cenaforge/scripts/new_scene.py --id ep01-cena02 \\
|
||||
--set overlay.title="Um pacote sem remetente." --set rider.travelMeters=36 \\
|
||||
--set camera.offset=[1.2,2.8,5.6]
|
||||
Opções: --base (padrão config/demo-street.json), --force (sobrescreve), --no-validate.
|
||||
Valores são lidos como JSON quando possível (números, listas, true, null); senão, como texto.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from _common import REPO_ROOT, find_tool, load_json, rel, utf8_stdout
|
||||
|
||||
|
||||
def parse_value(raw: str):
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return raw
|
||||
|
||||
|
||||
def main() -> int:
|
||||
utf8_stdout()
|
||||
ap = argparse.ArgumentParser(description="Cria uma cena nova a partir de outra.")
|
||||
ap.add_argument("--id", required=True)
|
||||
ap.add_argument("--base", default="config/demo-street.json")
|
||||
ap.add_argument("--set", action="append", default=[], metavar="caminho=valor")
|
||||
ap.add_argument("--force", action="store_true")
|
||||
ap.add_argument("--no-validate", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,63}", args.id):
|
||||
print("id inválido: use minúsculas, números, '-' e '_'")
|
||||
return 2
|
||||
base = Path(args.base) if Path(args.base).is_absolute() else REPO_ROOT / args.base
|
||||
scene = load_json(base)
|
||||
scene["id"] = args.id
|
||||
for item in args.set:
|
||||
if "=" not in item:
|
||||
print(f"--set sem '=': {item}")
|
||||
return 2
|
||||
path, raw = item.split("=", 1)
|
||||
keys = path.split(".")
|
||||
node = scene
|
||||
for k in keys[:-1]:
|
||||
if not isinstance(node.get(k), dict):
|
||||
print(f"caminho inexistente na cena base: {path}")
|
||||
return 2
|
||||
node = node[k]
|
||||
node[keys[-1]] = parse_value(raw)
|
||||
|
||||
out = REPO_ROOT / "config" / f"{args.id}.json"
|
||||
if out.exists() and not args.force:
|
||||
print(f"{rel(out)} já existe (use --force)")
|
||||
return 2
|
||||
text = json.dumps(scene, ensure_ascii=False, indent=2)
|
||||
# Vetores [x, y, z] numa linha só, como nos exemplos do projeto.
|
||||
text = re.sub(r"\[\s*([-\d.eE]+),\s*([-\d.eE]+),\s*([-\d.eE]+)\s*\]", r"[\1, \2, \3]", text)
|
||||
out.write_text(text + "\n", encoding="utf-8", newline="\n")
|
||||
print("criado", rel(out))
|
||||
|
||||
if args.no_validate:
|
||||
return 0
|
||||
godot = find_tool("godot")
|
||||
if not godot:
|
||||
print("Godot não encontrada; validação pulada (pnpm render valida antes de renderizar)")
|
||||
return 0
|
||||
r = subprocess.run([godot, "--headless", "--path", str(REPO_ROOT / "godot"), "--",
|
||||
"--config", str(out), "--validate-only"],
|
||||
capture_output=True, text=True, encoding="utf-8", errors="replace")
|
||||
lines = [l for l in (r.stdout + r.stderr).splitlines() if l.startswith(("CONFIG_", " - "))]
|
||||
print("\n".join(lines) or f"validação saiu com código {r.returncode}")
|
||||
return 0 if r.returncode == 0 else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Resumo compacto das execuções em output/runs/.
|
||||
|
||||
Economiza tokens: em vez de ler report.json/render.log inteiros, imprime uma linha por
|
||||
execução com status, perfil, verificações, tempos e digest.
|
||||
|
||||
Uso:
|
||||
python .claude/skills/cenaforge/scripts/runs_summary.py # últimas 10
|
||||
python .claude/skills/cenaforge/scripts/runs_summary.py --last 3 --details
|
||||
python .claude/skills/cenaforge/scripts/runs_summary.py --run <pasta> --details
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
from _common import LAST_SUCCESS, RUNS_DIR, load_json, rel, utf8_stdout
|
||||
|
||||
|
||||
def main() -> int:
|
||||
utf8_stdout()
|
||||
ap = argparse.ArgumentParser(description="Resumo compacto das execuções de render.")
|
||||
ap.add_argument("--last", type=int, default=10, help="quantas execuções mostrar (mais novas)")
|
||||
ap.add_argument("--run", help="uma pasta de execução específica")
|
||||
ap.add_argument("--details", action="store_true", help="falhas, avisos, MP4 e imagem de inspeção")
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.run:
|
||||
runs = [Path(args.run).resolve()]
|
||||
else:
|
||||
runs = sorted((p for p in RUNS_DIR.glob("*") if (p / "report.json").is_file()), reverse=True)[: args.last]
|
||||
if not runs:
|
||||
print("nenhuma execução encontrada em", rel(RUNS_DIR))
|
||||
return 1
|
||||
|
||||
last_ok = load_json(LAST_SUCCESS).get("runDir") if LAST_SUCCESS.is_file() else None
|
||||
print("status perfil total_s godot_s checks digest execução")
|
||||
for run in runs:
|
||||
r = load_json(run / "report.json")
|
||||
checks = r.get("checks", [])
|
||||
failed = [c for c in checks if not c.get("ok")]
|
||||
t = r.get("timingsSeconds", {})
|
||||
digest = ((r.get("godot") or {}).get("stateDigest") or "-")[:8]
|
||||
mark = " *" if last_ok and rel(run) == last_ok else ""
|
||||
print(f"{r.get('status', '?'):9} {r.get('profile', '?'):8} {t.get('total', '-'):>8} {t.get('godotRender', '-'):>8}"
|
||||
f" {len(checks) - len(failed):>2}/{len(checks):<3} {digest:9} {run.name}{mark}")
|
||||
if args.details:
|
||||
if r.get("error"):
|
||||
print(f" erro ({r.get('failedStage')}): {r['error'].splitlines()[0]}")
|
||||
for c in failed:
|
||||
print(f" FALHA {c['name']}: {c['detail']}")
|
||||
for w in r.get("warnings", []):
|
||||
print(f" AVISO {w}")
|
||||
if r.get("mp4"):
|
||||
print(f" mp4: {r['mp4']}")
|
||||
if r.get("inspection"):
|
||||
print(f" inspeção: {r['inspection'][-1]}")
|
||||
if last_ok:
|
||||
print("* = output/last-success.json")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user