#!/usr/bin/env python3 """Build a byte-accurate, derived index for a short-drama Markdown screenplay. The indexer recognizes only the screenplay grammar documented by the write skill. It never rewrites the screenplay and never guesses through a split/merge revision. """ from __future__ import annotations import argparse import json import os import re import sys import tempfile from collections import defaultdict from pathlib import Path from typing import Any, NamedTuple # Creators run these scripts on whatever interpreter their machine provides, so # an unsupported version must say so instead of failing inside an import. MINIMUM_PYTHON = (3, 9) if sys.version_info < MINIMUM_PYTHON: raise SystemExit( "short-drama needs Python {}.{} or newer; this interpreter is {}.{}".format( *MINIMUM_PYTHON, sys.version_info.major, sys.version_info.minor ) ) # --------------------------------------------------------------------------- # REFERENCE RESOLVER -- reference implementation. # # Each skill checker carries its own copy of this block. The suite has no shared # library on purpose: a skill must stay runnable after copying only its own # directory, so duplicating these few lines across skills is the correct shape. # Copy the block verbatim; do not import it. # --------------------------------------------------------------------------- SOURCES_RECORD_TYPE = "sources" SOURCES_SCHEMA_VERSION = "1.0.0" SOURCES_KEY = "sources" class ResolvedRef(NamedTuple): """An upstream reference with its snapshot resolved, whichever form it used.""" owner: str artifact: str record_id: str | None field: str | None authority: str | None class RefFinding(NamedTuple): """A structural defect in a reference object.""" code: str location: str detail: str def load_sources(document: Any) -> dict[str, dict[str, Any]]: """Return the ``sources`` declaration of a parsed file, or ``{}`` if absent. Accepts a parsed ``.json`` document (a dict) or the parsed record list of a ``.jsonl`` file, whose declaration lives on the first record. """ if isinstance(document, list): document = document[0] if document else None if not isinstance(document, dict): return {} declared = document.get("sources") if not isinstance(declared, dict): return {} return {key: value for key, value in declared.items() if isinstance(value, dict)} def resolve_ref( ref: Any, sources: dict[str, dict[str, Any]], location: str ) -> tuple[ResolvedRef | None, RefFinding | None]: """Resolve a reference object written in either the compact or expanded form.""" if not isinstance(ref, dict): return None, RefFinding("REF_IS_NOT_AN_OBJECT", location, f"got {type(ref).__name__}") src = ref.get("src") if isinstance(src, str): entry = sources.get(src) if entry is None: return None, RefFinding( "REF_SRC_IS_NOT_DECLARED", location, f"src {src!r} has no sources entry" ) owner, artifact = entry.get("owner"), entry.get("artifact") if not (isinstance(owner, str) and isinstance(artifact, str)): return None, RefFinding( "SOURCE_ENTRY_IS_INCOMPLETE", location, f"sources[{src!r}] needs owner/artifact", ) elif all(isinstance(ref.get(key), str) for key in ("owner", "artifact")): owner, artifact = ref["owner"], ref["artifact"] else: return None, RefFinding( "REF_HAS_NO_UPSTREAM_BINDING", location, "needs src, or owner+artifact" ) optional = { key: ref[key] for key in ("record_id", "field", "authority") if isinstance(ref.get(key), str) } return ( ResolvedRef( owner, artifact, optional.get("record_id"), optional.get("field"), optional.get("authority"), ), None, ) # --------------------------------------------------------------------------- # END REFERENCE RESOLVER # --------------------------------------------------------------------------- SCHEMA_VERSION = "1.0.0" # An index declares its upstream screenplay once, on the meta record, and every # reference in the file names it by key. A rebuild against a previous index adds # a second key only when the previous screenplay is a different snapshot. SCREENPLAY_SOURCE_KEY = "screenplay" PREVIOUS_SCREENPLAY_SOURCE_KEY = "previous-screenplay" SUPPORTED_TAGS = ("VO", "OS", "SFX", "画面文字", "连续性", "转场") KIND_CODES = { "scene_heading": "H", "action": "A", "dialogue": "D", "production_tag": "P", "comment": "C", "code_fence": "F", } # Three digits through EP999, then unpadded — the same single spelling per # episode number the lifecycle tool enforces on `episodes//`. A fixed three # digits would have made EP1000 a legal directory but an illegal heading. _EPISODE = r"EP(?:[0-9]{3}|[1-9][0-9]{3,})" _SCENE = r"SC(?:[0-9]{3}|[1-9][0-9]{3,})" _WS = r"[ \t\u3000]" EPISODE_HEADING_RE = re.compile( rf"^#{_WS}+(?P{_EPISODE})" rf"(?![0-9])(?!{_WS}*(?:——|[·::–—-])?{_WS}*SC[0-9])" rf"(?:{_WS}*(?:——|[·::–—-])(?:{_WS}*.+)?|{_WS}+.+)?$" ) # A project that scopes ids by season writes `S01-EP001-SC001`; the episode is # still the `EP` segment, and the cross-document checker accepts the same form. # Whitespace around `·` is optional so `内·客厅·夜` and `内 · 客厅 · 夜` both # parse instead of silently dropping the scene's blocks. SCENE_HEADING_RE = re.compile( rf"^##{_WS}+(?P(?:[A-Za-z0-9]+-)*?(?P{_EPISODE})-{_SCENE})" rf"(?:{_WS}+|{_WS}*·{_WS}*)" rf"(?P内外|内|外){_WS}*·{_WS}*(?P[^\s·](?:.*?[^\s·])?){_WS}*·{_WS}*" r"(?P