#!/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//ep01.md python .claude/skills/cenaforge/scripts/check_script.py stories/ (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: 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())