#!/usr/bin/env python3 """Estimate how long a screenplay runs, using the project's own declared rates. This reports a number; it never judges one. The suite carries no cross-project speech rate and no tolerance band, because a 90-second episode of dense argument and a 90-second episode of silent work do not convert at the same ratio. The creator declares the two rates their project actually uses, and this script applies them. Without declared rates the script still counts dialogue characters and action paragraphs -- those counts are facts about the text -- and says the seconds cannot be derived yet. That is the honest output, not a guess from a default. What counts as a line and what counts as a paragraph is decided by the ``screenplay_index`` parser, never by a separate ad-hoc grammar here. In ``--script`` mode this script parses ``剧本.md`` directly in memory through ``screenplay_index`` (auto-discovering speakers or honoring ``人物:`` / ``--extra-speaker`` / ``--speaker``), and in ``--index`` mode it reads a prebuilt ``screenplay-index.jsonl`` (and also honors ``--speaker`` / ``--extra-speaker`` speaker overrides after verifying the index matches the screenplay bytes). Sharing the single parser keeps ``[VO]``/``[OS]`` lines, Markdown comments, fenced code blocks, colon-bearing action prose, and multi-line action paragraphs classified identically across estimation and indexing. """ from __future__ import annotations import argparse import importlib.util import json import math import re import sys import unicodedata from pathlib import Path from types import ModuleType from typing import Any, Iterable, Mapping # 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 ) ) # [VO] and [OS] are spoken off-camera. The format contract writes them as # ``[VO] 角色:台词`` -- a real line. Timing them at zero silently shortens every # episode that carries its interiority in voice-over, and the estimate then reads # as a deficit the writer pads to fill. VOICED_TAGS = {"VO", "OS"} VOICE_TAG_PREFIX = re.compile(r"^\[(?:VO|OS)\]\s*") MAX_SPEAKER_LENGTH = 40 _WS = r"[ \t\u3000]" _SPEAKER_TOKEN = r"[^\s::()()\[\]#,。!?;,!?;—]+" _SPEAKER_LABEL = ( rf"(?=.{{1,{MAX_SPEAKER_LENGTH}}}(?:{_WS}*[((]|:|:))" rf"{_SPEAKER_TOKEN}(?: {_SPEAKER_TOKEN}){{0,3}}" ) # ``角色(提示):台词`` or ``Dr. Lin (quietly): ...`` -- the speaker label may # carry a parenthesised direction in full-width or ASCII parens. Only the # spoken half is timed; the direction is a note to the performer. _NOT_CLOCK_PREFIX = r"(?!\d{1,2}[::]\d{2}(?:\D|$))" _NOT_URL_PREFIX = r"(?![A-Za-z][A-Za-z0-9+.-]*://)(?!(?:https?|ftp|mailto|file|ws|wss):(?://|\s|$))" _HTML_COMMENT_RE = re.compile(r"") DIALOGUE = re.compile( rf"^{_NOT_CLOCK_PREFIX}{_NOT_URL_PREFIX}(?P{_SPEAKER_LABEL})" rf"(?:{_WS}*(?:([^()\r\n]*)|\([^()\r\n]*\)))?(?P[::]){_WS}*(?P\S[\s\S]*)$" ) _SCREENPLAY_INDEX_MODULE: ModuleType | None = None def _load_screenplay_index() -> ModuleType: global _SCREENPLAY_INDEX_MODULE if _SCREENPLAY_INDEX_MODULE is not None: return _SCREENPLAY_INDEX_MODULE script_path = Path(__file__).resolve().with_name("screenplay_index.py") spec = importlib.util.spec_from_file_location( "_short_drama_write_screenplay_index", script_path ) if spec is None or spec.loader is None: raise RuntimeError(f"cannot load screenplay_index.py from {script_path}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) _SCREENPLAY_INDEX_MODULE = module return module CAST_LINE_RE = re.compile( rf"^{_WS}*(?:[-*+]{_WS}+)?(?:" rf"人物{_WS}*[::]" rf"|\*\*\*人物(?:{_WS}*\*\*\*{_WS}*[::]|{_WS}*[::]{_WS}*\*\*\*)" rf"|___人物(?:{_WS}*___{_WS}*[::]|{_WS}*[::]{_WS}*___)" rf"|\*\*人物(?:{_WS}*\*\*{_WS}*[::]|{_WS}*[::]{_WS}*\*\*)" rf"|__人物(?:{_WS}*__{_WS}*[::]|{_WS}*[::]{_WS}*__)" rf"|\*人物(?:{_WS}*\*{_WS}*[::]|{_WS}*[::]{_WS}*\*)" rf"|_人物(?:{_WS}*_{_WS}*[::]|{_WS}*[::]{_WS}*_)" rf"){_WS}*(?P.*)$" ) CLOCK_PREFIX_RE = re.compile(r"^\d{1,2}[::]\d{2}(?=\D|$)") URL_SCHEME_NON_SPEAKER_RE = re.compile( r"^(?:https?|ftp|mailto|file|ws|wss)$", re.IGNORECASE ) PANEL_OR_UNIT_LABEL_RE = re.compile( r"^第[一二三四五六七八九十百千万零〇两\d]+[格幕场镜回章集节拍]$" ) ACTION_PROSE_MARKER_RE = re.compile( r"^(?:[他她它](?:们)?|[我你]们|这(?:里|边|儿|个|行|张|份|句|段|块|台|扇|道|声|下|时|一刻)?|" r"那(?:里|边|儿|个|头|行|张|份|句|段|块|台|扇|道|声|下|时|一刻)).+" r"|(?:写下|写着|写道|写有|写明|印着|印有|刻着|刻有|贴着|标着|标明|" r"显示|弹出|跳出|浮现|亮起|亮出|映出|注明|" r"看到|看见|看清|看向|盯着|望着|瞥见|瞧见|" r"听到|听见|传来|响起|" r"走到|走向|走近|转身|转头|回头|抬头|低头|伸手|抬手|" r"拿起|拿出|握住|按下|推开|拉开|打开|翻开|掀开|" r"意思是|内容是|内容为|如下所示)" ) NUMERIC_NON_SPEAKER_RE = re.compile( r"^(?:[00]+|[1-91-9]\d*)$" r"|\d+\s*(?:年|月|日|点|时|分|秒|分钟|小时|天|周|星期|礼拜|个|名|位|条|行|句|页|张|份|次|遍|轮|集|场|幕|镜|格|拍|步|章|节|元|块|万|亿|%|%)" ) DISQUALIFYING_SPEAKER_PUNCT_RE = re.compile( r"[,。!?;、,;!?”“’‘\"—…《》<>\[\]【】]" ) SPEAKER_PARTICLE_RE = re.compile(r"[的了着过]") def _declared_script_speakers( lines: list[dict[str, Any]], ) -> tuple[bool, set[str]]: idx = _load_screenplay_index() declared: tuple[bool, set[str]] = idx._declared_script_speakers(lines) return declared def _is_latin_speaker_phrase(name: str) -> bool: tokens = name.split() if not (1 <= len(tokens) <= 4 and len(name) <= MAX_SPEAKER_LENGTH): return False has_latin = False for character in name: if character.isspace() or character in ".-'’" or ( character.isascii() and character.isdigit() ): continue if character.isalpha() and "LATIN" in unicodedata.name(character, ""): has_latin = True continue return False return has_latin def _is_plausible_auto_speaker(candidate: str, occurrences: int) -> bool: name = " ".join(candidate.split()) if not name or len(name) > MAX_SPEAKER_LENGTH or name.startswith(("[", "【")): return False if URL_SCHEME_NON_SPEAKER_RE.fullmatch(name) is not None: return False if PANEL_OR_UNIT_LABEL_RE.fullmatch(name) is not None: return False if NUMERIC_NON_SPEAKER_RE.search(name) is not None: return False if DISQUALIFYING_SPEAKER_PUNCT_RE.search(name) is not None: return False if ACTION_PROSE_MARKER_RE.search(name) is not None: return False if occurrences >= 2: return True if _is_latin_speaker_phrase(name): return True clean_chars = re.sub(r"[\s.\-·・]", "", name) return ( 1 <= len(clean_chars) <= 6 and SPEAKER_PARTICLE_RE.search(name) is None ) def _discover_script_speakers(idx: ModuleType, screenplay: bytes) -> frozenset[str]: screenplay.decode("utf-8") lines = idx._line_table(screenplay) has_cast_line, cast_speakers = _declared_script_speakers(lines) if has_cast_line: return frozenset(cast_speakers) counts: dict[str, int] = {} fw_or_voice_counts: dict[str, int] = {} episode_id: str | None = None scene_id: str | None = None seen_scene_heading = False at_scene_head = False cursor = 0 while cursor < len(lines): raw_text = lines[cursor]["text"] stripped = raw_text.strip() if not stripped: cursor += 1 continue if stripped.startswith("