diff --git a/.claude/settings.json b/.claude/settings.json index 49da0e9..c94ccb3 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -6,7 +6,7 @@ "hooks": [ { "type": "command", - "command": "uv run --quiet ruff format --quiet src tests 2>/dev/null || true" + "command": "uv run --quiet ruff format --quiet tests 2>/dev/null || true" } ] } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1c86571..c5c42e6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,6 +11,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + # TODO: pyproject.toml points to a local vnpipe checkout (absolute path). CI needs vnpipe + # available at that path (e.g. an extra checkout step for the vnpipe repo) before `uv sync`. - uses: astral-sh/setup-uv@v5 - run: uv sync --locked - name: Lint diff --git a/docs/annotation.md b/docs/annotation.md deleted file mode 100644 index 640a61f..0000000 --- a/docs/annotation.md +++ /dev/null @@ -1,70 +0,0 @@ -# Annotation stage - -Turns `data/parsed.json` into `data/annotated.json`: every parsed line gets an `ann` block -(emotion, who is on stage and where, music). Judgement calls are made by LLM sub-agents; -`vnpipe annotate` only prepares their input, checks their output and merges it. - -``` -parsed.json ──chunk──▶ annotations/chunks/.json (annotator input) - sub-agent ──────────▶ annotations/cache/.json (annotator output) - ──merge──▶ data/annotated.json -``` - -## Chunks - -- Id `_cNN`. A chunk never crosses a scene and holds at most 60 lines. Splits - prefer speech boundaries, then stanza boundaries, and only then cut mid-stanza. -- `input_sha256` is the SHA-256 of the canonical JSON of the chunk without that field. It - includes `prompt_version` (SHA-256 of `src/vnpipe/prompts/annotate.md`), so editing the - prompt, the text, `work.toml` scenes/cast or the schema enums invalidates the cache. -- Contents: `scene`, `allowed` (speakers, characters, locations, emotions, positions, - music), `context_before` (up to 6 preceding lines, read-only) and `lines`, each with a - `defaults` block that is deterministic and must be copied verbatim: - - verse with a speaker: `dialogue` / that speaker; - - verse without speaker: `narration` / `[work].lyric_voice` from `work.toml`; - - direction and cast list: `stage_direction` / `narrator`; - - `location` and `time_of_day` from the scene config. -- `allowed.characters` are the cast ids except `narrator` and the lyric voice. Cast members - with `sprite = false` are valid on stage; the Ren'Py generator filters them. - -## Cache - -One file per chunk, `annotation.schema.json`: `chunk_id`, `input_sha256` (copied from the -chunk) and `annotations` (one per line, in order). Cache files are never deleted by the -tool; a cache whose hash no longer matches is simply `stale` and gets redone. - -## Commands - -| Command | Effect | -|---|---| -| `vnpipe annotate chunk` | Write chunk files, remove chunk files that no longer exist. | -| `vnpipe annotate status [id ...]` | Per chunk `ok`, `missing`, `stale` or `invalid` (with reason) plus a summary. Always exits 0. | -| `vnpipe annotate prompt ` | Print the full annotator instructions for a chunk (absolute paths filled in). | -| `vnpipe annotate merge [--fallback]` | Validate every cache and write `data/annotated.json`. | - -A cache is `ok` when it validates against the schema, carries the chunk's hash, covers exactly -the chunk's line ids in order, keeps `speaker`/`kind`/`location`/`time_of_day` equal to the -defaults, and uses only allowed characters (each at most once per line). `stale` means the -hash differs; everything else wrong is `invalid`. - -`merge` without `--fallback` prints every problem and exits 1 without writing anything. With -`--fallback`, each non-ok chunk gets deterministic annotations (defaults, emotion `neutral`, -music `null`, on stage: the speakers seen so far in the scene who have sprites, placed -left/right/center in order of appearance), a warning is printed, and the chunk ids are listed -in `fallback_chunks`. Output is byte-identical across runs. - -## Running the annotators - -1. `vnpipe annotate chunk` -2. For each chunk that is not `ok` in `vnpipe annotate status`, start one cheap-model - sub-agent whose whole instruction is the output of `vnpipe annotate prompt `. - Chunks are independent, so run them in parallel. -3. `vnpipe annotate status` until everything is `ok`; relaunch only the failing chunks. -4. `vnpipe annotate merge`. - -## Resumability - -Re-running is safe: only `missing`, `stale` and `invalid` chunks need work. After changing the -prompt every chunk becomes stale; after changing the text only the affected chunks do. Always -run `vnpipe annotate chunk` after changing `parsed.json`, `work.toml` or the prompt, before -starting annotators (`status` warns when chunk files are out of date). diff --git a/pyproject.toml b/pyproject.toml index 62f86e2..38ce9ab 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,30 +1,28 @@ [project] -name = "vnpipe" +name = "faust-vn" version = "0.1.0" -description = "Public-domain play text -> annotated JSON -> Ren'Py visual novel pipeline" +description = "Faust (Part I, opening) as a Ren'Py visual novel, built with vnpipe" readme = "README.md" requires-python = ">=3.12" license = "MIT" dependencies = [ - "jsonschema>=4.23", - "pillow>=11.0", + "vnpipe", ] -[project.scripts] -vnpipe = "vnpipe.cli:main" - [dependency-groups] dev = [ "pytest>=8.3", "ruff>=0.8", ] -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" +[tool.uv] +package = false -[tool.hatch.build.targets.wheel] -packages = ["src/vnpipe"] +# Absolute because uv resolves relative paths against the project directory and this repo is +# used from both the main checkout and `.worktrees/` (two levels deeper). From the main +# checkout alone this could be `../vnpipe`. Adjust to where vnpipe is cloned. +[tool.uv.sources] +vnpipe = { path = "/home/dasemu/Hacking/Darío/vnpipe", editable = true } [tool.ruff] line-length = 100 diff --git a/src/vnpipe/__init__.py b/src/vnpipe/__init__.py deleted file mode 100644 index aabafb9..0000000 --- a/src/vnpipe/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -"""vnpipe: public-domain play text -> annotated JSON -> Ren'Py visual novel.""" - -from pathlib import Path - -PACKAGE_DIR = Path(__file__).resolve().parent -SCHEMA_DIR = PACKAGE_DIR / "schemas" diff --git a/src/vnpipe/annotate.py b/src/vnpipe/annotate.py deleted file mode 100644 index 1c92c11..0000000 --- a/src/vnpipe/annotate.py +++ /dev/null @@ -1,497 +0,0 @@ -"""Annotation stage: chunk parsed.json for LLM annotators, track the cache and merge. - -LLM sub-agents (run by the orchestrator) read ``annotations/chunks/.json`` and write -``annotations/cache/.json``. This module only prepares chunks, checks cache state and -merges; everything here is deterministic and idempotent. -""" - -import argparse -import hashlib -import json -import sys -from dataclasses import dataclass, field -from itertools import groupby -from pathlib import Path -from typing import Any - -from vnpipe import PACKAGE_DIR, SCHEMA_DIR -from vnpipe.config import Work, load_work -from vnpipe.schema import SchemaError, validate - -MAX_CHUNK_LINES = 60 -CONTEXT_LINES = 6 -NARRATOR = "narrator" -PROMPT_PATH = PACKAGE_DIR / "prompts" / "annotate.md" -PRESET_POSITIONS = ("left", "right", "center") # order used by the fallback -DEFAULT_FIELDS = ("speaker", "kind", "location", "time_of_day") -ANN_ORDER = ("speaker", "kind", "emotion", "location", "time_of_day", "on_stage", "music") - -OK, MISSING, STALE, INVALID = "ok", "missing", "stale", "invalid" - - -class AnnotateError(ValueError): - """Inconsistent input (parsed.json against work.toml).""" - - -# --------------------------------------------------------------------------- helpers - - -def dumps(data: Any) -> str: - return json.dumps(data, ensure_ascii=False, indent=2) + "\n" - - -def _write(path: Path, text: str) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text, encoding="utf-8", newline="\n") - - -def canonical_sha256(data: Any) -> str: - blob = json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":")) - return hashlib.sha256(blob.encode("utf-8")).hexdigest() - - -def prompt_version() -> str: - return hashlib.sha256(PROMPT_PATH.read_bytes()).hexdigest() - - -def chunks_dir(work: Work) -> Path: - return work.path("annotations/chunks") - - -def cache_dir(work: Work) -> Path: - return work.path("annotations/cache") - - -def _schema_enums() -> dict[str, list[str]]: - defs = json.loads((SCHEMA_DIR / "annotation.schema.json").read_text(encoding="utf-8"))["$defs"] - props = defs["annotation"]["properties"] - return { - "emotions": list(props["emotion"]["enum"]), - "positions": list(defs["position"]["enum"]), - "music": [m for m in props["music"]["enum"] if m is not None], - } - - -def lyric_voice(work: Work) -> str: - return work.data["work"].get("lyric_voice", NARRATOR) - - -def allowed_for(work: Work) -> dict[str, list[str]]: - """Vocabularies an annotation may use, derived from work.toml and the schema.""" - cast = list(work.cast) - voice = lyric_voice(work) - if NARRATOR not in cast: - cast.insert(0, NARRATOR) - if voice not in cast: - raise AnnotateError(f"work.lyric_voice {voice!r} is not a cast id") - locations: list[str] = [] - for scene in work.scenes: - if scene["location"] not in locations: - locations.append(scene["location"]) - return { - "speakers": cast, - "characters": [c for c in cast if c not in (NARRATOR, voice)], - "locations": locations, - **_schema_enums(), - } - - -def has_sprite(work: Work, character: str) -> bool: - return bool(work.cast.get(character, {}).get("sprite", True)) - - -# --------------------------------------------------------------------------- chunking - - -def _pack(lines: list[dict], keys: tuple[str, ...], limit: int) -> list[list[dict]]: - """Split ``lines`` into pieces of at most ``limit``, preferring boundaries of ``keys[0]``, - then ``keys[1]`` ..., and finally cutting anywhere.""" - if len(lines) <= limit: - return [lines] - if not keys: - return [lines[i : i + limit] for i in range(0, len(lines), limit)] - pieces: list[list[dict]] = [] - current: list[dict] = [] - for _, group in groupby(lines, key=lambda ln: ln[keys[0]]): - block = list(group) - if len(block) > limit: - if current: - pieces.append(current) - current = [] - pieces.extend(_pack(block, keys[1:], limit)) - elif len(current) + len(block) > limit: - pieces.append(current) - current = block - else: - current += block - if current: - pieces.append(current) - return pieces - - -def _line_defaults(work: Work, scene_cfg: dict, line: dict, voice: str) -> dict[str, str]: - kind, speaker = line["kind"], line["speaker"] - if kind == "verse" and speaker: - ann_kind, ann_speaker = "dialogue", speaker - elif kind == "verse": - ann_kind, ann_speaker = "narration", voice - else: - ann_kind, ann_speaker = "stage_direction", NARRATOR - if ann_speaker not in work.cast and ann_speaker != NARRATOR: - raise AnnotateError(f"line {line['id']}: speaker {ann_speaker!r} is not in work.toml cast") - return { - "speaker": ann_speaker, - "kind": ann_kind, - "location": scene_cfg["location"], - "time_of_day": scene_cfg["time_of_day"], - } - - -def build_chunks(work: Work, parsed: dict[str, Any]) -> list[dict[str, Any]]: - """Deterministically split parsed scenes into annotation chunks (with input hashes).""" - scene_cfgs = {s["id"]: s for s in work.scenes} - allowed = allowed_for(work) - voice = lyric_voice(work) - version = prompt_version() - chunks: list[dict[str, Any]] = [] - for scene in parsed["scenes"]: - cfg = scene_cfgs.get(scene["id"]) - if cfg is None: - raise AnnotateError(f"scene {scene['id']!r} is not configured in work.toml") - lines = scene["lines"] - start = 0 - for number, piece in enumerate(_pack(lines, ("speech", "stanza"), MAX_CHUNK_LINES), 1): - before = [ - { - "id": ln["id"], - "speaker": _line_defaults(work, cfg, ln, voice)["speaker"], - "text": ln["text"], - } - for ln in lines[max(0, start - CONTEXT_LINES) : start] - ] - start += len(piece) - chunk: dict[str, Any] = { - "chunk_id": f"{scene['id']}_c{number:02d}", - "prompt_version": version, - "scene": { - "id": scene["id"], - "heading": scene["heading"], - "location": cfg["location"], - "time_of_day": cfg["time_of_day"], - }, - "allowed": allowed, - "context_before": before, - "lines": [ - { - "id": ln["id"], - "kind": ln["kind"], - "speaker": ln["speaker"], - "speaker_note": ln["speaker_note"], - "text": ln["text"], - "defaults": _line_defaults(work, cfg, ln, voice), - } - for ln in piece - ], - } - chunk["input_sha256"] = canonical_sha256(chunk) - chunks.append(chunk) - return chunks - - -def load_parsed(work: Work) -> tuple[dict[str, Any], bytes]: - path = work.path("data/parsed.json") - if not path.is_file(): - raise SystemExit(f"{path} missing; run `vnpipe parse` first") - raw = path.read_bytes() - parsed = json.loads(raw) - validate(parsed, "parsed") - return parsed, raw - - -def write_chunks(work: Work, chunks: list[dict[str, Any]]) -> list[Path]: - """Write chunk files and remove stale ones; returns the removed paths.""" - out = chunks_dir(work) - out.mkdir(parents=True, exist_ok=True) - keep = {f"{c['chunk_id']}.json" for c in chunks} - for chunk in chunks: - _write(out / f"{chunk['chunk_id']}.json", dumps(chunk)) - removed = sorted(p for p in out.glob("*.json") if p.name not in keep) - for path in removed: - path.unlink() - return removed - - -# --------------------------------------------------------------------------- checking - - -def _schema_reason(exc: SchemaError) -> str: - return "; ".join(s.strip() for s in str(exc).splitlines()[1:4]) - - -def check_cache(work: Work, chunk: dict[str, Any]) -> tuple[str, list[str]]: - """Classify the cache file of ``chunk``; returns (state, problems).""" - path = cache_dir(work) / f"{chunk['chunk_id']}.json" - if not path.is_file(): - return MISSING, ["no cache file"] - try: - data = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: - return INVALID, [f"unreadable JSON: {exc}"] - try: - validate(data, "annotation") - except SchemaError as exc: - return INVALID, [f"schema: {_schema_reason(exc)}"] - if data["chunk_id"] != chunk["chunk_id"]: - return INVALID, [f"chunk_id is {data['chunk_id']!r}"] - if data["input_sha256"] != chunk["input_sha256"]: - return STALE, ["input_sha256 does not match the current chunk"] - problems = _semantic_problems(chunk, data["annotations"]) - return (INVALID, problems) if problems else (OK, []) - - -def _semantic_problems(chunk: dict[str, Any], annotations: list[dict]) -> list[str]: - problems: list[str] = [] - expected = [ln["id"] for ln in chunk["lines"]] - got = [a["id"] for a in annotations] - if got != expected: - missing = [i for i in expected if i not in got] - extra = [i for i in got if i not in expected] - dupes = sorted({i for i in got if got.count(i) > 1}) - if missing: - problems.append( - f"missing lines: {', '.join(missing[:5])}{' ...' if len(missing) > 5 else ''}" - ) - if extra: - problems.append(f"unknown line ids: {', '.join(extra[:5])}") - if dupes: - problems.append(f"duplicate line ids: {', '.join(dupes[:5])}") - if not (missing or extra or dupes): - problems.append("lines are not in chunk order") - return problems - characters = set(chunk["allowed"]["characters"]) - for line, ann in zip(chunk["lines"], annotations, strict=True): - for key in DEFAULT_FIELDS: - if ann[key] != line["defaults"][key]: - problems.append( - f"{line['id']}: {key} is {ann[key]!r}, expected {line['defaults'][key]!r}" - ) - seen: set[str] = set() - for slot in ann["on_stage"]: - who = slot["character"] - if who not in characters: - problems.append(f"{line['id']}: unknown character {who!r} on stage") - elif who in seen: - problems.append(f"{line['id']}: {who!r} on stage more than once") - seen.add(who) - return problems - - -# --------------------------------------------------------------------------- fallback - - -def fallback_annotations(work: Work, scene_chunks: list[dict[str, Any]]) -> dict[str, list[dict]]: - """Deterministic annotations for every chunk of one scene, keyed by chunk id.""" - seen: list[str] = [] # speakers with a sprite, in order of appearance in the scene - result: dict[str, list[dict]] = {} - for chunk in scene_chunks: - anns = [] - for line in chunk["lines"]: - who = line["defaults"]["speaker"] - if ( - who in chunk["allowed"]["characters"] - and has_sprite(work, who) - and who not in seen - and len(seen) < len(PRESET_POSITIONS) - ): - seen.append(who) - anns.append( - { - "id": line["id"], - **line["defaults"], - "emotion": "neutral", - "on_stage": [ - {"character": c, "position": PRESET_POSITIONS[i]} - for i, c in enumerate(seen) - ], - "music": None, - } - ) - result[chunk["chunk_id"]] = anns - return result - - -def _normalise(ann: dict[str, Any]) -> dict[str, Any]: - out = {key: ann.get(key) for key in ANN_ORDER} - out["on_stage"] = [ - {"character": s["character"], "position": s["position"]} for s in ann["on_stage"] - ] - return out - - -# --------------------------------------------------------------------------- merge - - -@dataclass -class MergeResult: - document: dict[str, Any] | None = None - problems: list[str] = field(default_factory=list) - warnings: list[str] = field(default_factory=list) - - -def merge(work: Work, fallback: bool = False) -> MergeResult: - parsed, raw = load_parsed(work) - chunks = build_chunks(work, parsed) - result = MergeResult() - states = {c["chunk_id"]: check_cache(work, c) for c in chunks} - bad = [c["chunk_id"] for c in chunks if states[c["chunk_id"]][0] != OK] - if bad and not fallback: - for cid in bad: - state, why = states[cid] - result.problems.append(f"{cid}: {state}: {'; '.join(why)}") - return result - - by_scene: dict[str, list[dict]] = {} - for chunk in chunks: - by_scene.setdefault(chunk["scene"]["id"], []).append(chunk) - anns: dict[str, dict[str, Any]] = {} # line id -> normalised annotation - for scene_chunks in by_scene.values(): - fb = fallback_annotations(work, scene_chunks) if bad else {} - for chunk in scene_chunks: - cid = chunk["chunk_id"] - if states[cid][0] == OK: - data = json.loads((cache_dir(work) / f"{cid}.json").read_text(encoding="utf-8")) - items = data["annotations"] - else: - items = fb[cid] - state, why = states[cid] - result.warnings.append(f"{cid}: {state} ({'; '.join(why)}), using fallback") - for item in items: - anns[item["id"]] = _normalise(item) - - doc = { - "work": parsed["work"], - "parsed_sha256": hashlib.sha256(raw).hexdigest(), - "fallback_chunks": bad, - "scenes": [ - { - "id": scene["id"], - "heading": scene["heading"], - "lines": [{**ln, "ann": anns[ln["id"]]} for ln in scene["lines"]], - } - for scene in parsed["scenes"] - ], - } - validate(doc, "annotated") - result.document = doc - return result - - -# --------------------------------------------------------------------------- commands - - -def cmd_chunk(args: argparse.Namespace) -> int: - work = load_work(args.work) - parsed, _ = load_parsed(work) - chunks = build_chunks(work, parsed) - removed = write_chunks(work, chunks) - for chunk in chunks: - print(f"chunk: {chunk['chunk_id']}: {len(chunk['lines'])} lines") - for path in removed: - print(f"chunk: removed stale {path.name}") - return 0 - - -def cmd_status(args: argparse.Namespace) -> int: - work = load_work(args.work) - parsed, _ = load_parsed(work) - chunks = build_chunks(work, parsed) - wanted = set(args.chunk_ids) - unknown = wanted - {c["chunk_id"] for c in chunks} - if unknown: - print(f"status: unknown chunk id(s): {', '.join(sorted(unknown))}", file=sys.stderr) - return 0 - counts: dict[str, int] = {} - for chunk in chunks: - if wanted and chunk["chunk_id"] not in wanted: - continue - state, why = check_cache(work, chunk) - counts[state] = counts.get(state, 0) + 1 - suffix = f" ({'; '.join(why)})" if why and state != MISSING else "" - print(f"{chunk['chunk_id']}: {state}{suffix}") - stale_files = {p.name for p in chunks_dir(work).glob("*.json")} ^ { - f"{c['chunk_id']}.json" for c in chunks - } - on_disk_differs = bool(stale_files) or any( - _read_json(chunks_dir(work) / f"{c['chunk_id']}.json") != c for c in chunks - ) - if on_disk_differs: - print("note: chunk files are out of date; run `vnpipe annotate chunk`") - summary = ", ".join(f"{counts.get(s, 0)} {s}" for s in (OK, MISSING, STALE, INVALID)) - print(f"summary: {sum(counts.values())} chunks: {summary}") - return 0 - - -def _read_json(path: Path) -> Any: - try: - return json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError): - return None - - -def cmd_merge(args: argparse.Namespace) -> int: - work = load_work(args.work) - result = merge(work, fallback=args.fallback) - if result.document is None: - print("merge: refusing to merge, problems found:", file=sys.stderr) - for problem in result.problems: - print(f" {problem}", file=sys.stderr) - print("merge: fix them or use --fallback; nothing written", file=sys.stderr) - return 1 - for warning in result.warnings: - print(f"warning: {warning}", file=sys.stderr) - out = work.path("data/annotated.json") - _write(out, dumps(result.document)) - n_lines = sum(len(s["lines"]) for s in result.document["scenes"]) - n_fb = len(result.document["fallback_chunks"]) - print(f"merge: wrote {out} ({n_lines} lines, {n_fb} fallback chunks)") - return 0 - - -def render_prompt(work: Work, chunk_id: str) -> str: - parsed, _ = load_parsed(work) - ids = {c["chunk_id"] for c in build_chunks(work, parsed)} - if chunk_id not in ids: - raise SystemExit(f"prompt: unknown chunk id {chunk_id!r}") - repo = PACKAGE_DIR.parent.parent - values = { - "chunk_id": chunk_id, - "chunk_path": str((chunks_dir(work) / f"{chunk_id}.json").resolve()), - "cache_path": str((cache_dir(work) / f"{chunk_id}.json").resolve()), - "status_cmd": f"{repo / '.venv/bin/vnpipe'} --work {work.root.resolve()} annotate status", - } - text = PROMPT_PATH.read_text(encoding="utf-8") - for key, value in values.items(): - text = text.replace("{{" + key + "}}", value) - return text - - -def cmd_prompt(args: argparse.Namespace) -> int: - sys.stdout.write(render_prompt(load_work(args.work), args.chunk_id)) - return 0 - - -def register(subparsers: argparse._SubParsersAction) -> None: - annotate = subparsers.add_parser("annotate", help="LLM annotation stage tooling") - sub = annotate.add_subparsers(dest="annotate_command", required=True) - sub.add_parser("chunk", help="Write annotation chunks").set_defaults(handler=cmd_chunk) - status = sub.add_parser("status", help="Show cache state per chunk") - status.add_argument("chunk_ids", nargs="*", help="Limit to these chunks") - status.set_defaults(handler=cmd_status) - merge_cmd = sub.add_parser("merge", help="Validate caches and write data/annotated.json") - merge_cmd.add_argument( - "--fallback", action="store_true", help="Fill non-ok chunks with deterministic defaults" - ) - merge_cmd.set_defaults(handler=cmd_merge) - prompt = sub.add_parser("prompt", help="Print the annotator instructions for one chunk") - prompt.add_argument("chunk_id") - prompt.set_defaults(handler=cmd_prompt) diff --git a/src/vnpipe/assets.py b/src/vnpipe/assets.py deleted file mode 100644 index da6d22f..0000000 --- a/src/vnpipe/assets.py +++ /dev/null @@ -1,307 +0,0 @@ -"""Asset manifest management: import generated images, key out sprite backgrounds, -fall back to placeholders, and build contact sheets for visual review. - -The manifest (``/assets/assets.json``) is the single source of truth for every -image: prompt, origin, hash and review status. Image generation itself happens -outside this module (an MCP tool driven by an agent); ``import`` ingests its result. -""" - -import argparse -import base64 -import hashlib -import json -from pathlib import Path -from typing import Any - -from PIL import Image, ImageDraw, ImageFont, ImageOps - -from vnpipe.config import load_work -from vnpipe.schema import validate - -MANIFEST = "assets/assets.json" -BG_SIZE = (1920, 1080) -SPRITE_HEIGHT = 1000 -USABLE = {"processed", "approved"} - -# Chroma key thresholds on "greenness" = g - max(r, b). -KEY_FULL = 60 # at or above: fully transparent -KEY_NONE = 20 # at or below: fully opaque - - -def sha256_file(path: Path) -> str: - return hashlib.sha256(path.read_bytes()).hexdigest() - - -def load_manifest(work_root: Path) -> dict[str, Any]: - data = json.loads((work_root / MANIFEST).read_text(encoding="utf-8")) - validate(data, "manifest") - return data - - -def save_manifest(work_root: Path, data: dict[str, Any]) -> None: - validate(data, "manifest") - text = json.dumps(data, ensure_ascii=False, indent=2) + "\n" - (work_root / MANIFEST).write_text(text, encoding="utf-8") - - -def find_asset(manifest: dict[str, Any], asset_id: str) -> dict[str, Any]: - for asset in manifest["assets"]: - if asset["id"] == asset_id: - return asset - raise KeyError(f"unknown asset id: {asset_id}") - - -def full_prompt(manifest: dict[str, Any], asset: dict[str, Any]) -> str: - """Prompt actually sent to the generator: base + kind template + asset prompt.""" - kind = "variant" if asset.get("reference") and asset["kind"] == "sprite" else asset["kind"] - template = manifest["templates"][kind] - return "\n\n".join(p for p in (manifest["base_prompt"], template, asset["prompt"]) if p) - - -# --- import ----------------------------------------------------------------- - - -def load_tool_result(path: Path) -> dict[str, Any]: - """Read a stored query_tasks result (raw object or [{"type": "text", "text": ...}]).""" - data = json.loads(path.read_text(encoding="utf-8")) - if isinstance(data, list) and data and isinstance(data[0], dict) and "text" in data[0]: - data = json.loads(data[0]["text"]) - if isinstance(data, str): - data = json.loads(data) - return data - - -def decode_output(result: dict[str, Any], index: int = 0) -> bytes: - if result.get("status") != "COMPLETED": - raise ValueError(f"generation not completed: status={result.get('status')}") - outputs = [o for o in result.get("outputs", []) if o.get("base64")] - if len(outputs) <= index: - raise ValueError("no base64 output; query again with include_base64=true") - out = outputs[index] - raw = base64.b64decode(out["base64"]) - expected = out.get("sha256") - if expected and hashlib.sha256(raw).hexdigest() != expected: - raise ValueError("sha256 mismatch between decoded image and the MCP report") - return raw - - -def import_image(work_root: Path, asset_id: str, raw: bytes, generation_id: str | None) -> Path: - manifest = load_manifest(work_root) - asset = find_asset(manifest, asset_id) - raw_rel = f"raw/{asset_id}.png" - raw_path = work_root / "assets" / raw_rel - raw_path.parent.mkdir(parents=True, exist_ok=True) - with Image.open(_bytes_io(raw)) as img: - img.convert("RGB").save(raw_path, "PNG") - asset.update(raw_file=raw_rel, generation_id=generation_id, status="generated") - asset.setdefault("source", "chatgpt-web") - save_manifest(work_root, manifest) - return raw_path - - -def _bytes_io(raw: bytes): - import io - - return io.BytesIO(raw) - - -# --- processing ------------------------------------------------------------- - - -def chroma_key(img: Image.Image) -> Image.Image: - """Make the flat green field transparent with a soft edge and green despill.""" - rgb = img.convert("RGB") - pixels = [] - for r, g, b in rgb.getdata(): - greenness = g - max(r, b) - if greenness >= KEY_FULL: - pixels.append((0, 0, 0, 0)) - continue - if greenness <= KEY_NONE: - alpha = 255 - else: - alpha = round(255 * (KEY_FULL - greenness) / (KEY_FULL - KEY_NONE)) - if greenness > 0: - g = max(r, b) # despill: clamp green to the other channels - pixels.append((r, g, b, alpha)) - out = Image.new("RGBA", rgb.size) - out.putdata(pixels) - return out - - -def trim_and_scale_sprite(img: Image.Image, height: int = SPRITE_HEIGHT) -> Image.Image: - bbox = img.getchannel("A").point(lambda a: 255 if a > 16 else 0).getbbox() - if bbox: - img = img.crop(bbox) - scale = height / img.height - return img.resize((max(1, round(img.width * scale)), height), Image.Resampling.LANCZOS) - - -def process_asset(work_root: Path, asset: dict[str, Any]) -> None: - raw_path = work_root / "assets" / asset["raw_file"] - final = work_root / "assets" / asset["file"] - final.parent.mkdir(parents=True, exist_ok=True) - with Image.open(raw_path) as img: - if asset["kind"] == "sprite": - out = trim_and_scale_sprite(chroma_key(img)) - else: - out = ImageOps.fit(img.convert("RGB"), BG_SIZE, Image.Resampling.LANCZOS) - out.save(final, "WEBP", quality=90, method=6) - asset["sha256"] = sha256_file(final) - asset["status"] = "processed" - - -def placeholder(asset: dict[str, Any], label_color: str = "#d8cfc0") -> Image.Image: - """Deterministic stand-in image so the game always runs.""" - if asset["kind"] == "background": - img = Image.new("RGB", BG_SIZE, "#1d1a17") - draw = ImageDraw.Draw(img) - for y in range(BG_SIZE[1]): - shade = 23 + round(30 * y / BG_SIZE[1]) - draw.line([(0, y), (BG_SIZE[0], y)], fill=(shade, shade - 4, shade - 8)) - else: - img = Image.new("RGBA", (500, SPRITE_HEIGHT), (0, 0, 0, 0)) - draw = ImageDraw.Draw(img) - draw.ellipse([170, 40, 330, 220], fill=(60, 52, 46, 230)) - draw.rounded_rectangle([110, 230, 390, SPRITE_HEIGHT], 60, fill=(60, 52, 46, 230)) - draw = ImageDraw.Draw(img) - font = ImageFont.load_default(size=40) - draw.text((30, 30), asset["id"], fill=label_color, font=font) - return img - - -def ensure_placeholder(work_root: Path, asset: dict[str, Any]) -> None: - final = work_root / "assets" / asset["file"] - final.parent.mkdir(parents=True, exist_ok=True) - placeholder(asset).save(final, "WEBP", quality=90) - asset.update(source="placeholder", status="placeholder", sha256=sha256_file(final)) - - -def contact_sheet(work_root: Path, ids: list[str], out: Path, thumb: int = 360) -> Path: - """Tile raw or processed images (sprites over a checkerboard) for visual review.""" - manifest = load_manifest(work_root) - tiles = [] - for asset_id in ids: - asset = find_asset(manifest, asset_id) - rel = asset["file"] if asset["status"] in USABLE else asset.get("raw_file") - if not rel: - continue - with Image.open(work_root / "assets" / rel) as img: - img = img.convert("RGBA") - img.thumbnail((thumb, thumb)) - tile = _checker((thumb, thumb)) - tile.alpha_composite(img, ((thumb - img.width) // 2, (thumb - img.height) // 2)) - ImageDraw.Draw(tile).text((6, 6), asset_id, fill="white") - tiles.append(tile) - cols = min(4, max(1, len(tiles))) - rows = (len(tiles) + cols - 1) // cols - sheet = Image.new("RGBA", (cols * thumb, max(1, rows) * thumb), "black") - for i, tile in enumerate(tiles): - sheet.paste(tile, ((i % cols) * thumb, (i // cols) * thumb)) - out.parent.mkdir(parents=True, exist_ok=True) - sheet.convert("RGB").save(out) - return out - - -def _checker(size: tuple[int, int], cell: int = 20) -> Image.Image: - img = Image.new("RGBA", size, (90, 90, 90, 255)) - draw = ImageDraw.Draw(img) - for y in range(0, size[1], cell): - for x in range((y // cell % 2) * cell, size[0], cell * 2): - draw.rectangle([x, y, x + cell - 1, y + cell - 1], fill=(130, 130, 130, 255)) - return img - - -# --- CLI -------------------------------------------------------------------- - - -def _cmd_import(args: argparse.Namespace) -> int: - work = load_work(args.work) - result = load_tool_result(args.tool_result) - raw = decode_output(result, args.index) - path = import_image(work.root, args.asset_id, raw, result.get("generationId")) - print(f"{args.asset_id}: imported {path} ({len(raw)} bytes, sha256 verified)") - return 0 - - -def _cmd_process(args: argparse.Namespace) -> int: - work = load_work(args.work) - manifest = load_manifest(work.root) - for asset in manifest["assets"]: - if args.ids and asset["id"] not in args.ids: - continue - if asset["status"] == "generated" or (args.force and asset.get("raw_file")): - process_asset(work.root, asset) - print(f"{asset['id']}: processed") - save_manifest(work.root, manifest) - return 0 - - -def _cmd_status(args: argparse.Namespace) -> int: - work = load_work(args.work) - manifest = load_manifest(work.root) - if args.set: - asset = find_asset(manifest, args.set[0]) - asset["status"] = args.set[1] - if len(args.set) > 2: - asset["notes"] = args.set[2] - save_manifest(work.root, manifest) - for asset in manifest["assets"]: - print(f"{asset['status']:<11} {asset['id']}") - return 0 - - -def _cmd_placeholders(args: argparse.Namespace) -> int: - work = load_work(args.work) - manifest = load_manifest(work.root) - for asset in manifest["assets"]: - if asset["status"] not in USABLE: - ensure_placeholder(work.root, asset) - print(f"{asset['id']}: placeholder") - save_manifest(work.root, manifest) - return 0 - - -def _cmd_prompt(args: argparse.Namespace) -> int: - work = load_work(args.work) - manifest = load_manifest(work.root) - print(full_prompt(manifest, find_asset(manifest, args.asset_id))) - return 0 - - -def _cmd_sheet(args: argparse.Namespace) -> int: - work = load_work(args.work) - print(contact_sheet(work.root, args.ids, args.out)) - return 0 - - -def register(sub: argparse._SubParsersAction) -> None: - parser = sub.add_parser("assets", help="Manage the asset manifest and images") - cmds = parser.add_subparsers(dest="assets_command", required=True) - - p = cmds.add_parser("prompt", help="Print the full generation prompt for an asset") - p.add_argument("asset_id") - p.set_defaults(handler=_cmd_prompt) - - p = cmds.add_parser("import", help="Decode a stored query_tasks result into an asset") - p.add_argument("asset_id") - p.add_argument("tool_result", type=Path) - p.add_argument("--index", type=int, default=0) - p.set_defaults(handler=_cmd_import) - - p = cmds.add_parser("process", help="Cut out sprites / fit backgrounds") - p.add_argument("ids", nargs="*") - p.add_argument("--force", action="store_true", help="Reprocess already processed assets") - p.set_defaults(handler=_cmd_process) - - p = cmds.add_parser("status", help="List statuses, or --set ID STATUS [NOTE]") - p.add_argument("--set", nargs="+", metavar="ARG") - p.set_defaults(handler=_cmd_status) - - p = cmds.add_parser("placeholders", help="Create placeholders for unusable assets") - p.set_defaults(handler=_cmd_placeholders) - - p = cmds.add_parser("sheet", help="Build a contact sheet PNG for review") - p.add_argument("out", type=Path) - p.add_argument("ids", nargs="+") - p.set_defaults(handler=_cmd_sheet) diff --git a/src/vnpipe/cli.py b/src/vnpipe/cli.py deleted file mode 100644 index a247a12..0000000 --- a/src/vnpipe/cli.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Command-line entry point. - -Each pipeline stage lives in its own module exposing ``register(subparsers)``, -which adds a subcommand whose handler takes the parsed ``argparse.Namespace``. -""" - -import argparse -import importlib -from pathlib import Path - -STAGE_MODULES = ["text", "annotate", "assets", "renpy_gen"] - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(prog="vnpipe", description=__doc__) - parser.add_argument( - "--work", - type=Path, - default=Path("works/faust"), - help="Work directory containing work.toml (default: works/faust)", - ) - sub = parser.add_subparsers(dest="command", required=True) - for name in STAGE_MODULES: - try: - module = importlib.import_module(f"vnpipe.{name}") - except ModuleNotFoundError as exc: - if exc.name != f"vnpipe.{name}": - raise - continue - module.register(sub) - args = parser.parse_args(argv) - return args.handler(args) or 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/src/vnpipe/config.py b/src/vnpipe/config.py deleted file mode 100644 index 3e818cb..0000000 --- a/src/vnpipe/config.py +++ /dev/null @@ -1,37 +0,0 @@ -"""Load a work's configuration (works//work.toml).""" - -import tomllib -from dataclasses import dataclass -from pathlib import Path -from typing import Any - - -@dataclass(frozen=True) -class Work: - root: Path - data: dict[str, Any] - - @property - def id(self) -> str: - return self.data["work"]["id"] - - @property - def cast(self) -> dict[str, dict[str, Any]]: - return self.data["cast"] - - @property - def speakers(self) -> dict[str, str]: - return self.data["speakers"] - - @property - def scenes(self) -> list[dict[str, Any]]: - return self.data["scenes"] - - def path(self, relative: str) -> Path: - return self.root / relative - - -def load_work(root: Path) -> Work: - root = Path(root) - with (root / "work.toml").open("rb") as fh: - return Work(root=root, data=tomllib.load(fh)) diff --git a/src/vnpipe/prompts/annotate.md b/src/vnpipe/prompts/annotate.md deleted file mode 100644 index e900741..0000000 --- a/src/vnpipe/prompts/annotate.md +++ /dev/null @@ -1,88 +0,0 @@ -# Task: annotate one chunk of a verse play for a visual novel - -You annotate chunk `{{chunk_id}}`. Do not read or write any other file than the two below. - -- Input (read it): `{{chunk_path}}` -- Output (write it, nothing else): `{{cache_path}}` - -## Input - -The chunk JSON has `scene`, `allowed`, `context_before` (earlier lines, read-only context, -do not annotate them) and `lines`. Each line has `id`, `kind`, `speaker`, `speaker_note`, -`text` and `defaults`. - -## Output - -One JSON file, exactly this shape: - -```json -{ - "chunk_id": "", - "input_sha256": "", - "annotations": [ - { - "id": "", - "speaker": "", - "kind": "", - "emotion": "neutral", - "location": "", - "time_of_day": "", - "on_stage": [{"character": "faust", "position": "left"}], - "music": null - } - ] -} -``` - -Rules: - -1. Exactly one annotation per input line, in the same order, same `id`s. No extras, no omissions. -2. Copy `speaker`, `kind`, `location`, `time_of_day` verbatim from the line's `defaults`. -3. `emotion`: one of `allowed.emotions`, chosen from the meaning of the verse in its context - (read `context_before` and the neighbouring lines). -4. `on_stage`: the characters present in the scene at that moment, not only the speaker. - Only ids from `allowed.characters`, each at most once per line, `position` one of - `left`, `center`, `right`. Include present characters even if - they are never drawn (the Lord, the Spirit): the renderer filters them. Use `[]` for - lyric text with nobody in the scene (the Dedicatoria). -5. `music`: a mood from `allowed.music` only at a real mood shift (a new scene, a hymn - starting, the Spirit appearing); `null` on every other line. Never repeat the same mood. -6. Output only valid JSON, no comments, no extra keys, no markdown fences in the file. - -## Emotions - -- `neutral`: plain statement, exposition, stage business, questions of fact. -- `joyful`: warmth, laughter, praise, light banter. Comic exchanges between the Clown and - the Director: joyful or ironic. -- `melancholic`: lyric longing, memory, loss, weariness. The Dedicatoria is melancholic - ("Tornáis de nuevo, hermosas imágenes flotantes..."). -- `solemn`: sacred, ceremonial, grave. The archangels' hymn and the Lord's words are solemn. -- `ironic`: sarcasm, wit, mockery, cynicism. Mephistopheles' sly remarks are ironic, even - when they sound polite. -- `angry`: rage, scorn, disgust, bitter rebuke. -- `fearful`: terror, dread, shrinking back. Faust before the Earth Spirit ("aterrado") is fearful. -- `ecstatic`: rapture, exaltation, overwhelming vision. Faust at the sign of the Macrocosm. - Faust's despair is melancholic or angry; his ecstasy is ecstatic. - -Check `speaker_note` too (for example "aterrado" means fearful). Do not default everything -to `neutral`; do not swing wildly between lines of one continuous thought. - -## Staging - -- Work out who is in the scene from the cast list (a `cast` line is only a list of who is - there), the stage directions and who has spoken so far (use `context_before`). -- A character who has not yet entered or who has left must not appear in `on_stage`. -- Positions must stay stable within the scene: once a character is `left`, keep them `left` - in every later line. With two characters use `left` and `right`; a third takes `center`. -- Stage directions say who enters, leaves or appears; apply them from the line after. - -## Before finishing - -Run this and make sure the line for `{{chunk_id}}` says `ok`: - -``` -{{status_cmd}} {{chunk_id}} -``` - -If it reports `invalid` or `stale`, fix the file (never edit the input) and run it again. -Finish with one short line saying the chunk is ok. diff --git a/src/vnpipe/renpy_gen.py b/src/vnpipe/renpy_gen.py deleted file mode 100644 index 1e8fde1..0000000 --- a/src/vnpipe/renpy_gen.py +++ /dev/null @@ -1,766 +0,0 @@ -"""Ren'Py generator: annotated play + asset manifest -> a complete Ren'Py 8 project. - -The output is deterministic (no timestamps, sorted iteration, copied bytes), so -re-running the command yields identical files. Staging rules are documented in -``docs/adaptation-rules.md``; work-specific choices come from ``work.toml``. - -The GUI files in ``renpy_templates/`` were produced once with the Ren'Py SDK's -``generate_gui`` command and are MIT-licensed Ren'Py files (see ``docs/running.md``). -""" - -import argparse -import hashlib -import json -import shutil -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -from PIL import Image, ImageDraw - -from vnpipe import PACKAGE_DIR -from vnpipe.assets import USABLE, load_manifest, placeholder -from vnpipe.config import Work, load_work -from vnpipe.schema import validate - -TEMPLATE_DIR = PACKAGE_DIR / "renpy_templates" -USABLE_STATUS = USABLE | {"placeholder"} - -ADV_MAX_LINES = 4 -NVL_MAX_LINES = 8 -SPLIT_INDENT = 6 # parsed `indent` at or above this marks a split verse line -TITLE_PAUSE = 2.0 -END_PAUSE = 3.0 - -VALID_POSITIONS = ("left", "center", "right") -EMOTIONS = ( - "neutral", - "joyful", - "melancholic", - "solemn", - "ironic", - "angry", - "fearful", - "ecstatic", -) -POSITIONS = ("left", "right", "center") # order in which --from-parsed assigns positions -TRANSITIONS = { - "dissolve": "dissolve", - "fade": "fade", - "slow": "vn_slow", - "flash": "vn_flash", -} -TINTS = ("none", "dark", "red") -DEFAULT_LYRIC_VOICE = "poet_voice" -DEFAULT_END_TEXT = "Continuará…" -MENU_BG_FALLBACK = "gui/main_menu.png" - -ABOUT_LABELS = { - "es": ("Texto", "Traducción", "Adaptación a novela visual generada con vnpipe."), - "en": ("Text", "Translation", "Visual novel adaptation generated with vnpipe."), -} - - -# --- text helpers ------------------------------------------------------------- - - -def escape_text(text: str) -> str: - """Escape a text for use inside a double-quoted Ren'Py say/define string.""" - return ( - text.replace("\\", "\\\\") - .replace('"', '\\"') - .replace("[", "[[") - .replace("{", "{{") - .replace("\n", "\\n") - ) - - -def quote(text: str) -> str: - return f'"{escape_text(text)}"' - - -def _plain_quote(text: str) -> str: - """Quote a path or identifier-like string (no Ren'Py text markup).""" - return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"' - - -def char_var(cast_id: str, nvl: bool = False) -> str: - """Ren'Py variable of a cast member's Character (prefixed: `director` etc. are built-ins).""" - return f"c_{cast_id}" + ("_nvl" if nvl else "") - - -def bg_image_name(asset_id: str) -> str: - """``bg_heaven_lord`` -> ``bg heaven_lord`` (tag ``bg``, attribute ``heaven_lord``).""" - return "bg " + asset_id.removeprefix("bg_") - - -# --- annotations ---------------------------------------------------------------- - - -def lyric_voice(work: Work) -> str: - return work.data["work"].get("lyric_voice", DEFAULT_LYRIC_VOICE) - - -def annotations_from_parsed(work: Work, parsed: dict[str, Any]) -> dict[str, Any]: - """Trivial in-memory annotations (used before the LLM annotations exist).""" - voice = lyric_voice(work) - scene_cfg = {s["id"]: s for s in work.scenes} - digest = hashlib.sha256( - json.dumps(parsed, sort_keys=True, ensure_ascii=False).encode("utf-8") - ).hexdigest() - scenes = [] - for scene in parsed["scenes"]: - cfg = scene_cfg.get(scene["id"], {}) - spoken: list[str] = [] - positions: dict[str, str] = {} - lines = [] - for line in scene["lines"]: - speaker = line["speaker"] - if line["kind"] == "direction": - ann_speaker, kind = "narrator", "stage_direction" - elif speaker: - ann_speaker, kind = speaker, "dialogue" - else: - ann_speaker, kind = voice, "narration" - if line["kind"] == "verse" and speaker and work.cast.get(speaker, {}).get("sprite"): - if speaker not in positions: - positions[speaker] = POSITIONS[len(positions) % len(POSITIONS)] - if speaker not in spoken: - spoken.append(speaker) - lines.append( - { - **line, - "ann": { - "speaker": ann_speaker, - "kind": kind, - "emotion": "neutral", - "location": cfg.get("location", "unknown"), - "time_of_day": cfg.get("time_of_day", "timeless"), - "on_stage": [{"character": c, "position": positions[c]} for c in spoken], - }, - } - ) - scenes.append({"id": scene["id"], "heading": scene["heading"], "lines": lines}) - return { - "work": parsed["work"], - "parsed_sha256": digest, - "fallback_chunks": [], - "scenes": scenes, - } - - -# --- assets ----------------------------------------------------------------------- - - -@dataclass -class ImageEntry: - name: str # Ren'Py image name, e.g. "bg heaven" or "faust neutral" - rel: str # path below game/images/ - asset: dict[str, Any] - source: Path | None # file to copy, or None to generate a placeholder - - -def _sprite_asset(character: str, expression: str) -> dict[str, Any]: - return { - "id": f"sprite_{character}_{expression}", - "kind": "sprite", - "character": character, - "expression": expression, - "file": f"sprites/{character}_{expression}.webp", - } - - -def _bg_asset(asset_id: str) -> dict[str, Any]: - return { - "id": asset_id, - "kind": "background", - "file": f"bg/{asset_id.removeprefix('bg_')}.webp", - } - - -def _needed_bg_ids(work: Work) -> list[str]: - ids = [cfg["bg"] for cfg in work.data.get("staging", {}).values() if cfg.get("bg")] - ids += [cue["bg"] for cue in work.data.get("cues", []) if cue.get("bg")] - return ids - - -def collect_images(work: Work, manifest: dict[str, Any] | None) -> list[ImageEntry]: - """Every image the project declares: manifest assets plus anything the staging needs.""" - assets: dict[str, dict[str, Any]] = {} - for asset in (manifest or {}).get("assets", []): - assets[asset["id"]] = asset - for asset_id in _needed_bg_ids(work): - assets.setdefault(asset_id, _bg_asset(asset_id)) - for cid, info in work.cast.items(): - if not info.get("sprite"): - continue - for expression in sorted(set(info.get("expressions", {}).values())): - sprite = _sprite_asset(cid, expression) - assets.setdefault(sprite["id"], sprite) - entries = [] - for asset_id in sorted(assets): - asset = assets[asset_id] - if asset["kind"] == "background": - name = bg_image_name(asset_id) - else: - name = f"{asset['character']} {asset['expression']}" - source = None - if asset.get("status") in USABLE_STATUS and asset.get("file"): - candidate = work.path("assets") / asset["file"] - if candidate.is_file(): - source = candidate - entries.append(ImageEntry(name, asset["file"], asset, source)) - return entries - - -# --- script generation ---------------------------------------------------------------- - - -@dataclass -class Box: - lines: list[dict[str, Any]] = field(default_factory=list) - key: tuple | None = None - speaker: str = "" - is_direction: bool = False - - -def _is_direction(line: dict[str, Any]) -> bool: - return line["kind"] == "direction" or line["ann"]["kind"] == "stage_direction" - - -class SceneWriter: - """Turns one scene's lines into Ren'Py statements, tracking staging state.""" - - def __init__( - self, work: Work, scene: dict[str, Any], moods: set[str], music_state: dict[str, str | None] - ): - self.work = work - self.scene = scene - self.moods = moods - self.voice = lyric_voice(work) - self.cues = {c["at"]: c for c in work.data.get("cues", [])} - staging = work.data.get("staging", {}).get(scene["id"], {}) - self.mode: str = staging.get("mode", "adv") - self.bg: str | None = staging.get("bg") - self.tint = "none" - self.music_state = music_state # {'playing': mood}, shared across scenes - self.shown: dict[str, str] = {} # character -> expression currently shown - self.pinned: dict[str, str] = dict(staging.get("cast", {})) # always on stage in ADV - self.positions: dict[str, str] = dict(self.pinned) # character -> position in this scene - self.last_on_stage: list[dict[str, str]] = [] # on_stage of the last non-direction box - self.out: list[str] = [] - self.box: Box | None = None - - def emit(self, text: str = "") -> None: - self.out.append((" " + text) if text else "") - - # -- speakers --------------------------------------------------------------- - - def speaker_of(self, line: dict[str, Any]) -> str: - if _is_direction(line): - return "narrator" - speaker = line["ann"]["speaker"] or self.voice - if speaker != "narrator" and speaker not in self.work.cast: - raise ValueError(f"{line['id']}: speaker {speaker!r} is not in [cast]") - return speaker - - # -- cues ---------------------------------------------------------------------- - - def apply_cue(self, cue: dict[str, Any]) -> None: - changes = False - new_mode = cue.get("mode", self.mode) - if self.mode == "nvl" and new_mode != "nvl": - self.emit("nvl hide dissolve") - if new_mode == "nvl" or cue.get("hide_all"): - changes |= self.hide_sprites(list(self.shown)) - self.mode = new_mode - if cue.get("tint") is not None: - if cue["tint"] not in TINTS: - raise ValueError(f"cue at {cue['at']}: unknown tint {cue['tint']!r}") - self.tint = cue["tint"] - if cue.get("bg") or cue.get("tint") is not None: - self.bg = cue.get("bg") or self.bg - self.emit(f"show {bg_image_name(self.bg)} at tint_{self.tint}") - changes = True - if changes: - transition = cue.get("transition", "dissolve") - if transition not in TRANSITIONS: - raise ValueError(f"cue at {cue['at']}: unknown transition {transition!r}") - self.emit(f"with {TRANSITIONS[transition]}") - if cue.get("shake"): - self.emit("show layer master at vn_shake") - moved = False - for cid, position in cue.get("move", {}).items(): - self.positions[cid] = position - if cid in self.shown: - self.emit(f"show {cid} {self.shown[cid]} at vn_{position}") - moved = True - if moved: - self.emit("with vn_move") - - def hide_sprites(self, characters: list[str]) -> bool: - for cid in characters: - self.emit(f"hide {cid}") - del self.shown[cid] - return bool(characters) - - # -- boxes ---------------------------------------------------------------------- - - def limit(self) -> int: - return NVL_MAX_LINES if self.mode == "nvl" else ADV_MAX_LINES - - def feed(self, line: dict[str, Any]) -> None: - if line["kind"] == "cast": - return - cue = self.cues.get(line["id"]) - if cue: - self.flush() - self.apply_cue(cue) - direction = _is_direction(line) - key = (self.speaker_of(line), line["speech"], line["stanza"]) - split = self.mode == "adv" and not direction and line["indent"] >= SPLIT_INDENT - box = self.box - if box and ( - direction - or box.is_direction - or key != box.key - or len(box.lines) >= self.limit() - or split - or (self.mode == "adv" and box.lines[-1]["indent"] >= SPLIT_INDENT) - ): - self.flush() - if self.box is None: - self.box = Box(key=key, speaker=key[0], is_direction=direction) - self.box.lines.append(line) - - def flush(self) -> None: - box = self.box - if not box: - return - self.box = None - first, last = box.lines[0], box.lines[-1] - ids = first["id"] if first is last else f"{first['id']} .. {last['id']}" - self.emit(f"# {ids}") - self.music(first["ann"].get("music")) - if self.mode == "adv": - self.stage(box) - text = "\\n".join(escape_text(line["text"]) for line in box.lines) - variable = char_var(box.speaker, nvl=self.mode == "nvl") - self.emit(f'{variable} "{text}"') - if self.mode == "nvl": - self.emit("nvl clear") - - def music(self, mood: str | None) -> None: - if mood is None: - return - if mood == "none": - if self.music_state["playing"]: - self.emit("stop music fadeout 1.0") - self.music_state["playing"] = None - elif mood in self.moods and self.music_state["playing"] != mood: - self.emit(f'play music "audio/{mood}.ogg" fadeout 1.0 fadein 1.0') - self.music_state["playing"] = mood - - # -- sprites --------------------------------------------------------------------- - - def stage(self, box: Box) -> None: - first = box.lines[0] - ann = first["ann"] - desired: list[str] = [] - # stage directions never change who is on stage - on_stage = self.last_on_stage if box.is_direction else ann["on_stage"] - if not box.is_direction: - self.last_on_stage = on_stage - for cid in self.pinned: - if self.work.cast[cid].get("sprite"): - desired.append(cid) - for entry in on_stage: - cid = entry["character"] - if cid not in self.work.cast: - raise ValueError(f"{first['id']}: on_stage character {cid!r} is not in [cast]") - if not self.work.cast[cid].get("sprite"): - continue - self.positions.setdefault(cid, entry["position"]) - if cid not in desired: - desired.append(cid) - changed = self.hide_sprites([c for c in list(self.shown) if c not in desired]) - for cid in desired: - expressions = self.work.cast[cid].get("expressions", {}) - neutral = expressions.get("neutral", "neutral") - if cid == box.speaker: - expression = expressions.get(ann["emotion"], neutral) - else: - expression = self.shown.get(cid, neutral) - if self.shown.get(cid) != expression: - self.emit(f"show {cid} {expression} at vn_{self.positions[cid]}") - self.shown[cid] = expression - changed = True - if changed: - self.emit("with dissolve") - - # -- scene --------------------------------------------------------------------------- - - def render(self) -> list[str]: - scene = self.scene - self.out.append(f"label scene_{scene['id']}:") - self.emit("scene black") - self.emit(f"show card_{scene['id']} at truecenter") - self.emit("with fade") - self.emit(f"pause {TITLE_PAUSE}") - self.emit(f"hide card_{scene['id']}") - if self.bg: - self.emit(f"scene {bg_image_name(self.bg)} at tint_{self.tint}") - self.emit("with fade") - for line in scene["lines"]: - self.feed(line) - self.flush() - if self.mode == "nvl": - self.emit("nvl hide dissolve") - self.out.append("") - return self.out - - -def validate_staging(work: Work, annotated: dict[str, Any]) -> None: - """Check the human-judgment layer (staging.cast, cue move, overrides) against the data.""" - cast = work.cast - scene_ids = [sc["id"] for sc in annotated["scenes"]] - for sid, cfg in work.data.get("staging", {}).items(): - if sid not in scene_ids: - raise ValueError(f"[staging.{sid}]: unknown scene") - for cid, pos in cfg.get("cast", {}).items(): - if cid not in cast: - raise ValueError(f"[staging.{sid}].cast: unknown character {cid!r}") - if pos not in VALID_POSITIONS: - raise ValueError(f"[staging.{sid}].cast: unknown position {pos!r}") - for cue in work.data.get("cues", []): - for cid, pos in cue.get("move", {}).items(): - if cid not in cast: - raise ValueError(f"cue at {cue['at']}: move of unknown character {cid!r}") - if pos not in VALID_POSITIONS: - raise ValueError(f"cue at {cue['at']}: unknown position {pos!r}") - - -def apply_overrides(work: Work, annotated: dict[str, Any]) -> dict[str, Any]: - """Return a copy of ``annotated`` with ``[[overrides]]`` emotions applied (inclusive ranges).""" - result = json.loads(json.dumps(annotated)) - where = {ln["id"]: (sc, i) for sc in result["scenes"] for i, ln in enumerate(sc["lines"])} - for ov in work.data.get("overrides", []): - if ov["emotion"] not in EMOTIONS: - raise ValueError( - f"override {ov['from']}..{ov['to']}: unknown emotion {ov['emotion']!r}" - ) - for key in ("from", "to"): - if ov[key] not in where: - raise ValueError(f"override: unknown line id {ov[key]!r}") - (scene, start), (scene_to, end) = where[ov["from"]], where[ov["to"]] - if scene is not scene_to or end < start: - raise ValueError(f"override {ov['from']}..{ov['to']}: not a range within one scene") - for line in scene["lines"][start : end + 1]: - line["ann"]["emotion"] = ov["emotion"] - return result - - -def render_script(work: Work, annotated: dict[str, Any], moods: set[str]) -> str: - validate_staging(work, annotated) - annotated = apply_overrides(work, annotated) - out = [ - "## Generated by `vnpipe renpy`. Do not edit: regenerate instead.", - "", - "label start:", - " window auto", - "", - ] - known = {c["at"] for c in work.data.get("cues", [])} - seen: set[str] = set() - music_state: dict[str, str | None] = {"playing": None} - for scene in annotated["scenes"]: - out.extend(SceneWriter(work, scene, moods, music_state).render()) - seen |= {line["id"] for line in scene["lines"]} - missing = known - seen - if missing: - raise ValueError(f"cues refer to unknown line ids: {sorted(missing)}") - out += [ - "label the_end:", - " scene black", - " with fade", - " show card_end at truecenter", - " with dissolve", - f" pause {END_PAUSE}", - " return", - "", - ] - return "\n".join(out) - - -# --- GUI images the SDK template leaves out -------------------------------------------------- -# `generate_gui` only makes a few GUI images; button, bar, scrollbar, slider, check and radio -# images are expected to exist (Ren'Py's prefix search falls back to the un-prefixed name). - -ACCENT = (201, 162, 91) -IVORY = (239, 230, 210) -DARK = (20, 17, 14) - - -def _solid(size: tuple[int, int], color: tuple[int, ...]) -> Image.Image: - return Image.new("RGBA", size, color) - - -def _check_image(selected: bool, round_: bool) -> Image.Image: - img = Image.new("RGBA", (38, 38), (0, 0, 0, 0)) - draw = ImageDraw.Draw(img) - box = [4, 4, 33, 33] - shape = draw.ellipse if round_ else draw.rectangle - shape(box, outline=IVORY + (255,), width=3) - if selected: - shape([12, 12, 25, 25], fill=ACCENT + (255,)) - return img - - -def gui_extra_images() -> dict[str, Image.Image]: - """Deterministic simple GUI images, keyed by path relative to ``game/``.""" - base: dict[str, Image.Image] = { - "button/background.png": _solid((24, 24), (0, 0, 0, 0)), - "button/hover_background.png": _solid((24, 24), ACCENT + (60,)), - "button/selected_background.png": _solid((24, 24), ACCENT + (35,)), - "button/check_foreground.png": _check_image(False, False), - "button/check_selected_foreground.png": _check_image(True, False), - "button/radio_foreground.png": _check_image(False, True), - "button/radio_selected_foreground.png": _check_image(True, True), - "bar/left.png": _solid((48, 48), ACCENT + (255,)), - "bar/right.png": _solid((48, 48), IVORY + (60,)), - "bar/top.png": _solid((48, 48), IVORY + (60,)), - "bar/bottom.png": _solid((48, 48), ACCENT + (255,)), - "slider/horizontal_bar.png": _solid((48, 48), IVORY + (60,)), - "slider/horizontal_thumb.png": _solid((20, 38), ACCENT + (255,)), - "slider/vertical_bar.png": _solid((48, 48), IVORY + (60,)), - "slider/vertical_thumb.png": _solid((38, 20), ACCENT + (255,)), - "scrollbar/horizontal_bar.png": _solid((48, 48), IVORY + (40,)), - "scrollbar/horizontal_thumb.png": _solid((48, 48), ACCENT + (255,)), - "scrollbar/vertical_bar.png": _solid((48, 48), IVORY + (40,)), - "scrollbar/vertical_thumb.png": _solid((48, 48), ACCENT + (255,)), - } - result = dict(base) - for path, img in base.items(): - result[f"phone/{path}"] = img - return {f"gui/{path}": img for path, img in sorted(result.items())} - - -E2E_FILE = "e2e_test.rpy" -E2E_TESTCASE = """## Generated by `vnpipe renpy --with-test`: end-to-end playthrough (testing only). -## Run with `renpy.sh test` (see docs/running.md). - -# The test runner only advances when frames are drawn; an always-running transform keeps -# the software renderer (used headless) drawing, including on the main menu. -transform e2e_tick: - xpos 0 - linear 0.05 xpos 1 - repeat - -screen e2e_ticker(): - zorder 1000 - add Null(1, 1) at e2e_tick - -init 999 python: - config.always_shown_screens.append("e2e_ticker") - e2e_state = {"end": False} - - def e2e_label(name, abnormal): - if name == "the_end": - e2e_state["end"] = True - - config.label_callbacks.append(e2e_label) - -testsuite global: - teardown: - exit - -testcase default: - $ _test.transition_timeout = 0.05 - $ _test.timeout = 30.0 - pause 1.0 - click "Start" - advance until eval (e2e_state["end"]) timeout 900 - advance until screen "main_menu" timeout 60 - assert eval (e2e_state["end"]) -""" - - -# --- static project files ----------------------------------------------------------------- - - -def render_characters(work: Work) -> str: - cast = dict(work.cast) - cast.setdefault("narrator", {"name": "", "color": "#d8cfc0"}) - out = ["## Generated by `vnpipe renpy`. Do not edit: regenerate instead.", ""] - for cid, info in cast.items(): - name = info.get("name") or "" - color = info.get("color") - who = quote(name) if name else "None" - props: list[str] = [] - if name and color: - props.append(f"who_color={_plain_quote(color)}") - if not name and color: - props.append(f"what_color={_plain_quote(color)}") - if cid == "narrator": - props.append("what_italic=True") - adv = ", ".join([who, *props]) - nvl_props = ["kind=nvl", *props] - if not name: - nvl_props.append('what_style="nvl_thought"') - out.append(f"define {char_var(cid)} = Character({adv})") - out.append(f"define {char_var(cid, nvl=True)} = Character({', '.join([who, *nvl_props])})") - out.append("") - return "\n".join(out) - - -def title_cards(work: Work, annotated: dict[str, Any]) -> dict[str, str]: - cards = {f"card_{sc['id']}": sc["heading"] for sc in annotated["scenes"]} - cards["card_end"] = work.data["work"].get("end_text", DEFAULT_END_TEXT) - return cards - - -def render_images(entries: list[ImageEntry], cards: dict[str, str]) -> str: - out = ["## Generated by `vnpipe renpy`. Do not edit: regenerate instead.", ""] - for name, text in cards.items(): # title cards: plain images, not `show text` - out.append(f'image {name} = Text("{escape_text(text)}", size=60, text_align=0.5)') - for e in entries: - out.append(f"image {e.name} = {_plain_quote('images/' + e.rel)}") - out.append("") - return "\n".join(out) - - -def _about(work: Work) -> str: - info = work.data["work"] - text_l, trans_l, tail = ABOUT_LABELS.get(info.get("language", "es"), ABOUT_LABELS["en"]) - parts = [info.get("subtitle", "")] - if info.get("author"): - parts.append(f"{text_l}: {info['author']}") - if info.get("translator"): - parts.append(f"{trans_l}: {info['translator']}") - parts.append(tail) - return "\\n\\n".join(escape_text(p) for p in parts if p) - - -def _substitute(text: str, values: dict[str, str]) -> str: - for key, value in values.items(): - text = text.replace(f"@@{key}@@", value) - if "@@" in text: - raise ValueError("unreplaced template token") - return text - - -def write_text(path: Path, text: str) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text, encoding="utf-8", newline="\n") - - -def _audio_moods(out: Path) -> set[str]: - audio = out / "game" / "audio" - return {p.stem for p in audio.glob("*.ogg")} if audio.is_dir() else set() - - -def generate( - work: Work, annotated: dict[str, Any], out: Path, with_test: bool = False -) -> list[Path]: - """Write the Ren'Py project into ``out``; returns every generated file (sorted).""" - info = work.data["work"] - manifest_path = work.path("assets/assets.json") - manifest = load_manifest(work.root) if manifest_path.is_file() else None - entries = collect_images(work, manifest) - game = out / "game" - for sub in ("images", "gui", "fonts"): - shutil.rmtree(game / sub, ignore_errors=True) - game.mkdir(parents=True, exist_ok=True) - - # GUI template: copy binaries, substitute tokens in .rpy files. - menu_bg = MENU_BG_FALLBACK - staging = work.data.get("staging", {}) - first_bg = info.get("menu_bg") or next((c["bg"] for c in staging.values() if c.get("bg")), None) - if first_bg: - menu_bg = bg_image_name(first_bg) - values = { - "TITLE": escape_text(info["title"]), - "VERSION": "0.1", - "ABOUT": _about(work), - "BUILD_NAME": f"{info['id']}-vn", - "SAVE_DIR": f"{info['id']}-vn", - "MENU_BG": menu_bg, - } - written: list[Path] = [] - for src in sorted((TEMPLATE_DIR / "game").rglob("*")): - if not src.is_file(): - continue - dest = game / src.relative_to(TEMPLATE_DIR / "game") - dest.parent.mkdir(parents=True, exist_ok=True) - written.append(dest) - if src.suffix == ".rpy": - write_text(dest, _substitute(src.read_text(encoding="utf-8"), values)) - else: - shutil.copyfile(src, dest) - - for rel, img in gui_extra_images().items(): - dest = game / rel - dest.parent.mkdir(parents=True, exist_ok=True) - if not dest.exists(): # never override an image shipped by the template - img.save(dest, "PNG") - written.append(dest) - test_file = game / E2E_FILE - test_file.unlink(missing_ok=True) - if with_test: - write_text(test_file, E2E_TESTCASE) - written.append(test_file) - for name, text in ( - ("characters.rpy", render_characters(work)), - ("images.rpy", render_images(entries, title_cards(work, annotated))), - ("script.rpy", render_script(work, annotated, _audio_moods(out))), - ): - write_text(game / name, text) - written.append(game / name) - - for e in entries: - dest = game / "images" / e.rel - dest.parent.mkdir(parents=True, exist_ok=True) - written.append(dest) - if e.source: - shutil.copyfile(e.source, dest) - else: - placeholder(e.asset).save(dest, "WEBP", quality=90) - - return sorted(written) - - -# --- CLI ---------------------------------------------------------------------------------- - - -def cmd_renpy(args: argparse.Namespace) -> int: - work = load_work(args.work) - if args.from_parsed: - parsed = json.loads(work.path("data/parsed.json").read_text(encoding="utf-8")) - validate(parsed, "parsed") - annotated = annotations_from_parsed(work, parsed) - else: - path = work.path("data/annotated.json") - if not path.is_file(): - raise SystemExit(f"renpy: {path} missing; run annotation or pass --from-parsed") - annotated = json.loads(path.read_text(encoding="utf-8")) - validate(annotated, "annotated") - out = args.out or Path("vn") / work.id - files = generate(work, annotated, out, with_test=args.with_test) - print(f"renpy: wrote {len(files)} files under {out}") - return 0 - - -def register(subparsers: argparse._SubParsersAction) -> None: - parser = subparsers.add_parser("renpy", help="Generate the Ren'Py project") - parser.add_argument( - "--from-parsed", - action="store_true", - help="Build trivial annotations from parsed.json instead of reading annotated.json", - ) - parser.add_argument( - "--with-test", - action="store_true", - help=f"Also write game/{E2E_FILE}: an end-to-end playthrough for `renpy.sh test`", - ) - parser.add_argument("--out", type=Path, help="Output directory (default: vn/)") - parser.set_defaults(handler=cmd_renpy) diff --git a/src/vnpipe/renpy_templates/game/fonts/RobotoSlab-Bold.ttf b/src/vnpipe/renpy_templates/game/fonts/RobotoSlab-Bold.ttf deleted file mode 100644 index df5d1df..0000000 Binary files a/src/vnpipe/renpy_templates/game/fonts/RobotoSlab-Bold.ttf and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/fonts/RobotoSlab-Regular.ttf b/src/vnpipe/renpy_templates/game/fonts/RobotoSlab-Regular.ttf deleted file mode 100644 index eb52a79..0000000 Binary files a/src/vnpipe/renpy_templates/game/fonts/RobotoSlab-Regular.ttf and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui.rpy b/src/vnpipe/renpy_templates/game/gui.rpy deleted file mode 100644 index 95e08eb..0000000 --- a/src/vnpipe/renpy_templates/game/gui.rpy +++ /dev/null @@ -1,480 +0,0 @@ -################################################################################ -## Initialization -################################################################################ - -## The init offset statement causes the initialization statements in this file -## to run before init statements in any other file. -init offset = -2 - -## Calling gui.init resets the styles to sensible default values, and sets the -## width and height of the game. -init python: - gui.init(1920, 1080) - -## Enable checks for invalid or unstable properties in screens or transforms -define config.check_conflicting_properties = True - - -################################################################################ -## GUI Configuration Variables -################################################################################ - - -## Colors ###################################################################### -## -## The colors of text in the interface. - -## An accent color used throughout the interface to label and highlight text. -define gui.accent_color = '#c9a25b' - -## The color used for a text button when it is neither selected nor hovered. -define gui.idle_color = '#888888' - -## The small color is used for small text, which needs to be brighter/darker to -## achieve the same effect. -define gui.idle_small_color = '#aaaaaa' - -## The color that is used for buttons and bars that are hovered. -define gui.hover_color = '#dec79c' - -## The color used for a text button when it is selected but not focused. A -## button is selected if it is the current screen or preference value. -define gui.selected_color = '#ffffff' - -## The color used for a text button when it cannot be selected. -define gui.insensitive_color = '#8888887f' - -## Colors used for the portions of bars that are not filled in. These are not -## used directly, but are used when re-generating bar image files. -define gui.muted_color = '#504024' -define gui.hover_muted_color = '#786136' - -## The colors used for dialogue and menu choice text. -define gui.text_color = '#efe6d2' -define gui.interface_text_color = '#efe6d2' - - -## Fonts and Font Sizes ######################################################## - -## The font used for in-game text. -define gui.text_font = "fonts/RobotoSlab-Regular.ttf" - -## The font used for character names. -define gui.name_text_font = "fonts/RobotoSlab-Regular.ttf" - -## The font used for out-of-game text. -define gui.interface_text_font = "fonts/RobotoSlab-Regular.ttf" - -## The size of normal dialogue text. -define gui.text_size = 33 - -## The size of character names. -define gui.name_text_size = 45 - -## The size of text in the game's user interface. -define gui.interface_text_size = 33 - -## The size of labels in the game's user interface. -define gui.label_text_size = 36 - -## The size of text on the notify screen. -define gui.notify_text_size = 24 - -## The size of the game's title. -define gui.title_text_size = 75 - - -## Main and Game Menus ######################################################### - -## The images used for the main and game menus. -define gui.main_menu_background = "@@MENU_BG@@" -define gui.game_menu_background = "@@MENU_BG@@" - - -## Dialogue #################################################################### -## -## These variables control how dialogue is displayed on the screen one line at a -## time. - -## The height of the textbox containing dialogue. -define gui.textbox_height = 278 - -## The placement of the textbox vertically on the screen. 0.0 is the top, 0.5 is -## center, and 1.0 is the bottom. -define gui.textbox_yalign = 1.0 - - -## The placement of the speaking character's name, relative to the textbox. -## These can be a whole number of pixels from the left or top, or 0.5 to center. -define gui.name_xpos = 360 -define gui.name_ypos = 0 - -## The horizontal alignment of the character's name. This can be 0.0 for left- -## aligned, 0.5 for centered, and 1.0 for right-aligned. -define gui.name_xalign = 0.0 - -## The width, height, and borders of the box containing the character's name, or -## None to automatically size it. -define gui.namebox_width = None -define gui.namebox_height = None - -## The borders of the box containing the character's name, in left, top, right, -## bottom order. -define gui.namebox_borders = Borders(5, 5, 5, 5) - -## If True, the background of the namebox will be tiled, if False, the -## background of the namebox will be scaled. -define gui.namebox_tile = False - - -## The placement of dialogue relative to the textbox. These can be a whole -## number of pixels relative to the left or top side of the textbox, or 0.5 to -## center. -define gui.dialogue_xpos = 402 -define gui.dialogue_ypos = 75 - -## The maximum width of dialogue text, in pixels. -define gui.dialogue_width = 1116 - -## The horizontal alignment of the dialogue text. This can be 0.0 for left- -## aligned, 0.5 for centered, and 1.0 for right-aligned. -define gui.dialogue_text_xalign = 0.0 - - -## Buttons ##################################################################### -## -## These variables, along with the image files in gui/button, control aspects of -## how buttons are displayed. - -## The width and height of a button, in pixels. If None, Ren'Py computes a size. -define gui.button_width = None -define gui.button_height = None - -## The borders on each side of the button, in left, top, right, bottom order. -define gui.button_borders = Borders(6, 6, 6, 6) - -## If True, the background image will be tiled. If False, the background image -## will be linearly scaled. -define gui.button_tile = False - -## The font used by the button. -define gui.button_text_font = gui.interface_text_font - -## The size of the text used by the button. -define gui.button_text_size = gui.interface_text_size - -## The color of button text in various states. -define gui.button_text_idle_color = gui.idle_color -define gui.button_text_hover_color = gui.hover_color -define gui.button_text_selected_color = gui.selected_color -define gui.button_text_insensitive_color = gui.insensitive_color - -## The horizontal alignment of the button text. (0.0 is left, 0.5 is center, 1.0 -## is right). -define gui.button_text_xalign = 0.0 - - -## These variables override settings for different kinds of buttons. Please see -## the gui documentation for the kinds of buttons available, and what each is -## used for. -## -## These customizations are used by the default interface: - -define gui.radio_button_borders = Borders(27, 6, 6, 6) - -define gui.check_button_borders = Borders(27, 6, 6, 6) - -define gui.confirm_button_text_xalign = 0.5 - -define gui.page_button_borders = Borders(15, 6, 15, 6) - -define gui.quick_button_borders = Borders(15, 6, 15, 0) -define gui.quick_button_text_size = 21 -define gui.quick_button_text_idle_color = gui.idle_small_color -define gui.quick_button_text_selected_color = gui.accent_color - -## You can also add your own customizations, by adding properly-named variables. -## For example, you can uncomment the following line to set the width of a -## navigation button. - -# define gui.navigation_button_width = 250 - - -## Choice Buttons ############################################################## -## -## Choice buttons are used in the in-game menus. - -define gui.choice_button_width = 1185 -define gui.choice_button_height = None -define gui.choice_button_tile = False -define gui.choice_button_borders = Borders(150, 8, 150, 8) -define gui.choice_button_text_font = gui.text_font -define gui.choice_button_text_size = gui.text_size -define gui.choice_button_text_xalign = 0.5 -define gui.choice_button_text_idle_color = '#888888' -define gui.choice_button_text_hover_color = "#ffffff" -define gui.choice_button_text_insensitive_color = '#8888887f' - - -## File Slot Buttons ########################################################### -## -## A file slot button is a special kind of button. It contains a thumbnail -## image, and text describing the contents of the save slot. A save slot uses -## image files in gui/button, like the other kinds of buttons. - -## The save slot button. -define gui.slot_button_width = 414 -define gui.slot_button_height = 309 -define gui.slot_button_borders = Borders(15, 15, 15, 15) -define gui.slot_button_text_size = 21 -define gui.slot_button_text_xalign = 0.5 -define gui.slot_button_text_idle_color = gui.idle_small_color -define gui.slot_button_text_selected_idle_color = gui.selected_color -define gui.slot_button_text_selected_hover_color = gui.hover_color - -## The width and height of thumbnails used by the save slots. -define config.thumbnail_width = 384 -define config.thumbnail_height = 216 - -## The number of columns and rows in the grid of save slots. -define gui.file_slot_cols = 3 -define gui.file_slot_rows = 2 - - -## Positioning and Spacing ##################################################### -## -## These variables control the positioning and spacing of various user interface -## elements. - -## The position of the left side of the navigation buttons, relative to the left -## side of the screen. -define gui.navigation_xpos = 60 - -## The vertical position of the skip indicator. -define gui.skip_ypos = 15 - -## The vertical position of the notify screen. -define gui.notify_ypos = 68 - -## The spacing between menu choices. -define gui.choice_spacing = 33 - -## Buttons in the navigation section of the main and game menus. -define gui.navigation_spacing = 6 - -## Controls the amount of spacing between preferences. -define gui.pref_spacing = 15 - -## Controls the amount of spacing between preference buttons. -define gui.pref_button_spacing = 0 - -## The spacing between file page buttons. -define gui.page_spacing = 0 - -## The spacing between file slots. -define gui.slot_spacing = 15 - -## The position of the main menu text. -define gui.main_menu_text_xalign = 1.0 - - -## Frames ###################################################################### -## -## These variables control the look of frames that can contain user interface -## components when an overlay or window is not present. - -## Generic frames. -define gui.frame_borders = Borders(6, 6, 6, 6) - -## The frame that is used as part of the confirm screen. -define gui.confirm_frame_borders = Borders(60, 60, 60, 60) - -## The frame that is used as part of the skip screen. -define gui.skip_frame_borders = Borders(24, 8, 75, 8) - -## The frame that is used as part of the notify screen. -define gui.notify_frame_borders = Borders(24, 8, 60, 8) - -## Should frame backgrounds be tiled? -define gui.frame_tile = False - - -## Bars, Scrollbars, and Sliders ############################################### -## -## These control the look and size of bars, scrollbars, and sliders. -## -## The default GUI only uses sliders and vertical scrollbars. All of the other -## bars are only used in creator-written screens. - -## The height of horizontal bars, scrollbars, and sliders. The width of vertical -## bars, scrollbars, and sliders. -define gui.bar_size = 38 -define gui.scrollbar_size = 18 -define gui.slider_size = 38 - -## True if bar images should be tiled. False if they should be linearly scaled. -define gui.bar_tile = False -define gui.scrollbar_tile = False -define gui.slider_tile = False - -## Horizontal borders. -define gui.bar_borders = Borders(6, 6, 6, 6) -define gui.scrollbar_borders = Borders(6, 6, 6, 6) -define gui.slider_borders = Borders(6, 6, 6, 6) - -## Vertical borders. -define gui.vbar_borders = Borders(6, 6, 6, 6) -define gui.vscrollbar_borders = Borders(6, 6, 6, 6) -define gui.vslider_borders = Borders(6, 6, 6, 6) - -## What to do with unscrollable scrollbars in the game menu. "hide" hides them, -## while None shows them. -define gui.unscrollable = "hide" - - -## History ##################################################################### -## -## The history screen displays dialogue that the player has already dismissed. - -## The number of blocks of dialogue history Ren'Py will keep. -define config.history_length = 250 - -## The height of a history screen entry, or None to make the height variable at -## the cost of performance. -define gui.history_height = 210 - -## Additional space to add between history screen entries. -define gui.history_spacing = 0 - -## The position, width, and alignment of the label giving the name of the -## speaking character. -define gui.history_name_xpos = 233 -define gui.history_name_ypos = 0 -define gui.history_name_width = 233 -define gui.history_name_xalign = 1.0 - -## The position, width, and alignment of the dialogue text. -define gui.history_text_xpos = 255 -define gui.history_text_ypos = 3 -define gui.history_text_width = 1110 -define gui.history_text_xalign = 0.0 - - -## NVL-Mode #################################################################### -## -## The NVL-mode screen displays the dialogue spoken by NVL-mode characters. - -## The borders of the background of the NVL-mode background window. -define gui.nvl_borders = Borders(0, 15, 0, 30) - -## The maximum number of NVL-mode entries Ren'Py will display. When more entries -## than this are to be show, the oldest entry will be removed. -define gui.nvl_list_length = 12 - -## The height of an NVL-mode entry. Set this to None to have the entries -## dynamically adjust height. -define gui.nvl_height = None - -## The spacing between NVL-mode entries when gui.nvl_height is None, and between -## NVL-mode entries and an NVL-mode menu. -define gui.nvl_spacing = 15 - -## The position, width, and alignment of the label giving the name of the -## speaking character. -define gui.nvl_name_xpos = 645 -define gui.nvl_name_ypos = 0 -define gui.nvl_name_width = 225 -define gui.nvl_name_xalign = 1.0 - -## The position, width, and alignment of the dialogue text. -define gui.nvl_text_xpos = 675 -define gui.nvl_text_ypos = 12 -define gui.nvl_text_width = 885 -define gui.nvl_text_xalign = 0.0 - -## The position, width, and alignment of nvl_thought text (the text said by the -## nvl_narrator character.) -define gui.nvl_thought_xpos = 360 -define gui.nvl_thought_ypos = 0 -define gui.nvl_thought_width = 1170 -define gui.nvl_thought_xalign = 0.0 - -## The position of nvl menu_buttons. -define gui.nvl_button_xpos = 675 -define gui.nvl_button_xalign = 0.0 - - -## Localization ################################################################ - -## This controls where a line break is permitted. The default is suitable -## for most languages. A list of available values can be found at https:// -## www.renpy.org/doc/html/style_properties.html#style-property-language - -define gui.language = "unicode" - - -################################################################################ -## Mobile devices -################################################################################ - -init python: - - ## This increases the size of the quick buttons to make them easier to touch - ## on tablets and phones. - @gui.variant - def touch(): - - gui.quick_button_borders = Borders(60, 21, 60, 0) - - ## This changes the size and spacing of various GUI elements to ensure they - ## are easily visible on phones. - @gui.variant - def small(): - - ## Font sizes. - gui.text_size = 45 - gui.name_text_size = 54 - gui.notify_text_size = 38 - gui.interface_text_size = 45 - gui.button_text_size = 45 - gui.label_text_size = 51 - - ## Adjust the location of the textbox. - gui.textbox_height = 360 - gui.name_xpos = 120 - gui.dialogue_xpos = 135 - gui.dialogue_width = 1650 - - ## Change the size and spacing of various things. - gui.slider_size = 54 - - gui.choice_button_width = 1860 - gui.choice_button_text_size = 45 - - gui.navigation_spacing = 30 - gui.pref_button_spacing = 15 - - gui.history_height = 285 - gui.history_text_width = 1035 - - gui.quick_button_text_size = 30 - - ## File button layout. - gui.file_slot_cols = 2 - gui.file_slot_rows = 2 - - ## NVL-mode. - gui.nvl_height = None - - gui.nvl_name_width = 458 - gui.nvl_name_xpos = 488 - - gui.nvl_text_width = 1373 - gui.nvl_text_xpos = 518 - gui.nvl_text_ypos = 8 - - gui.nvl_thought_width = 1860 - gui.nvl_thought_xpos = 30 - - gui.nvl_button_width = 1860 - gui.nvl_button_xpos = 30 diff --git a/src/vnpipe/renpy_templates/game/gui/bubble.png b/src/vnpipe/renpy_templates/game/gui/bubble.png deleted file mode 100644 index 3b23ff3..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/bubble.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/button/choice_hover_background.png b/src/vnpipe/renpy_templates/game/gui/button/choice_hover_background.png deleted file mode 100644 index d2cdd41..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/button/choice_hover_background.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/button/choice_idle_background.png b/src/vnpipe/renpy_templates/game/gui/button/choice_idle_background.png deleted file mode 100644 index 1570796..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/button/choice_idle_background.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/button/quick_hover_background.png b/src/vnpipe/renpy_templates/game/gui/button/quick_hover_background.png deleted file mode 100644 index 0ecc7c9..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/button/quick_hover_background.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/button/quick_idle_background.png b/src/vnpipe/renpy_templates/game/gui/button/quick_idle_background.png deleted file mode 100644 index 0ecc7c9..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/button/quick_idle_background.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/frame.png b/src/vnpipe/renpy_templates/game/gui/frame.png deleted file mode 100644 index 4a8851d..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/frame.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/game_menu.png b/src/vnpipe/renpy_templates/game/gui/game_menu.png deleted file mode 100644 index ffbba15..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/game_menu.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/main_menu.png b/src/vnpipe/renpy_templates/game/gui/main_menu.png deleted file mode 100644 index ffbba15..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/main_menu.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/namebox.png b/src/vnpipe/renpy_templates/game/gui/namebox.png deleted file mode 100644 index c24135c..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/namebox.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/notify.png b/src/vnpipe/renpy_templates/game/gui/notify.png deleted file mode 100644 index c27b714..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/notify.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/nvl.png b/src/vnpipe/renpy_templates/game/gui/nvl.png deleted file mode 100644 index 5e55ec8..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/nvl.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/overlay/confirm.png b/src/vnpipe/renpy_templates/game/gui/overlay/confirm.png deleted file mode 100644 index b95c47c..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/overlay/confirm.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/overlay/game_menu.png b/src/vnpipe/renpy_templates/game/gui/overlay/game_menu.png deleted file mode 100644 index 5c588b7..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/overlay/game_menu.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/overlay/main_menu.png b/src/vnpipe/renpy_templates/game/gui/overlay/main_menu.png deleted file mode 100644 index e56f58e..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/overlay/main_menu.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/phone/button/choice_hover_background.png b/src/vnpipe/renpy_templates/game/gui/phone/button/choice_hover_background.png deleted file mode 100644 index d2cdd41..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/phone/button/choice_hover_background.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/phone/button/choice_idle_background.png b/src/vnpipe/renpy_templates/game/gui/phone/button/choice_idle_background.png deleted file mode 100644 index 1570796..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/phone/button/choice_idle_background.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/phone/nvl.png b/src/vnpipe/renpy_templates/game/gui/phone/nvl.png deleted file mode 100644 index 51d2c7b..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/phone/nvl.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/phone/overlay/game_menu.png b/src/vnpipe/renpy_templates/game/gui/phone/overlay/game_menu.png deleted file mode 100644 index 564cff0..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/phone/overlay/game_menu.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/phone/overlay/main_menu.png b/src/vnpipe/renpy_templates/game/gui/phone/overlay/main_menu.png deleted file mode 100644 index a599090..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/phone/overlay/main_menu.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/phone/textbox.png b/src/vnpipe/renpy_templates/game/gui/phone/textbox.png deleted file mode 100644 index 2321b23..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/phone/textbox.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/skip.png b/src/vnpipe/renpy_templates/game/gui/skip.png deleted file mode 100644 index 2f529ac..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/skip.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/textbox.png b/src/vnpipe/renpy_templates/game/gui/textbox.png deleted file mode 100644 index 9374b64..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/textbox.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/thoughtbubble.png b/src/vnpipe/renpy_templates/game/gui/thoughtbubble.png deleted file mode 100644 index 8d5d44b..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/thoughtbubble.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/window_icon.png b/src/vnpipe/renpy_templates/game/gui/window_icon.png deleted file mode 100644 index 64b4326..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/window_icon.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/options.rpy b/src/vnpipe/renpy_templates/game/options.rpy deleted file mode 100644 index 8d12ee3..0000000 --- a/src/vnpipe/renpy_templates/game/options.rpy +++ /dev/null @@ -1,208 +0,0 @@ -## This file contains options that can be changed to customize your game. -## -## Lines beginning with two '#' marks are comments, and you shouldn't uncomment -## them. Lines beginning with a single '#' mark are commented-out code, and you -## may want to uncomment them when appropriate. - - -## Basics ###################################################################### - -## A human-readable name of the game. This is used to set the default window -## title, and shows up in the interface and error reports. -## -## The _() surrounding the string marks it as eligible for translation. - -define config.name = _("@@TITLE@@") - - -## Determines if the title given above is shown on the main menu screen. Set -## this to False to hide the title. - -define gui.show_name = True - - -## The version of the game. - -define config.version = "@@VERSION@@" - - -## Text that is placed on the game's about screen. Place the text between the -## triple-quotes, and leave a blank line between paragraphs. - -define gui.about = _p("""@@ABOUT@@""") - - -## A short name for the game used for executables and directories in the built -## distribution. This must be ASCII-only, and must not contain spaces, colons, -## or semicolons. - -define build.name = "@@BUILD_NAME@@" - - -## Sounds and music ############################################################ - -## These three variables control, among other things, which mixers are shown -## to the player by default. Setting one of these to False will hide the -## appropriate mixer. - -define config.has_sound = False -define config.has_music = False -define config.has_voice = True - - -## To allow the user to play a test sound on the sound or voice channel, -## uncomment a line below and use it to set a sample sound to play. - -# define config.sample_sound = "sample-sound.ogg" -# define config.sample_voice = "sample-voice.ogg" - - -## Uncomment the following line to set an audio file that will be played while -## the player is at the main menu. This file will continue playing into the -## game, until it is stopped or another file is played. - -# define config.main_menu_music = "main-menu-theme.ogg" - - -## Transitions ################################################################# -## -## These variables set transitions that are used when certain events occur. -## Each variable should be set to a transition, or None to indicate that no -## transition should be used. - -## Entering or exiting the game menu. - -define config.enter_transition = dissolve -define config.exit_transition = dissolve - - -## Between screens of the game menu. - -define config.intra_transition = dissolve - - -## A transition that is used after a game has been loaded. - -define config.after_load_transition = None - - -## Used when entering the main menu after the game has ended. - -define config.end_game_transition = None - - -## A variable to set the transition used when the game starts does not exist. -## Instead, use a with statement after showing the initial scene. - - -## Window management ########################################################### -## -## This controls when the dialogue window is displayed. If "show", it is always -## displayed. If "hide", it is only displayed when dialogue is present. If -## "auto", the window is hidden before scene statements and shown again once -## dialogue is displayed. -## -## After the game has started, this can be changed with the "window show", -## "window hide", and "window auto" statements. - -define config.window = "auto" - - -## Transitions used to show and hide the dialogue window - -define config.window_show_transition = Dissolve(.2) -define config.window_hide_transition = Dissolve(.2) - - -## Preference defaults ######################################################### - -## Controls the default text speed. The default, 0, is infinite, while any other -## number is the number of characters per second to type out. - -default preferences.text_cps = 0 - - -## The default auto-forward delay. Larger numbers lead to longer waits, with 0 -## to 30 being the valid range. - -default preferences.afm_time = 15 - - -## Save directory ############################################################## -## -## Controls the platform-specific place Ren'Py will place the save files for -## this game. The save files will be placed in: -## -## Windows: %APPDATA\RenPy\ -## -## Macintosh: $HOME/Library/RenPy/ -## -## Linux: $HOME/.renpy/ -## -## This generally should not be changed, and if it is, should always be a -## literal string, not an expression. - -define config.save_directory = "@@SAVE_DIR@@" - - -## Icon ######################################################################## -## -## The icon displayed on the taskbar or dock. - -define config.window_icon = "gui/window_icon.png" - - -## Build configuration ######################################################### -## -## This section controls how Ren'Py turns your project into distribution files. - -init python: - - ## The following functions take file patterns. File patterns are case- - ## insensitive, and matched against the path relative to the base directory, - ## with and without a leading /. If multiple patterns match, the first is - ## used. - ## - ## In a pattern: - ## - ## / is the directory separator. - ## - ## * matches all characters, except the directory separator. - ## - ## ** matches all characters, including the directory separator. - ## - ## For example, "*.txt" matches txt files in the base directory, "game/ - ## **.ogg" matches ogg files in the game directory or any of its - ## subdirectories, and "**.psd" matches psd files anywhere in the project. - - ## Classify files as None to exclude them from the built distributions. - - build.classify('**~', None) - build.classify('**.bak', None) - build.classify('**/.**', None) - build.classify('**/#**', None) - build.classify('**/thumbs.db', None) - - ## To archive files, classify them as 'archive'. - - # build.classify('game/**.png', 'archive') - # build.classify('game/**.jpg', 'archive') - - ## Files matching documentation patterns are duplicated in a mac app build, - ## so they appear in both the app and the zip file. - - build.documentation('*.html') - build.documentation('*.txt') - - -## A Google Play license key is required to perform in-app purchases. It can be -## found in the Google Play developer console, under "Monetize" > "Monetization -## Setup" > "Licensing". - -# define build.google_play_key = "..." - - -## The username and project name associated with an itch.io project, separated -## by a slash. - -# define build.itch_project = "renpytom/test-project" diff --git a/src/vnpipe/renpy_templates/game/screens.rpy b/src/vnpipe/renpy_templates/game/screens.rpy deleted file mode 100644 index d601f80..0000000 --- a/src/vnpipe/renpy_templates/game/screens.rpy +++ /dev/null @@ -1,1621 +0,0 @@ -################################################################################ -## Initialization -################################################################################ - -init offset = -1 - - -################################################################################ -## Styles -################################################################################ - -style default: - properties gui.text_properties() - language gui.language - -style input: - properties gui.text_properties("input", accent=True) - adjust_spacing False - -style hyperlink_text: - properties gui.text_properties("hyperlink", accent=True) - hover_underline True - -style gui_text: - properties gui.text_properties("interface") - - -style button: - properties gui.button_properties("button") - -style button_text is gui_text: - properties gui.text_properties("button") - yalign 0.5 - - -style label_text is gui_text: - properties gui.text_properties("label", accent=True) - -style prompt_text is gui_text: - properties gui.text_properties("prompt") - - -style bar: - ysize gui.bar_size - left_bar Frame("gui/bar/left.png", gui.bar_borders, tile=gui.bar_tile) - right_bar Frame("gui/bar/right.png", gui.bar_borders, tile=gui.bar_tile) - -style vbar: - xsize gui.bar_size - top_bar Frame("gui/bar/top.png", gui.vbar_borders, tile=gui.bar_tile) - bottom_bar Frame("gui/bar/bottom.png", gui.vbar_borders, tile=gui.bar_tile) - -style scrollbar: - ysize gui.scrollbar_size - base_bar Frame("gui/scrollbar/horizontal_[prefix_]bar.png", gui.scrollbar_borders, tile=gui.scrollbar_tile) - thumb Frame("gui/scrollbar/horizontal_[prefix_]thumb.png", gui.scrollbar_borders, tile=gui.scrollbar_tile) - -style vscrollbar: - xsize gui.scrollbar_size - base_bar Frame("gui/scrollbar/vertical_[prefix_]bar.png", gui.vscrollbar_borders, tile=gui.scrollbar_tile) - thumb Frame("gui/scrollbar/vertical_[prefix_]thumb.png", gui.vscrollbar_borders, tile=gui.scrollbar_tile) - -style slider: - ysize gui.slider_size - base_bar Frame("gui/slider/horizontal_[prefix_]bar.png", gui.slider_borders, tile=gui.slider_tile) - thumb "gui/slider/horizontal_[prefix_]thumb.png" - -style vslider: - xsize gui.slider_size - base_bar Frame("gui/slider/vertical_[prefix_]bar.png", gui.vslider_borders, tile=gui.slider_tile) - thumb "gui/slider/vertical_[prefix_]thumb.png" - - -style frame: - padding gui.frame_borders.padding - background Frame("gui/frame.png", gui.frame_borders, tile=gui.frame_tile) - - - -################################################################################ -## In-game screens -################################################################################ - - -## Say screen ################################################################## -## -## The say screen is used to display dialogue to the player. It takes two -## parameters, who and what, which are the name of the speaking character and -## the text to be displayed, respectively. (The who parameter can be None if no -## name is given.) -## -## This screen must create a text displayable with id "what", as Ren'Py uses -## this to manage text display. It can also create displayables with id "who" -## and id "window" to apply style properties. -## -## https://www.renpy.org/doc/html/screen_special.html#say - -screen say(who, what): - - window: - id "window" - - if who is not None: - - window: - id "namebox" - style "namebox" - text who id "who" - - text what id "what" - - - ## If there's a side image, display it above the text. Do not display on the - ## phone variant - there's no room. - if not renpy.variant("small"): - add SideImage() xalign 0.0 yalign 1.0 - - -## Make the namebox available for styling through the Character object. -init python: - config.character_id_prefixes.append('namebox') - -style window is default -style say_label is default -style say_dialogue is default -style say_thought is say_dialogue - -style namebox is default -style namebox_label is say_label - - -style window: - xalign 0.5 - xfill True - yalign gui.textbox_yalign - ysize gui.textbox_height - - background Image("gui/textbox.png", xalign=0.5, yalign=1.0) - -style namebox: - xpos gui.name_xpos - xanchor gui.name_xalign - xsize gui.namebox_width - ypos gui.name_ypos - ysize gui.namebox_height - - background Frame("gui/namebox.png", gui.namebox_borders, tile=gui.namebox_tile, xalign=gui.name_xalign) - padding gui.namebox_borders.padding - -style say_label: - properties gui.text_properties("name", accent=True) - xalign gui.name_xalign - yalign 0.5 - -style say_dialogue: - properties gui.text_properties("dialogue") - - xpos gui.dialogue_xpos - xsize gui.dialogue_width - ypos gui.dialogue_ypos - - adjust_spacing False - -## Input screen ################################################################ -## -## This screen is used to display renpy.input. The prompt parameter is used to -## pass a text prompt in. -## -## This screen must create an input displayable with id "input" to accept the -## various input parameters. -## -## https://www.renpy.org/doc/html/screen_special.html#input - -screen input(prompt): - style_prefix "input" - - window: - - vbox: - xanchor gui.dialogue_text_xalign - xpos gui.dialogue_xpos - xsize gui.dialogue_width - ypos gui.dialogue_ypos - - text prompt style "input_prompt" - input id "input" - -style input_prompt is default - -style input_prompt: - xalign gui.dialogue_text_xalign - properties gui.text_properties("input_prompt") - -style input: - xalign gui.dialogue_text_xalign - xmaximum gui.dialogue_width - - -## Choice screen ############################################################### -## -## This screen is used to display the in-game choices presented by the menu -## statement. The one parameter, items, is a list of objects, each with caption -## and action fields. -## -## https://www.renpy.org/doc/html/screen_special.html#choice - -screen choice(items): - style_prefix "choice" - - vbox: - for i in items: - textbutton i.caption action i.action - - -style choice_vbox is vbox -style choice_button is button -style choice_button_text is button_text - -style choice_vbox: - xalign 0.5 - ypos 405 - yanchor 0.5 - - spacing gui.choice_spacing - -style choice_button is default: - properties gui.button_properties("choice_button") - -style choice_button_text is default: - properties gui.text_properties("choice_button") - - -## Quick Menu screen ########################################################### -## -## The quick menu is displayed in-game to provide easy access to the out-of-game -## menus. - -screen quick_menu(): - - ## Ensure this appears on top of other screens. - zorder 100 - - if quick_menu: - - hbox: - style_prefix "quick" - style "quick_menu" - - textbutton _("Back") action Rollback() - textbutton _("History") action ShowMenu('history') - textbutton _("Skip") action Skip() alternate Skip(fast=True, confirm=True) - textbutton _("Auto") action Preference("auto-forward", "toggle") - textbutton _("Save") action ShowMenu('save') - textbutton _("Q.Save") action QuickSave() - textbutton _("Q.Load") action QuickLoad() - textbutton _("Prefs") action ShowMenu('preferences') - - -## This code ensures that the quick_menu screen is displayed in-game, whenever -## the player has not explicitly hidden the interface. -init python: - config.overlay_screens.append("quick_menu") - -default quick_menu = True - -style quick_menu is hbox -style quick_button is default -style quick_button_text is button_text - -style quick_menu: - xalign 0.5 - yalign 1.0 - -style quick_button: - properties gui.button_properties("quick_button") - -style quick_button_text: - properties gui.text_properties("quick_button") - - -################################################################################ -## Main and Game Menu Screens -################################################################################ - -## Navigation screen ########################################################### -## -## This screen is included in the main and game menus, and provides navigation -## to other menus, and to start the game. - -screen navigation(): - - vbox: - style_prefix "navigation" - - xpos gui.navigation_xpos - yalign 0.5 - - spacing gui.navigation_spacing - - if main_menu: - - textbutton _("Start") action Start() - - else: - - textbutton _("History") action ShowMenu("history") - - textbutton _("Save") action ShowMenu("save") - - textbutton _("Load") action ShowMenu("load") - - textbutton _("Preferences") action ShowMenu("preferences") - - if _in_replay: - - textbutton _("End Replay") action EndReplay(confirm=True) - - elif not main_menu: - - textbutton _("Main Menu") action MainMenu() - - textbutton _("About") action ShowMenu("about") - - if renpy.variant("pc") or (renpy.variant("web") and not renpy.variant("mobile")): - - ## Help isn't necessary or relevant to mobile devices. - textbutton _("Help") action ShowMenu("help") - - if renpy.variant("pc"): - - ## The quit button is banned on iOS and unnecessary on Android and - ## Web. - textbutton _("Quit") action Quit(confirm=not main_menu) - - -style navigation_button is gui_button -style navigation_button_text is gui_button_text - -style navigation_button: - size_group "navigation" - properties gui.button_properties("navigation_button") - -style navigation_button_text: - properties gui.text_properties("navigation_button") - - -## Main Menu screen ############################################################ -## -## Used to display the main menu when Ren'Py starts. -## -## https://www.renpy.org/doc/html/screen_special.html#main-menu - -screen main_menu(): - - ## This ensures that any other menu screen is replaced. - tag menu - - add gui.main_menu_background - - ## This empty frame darkens the main menu. - frame: - style "main_menu_frame" - - ## The use statement includes another screen inside this one. The actual - ## contents of the main menu are in the navigation screen. - use navigation - - if gui.show_name: - - vbox: - style "main_menu_vbox" - - text "[config.name!t]": - style "main_menu_title" - - text "[config.version]": - style "main_menu_version" - - -style main_menu_frame is empty -style main_menu_vbox is vbox -style main_menu_text is gui_text -style main_menu_title is main_menu_text -style main_menu_version is main_menu_text - -style main_menu_frame: - xsize 420 - yfill True - - background "gui/overlay/main_menu.png" - -style main_menu_vbox: - xalign 1.0 - xoffset -30 - xmaximum 1200 - yalign 1.0 - yoffset -30 - -style main_menu_text: - properties gui.text_properties("main_menu", accent=True) - -style main_menu_title: - properties gui.text_properties("title") - -style main_menu_version: - properties gui.text_properties("version") - - -## Game Menu screen ############################################################ -## -## This lays out the basic common structure of a game menu screen. It's called -## with the screen title, and displays the background, title, and navigation. -## -## The scroll parameter can be None, or one of "viewport" or "vpgrid". -## This screen is intended to be used with one or more children, which are -## transcluded (placed) inside it. - -screen game_menu(title, scroll=None, yinitial=0.0, spacing=0): - - style_prefix "game_menu" - - if main_menu: - add gui.main_menu_background - else: - add gui.game_menu_background - - frame: - style "game_menu_outer_frame" - - hbox: - - ## Reserve space for the navigation section. - frame: - style "game_menu_navigation_frame" - - frame: - style "game_menu_content_frame" - - if scroll == "viewport": - - viewport: - yinitial yinitial - scrollbars "vertical" - mousewheel True - draggable True - pagekeys True - - side_yfill True - - vbox: - spacing spacing - - transclude - - elif scroll == "vpgrid": - - vpgrid: - cols 1 - yinitial yinitial - - scrollbars "vertical" - mousewheel True - draggable True - pagekeys True - - side_yfill True - - spacing spacing - - transclude - - else: - - transclude - - use navigation - - textbutton _("Return"): - style "return_button" - - action Return() - - label title - - if main_menu: - key "game_menu" action ShowMenu("main_menu") - - -style game_menu_outer_frame is empty -style game_menu_navigation_frame is empty -style game_menu_content_frame is empty -style game_menu_viewport is gui_viewport -style game_menu_side is gui_side -style game_menu_scrollbar is gui_vscrollbar - -style game_menu_label is gui_label -style game_menu_label_text is gui_label_text - -style return_button is navigation_button -style return_button_text is navigation_button_text - -style game_menu_outer_frame: - bottom_padding 45 - top_padding 180 - - background "gui/overlay/game_menu.png" - -style game_menu_navigation_frame: - xsize 420 - yfill True - -style game_menu_content_frame: - left_margin 60 - right_margin 30 - top_margin 15 - -style game_menu_viewport: - xsize 1380 - -style game_menu_vscrollbar: - unscrollable gui.unscrollable - -style game_menu_side: - spacing 15 - -style game_menu_label: - xpos 75 - ysize 180 - -style game_menu_label_text: - size 75 - color gui.accent_color - yalign 0.5 - -style return_button: - xpos gui.navigation_xpos - yalign 1.0 - yoffset -45 - - -## About screen ################################################################ -## -## This screen gives credit and copyright information about the game and Ren'Py. -## -## There's nothing special about this screen, and hence it also serves as an -## example of how to make a custom screen. - -screen about(): - - tag menu - - ## This use statement includes the game_menu screen inside this one. The - ## vbox child is then included inside the viewport inside the game_menu - ## screen. - use game_menu(_("About"), scroll="viewport"): - - style_prefix "about" - - vbox: - - label "[config.name!t]" - text _("Version [config.version!t]\n") - - ## gui.about is usually set in options.rpy. - if gui.about: - text "[gui.about!t]\n" - - text _("Made with {a=https://www.renpy.org/}Ren'Py{/a} [renpy.version_only].\n\n[renpy.license!t]") - - -style about_label is gui_label -style about_label_text is gui_label_text -style about_text is gui_text - -style about_label_text: - size gui.label_text_size - - -## Load and Save screens ####################################################### -## -## These screens are responsible for letting the player save the game and load -## it again. Since they share nearly everything in common, both are implemented -## in terms of a third screen, file_slots. -## -## https://www.renpy.org/doc/html/screen_special.html#save https:// -## www.renpy.org/doc/html/screen_special.html#load - -screen save(): - - tag menu - - use file_slots(_("Save")) - - -screen load(): - - tag menu - - use file_slots(_("Load")) - - -screen file_slots(title): - - default page_name_value = FilePageNameInputValue(pattern=_("Page {}"), auto=_("Automatic saves"), quick=_("Quick saves")) - - use game_menu(title): - - fixed: - - ## This ensures the input will get the enter event before any of the - ## buttons do. - order_reverse True - - ## The page name, which can be edited by clicking on a button. - button: - style "page_label" - - key_events True - xalign 0.5 - action page_name_value.Toggle() - - input: - style "page_label_text" - value page_name_value - - ## The grid of file slots. - grid gui.file_slot_cols gui.file_slot_rows: - style_prefix "slot" - - xalign 0.5 - yalign 0.5 - - spacing gui.slot_spacing - - for i in range(gui.file_slot_cols * gui.file_slot_rows): - - $ slot = i + 1 - - button: - action FileAction(slot) - - has vbox - - add FileScreenshot(slot) xalign 0.5 - - text FileTime(slot, format=_("{#file_time}%A, %B %d %Y, %H:%M"), empty=_("empty slot")): - style "slot_time_text" - - text FileSaveName(slot): - style "slot_name_text" - - key "save_delete" action FileDelete(slot) - - ## Buttons to access other pages. - vbox: - style_prefix "page" - - xalign 0.5 - yalign 1.0 - - hbox: - xalign 0.5 - - spacing gui.page_spacing - - textbutton _("<") action FilePagePrevious() - key "save_page_prev" action FilePagePrevious() - - if config.has_autosave: - textbutton _("{#auto_page}A") action FilePage("auto") - - if config.has_quicksave: - textbutton _("{#quick_page}Q") action FilePage("quick") - - ## range(1, 10) gives the numbers from 1 to 9. - for page in range(1, 10): - textbutton "[page]" action FilePage(page) - - textbutton _(">") action FilePageNext() - key "save_page_next" action FilePageNext() - - if config.has_sync: - if CurrentScreenName() == "save": - textbutton _("Upload Sync"): - action UploadSync() - xalign 0.5 - else: - textbutton _("Download Sync"): - action DownloadSync() - xalign 0.5 - - -style page_label is gui_label -style page_label_text is gui_label_text -style page_button is gui_button -style page_button_text is gui_button_text - -style slot_button is gui_button -style slot_button_text is gui_button_text -style slot_time_text is slot_button_text -style slot_name_text is slot_button_text - -style page_label: - xpadding 75 - ypadding 5 - xalign 0.5 - -style page_label_text: - textalign 0.5 - layout "subtitle" - hover_color gui.hover_color - -style page_button: - properties gui.button_properties("page_button") - -style page_button_text: - properties gui.text_properties("page_button") - -style slot_button: - properties gui.button_properties("slot_button") - -style slot_button_text: - properties gui.text_properties("slot_button") - - -## Preferences screen ########################################################## -## -## The preferences screen allows the player to configure the game to better suit -## themselves. -## -## https://www.renpy.org/doc/html/screen_special.html#preferences - -screen preferences(): - - tag menu - - use game_menu(_("Preferences"), scroll="viewport"): - - vbox: - - hbox: - box_wrap True - - if renpy.variant("pc") or renpy.variant("web"): - - vbox: - style_prefix "radio" - label _("Display") - textbutton _("Window") action Preference("display", "window") - textbutton _("Fullscreen") action Preference("display", "fullscreen") - - vbox: - style_prefix "check" - label _("Skip") - textbutton _("Unseen Text") action Preference("skip", "toggle") - textbutton _("After Choices") action Preference("after choices", "toggle") - textbutton _("Transitions") action InvertSelected(Preference("transitions", "toggle")) - - ## Additional vboxes of type "radio_pref" or "check_pref" can be - ## added here, to add additional creator-defined preferences. - - null height (4 * gui.pref_spacing) - - hbox: - style_prefix "slider" - box_wrap True - - vbox: - - label _("Text Speed") - - bar value Preference("text speed") - - label _("Auto-Forward Time") - - bar value Preference("auto-forward time") - - vbox: - - if config.has_music: - label _("Music Volume") - - hbox: - bar value Preference("music volume") - - if config.has_sound: - - label _("Sound Volume") - - hbox: - bar value Preference("sound volume") - - if config.sample_sound: - textbutton _("Test") action Play("sound", config.sample_sound) - - - if config.has_voice: - label _("Voice Volume") - - hbox: - bar value Preference("voice volume") - - if config.sample_voice: - textbutton _("Test") action Play("voice", config.sample_voice) - - if config.has_music or config.has_sound or config.has_voice: - null height gui.pref_spacing - - textbutton _("Mute All"): - action Preference("all mute", "toggle") - style "mute_all_button" - - -style pref_label is gui_label -style pref_label_text is gui_label_text -style pref_vbox is vbox - -style radio_label is pref_label -style radio_label_text is pref_label_text -style radio_button is gui_button -style radio_button_text is gui_button_text -style radio_vbox is pref_vbox - -style check_label is pref_label -style check_label_text is pref_label_text -style check_button is gui_button -style check_button_text is gui_button_text -style check_vbox is pref_vbox - -style slider_label is pref_label -style slider_label_text is pref_label_text -style slider_slider is gui_slider -style slider_button is gui_button -style slider_button_text is gui_button_text -style slider_pref_vbox is pref_vbox - -style mute_all_button is check_button -style mute_all_button_text is check_button_text - -style pref_label: - top_margin gui.pref_spacing - bottom_margin 3 - -style pref_label_text: - yalign 1.0 - -style pref_vbox: - xsize 338 - -style radio_vbox: - spacing gui.pref_button_spacing - -style radio_button: - properties gui.button_properties("radio_button") - foreground "gui/button/radio_[prefix_]foreground.png" - -style radio_button_text: - properties gui.text_properties("radio_button") - -style check_vbox: - spacing gui.pref_button_spacing - -style check_button: - properties gui.button_properties("check_button") - foreground "gui/button/check_[prefix_]foreground.png" - -style check_button_text: - properties gui.text_properties("check_button") - -style slider_slider: - xsize 525 - -style slider_button: - properties gui.button_properties("slider_button") - yalign 0.5 - left_margin 15 - -style slider_button_text: - properties gui.text_properties("slider_button") - -style slider_vbox: - xsize 675 - - -## History screen ############################################################## -## -## This is a screen that displays the dialogue history to the player. While -## there isn't anything special about this screen, it does have to access the -## dialogue history stored in _history_list. -## -## https://www.renpy.org/doc/html/history.html - -screen history(): - - tag menu - - ## Avoid predicting this screen, as it can be very large. - predict False - - use game_menu(_("History"), scroll=("vpgrid" if gui.history_height else "viewport"), yinitial=1.0, spacing=gui.history_spacing): - - style_prefix "history" - - for h in _history_list: - - window: - - ## This lays things out properly if history_height is None. - has fixed: - yfit True - - if h.who: - - label h.who: - style "history_name" - substitute False - - ## Take the color of the who text from the Character, if - ## set. - if "color" in h.who_args: - text_color h.who_args["color"] - - $ what = renpy.filter_text_tags(h.what, allow=gui.history_allow_tags) - text what: - substitute False - - if not _history_list: - label _("The dialogue history is empty.") - - -## This determines what tags are allowed to be displayed on the history screen. - -define gui.history_allow_tags = { "alt", "noalt", "rt", "rb", "art" } - - -style history_window is empty - -style history_name is gui_label -style history_name_text is gui_label_text -style history_text is gui_text - -style history_label is gui_label -style history_label_text is gui_label_text - -style history_window: - xfill True - ysize gui.history_height - -style history_name: - xpos gui.history_name_xpos - xanchor gui.history_name_xalign - ypos gui.history_name_ypos - xsize gui.history_name_width - -style history_name_text: - min_width gui.history_name_width - textalign gui.history_name_xalign - -style history_text: - xpos gui.history_text_xpos - ypos gui.history_text_ypos - xanchor gui.history_text_xalign - xsize gui.history_text_width - min_width gui.history_text_width - textalign gui.history_text_xalign - layout ("subtitle" if gui.history_text_xalign else "tex") - -style history_label: - xfill True - -style history_label_text: - xalign 0.5 - - -## Help screen ################################################################# -## -## A screen that gives information about key and mouse bindings. It uses other -## screens (keyboard_help, mouse_help, and gamepad_help) to display the actual -## help. - -screen help(): - - tag menu - - default device = "keyboard" - - use game_menu(_("Help"), scroll="viewport"): - - style_prefix "help" - - vbox: - spacing 23 - - hbox: - - textbutton _("Keyboard") action SetScreenVariable("device", "keyboard") - textbutton _("Mouse") action SetScreenVariable("device", "mouse") - - if GamepadExists(): - textbutton _("Gamepad") action SetScreenVariable("device", "gamepad") - - if device == "keyboard": - use keyboard_help - elif device == "mouse": - use mouse_help - elif device == "gamepad": - use gamepad_help - - -screen keyboard_help(): - - hbox: - label _("Enter") - text _("Advances dialogue and activates the interface.") - - hbox: - label _("Space") - text _("Advances dialogue without selecting choices.") - - hbox: - label _("Arrow Keys") - text _("Navigate the interface.") - - hbox: - label _("Escape") - text _("Accesses the game menu.") - - hbox: - label _("Ctrl") - text _("Skips dialogue while held down.") - - hbox: - label _("Tab") - text _("Toggles dialogue skipping.") - - hbox: - label _("Page Up") - text _("Rolls back to earlier dialogue.") - - hbox: - label _("Page Down") - text _("Rolls forward to later dialogue.") - - hbox: - label "H" - text _("Hides the user interface.") - - hbox: - label "S" - text _("Takes a screenshot.") - - hbox: - label "V" - text _("Toggles assistive {a=https://www.renpy.org/l/voicing}self-voicing{/a}.") - - hbox: - label "Shift+A" - text _("Opens the accessibility menu.") - - -screen mouse_help(): - - hbox: - label _("Left Click") - text _("Advances dialogue and activates the interface.") - - hbox: - label _("Middle Click") - text _("Hides the user interface.") - - hbox: - label _("Right Click") - text _("Accesses the game menu.") - - hbox: - label _("Mouse Wheel Up") - text _("Rolls back to earlier dialogue.") - - hbox: - label _("Mouse Wheel Down") - text _("Rolls forward to later dialogue.") - - -screen gamepad_help(): - - hbox: - label _("Right Trigger\nA/Bottom Button") - text _("Advances dialogue and activates the interface.") - - hbox: - label _("Left Trigger\nLeft Shoulder") - text _("Rolls back to earlier dialogue.") - - hbox: - label _("Right Shoulder") - text _("Rolls forward to later dialogue.") - - hbox: - label _("D-Pad, Sticks") - text _("Navigate the interface.") - - hbox: - label _("Start, Guide, B/Right Button") - text _("Accesses the game menu.") - - hbox: - label _("Y/Top Button") - text _("Hides the user interface.") - - textbutton _("Calibrate") action GamepadCalibrate() - - -style help_button is gui_button -style help_button_text is gui_button_text -style help_label is gui_label -style help_label_text is gui_label_text -style help_text is gui_text - -style help_button: - properties gui.button_properties("help_button") - xmargin 12 - -style help_button_text: - properties gui.text_properties("help_button") - -style help_label: - xsize 375 - right_padding 30 - -style help_label_text: - size gui.text_size - xalign 1.0 - textalign 1.0 - - - -################################################################################ -## Additional screens -################################################################################ - - -## Confirm screen ############################################################## -## -## The confirm screen is called when Ren'Py wants to ask the player a yes or no -## question. -## -## https://www.renpy.org/doc/html/screen_special.html#confirm - -screen confirm(message, yes_action, no_action): - - ## Ensure other screens do not get input while this screen is displayed. - modal True - - zorder 200 - - style_prefix "confirm" - - add "gui/overlay/confirm.png" - - frame: - - vbox: - xalign .5 - yalign .5 - spacing 45 - - label _(message): - style "confirm_prompt" - xalign 0.5 - - hbox: - xalign 0.5 - spacing 150 - - textbutton _("Yes") action yes_action - textbutton _("No") action no_action - - ## Right-click and escape answer "no". - key "game_menu" action no_action - - -style confirm_frame is gui_frame -style confirm_prompt is gui_prompt -style confirm_prompt_text is gui_prompt_text -style confirm_button is gui_medium_button -style confirm_button_text is gui_medium_button_text - -style confirm_frame: - background Frame([ "gui/confirm_frame.png", "gui/frame.png"], gui.confirm_frame_borders, tile=gui.frame_tile) - padding gui.confirm_frame_borders.padding - xalign .5 - yalign .5 - -style confirm_prompt_text: - textalign 0.5 - layout "subtitle" - -style confirm_button: - properties gui.button_properties("confirm_button") - -style confirm_button_text: - properties gui.text_properties("confirm_button") - - -## Skip indicator screen ####################################################### -## -## The skip_indicator screen is displayed to indicate that skipping is in -## progress. -## -## https://www.renpy.org/doc/html/screen_special.html#skip-indicator - -screen skip_indicator(): - - zorder 100 - style_prefix "skip" - - frame: - - hbox: - spacing 9 - - text _("Skipping") - - text "▸" at delayed_blink(0.0, 1.0) style "skip_triangle" - text "▸" at delayed_blink(0.2, 1.0) style "skip_triangle" - text "▸" at delayed_blink(0.4, 1.0) style "skip_triangle" - - -## This transform is used to blink the arrows one after another. -transform delayed_blink(delay, cycle): - alpha .5 - - pause delay - - block: - linear .2 alpha 1.0 - pause .2 - linear .2 alpha 0.5 - pause (cycle - .4) - repeat - - -style skip_frame is empty -style skip_text is gui_text -style skip_triangle is skip_text - -style skip_frame: - ypos gui.skip_ypos - background Frame("gui/skip.png", gui.skip_frame_borders, tile=gui.frame_tile) - padding gui.skip_frame_borders.padding - -style skip_text: - size gui.notify_text_size - -style skip_triangle: - ## We have to use a font that has the BLACK RIGHT-POINTING SMALL TRIANGLE - ## glyph in it. - font "DejaVuSans.ttf" - - -## Notify screen ############################################################### -## -## The notify screen is used to show the player a message. (For example, when -## the game is quicksaved or a screenshot has been taken.) -## -## https://www.renpy.org/doc/html/screen_special.html#notify-screen - -screen notify(message): - - zorder 100 - style_prefix "notify" - - frame at notify_appear: - text "[message!tq]" - - timer 3.25 action Hide('notify') - - -transform notify_appear: - on show: - alpha 0 - linear .25 alpha 1.0 - on hide: - linear .5 alpha 0.0 - - -style notify_frame is empty -style notify_text is gui_text - -style notify_frame: - ypos gui.notify_ypos - - background Frame("gui/notify.png", gui.notify_frame_borders, tile=gui.frame_tile) - padding gui.notify_frame_borders.padding - -style notify_text: - properties gui.text_properties("notify") - - -## NVL screen ################################################################## -## -## This screen is used for NVL-mode dialogue and menus. -## -## https://www.renpy.org/doc/html/screen_special.html#nvl - - -screen nvl(dialogue, items=None): - - window: - style "nvl_window" - - has vbox: - spacing gui.nvl_spacing - - ## Displays dialogue in either a vpgrid or the vbox. - if gui.nvl_height: - - vpgrid: - cols 1 - yinitial 1.0 - - use nvl_dialogue(dialogue) - - else: - - use nvl_dialogue(dialogue) - - ## Displays the menu, if given. The menu may be displayed incorrectly if - ## config.narrator_menu is set to True. - for i in items: - - textbutton i.caption: - action i.action - style "nvl_button" - - add SideImage() xalign 0.0 yalign 1.0 - - -screen nvl_dialogue(dialogue): - - for d in dialogue: - - window: - id d.window_id - - fixed: - yfit gui.nvl_height is None - - if d.who is not None: - - text d.who: - id d.who_id - - text d.what: - id d.what_id - - -## This controls the maximum number of NVL-mode entries that can be displayed at -## once. -define config.nvl_list_length = gui.nvl_list_length - -style nvl_window is default -style nvl_entry is default - -style nvl_label is say_label -style nvl_dialogue is say_dialogue - -style nvl_button is button -style nvl_button_text is button_text - -style nvl_window: - xfill True - yfill True - - background "gui/nvl.png" - padding gui.nvl_borders.padding - -style nvl_entry: - xfill True - ysize gui.nvl_height - -style nvl_label: - xpos gui.nvl_name_xpos - xanchor gui.nvl_name_xalign - ypos gui.nvl_name_ypos - yanchor 0.0 - xsize gui.nvl_name_width - min_width gui.nvl_name_width - textalign gui.nvl_name_xalign - -style nvl_dialogue: - xpos gui.nvl_text_xpos - xanchor gui.nvl_text_xalign - ypos gui.nvl_text_ypos - xsize gui.nvl_text_width - min_width gui.nvl_text_width - textalign gui.nvl_text_xalign - layout ("subtitle" if gui.nvl_text_xalign else "tex") - -style nvl_thought is say_dialogue: - xpos gui.nvl_thought_xpos - xanchor gui.nvl_thought_xalign - ypos gui.nvl_thought_ypos - xsize gui.nvl_thought_width - min_width gui.nvl_thought_width - textalign gui.nvl_thought_xalign - layout ("subtitle" if gui.nvl_text_xalign else "tex") - -style nvl_button: - properties gui.button_properties("nvl_button") - xpos gui.nvl_button_xpos - xanchor gui.nvl_button_xalign - -style nvl_button_text: - properties gui.text_properties("nvl_button") - - -## Bubble screen ############################################################### -## -## The bubble screen is used to display dialogue to the player when using speech -## bubbles. The bubble screen takes the same parameters as the say screen, must -## create a displayable with the id of "what", and can create displayables with -## the "namebox", "who", and "window" ids. -## -## https://www.renpy.org/doc/html/bubble.html#bubble-screen - -screen bubble(who, what): - style_prefix "bubble" - - window: - id "window" - - if who is not None: - - window: - id "namebox" - style "bubble_namebox" - - text who: - id "who" - - text what: - id "what" - - default ctc = None - showif ctc: - add ctc - -style bubble_window is empty -style bubble_namebox is empty -style bubble_who is default -style bubble_what is default - -style bubble_window: - xpadding 30 - top_padding 5 - bottom_padding 5 - -style bubble_namebox: - xalign 0.5 - -style bubble_who: - xalign 0.5 - textalign 0.5 - color "#000" - -style bubble_what: - align (0.5, 0.5) - text_align 0.5 - layout "subtitle" - color "#000" - -define bubble.frame = Frame("gui/bubble.png", 55, 55, 55, 95) -define bubble.thoughtframe = Frame("gui/thoughtbubble.png", 55, 55, 55, 55) - -define bubble.properties = { - "bottom_left" : { - "window_background" : Transform(bubble.frame, xzoom=1, yzoom=1), - "window_bottom_padding" : 27, - }, - - "bottom_right" : { - "window_background" : Transform(bubble.frame, xzoom=-1, yzoom=1), - "window_bottom_padding" : 27, - }, - - "top_left" : { - "window_background" : Transform(bubble.frame, xzoom=1, yzoom=-1), - "window_top_padding" : 27, - }, - - "top_right" : { - "window_background" : Transform(bubble.frame, xzoom=-1, yzoom=-1), - "window_top_padding" : 27, - }, - - "thought" : { - "window_background" : bubble.thoughtframe, - } -} - -define bubble.expand_area = { - "bottom_left" : (0, 0, 0, 22), - "bottom_right" : (0, 0, 0, 22), - "top_left" : (0, 22, 0, 0), - "top_right" : (0, 22, 0, 0), - "thought" : (0, 0, 0, 0), -} - - - -################################################################################ -## Mobile Variants -################################################################################ - -style pref_vbox: - variant "medium" - xsize 675 - -## Since a mouse may not be present, we replace the quick menu with a version -## that uses fewer and bigger buttons that are easier to touch. -screen quick_menu(): - variant "touch" - - zorder 100 - - if quick_menu: - - hbox: - style "quick_menu" - style_prefix "quick" - - textbutton _("Back") action Rollback() - textbutton _("Skip") action Skip() alternate Skip(fast=True, confirm=True) - textbutton _("Auto") action Preference("auto-forward", "toggle") - textbutton _("Menu") action ShowMenu() - - -style window: - variant "small" - background "gui/phone/textbox.png" - -style radio_button: - variant "small" - foreground "gui/phone/button/radio_[prefix_]foreground.png" - -style check_button: - variant "small" - foreground "gui/phone/button/check_[prefix_]foreground.png" - -style nvl_window: - variant "small" - background "gui/phone/nvl.png" - -style main_menu_frame: - variant "small" - background "gui/phone/overlay/main_menu.png" - -style game_menu_outer_frame: - variant "small" - background "gui/phone/overlay/game_menu.png" - -style game_menu_navigation_frame: - variant "small" - xsize 510 - -style game_menu_content_frame: - variant "small" - top_margin 0 - -style game_menu_viewport: - variant "small" - xsize 1305 - -style pref_vbox: - variant "small" - xsize 600 - -style bar: - variant "small" - ysize gui.bar_size - left_bar Frame("gui/phone/bar/left.png", gui.bar_borders, tile=gui.bar_tile) - right_bar Frame("gui/phone/bar/right.png", gui.bar_borders, tile=gui.bar_tile) - -style vbar: - variant "small" - xsize gui.bar_size - top_bar Frame("gui/phone/bar/top.png", gui.vbar_borders, tile=gui.bar_tile) - bottom_bar Frame("gui/phone/bar/bottom.png", gui.vbar_borders, tile=gui.bar_tile) - -style scrollbar: - variant "small" - ysize gui.scrollbar_size - base_bar Frame("gui/phone/scrollbar/horizontal_[prefix_]bar.png", gui.scrollbar_borders, tile=gui.scrollbar_tile) - thumb Frame("gui/phone/scrollbar/horizontal_[prefix_]thumb.png", gui.scrollbar_borders, tile=gui.scrollbar_tile) - -style vscrollbar: - variant "small" - xsize gui.scrollbar_size - base_bar Frame("gui/phone/scrollbar/vertical_[prefix_]bar.png", gui.vscrollbar_borders, tile=gui.scrollbar_tile) - thumb Frame("gui/phone/scrollbar/vertical_[prefix_]thumb.png", gui.vscrollbar_borders, tile=gui.scrollbar_tile) - -style slider: - variant "small" - ysize gui.slider_size - base_bar Frame("gui/phone/slider/horizontal_[prefix_]bar.png", gui.slider_borders, tile=gui.slider_tile) - thumb "gui/phone/slider/horizontal_[prefix_]thumb.png" - -style vslider: - variant "small" - xsize gui.slider_size - base_bar Frame("gui/phone/slider/vertical_[prefix_]bar.png", gui.vslider_borders, tile=gui.slider_tile) - thumb "gui/phone/slider/vertical_[prefix_]thumb.png" - -style slider_vbox: - variant "small" - xsize None - -style slider_slider: - variant "small" - xsize 900 diff --git a/src/vnpipe/renpy_templates/game/support.rpy b/src/vnpipe/renpy_templates/game/support.rpy deleted file mode 100644 index c5b21f9..0000000 --- a/src/vnpipe/renpy_templates/game/support.rpy +++ /dev/null @@ -1,38 +0,0 @@ -## Support code for the generated script: transitions, stage positions, colour -## treatments and the screen shake. Static; copied verbatim by `vnpipe renpy`. - -define vn_slow = Dissolve(2.0) -define vn_flash = Fade(0.1, 0.0, 0.6, color="#ffffff") - -transform vn_left: - xalign 0.15 yalign 1.0 - -transform vn_center: - xalign 0.5 yalign 1.0 - -transform vn_right: - xalign 0.85 yalign 1.0 - -transform tint_none: - matrixcolor IdentityMatrix() - -transform tint_dark: - matrixcolor TintMatrix("#8a8498") * BrightnessMatrix(-0.2) - -transform tint_red: - matrixcolor TintMatrix("#f0968a") * BrightnessMatrix(-0.05) - -transform vn_shake: - xoffset 0 yoffset 0 - linear 0.05 xoffset 18 yoffset -8 - linear 0.05 xoffset -18 yoffset 8 - linear 0.05 xoffset 14 yoffset -6 - linear 0.05 xoffset -14 yoffset 6 - linear 0.05 xoffset 8 yoffset -3 - linear 0.05 xoffset 0 yoffset 0 - -init python: - config.font_replacement_map["fonts/RobotoSlab-Regular.ttf", True, False] = ( - "fonts/RobotoSlab-Bold.ttf", False, False) - -define vn_move = MoveTransition(0.8) diff --git a/src/vnpipe/schema.py b/src/vnpipe/schema.py deleted file mode 100644 index 75d84f8..0000000 --- a/src/vnpipe/schema.py +++ /dev/null @@ -1,37 +0,0 @@ -"""JSON Schema validation helper shared by all pipeline stages.""" - -import json -from functools import cache -from typing import Any - -from jsonschema import Draft202012Validator - -from vnpipe import SCHEMA_DIR - - -class SchemaError(ValueError): - """Raised when an instance does not conform to its schema.""" - - -@cache -def _validator(schema_name: str) -> Draft202012Validator: - path = SCHEMA_DIR / f"{schema_name}.schema.json" - if not path.is_file(): - raise FileNotFoundError(f"unknown schema {schema_name!r}: {path} does not exist") - schema = json.loads(path.read_text(encoding="utf-8")) - Draft202012Validator.check_schema(schema) - return Draft202012Validator(schema) - - -def validate(instance: Any, schema_name: str) -> None: - """Validate ``instance`` against ``SCHEMA_DIR/.schema.json``. - - Raises ``SchemaError`` listing every problem found (path and message). - """ - errors = sorted(_validator(schema_name).iter_errors(instance), key=lambda e: list(e.path)) - if not errors: - return - problems = [f" at /{'/'.join(str(p) for p in e.absolute_path)}: {e.message}" for e in errors] - raise SchemaError( - f"{len(errors)} problem(s) validating against {schema_name!r}:\n" + "\n".join(problems) - ) diff --git a/src/vnpipe/schemas/annotated.schema.json b/src/vnpipe/schemas/annotated.schema.json deleted file mode 100644 index 5c69181..0000000 --- a/src/vnpipe/schemas/annotated.schema.json +++ /dev/null @@ -1,224 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "vnpipe/annotated.schema.json", - "title": "Annotated play", - "description": "Output of `vnpipe annotate merge`: parsed lines plus one annotation each. The `ann` and line definitions duplicate annotation.schema.json and parsed.schema.json (schema.py has no cross-file registry); tests/test_annotation_schema.py guards against drift.", - "type": "object", - "required": [ - "work", - "parsed_sha256", - "fallback_chunks", - "scenes" - ], - "additionalProperties": false, - "properties": { - "work": { - "type": "string" - }, - "parsed_sha256": { - "type": "string", - "pattern": "^[0-9a-f]{64}$" - }, - "fallback_chunks": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Chunks filled with deterministic fallback annotations instead of LLM output" - }, - "scenes": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "required": [ - "id", - "heading", - "lines" - ], - "additionalProperties": false, - "properties": { - "id": { - "type": "string", - "pattern": "^[a-z0-9_]+$" - }, - "heading": { - "type": "string" - }, - "lines": { - "type": "array", - "items": { - "$ref": "#/$defs/line" - } - } - } - } - } - }, - "$defs": { - "ann": { - "type": "object", - "required": [ - "speaker", - "kind", - "emotion", - "location", - "time_of_day", - "on_stage" - ], - "additionalProperties": false, - "properties": { - "speaker": { - "type": [ - "string", - "null" - ], - "description": "Cast id; 'narrator' for stage directions, the work's lyric voice id for unattributed verse" - }, - "kind": { - "enum": [ - "dialogue", - "narration", - "stage_direction" - ] - }, - "emotion": { - "enum": [ - "neutral", - "joyful", - "melancholic", - "solemn", - "ironic", - "angry", - "fearful", - "ecstatic" - ] - }, - "location": { - "type": "string" - }, - "time_of_day": { - "enum": [ - "dawn", - "day", - "dusk", - "night", - "timeless" - ] - }, - "on_stage": { - "type": "array", - "description": "Characters visible (or present) while this line is shown, with stage position", - "items": { - "type": "object", - "required": [ - "character", - "position" - ], - "additionalProperties": false, - "properties": { - "character": { - "type": "string" - }, - "position": { - "$ref": "#/$defs/position" - } - } - } - }, - "music": { - "enum": [ - "contemplative", - "comic", - "sacred", - "ominous", - "mystical", - "none", - null - ], - "description": "Optional music mood; null = keep current" - } - } - }, - "line": { - "type": "object", - "required": [ - "id", - "kind", - "speaker", - "speaker_note", - "speech", - "stanza", - "indent", - "text", - "src_line", - "ann" - ], - "additionalProperties": false, - "properties": { - "id": { - "type": "string", - "pattern": "^[a-z0-9_]+_[0-9]{4}$", - "description": "_<4-digit index within scene>" - }, - "kind": { - "enum": [ - "verse", - "direction", - "cast" - ], - "description": "verse = spoken/recited text line; direction = stage direction (parenthesised or italic setting text); cast = list of characters under a scene heading" - }, - "speaker": { - "type": [ - "string", - "null" - ], - "description": "Cast id from work.toml [speakers], null when nobody speaks (e.g. Dedicatoria, directions)" - }, - "speaker_note": { - "type": [ - "string", - "null" - ], - "description": "Inline note in the speaker heading, e.g. 'solo', 'aterrado'" - }, - "speech": { - "type": "integer", - "minimum": 0, - "description": "Index of the speech (speaker turn) within the scene; directions get the index of the speech they occur in or precede" - }, - "stanza": { - "type": "integer", - "minimum": 0, - "description": "Stanza index within the speech (blank line = new stanza)" - }, - "indent": { - "type": "integer", - "minimum": 0, - "description": "Leading spaces beyond the base verse indent (split verse lines are deeply indented)" - }, - "text": { - "type": "string", - "minLength": 1, - "description": "Text with markup removed (_italics_ underscores stripped)" - }, - "src_line": { - "type": "integer", - "minimum": 1, - "description": "1-based line number in the raw Gutenberg file" - }, - "ann": { - "$ref": "#/$defs/ann" - } - } - }, - "position": { - "enum": [ - "left", - "center", - "right" - ] - } - } -} diff --git a/src/vnpipe/schemas/annotation.schema.json b/src/vnpipe/schemas/annotation.schema.json deleted file mode 100644 index d9ee5fc..0000000 --- a/src/vnpipe/schemas/annotation.schema.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "vnpipe/annotation.schema.json", - "title": "Line annotations", - "description": "One annotation per parsed line. Produced by LLM sub-agents per chunk, merged and validated by `vnpipe annotate merge`. Enumerations of cast ids and locations are checked against work.toml at merge time.", - "type": "object", - "required": ["chunk_id", "input_sha256", "annotations"], - "additionalProperties": false, - "properties": { - "chunk_id": {"type": "string"}, - "input_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, - "annotations": { - "type": "array", - "items": {"$ref": "#/$defs/annotation"} - } - }, - "$defs": { - "position": {"enum": ["left", "center", "right"]}, - "annotation": { - "type": "object", - "required": ["id", "speaker", "kind", "emotion", "location", "time_of_day", "on_stage"], - "additionalProperties": false, - "properties": { - "id": {"type": "string"}, - "speaker": {"type": ["string", "null"], "description": "Cast id; 'narrator' for stage directions, the work's lyric voice id for unattributed verse"}, - "kind": {"enum": ["dialogue", "narration", "stage_direction"]}, - "emotion": {"enum": ["neutral", "joyful", "melancholic", "solemn", "ironic", "angry", "fearful", "ecstatic"]}, - "location": {"type": "string"}, - "time_of_day": {"enum": ["dawn", "day", "dusk", "night", "timeless"]}, - "on_stage": { - "type": "array", - "description": "Characters visible (or present) while this line is shown, with stage position", - "items": { - "type": "object", - "required": ["character", "position"], - "additionalProperties": false, - "properties": { - "character": {"type": "string"}, - "position": {"$ref": "#/$defs/position"} - } - } - }, - "music": {"enum": ["contemplative", "comic", "sacred", "ominous", "mystical", "none", null], "description": "Optional music mood; null = keep current"} - } - } - } -} diff --git a/src/vnpipe/schemas/manifest.schema.json b/src/vnpipe/schemas/manifest.schema.json deleted file mode 100644 index 57fff83..0000000 --- a/src/vnpipe/schemas/manifest.schema.json +++ /dev/null @@ -1,120 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "vnpipe/manifest.schema.json", - "title": "Asset manifest", - "type": "object", - "required": [ - "base_prompt", - "templates", - "assets" - ], - "additionalProperties": false, - "properties": { - "base_prompt": { - "type": "string" - }, - "assets": { - "type": "array", - "items": { - "type": "object", - "required": [ - "id", - "kind", - "prompt", - "source", - "file", - "sha256", - "status" - ], - "additionalProperties": false, - "properties": { - "id": { - "type": "string", - "pattern": "^(bg|sprite)_[a-z0-9_]+$", - "description": "bg_[_] or sprite__" - }, - "kind": { - "enum": [ - "background", - "sprite" - ] - }, - "character": { - "type": "string" - }, - "expression": { - "type": "string" - }, - "prompt": { - "type": "string", - "description": "Asset-specific prompt; the full prompt sent is base_prompt + kind prompt + this" - }, - "source": { - "enum": [ - "chatgpt-web", - "zenvairo-media", - "placeholder", - "manual" - ] - }, - "generation_id": { - "type": [ - "string", - "null" - ] - }, - "reference": { - "type": [ - "string", - "null" - ], - "description": "Asset id used as reference image (identity consistency)" - }, - "raw_file": { - "type": [ - "string", - "null" - ], - "description": "Original generated image, relative to the work's assets dir" - }, - "file": { - "type": "string", - "description": "Final processed image used by the game, relative to the work's assets dir" - }, - "sha256": { - "type": [ - "string", - "null" - ], - "pattern": "^[0-9a-f]{64}$" - }, - "status": { - "enum": [ - "planned", - "generated", - "processed", - "approved", - "rejected", - "placeholder" - ] - }, - "notes": { - "type": "string" - } - } - } - }, - "templates": { - "type": "object", - "required": [ - "background", - "sprite", - "variant" - ], - "additionalProperties": { - "type": "string" - }, - "description": "Kind-specific prompt templates appended after base_prompt" - } - } -} diff --git a/src/vnpipe/schemas/parsed.schema.json b/src/vnpipe/schemas/parsed.schema.json deleted file mode 100644 index 90d4336..0000000 --- a/src/vnpipe/schemas/parsed.schema.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "vnpipe/parsed.schema.json", - "title": "Parsed play", - "description": "Deterministic parser output: scenes made of ordered lines.", - "type": "object", - "required": ["work", "source_sha256", "scenes"], - "additionalProperties": false, - "properties": { - "work": {"type": "string"}, - "source_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, - "scenes": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "required": ["id", "heading", "lines"], - "additionalProperties": false, - "properties": { - "id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, - "heading": {"type": "string"}, - "lines": { - "type": "array", - "items": { - "type": "object", - "required": ["id", "kind", "speaker", "speaker_note", "speech", "stanza", "indent", "text", "src_line"], - "additionalProperties": false, - "properties": { - "id": {"type": "string", "pattern": "^[a-z0-9_]+_[0-9]{4}$", "description": "_<4-digit index within scene>"}, - "kind": {"enum": ["verse", "direction", "cast"], "description": "verse = spoken/recited text line; direction = stage direction (parenthesised or italic setting text); cast = list of characters under a scene heading"}, - "speaker": {"type": ["string", "null"], "description": "Cast id from work.toml [speakers], null when nobody speaks (e.g. Dedicatoria, directions)"}, - "speaker_note": {"type": ["string", "null"], "description": "Inline note in the speaker heading, e.g. 'solo', 'aterrado'"}, - "speech": {"type": "integer", "minimum": 0, "description": "Index of the speech (speaker turn) within the scene; directions get the index of the speech they occur in or precede"}, - "stanza": {"type": "integer", "minimum": 0, "description": "Stanza index within the speech (blank line = new stanza)"}, - "indent": {"type": "integer", "minimum": 0, "description": "Leading spaces beyond the base verse indent (split verse lines are deeply indented)"}, - "text": {"type": "string", "minLength": 1, "description": "Text with markup removed (_italics_ underscores stripped)"}, - "src_line": {"type": "integer", "minimum": 1, "description": "1-based line number in the raw Gutenberg file"} - } - } - } - } - } - } - } -} diff --git a/src/vnpipe/text.py b/src/vnpipe/text.py deleted file mode 100644 index 62a5346..0000000 --- a/src/vnpipe/text.py +++ /dev/null @@ -1,258 +0,0 @@ -"""Text stage: fetch the Gutenberg source, clean/scope it and parse it into parsed.json.""" - -import argparse -import hashlib -import json -import re -import urllib.request -from pathlib import Path -from typing import Any - -from vnpipe.config import Work, load_work -from vnpipe.schema import validate - -BASE_INDENT = 4 -UPPER = "A-ZÁÉÍÓÚÜÑ" -ILLUSTRATION_RE = re.compile(r"^\[Ilustración[^\]]*\]$") -HEADING_RE = re.compile( - rf"^(?P[{UPPER}][{UPPER} ]*?)" - r"(?:,\s*_(?P[^_]+)_|\s*\(_(?P[^_]+)_\))?$" -) - -Line = tuple[int, str] # (1-based raw line number, text without line ending) - - -class ParseError(ValueError): - """The source text has a structure the parser does not know.""" - - -def _split(raw_text: str) -> list[str]: - text = raw_text.removeprefix("").replace("\r\n", "\n").replace("\r", "\n") - return text.split("\n") - - -def clean(raw_text: str, scope_cfg: dict[str, Any]) -> list[Line]: - """Cut the raw text to the configured scope and drop noise. - - The start marker is the first line whose stripped text equals ``start_marker``; the end - marker is the ``end_occurrence``-th such line after it (exclusive). Illustration markers - are removed, trailing whitespace stripped and blank runs collapsed to a single blank line. - Returned line numbers refer to the raw file. - """ - lines = _split(raw_text) - start_marker, end_marker = scope_cfg["start_marker"], scope_cfg["end_marker"] - occurrence = scope_cfg.get("end_occurrence", 1) - start = next((i for i, ln in enumerate(lines) if ln.strip() == start_marker), None) - if start is None: - raise ParseError(f"scope start marker {start_marker!r} not found") - matches = [i for i in range(start + 1, len(lines)) if lines[i].strip() == end_marker] - if len(matches) < occurrence: - raise ParseError(f"scope end marker {end_marker!r} occurrence {occurrence} not found") - end = matches[occurrence - 1] - - out: list[Line] = [] - for i in range(start, end): - text = lines[i].rstrip() - if ILLUSTRATION_RE.match(text.strip()): - continue - if not text and out and not out[-1][1]: - continue - out.append((i + 1, text)) - while out and not out[-1][1]: - out.pop() - return out - - -def clean_text(lines: list[Line]) -> str: - """Render cleaned lines as the contents of play.txt.""" - return "\n".join(text for _, text in lines) + "\n" - - -def _strip_markup(text: str) -> str: - return re.sub(r"\s+", " ", text.replace("_", "")).strip() - - -def _indent(text: str) -> int: - return len(text) - len(text.lstrip(" ")) - - -def _match_heading(text: str) -> re.Match[str] | None: - return HEADING_RE.match(text) if text and not text[0].isspace() else None - - -class _SceneBuilder: - def __init__(self, scene_cfg: dict[str, Any]): - self.id: str = scene_cfg["id"] - self.heading: str = scene_cfg["heading"] - self.lines: list[dict[str, Any]] = [] - self.speaker: str | None = None - self.note: str | None = None - self.speech = -1 - self.stanza = 0 - self.has_verse = False - self.pending_blank = False - - def add(self, kind: str, text: str, src: int, indent: int = 0, speaker: Any = False) -> None: - self.lines.append( - { - "id": f"{self.id}_{len(self.lines) + 1:04d}", - "kind": kind, - "speaker": self.speaker if speaker is False else speaker, - "speaker_note": self.note if speaker is False else None, - "speech": max(self.speech, 0), - "stanza": self.stanza, - "indent": indent, - "text": text, - "src_line": src, - } - ) - - def start_speech(self, speaker: str, note: str | None) -> None: - self.speech += 1 - self.speaker, self.note = speaker, note - self.stanza, self.has_verse, self.pending_blank = 0, False, False - - def verse(self, text: str, src: int) -> None: - if self.pending_blank and self.has_verse: - self.stanza += 1 - self.pending_blank, self.has_verse = False, True - self.add("verse", _strip_markup(text), src, max(_indent(text) - BASE_INDENT, 0)) - - def to_dict(self) -> dict[str, Any]: - return {"id": self.id, "heading": self.heading, "lines": self.lines} - - -def parse(lines: list[Line], work_cfg: dict[str, Any], source_sha256: str) -> dict[str, Any]: - """Parse cleaned lines into the structure described by parsed.schema.json.""" - scenes_by_heading = {s["heading"]: s for s in work_cfg["scenes"]} - speakers: dict[str, str] = work_cfg["speakers"] - scenes: list[_SceneBuilder] = [] - cur: _SceneBuilder | None = None - expect_block = False - i = 0 - - def fail(src: int, msg: str) -> ParseError: - return ParseError(f"raw line {src}: {msg}") - - while i < len(lines): - src, text = lines[i] - stripped = text.strip() - i += 1 - if not stripped: - if cur: - cur.pending_blank = True - continue - - if not text[0].isspace() and stripped in scenes_by_heading: - cur = _SceneBuilder(scenes_by_heading[stripped]) - scenes.append(cur) - expect_block = True - continue - if cur is None: - raise fail(src, f"text before any scene heading: {stripped!r}") - - indent = _indent(text) - match = _match_heading(text) - is_heading = match is not None - if indent and indent < BASE_INDENT: - # Indented heading (a typesetting quirk): only accepted for known speakers. - m = HEADING_RE.match(stripped) - nxt = lines[i][1].strip() if i < len(lines) else "" - if m and m["name"] in speakers and not nxt: - match, is_heading = m, True - - if expect_block: - expect_block = False - if indent < BASE_INDENT and (stripped.startswith("_") or not is_heading or indent): - block = [stripped] - while i < len(lines) and lines[i][1].strip(): - block.append(lines[i][1].strip()) - i += 1 - kind = "direction" if stripped.startswith("_") else "cast" - cur.add(kind, _strip_markup(" ".join(block)), src, speaker=None) - continue - - if stripped.startswith("(_"): - block = [stripped] - while not block[-1].endswith("_)"): - if i >= len(lines) or not lines[i][1].strip(): - raise fail(src, "unterminated stage direction") - block.append(lines[i][1].strip()) - i += 1 - joined = " ".join(block) - cur.add("direction", _strip_markup(joined[2:-2]), src, speaker=None) - continue - - if is_heading and match is not None: - name = match["name"].strip() - if name not in speakers: - raise fail(src, f"unknown speaker or scene heading {stripped!r}") - note = match["note1"] or match["note2"] - cur.start_speech(speakers[name], note.strip() if note else None) - continue - - if indent == 0: - raise fail(src, f"unrecognised line {stripped!r}") - cur.verse(text, src) - - return { - "work": work_cfg["work"]["id"], - "source_sha256": source_sha256, - "scenes": [s.to_dict() for s in scenes], - } - - -def build(raw_bytes: bytes, work_cfg: dict[str, Any]) -> tuple[list[Line], dict[str, Any]]: - """Clean and parse raw file bytes; returns (clean lines, validated parsed dict).""" - lines = clean(raw_bytes.decode("utf-8"), work_cfg["scope"]) - parsed = parse(lines, work_cfg, hashlib.sha256(raw_bytes).hexdigest()) - validate(parsed, "parsed") - return lines, parsed - - -def _raw_path(work: Work) -> Path: - return work.path(work.data["source"]["raw_file"]) - - -def cmd_fetch(args: argparse.Namespace) -> int: - work = load_work(args.work) - dest = _raw_path(work) - if dest.exists(): - print(f"fetch: {dest} already present, nothing to do") - return 0 - url = work.data["source"]["url"] - dest.parent.mkdir(parents=True, exist_ok=True) - request = urllib.request.Request(url, headers={"User-Agent": "vnpipe/0.1"}) - with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310 - payload = response.read() - tmp = dest.with_suffix(dest.suffix + ".part") - tmp.write_bytes(payload) - tmp.replace(dest) - print(f"fetch: wrote {dest} ({len(payload)} bytes)") - return 0 - - -def cmd_parse(args: argparse.Namespace) -> int: - work = load_work(args.work) - raw = _raw_path(work) - if not raw.is_file(): - raise SystemExit(f"parse: {raw} missing; run `vnpipe fetch` first") - lines, parsed = build(raw.read_bytes(), work.data) - out_dir = work.path("data") - out_dir.mkdir(parents=True, exist_ok=True) - (out_dir / "play.txt").write_text(clean_text(lines), encoding="utf-8", newline="\n") - payload = json.dumps(parsed, ensure_ascii=False, indent=2) + "\n" - (out_dir / "parsed.json").write_text(payload, encoding="utf-8", newline="\n") - for scene in parsed["scenes"]: - kinds: dict[str, int] = {} - for ln in scene["lines"]: - kinds[ln["kind"]] = kinds.get(ln["kind"], 0) + 1 - print(f"parse: {scene['id']}: {kinds}") - return 0 - - -def register(subparsers: argparse._SubParsersAction) -> None: - fetch = subparsers.add_parser("fetch", help="Download the Gutenberg source if missing") - fetch.set_defaults(handler=cmd_fetch) - parse_cmd = subparsers.add_parser("parse", help="Clean, scope and parse the source text") - parse_cmd.set_defaults(handler=cmd_parse) diff --git a/tests/fixtures/annotated_mini.json b/tests/fixtures/annotated_mini.json deleted file mode 100644 index 06ebda6..0000000 --- a/tests/fixtures/annotated_mini.json +++ /dev/null @@ -1,699 +0,0 @@ -{ - "work": "mini", - "parsed_sha256": "0000000000000000000000000000000000000000000000000000000000000000", - "fallback_chunks": [], - "scenes": [ - { - "id": "lyric", - "heading": "LÍRICA", - "lines": [ - { - "id": "lyric_0001", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "Tornáis de nuevo, imágenes flotantes,", - "src_line": 100, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "melancholic", - "location": "dedication", - "time_of_day": "timeless", - "on_stage": [], - "music": "sacred" - } - }, - { - "id": "lyric_0002", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "que un día contemplé,", - "src_line": 101, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "melancholic", - "location": "dedication", - "time_of_day": "timeless", - "on_stage": [] - } - }, - { - "id": "lyric_0003", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "¿Asiros podré feliz?", - "src_line": 102, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "melancholic", - "location": "dedication", - "time_of_day": "timeless", - "on_stage": [] - } - }, - { - "id": "lyric_0004", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "Venid, y envueltas en el velo,", - "src_line": 103, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "melancholic", - "location": "dedication", - "time_of_day": "timeless", - "on_stage": [] - } - }, - { - "id": "lyric_0005", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "girad en derredor;", - "src_line": 104, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "melancholic", - "location": "dedication", - "time_of_day": "timeless", - "on_stage": [] - } - }, - { - "id": "lyric_0006", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "el corazón aún late,", - "src_line": 105, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "melancholic", - "location": "dedication", - "time_of_day": "timeless", - "on_stage": [] - } - }, - { - "id": "lyric_0007", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "si aspira vuestro aliento.", - "src_line": 106, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "melancholic", - "location": "dedication", - "time_of_day": "timeless", - "on_stage": [] - } - }, - { - "id": "lyric_0008", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "Hoy vuelven de otro tiempo", - "src_line": 107, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "melancholic", - "location": "dedication", - "time_of_day": "timeless", - "on_stage": [] - } - }, - { - "id": "lyric_0009", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "la alegre historia,", - "src_line": 108, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "melancholic", - "location": "dedication", - "time_of_day": "timeless", - "on_stage": [] - } - }, - { - "id": "lyric_0010", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 1, - "indent": 0, - "text": "Y los queridos seres", - "src_line": 120, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "melancholic", - "location": "dedication", - "time_of_day": "timeless", - "on_stage": [] - } - }, - { - "id": "lyric_0011", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 1, - "indent": 0, - "text": "que la dicha nos robó.", - "src_line": 121, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "melancholic", - "location": "dedication", - "time_of_day": "timeless", - "on_stage": [] - } - } - ] - }, - { - "id": "talk", - "heading": "CONVERSACIÓN", - "lines": [ - { - "id": "talk_0001", - "kind": "cast", - "speaker": null, - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "EL DIRECTOR, EL POETA", - "src_line": 200, - "ann": { - "speaker": null, - "kind": "narration", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [] - } - }, - { - "id": "talk_0002", - "kind": "verse", - "speaker": "director", - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 2, - "text": "Decid, buenos amigos,", - "src_line": 201, - "ann": { - "speaker": "director", - "kind": "dialogue", - "emotion": "joyful", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "director", - "position": "left" - } - ] - } - }, - { - "id": "talk_0003", - "kind": "verse", - "speaker": "director", - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "de mi afán camaradas,", - "src_line": 202, - "ann": { - "speaker": "director", - "kind": "dialogue", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "director", - "position": "left" - } - ] - } - }, - { - "id": "talk_0004", - "kind": "verse", - "speaker": "director", - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "¿qué pensáis [ahora]?", - "src_line": 203, - "ann": { - "speaker": "director", - "kind": "dialogue", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "director", - "position": "left" - } - ] - } - }, - { - "id": "talk_0005", - "kind": "verse", - "speaker": "director", - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "Es mi {anhelo} preferente", - "src_line": 204, - "ann": { - "speaker": "director", - "kind": "dialogue", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "director", - "position": "left" - } - ] - } - }, - { - "id": "talk_0006", - "kind": "verse", - "speaker": "director", - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "al público dar gusto:", - "src_line": 205, - "ann": { - "speaker": "director", - "kind": "dialogue", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "director", - "position": "left" - } - ] - } - }, - { - "id": "talk_0007", - "kind": "verse", - "speaker": "director", - "speaker_note": null, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "lo \"mejor\" que pueda.", - "src_line": 206, - "ann": { - "speaker": "director", - "kind": "dialogue", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "director", - "position": "left" - } - ] - } - }, - { - "id": "talk_0008", - "kind": "verse", - "speaker": "poet", - "speaker_note": null, - "speech": 1, - "stanza": 0, - "indent": 26, - "text": "¡Vete, profano!", - "src_line": 207, - "ann": { - "speaker": "poet", - "kind": "dialogue", - "emotion": "angry", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "director", - "position": "left" - }, - { - "character": "poet", - "position": "right" - } - ] - } - }, - { - "id": "talk_0009", - "kind": "verse", - "speaker": "director", - "speaker_note": null, - "speech": 2, - "stanza": 0, - "indent": 20, - "text": "Calla, que oye.", - "src_line": 208, - "ann": { - "speaker": "director", - "kind": "dialogue", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "director", - "position": "left" - }, - { - "character": "poet", - "position": "right" - } - ] - } - }, - { - "id": "talk_0010", - "kind": "direction", - "speaker": null, - "speaker_note": null, - "speech": 2, - "stanza": 0, - "indent": 0, - "text": "Se aleja.", - "src_line": 209, - "ann": { - "speaker": "narrator", - "kind": "stage_direction", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "director", - "position": "left" - }, - { - "character": "poet", - "position": "right" - } - ] - } - }, - { - "id": "talk_0011", - "kind": "verse", - "speaker": "poet", - "speaker_note": null, - "speech": 3, - "stanza": 0, - "indent": 0, - "text": "Mi pecho se oprime", - "src_line": 210, - "ann": { - "speaker": "poet", - "kind": "dialogue", - "emotion": "melancholic", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "poet", - "position": "center" - } - ] - } - }, - { - "id": "talk_0012", - "kind": "verse", - "speaker": "poet", - "speaker_note": null, - "speech": 3, - "stanza": 0, - "indent": 0, - "text": "bajo tanto peso,", - "src_line": 211, - "ann": { - "speaker": "poet", - "kind": "dialogue", - "emotion": "melancholic", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "poet", - "position": "center" - } - ] - } - }, - { - "id": "talk_0013", - "kind": "verse", - "speaker": "poet", - "speaker_note": null, - "speech": 3, - "stanza": 0, - "indent": 0, - "text": "y el ocaso llega.", - "src_line": 212, - "ann": { - "speaker": "poet", - "kind": "dialogue", - "emotion": "melancholic", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "poet", - "position": "center" - } - ] - } - }, - { - "id": "talk_0014", - "kind": "verse", - "speaker": "lord", - "speaker_note": null, - "speech": 4, - "stanza": 0, - "indent": 0, - "text": "¡Mi siervo!", - "src_line": 213, - "ann": { - "speaker": "lord", - "kind": "dialogue", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "poet", - "position": "right" - }, - { - "character": "lord", - "position": "center" - } - ], - "music": "none" - } - }, - { - "id": "talk_0015", - "kind": "verse", - "speaker": "lord", - "speaker_note": null, - "speech": 4, - "stanza": 0, - "indent": 0, - "text": "Tentarlo puedes.", - "src_line": 214, - "ann": { - "speaker": "lord", - "kind": "dialogue", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "poet", - "position": "right" - }, - { - "character": "lord", - "position": "center" - } - ] - } - }, - { - "id": "talk_0016", - "kind": "verse", - "speaker": "director", - "speaker_note": null, - "speech": 5, - "stanza": 0, - "indent": 0, - "text": "Basta ya de charla.", - "src_line": 215, - "ann": { - "speaker": "director", - "kind": "dialogue", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "director", - "position": "left" - }, - { - "character": "poet", - "position": "right" - } - ] - } - }, - { - "id": "talk_0017", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 6, - "stanza": 0, - "indent": 0, - "text": "Callan los pájaros;", - "src_line": 216, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [] - } - }, - { - "id": "talk_0018", - "kind": "verse", - "speaker": null, - "speaker_note": null, - "speech": 6, - "stanza": 0, - "indent": 0, - "text": "la noche cae.", - "src_line": 217, - "ann": { - "speaker": "poet_voice", - "kind": "narration", - "emotion": "neutral", - "location": "stage", - "time_of_day": "day", - "on_stage": [] - } - }, - { - "id": "talk_0019", - "kind": "verse", - "speaker": "poet", - "speaker_note": null, - "speech": 7, - "stanza": 0, - "indent": 0, - "text": "Despierto.", - "src_line": 218, - "ann": { - "speaker": "poet", - "kind": "dialogue", - "emotion": "angry", - "location": "stage", - "time_of_day": "day", - "on_stage": [ - { - "character": "director", - "position": "left" - }, - { - "character": "poet", - "position": "right" - } - ] - } - } - ] - } - ] -} diff --git a/tests/fixtures/mini_raw.txt b/tests/fixtures/mini_raw.txt deleted file mode 100644 index b64fe26..0000000 --- a/tests/fixtures/mini_raw.txt +++ /dev/null @@ -1,103 +0,0 @@ -The Project Gutenberg eBook of Fausto - -*** START OF THE PROJECT GUTENBERG EBOOK FAUSTO *** - - DEDICATORIA ................................................ 17 - TEODORO LLORENTE. - -DEDICATORIA - - - Tornáis de nuevo, hermosas imágenes flotantes, - que dulce y melancólico un día contemplé. - ¿Asiros y teneros podré feliz como antes? - ¡Aún vuela hacia vosotras el alma cuando os ve! - - Hoy vuelven de otro tiempo mejor la alegre historia, - y las risueñas sombras de la feliz edad, - -[Ilustración] - - - - -[Ilustración] - -PRÓLOGO EN EL TEATRO - - -EL DIRECTOR, EL POETA DRAMÁTICO, EL GRACIOSO - -EL DIRECTOR - - Decid, buenos amigos, - de mi afán camaradas y testigos, - ¿qué pensáis? Es mi anhelo preferente - - En complacer al público soy ducho; - mas tranquilo no estoy, no estoy sereno: - -EL POETA - - ¡Vete, profano! - ¡Vete! Romper mi servidumbre quiero. - -[Ilustración] - -PRÓLOGO EN EL CIELO - - - EL SEÑOR, - _los_ EJÉRCITOS CELESTIALES. _Después_ MEFISTÓFELES. - _Los tres_ ARCÁNGELES _se adelantan_ - -EL SEÑOR - - ¿Conoces a Fausto? - - MEFISTÓFELES - - ¿A Fausto - el Doctor? - -EL SEÑOR - - ¡Mi siervo! - -(_El cielo se cierra y los Arcángeles se dispersan._) - -MEFISTÓFELES, _solo_ - - De vez en cuando olvido mis rencillas, - y busco al Viejo, y pláticas entablo. - -DE NOCHE - - -_En un aposento gótico, estrecho, con elevada bóveda_, FAUSTO -_intranquilo sentado a su pupitre._ - -FAUSTO - - Filosofía, ¡ay, Dios!, Jurisprudencia, - Medicina además, y Teología, - la _Razón_ lo nombra - -(_Toma el libro y pronuncia misteriosamente el nombre del Espíritu. -Enciéndese una luz rojiza y trémula. El Espíritu aparece en ella._) - -EL ESPÍRITU - - ¿Quién me llama? - -FAUSTO (_aterrado_) - - ¿No a ti? Pues dime: ¿a quién? ¿Imagen - soy de Dios, y ni a ti llegar podría? - -(_Llaman._) - -WAGNER - - Not in scope. -*** END OF THE PROJECT GUTENBERG EBOOK FAUSTO *** diff --git a/tests/fixtures/mini_work/work.toml b/tests/fixtures/mini_work/work.toml deleted file mode 100644 index e4190a1..0000000 --- a/tests/fixtures/mini_work/work.toml +++ /dev/null @@ -1,61 +0,0 @@ -# Minimal work used by tests/test_renpy_gen.py (no assets: the generator falls back to placeholders). -[work] -id = "mini" -title = "Mini" -subtitle = "Fixture work" -author = "A. Author" -translator = "T. Translator" -language = "es" - -[cast.narrator] -name = "" -color = "#d8cfc0" - -[cast.poet_voice] -name = "" -color = "#e8dcc2" -sprite = false - -[cast.director] -name = "El Director" -color = "#c9a25b" -sprite = true -expressions = { neutral = "neutral", joyful = "pleased", angry = "worried" } - -[cast.poet] -name = "El Poeta" -color = "#8fa8c8" -sprite = true -expressions = { neutral = "neutral", melancholic = "neutral", angry = "indignant" } - -[cast.lord] -name = "El Señor" -color = "#fff4c8" -sprite = false - -[staging.lyric] -bg = "bg_dedication" -mode = "nvl" - -[staging.talk] -bg = "bg_theatre" -mode = "adv" - -[[cues]] -at = "talk_0014" -bg = "bg_heaven" -transition = "slow" -tint = "dark" -hide_all = true - -[[cues]] -at = "talk_0016" -mode = "nvl" - -[[cues]] -at = "talk_0019" -bg = "bg_theatre" -transition = "flash" -tint = "none" -mode = "adv" -shake = true diff --git a/tests/test_annotate.py b/tests/test_annotate.py deleted file mode 100644 index bb4d03b..0000000 --- a/tests/test_annotate.py +++ /dev/null @@ -1,376 +0,0 @@ -import json -from pathlib import Path - -import pytest - -from vnpipe import annotate -from vnpipe.cli import main -from vnpipe.config import Work, load_work - -WORK_TOML = """ -[work] -id = "t" -lyric_voice = "voice" - -[[scenes]] -heading = "ONE" -id = "one" -location = "hall" -time_of_day = "day" - -[[scenes]] -heading = "TWO" -id = "two" -location = "yard" -time_of_day = "night" - -[cast.narrator] -name = "" -[cast.voice] -name = "" -sprite = false -[cast.alice] -name = "Alice" -sprite = true -[cast.bob] -name = "Bob" -sprite = true -[cast.god] -name = "God" -sprite = false -""" - - -def _line(scene, n, speech, stanza=0, kind="verse", speaker="alice", note=None): - return { - "id": f"{scene}_{n:04d}", - "kind": kind, - "speaker": speaker if kind == "verse" else None, - "speaker_note": note, - "speech": speech, - "stanza": stanza, - "indent": 0, - "text": f"text {scene} {n}", - "src_line": n + 1, - } - - -def _scene_lines(scene, speeches): - """speeches: list of (speaker, line count).""" - lines = [] - for si, (speaker, count) in enumerate(speeches): - for _ in range(count): - lines.append(_line(scene, len(lines) + 1, si, speaker=speaker)) - return lines - - -def make_work(tmp_path: Path, parsed_scenes) -> Work: - root = tmp_path / "work" - (root / "data").mkdir(parents=True, exist_ok=True) - (root / "work.toml").write_text(WORK_TOML, encoding="utf-8") - parsed = {"work": "t", "source_sha256": "b" * 64, "scenes": parsed_scenes} - (root / "data/parsed.json").write_text(json.dumps(parsed), encoding="utf-8") - return load_work(root) - - -@pytest.fixture -def work(tmp_path): - one = _scene_lines("one", [("alice", 3), ("bob", 2)]) - one.insert(0, _line("one", 0, 0, kind="cast")) - one.insert(2, _line("one", 99, 0, kind="direction")) - two = [_line("two", i + 1, 0, speaker=None) for i in range(2)] - scenes = [ - {"id": "one", "heading": "ONE", "lines": one}, - {"id": "two", "heading": "TWO", "lines": two}, - ] - return make_work(tmp_path, scenes) - - -def chunks_of(work): - parsed, _ = annotate.load_parsed(work) - return annotate.build_chunks(work, parsed) - - -def good_cache(work, chunk, **line_over): - anns = [] - for line in chunk["lines"]: - anns.append( - { - "id": line["id"], - **line["defaults"], - "emotion": "joyful", - "on_stage": [{"character": "alice", "position": "left"}], - "music": None, - } - ) - doc = { - "chunk_id": chunk["chunk_id"], - "input_sha256": chunk["input_sha256"], - "annotations": anns, - } - return doc - - -def put_cache(work, doc): - path = annotate.cache_dir(work) / f"{doc['chunk_id']}.json" - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(doc), encoding="utf-8") - - -def fill_all(work): - for chunk in chunks_of(work): - put_cache(work, good_cache(work, chunk)) - - -# ---------------------------------------------------------------- chunking - - -def test_defaults_and_content(work): - one, two = chunks_of(work) - assert [c["chunk_id"] for c in (one, two)] == ["one_c01", "two_c01"] - by_id = {ln["id"]: ln for ln in one["lines"]} - assert by_id["one_0000"]["defaults"] == { - "speaker": "narrator", - "kind": "stage_direction", - "location": "hall", - "time_of_day": "day", - } - assert by_id["one_0099"]["defaults"]["kind"] == "stage_direction" - assert by_id["one_0001"]["defaults"]["speaker"] == "alice" - assert by_id["one_0001"]["defaults"]["kind"] == "dialogue" - # Unattributed verse -> narration spoken by the lyric voice - assert two["lines"][0]["defaults"] == { - "speaker": "voice", - "kind": "narration", - "location": "yard", - "time_of_day": "night", - } - allowed = one["allowed"] - assert allowed["characters"] == ["alice", "bob", "god"] - assert "narrator" in allowed["speakers"] and "voice" in allowed["speakers"] - assert allowed["locations"] == ["hall", "yard"] - assert "neutral" in allowed["emotions"] and "left" in allowed["positions"] - assert one["context_before"] == [] - assert one["prompt_version"] == annotate.prompt_version() - - -def test_never_crosses_scenes_and_respects_limit(tmp_path): - scenes = [ - {"id": "one", "heading": "ONE", "lines": _scene_lines("one", [("alice", 30)] * 5)}, - {"id": "two", "heading": "TWO", "lines": _scene_lines("two", [("bob", 7)])}, - ] - work = make_work(tmp_path, scenes) - chunks = chunks_of(work) - assert [c["chunk_id"] for c in chunks] == ["one_c01", "one_c02", "one_c03", "two_c01"] - for chunk in chunks: - assert len(chunk["lines"]) <= 60 - assert {ln["id"].rsplit("_", 1)[0] for ln in chunk["lines"]} == {chunk["scene"]["id"]} - assert [len(c["lines"]) for c in chunks] == [60, 60, 30, 7] - - -def test_splits_at_speech_boundaries(tmp_path): - speeches = [("alice", 25), ("bob", 25), ("alice", 25), ("bob", 10)] - work = make_work( - tmp_path, [{"id": "one", "heading": "O", "lines": _scene_lines("one", speeches)}] - ) - chunks = chunks_of(work) - assert [len(c["lines"]) for c in chunks] == [50, 35] - assert chunks[1]["lines"][0]["id"] == "one_0051" - assert len(chunks[1]["context_before"]) == 6 - assert chunks[1]["context_before"][-1]["id"] == "one_0050" - - -def test_oversized_speech_splits_at_stanza_then_hard(tmp_path): - lines = [_line("one", i + 1, 0, stanza=i // 50) for i in range(100)] # two stanzas of 50 - work = make_work(tmp_path, [{"id": "one", "heading": "O", "lines": lines}]) - assert [len(c["lines"]) for c in chunks_of(work)] == [50, 50] - lines = [_line("one", i + 1, 0, stanza=0) for i in range(130)] - work = make_work(tmp_path, [{"id": "one", "heading": "O", "lines": lines}]) - assert [len(c["lines"]) for c in chunks_of(work)] == [60, 60, 10] - - -def test_hash_deterministic_and_content_sensitive(work, tmp_path): - first = [c["input_sha256"] for c in chunks_of(work)] - assert first == [c["input_sha256"] for c in chunks_of(work)] - parsed, _ = annotate.load_parsed(work) - parsed["scenes"][0]["lines"][1]["text"] = "changed" - changed = annotate.build_chunks(work, parsed) - assert changed[0]["input_sha256"] != first[0] - assert changed[1]["input_sha256"] == first[1] - - -def test_prompt_change_invalidates_hash(work, monkeypatch, tmp_path): - before = chunks_of(work)[0]["input_sha256"] - fake = tmp_path / "prompt.md" - fake.write_text("different prompt", encoding="utf-8") - monkeypatch.setattr(annotate, "PROMPT_PATH", fake) - assert chunks_of(work)[0]["input_sha256"] != before - - -def test_chunk_command_writes_and_removes_stale(work, capsys): - assert main(["--work", str(work.root), "annotate", "chunk"]) == 0 - out = annotate.chunks_dir(work) - assert sorted(p.name for p in out.glob("*.json")) == ["one_c01.json", "two_c01.json"] - (out / "gone_c09.json").write_text("{}", encoding="utf-8") - snapshot = (out / "one_c01.json").read_bytes() - main(["--work", str(work.root), "annotate", "chunk"]) - assert not (out / "gone_c09.json").exists() - assert (out / "one_c01.json").read_bytes() == snapshot - assert json.loads(snapshot)["chunk_id"] == "one_c01" - assert "removed stale gone_c09.json" in capsys.readouterr().out - - -def test_unconfigured_scene_or_speaker_fails(tmp_path): - scenes = [{"id": "zzz", "heading": "Z", "lines": [_line("zzz", 1, 0)]}] - with pytest.raises(annotate.AnnotateError): - chunks_of(make_work(tmp_path, scenes)) - scenes = [{"id": "one", "heading": "O", "lines": [_line("one", 1, 0, speaker="ghost")]}] - with pytest.raises(annotate.AnnotateError): - chunks_of(make_work(tmp_path / "b", scenes)) - - -# ---------------------------------------------------------------- status / merge - - -def test_status_states(work, capsys): - one, two = chunks_of(work) - assert annotate.check_cache(work, one)[0] == "missing" - put_cache(work, good_cache(work, one)) - assert annotate.check_cache(work, one) == ("ok", []) - bad = good_cache(work, two) - bad["input_sha256"] = "c" * 64 - put_cache(work, bad) - assert annotate.check_cache(work, two)[0] == "stale" - (annotate.cache_dir(work) / "two_c01.json").write_text("{nope", encoding="utf-8") - assert annotate.check_cache(work, two)[0] == "invalid" - assert main(["--work", str(work.root), "annotate", "status"]) == 0 - out = capsys.readouterr().out - assert "one_c01: ok" in out and "two_c01: invalid" in out - assert "summary: 2 chunks: 1 ok, 0 missing, 0 stale, 1 invalid" in out - - -def merge_main(work, *extra): - return main(["--work", str(work.root), "annotate", "merge", *extra]) - - -def test_merge_ok_and_idempotent(work, capsys): - fill_all(work) - assert merge_main(work) == 0 - out = work.path("data/annotated.json") - first = out.read_bytes() - assert merge_main(work) == 0 - assert out.read_bytes() == first - doc = json.loads(first) - assert doc["fallback_chunks"] == [] - assert doc["parsed_sha256"] and doc["work"] == "t" - line = doc["scenes"][0]["lines"][0] - assert line["id"] == "one_0000" and line["text"] and line["ann"]["emotion"] == "joyful" - assert "id" not in line["ann"] and line["ann"]["music"] is None - assert first.endswith(b"\n") - - -def break_cache(work, mutate): - chunk = chunks_of(work)[0] - doc = good_cache(work, chunk) - mutate(doc) - path = annotate.cache_dir(work) / "one_c01.json" - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(doc), encoding="utf-8") - - -@pytest.mark.parametrize( - ("mutate", "expect"), - [ - (lambda d: d.update(input_sha256="d" * 64), "stale"), - (lambda d: d["annotations"].pop(), "missing lines"), - (lambda d: d["annotations"].reverse(), "not in chunk order"), - (lambda d: d["annotations"][1].update(kind="narration"), "kind is 'narration'"), - (lambda d: d["annotations"][1].update(speaker="bob"), "speaker is 'bob'"), - (lambda d: d["annotations"][1].update(location="yard"), "location is 'yard'"), - (lambda d: d["annotations"][1].update(time_of_day="dawn"), "time_of_day is 'dawn'"), - ( - lambda d: d["annotations"][1].update( - on_stage=[{"character": "zed", "position": "left"}] - ), - "unknown character 'zed'", - ), - ( - lambda d: d["annotations"][1].update( - on_stage=[ - {"character": "bob", "position": "left"}, - {"character": "bob", "position": "right"}, - ] - ), - "more than once", - ), - ( - lambda d: d["annotations"][1].update( - on_stage=[{"character": "narrator", "position": "left"}] - ), - "unknown character 'narrator'", - ), - (lambda d: d["annotations"][1].update(emotion="happy"), "schema"), - (lambda d: d.update(chunk_id="two_c01"), "chunk_id"), - ], -) -def test_merge_rejects_bad_cache(work, capsys, mutate, expect): - two = chunks_of(work)[1] - put_cache(work, good_cache(work, two)) - break_cache(work, mutate) - assert merge_main(work) == 1 - err = capsys.readouterr().err - assert "one_c01" in err and expect in err - assert not work.path("data/annotated.json").exists() - - -def test_merge_without_cache_lists_all_problems(work, capsys): - assert merge_main(work) == 1 - err = capsys.readouterr().err - assert "one_c01: missing" in err and "two_c01: missing" in err - - -def test_merge_fallback(work, capsys): - put_cache(work, good_cache(work, chunks_of(work)[1])) - assert merge_main(work, "--fallback") == 0 - captured = capsys.readouterr() - assert "warning: one_c01: missing" in captured.err - doc = json.loads(work.path("data/annotated.json").read_text(encoding="utf-8")) - assert doc["fallback_chunks"] == ["one_c01"] - lines = {ln["id"]: ln["ann"] for s in doc["scenes"] for ln in s["lines"]} - # cast/direction line before anyone spoke: nobody on stage - assert lines["one_0000"]["on_stage"] == [] - assert lines["one_0000"]["emotion"] == "neutral" and lines["one_0000"]["music"] is None - # alice speaks first -> left; bob joins -> right, alice stays - assert lines["one_0001"]["on_stage"] == [{"character": "alice", "position": "left"}] - assert lines["one_0005"]["on_stage"] == [ - {"character": "alice", "position": "left"}, - {"character": "bob", "position": "right"}, - ] - # the ok chunk is kept as annotated by the LLM - assert lines["two_0001"]["emotion"] == "joyful" - first = work.path("data/annotated.json").read_bytes() - merge_main(work, "--fallback") - assert work.path("data/annotated.json").read_bytes() == first - - -def test_fallback_skips_characters_without_sprite(tmp_path): - lines = [_line("one", 1, 0, speaker="god"), _line("one", 2, 1, speaker="alice")] - work = make_work(tmp_path, [{"id": "one", "heading": "O", "lines": lines}]) - result = annotate.merge(work, fallback=True) - anns = [ln["ann"] for ln in result.document["scenes"][0]["lines"]] - assert anns[0]["on_stage"] == [] - assert anns[1]["on_stage"] == [{"character": "alice", "position": "left"}] - - -# ---------------------------------------------------------------- prompt - - -def test_prompt_fills_placeholders(work): - text = annotate.render_prompt(work, "one_c01") - assert "{{" not in text - root = work.root.resolve() - assert str(root / "annotations/chunks/one_c01.json") in text - assert str(root / "annotations/cache/one_c01.json") in text - assert "annotate status one_c01" in text - with pytest.raises(SystemExit): - annotate.render_prompt(work, "nope_c01") diff --git a/tests/test_annotation_schema.py b/tests/test_annotation_schema.py deleted file mode 100644 index 98ab978..0000000 --- a/tests/test_annotation_schema.py +++ /dev/null @@ -1,150 +0,0 @@ -import copy -import json - -import pytest - -from vnpipe import SCHEMA_DIR -from vnpipe.schema import SchemaError, validate - -SHA = "a" * 64 - - -def _ann(**over): - ann = { - "id": "s_0001", - "speaker": "faust", - "kind": "dialogue", - "emotion": "neutral", - "location": "study", - "time_of_day": "night", - "on_stage": [{"character": "faust", "position": "left"}], - "music": None, - } - ann.update(over) - return ann - - -def _cache(**over): - doc = {"chunk_id": "s_c01", "input_sha256": SHA, "annotations": [_ann()]} - doc.update(over) - return doc - - -def _load(name): - return json.loads((SCHEMA_DIR / f"{name}.schema.json").read_text(encoding="utf-8")) - - -def test_valid_annotation_cache(): - validate(_cache(), "annotation") - - -def test_music_is_optional(): - ann = _ann() - del ann["music"] - validate(_cache(annotations=[ann]), "annotation") - - -@pytest.mark.parametrize("key", ["chunk_id", "input_sha256", "annotations"]) -def test_cache_required_fields(key): - doc = _cache() - del doc[key] - with pytest.raises(SchemaError): - validate(doc, "annotation") - - -@pytest.mark.parametrize( - "key", ["id", "speaker", "kind", "emotion", "location", "time_of_day", "on_stage"] -) -def test_annotation_required_fields(key): - ann = _ann() - del ann[key] - with pytest.raises(SchemaError): - validate(_cache(annotations=[ann]), "annotation") - - -@pytest.mark.parametrize( - "over", - [ - {"emotion": "happy"}, - {"kind": "verse"}, - {"time_of_day": "noon"}, - {"music": "loud"}, - {"extra": 1}, - {"on_stage": [{"character": "faust", "position": "top"}]}, - {"on_stage": [{"character": "faust"}]}, - {"on_stage": [{"character": "faust", "position": "left", "scale": 2}]}, - ], -) -def test_annotation_bad_values(over): - with pytest.raises(SchemaError): - validate(_cache(annotations=[_ann(**over)]), "annotation") - - -def test_cache_rejects_extra_field_and_bad_hash(): - with pytest.raises(SchemaError): - validate(_cache(extra=1), "annotation") - with pytest.raises(SchemaError): - validate(_cache(input_sha256="xyz"), "annotation") - - -def _annotated(): - ann = _ann() - del ann["id"] - line = { - "id": "s_0001", - "kind": "verse", - "speaker": "faust", - "speaker_note": None, - "speech": 0, - "stanza": 0, - "indent": 0, - "text": "Hola", - "src_line": 1, - "ann": ann, - } - return { - "work": "w", - "parsed_sha256": SHA, - "fallback_chunks": [], - "scenes": [{"id": "s", "heading": "H", "lines": [line]}], - } - - -def test_annotated_valid(): - validate(_annotated(), "annotated") - - -def test_annotated_rejects_problems(): - doc = _annotated() - del doc["scenes"][0]["lines"][0]["ann"] - with pytest.raises(SchemaError): - validate(doc, "annotated") - doc = _annotated() - doc["scenes"][0]["lines"][0]["ann"]["emotion"] = "happy" - with pytest.raises(SchemaError): - validate(doc, "annotated") - doc = _annotated() - doc["scenes"][0]["lines"][0]["ann"]["id"] = "s_0001" - with pytest.raises(SchemaError): - validate(doc, "annotated") - doc = _annotated() - del doc["fallback_chunks"] - with pytest.raises(SchemaError): - validate(doc, "annotated") - - -def test_annotated_definitions_match_source_schemas(): - """annotated.schema.json duplicates definitions from the other schemas; keep them in sync.""" - annotated = _load("annotated")["$defs"] - source = _load("annotation")["$defs"] - expected = copy.deepcopy(source["annotation"]) - expected["required"].remove("id") - del expected["properties"]["id"] - assert annotated["ann"] == expected - assert annotated["position"] == source["position"] - - parsed_line = _load("parsed")["properties"]["scenes"]["items"]["properties"]["lines"]["items"] - line = copy.deepcopy(annotated["line"]) - assert line["required"] == [*parsed_line["required"], "ann"] - del line["properties"]["ann"] - assert line["properties"] == parsed_line["properties"] diff --git a/tests/test_renpy_gen.py b/tests/test_renpy_gen.py deleted file mode 100644 index 18d0641..0000000 --- a/tests/test_renpy_gen.py +++ /dev/null @@ -1,415 +0,0 @@ -import json -import os -import subprocess -from pathlib import Path - -import pytest - -from vnpipe import renpy_gen -from vnpipe.config import load_work -from vnpipe.schema import validate - -ROOT = Path(__file__).resolve().parent.parent -FIXTURES = Path(__file__).parent / "fixtures" -SDK = ROOT / "tools/renpy-sdk/renpy.sh" - - -@pytest.fixture(scope="module") -def work(): - return load_work(FIXTURES / "mini_work") - - -@pytest.fixture(scope="module") -def annotated(): - data = json.loads((FIXTURES / "annotated_mini.json").read_text(encoding="utf-8")) - validate(data, "annotated") - return data - - -@pytest.fixture(scope="module") -def project(work, annotated, tmp_path_factory): - out = tmp_path_factory.mktemp("proj") - renpy_gen.generate(work, annotated, out) - return out - - -@pytest.fixture(scope="module") -def script(project) -> str: - return (project / "game/script.rpy").read_text(encoding="utf-8") - - -def scene_block(script: str, scene_id: str) -> list[str]: - lines = script.split("\n") - start = lines.index(f"label scene_{scene_id}:") - end = next((i for i in range(start + 1, len(lines)) if lines[i].startswith("label ")), None) - if end is None: - end = len(lines) - return [ln.strip() for ln in lines[start:end]] - - -def say_lines(block: list[str]) -> list[str]: - return [ln for ln in block if ln.startswith("c_")] - - -def test_escape_text(): - assert renpy_gen.escape_text("a [b] {c}") == "a [[b] {{c}" - assert renpy_gen.escape_text('say "hi"\\') == 'say \\"hi\\"\\\\' - assert renpy_gen.escape_text("a\nb") == "a\\nb" - - -def test_escaping_in_script(script): - assert "¿qué pensáis [[ahora]?" in script - assert "Es mi {{anhelo} preferente" in script - assert 'lo \\"mejor\\" que pueda.' in script - - -def test_title_card_and_end(script): - block = scene_block(script, "talk") - assert "show card_talk at truecenter" in block - assert "hide card_talk" in block - assert "with fade" in block - assert "scene bg theatre at tint_none" in block - assert script.rstrip().endswith("return") - assert "show card_end at truecenter" in script and "label the_end:" in script - - -def test_nvl_pages_per_stanza(script): - block = scene_block(script, "lyric") - says = say_lines(block) - # 9-line stanza -> pages of 8 and 1, then the 2-line second stanza - assert [s.count("\\n") + 1 for s in says] == [8, 1, 2] - assert all(s.startswith("c_poet_voice_nvl ") for s in says) - assert block.count("nvl clear") == 3 - assert block[-2:] == ["nvl hide dissolve", ""] - assert not any(ln.startswith("show ") and "vn_" in ln for ln in block) - - -def test_adv_grouping(script): - says = say_lines(scene_block(script, "talk")) - # director's 6 verse lines -> 4 + 2 - assert says[0].count("\\n") == 3 - assert says[1].count("\\n") == 1 - assert says[0].startswith("c_director ") - # split lines (indent >= 6) get their own boxes - assert says[2] == 'c_poet "¡Vete, profano!"' - assert says[3] == 'c_director "Calla, que oye."' - # stage direction: narrator, own box - assert says[4] == 'c_narrator "Se aleja."' - # poet's 3 lines in one box - assert says[5].count("\\n") == 2 - - -def test_cue_forces_box_break_and_emits_before_line(script): - block = scene_block(script, "talk") - cue_start = block.index("# talk_0014 .. talk_0015") - prefix = block[:cue_start] - # cue 1: slow bg change with dark tint and sprites hidden, before the Lord's lines - assert "show bg heaven at tint_dark" in prefix - assert prefix[prefix.index("show bg heaven at tint_dark") + 1] == "with vn_slow" - assert "hide poet" in prefix[-6:] - # Poet's box ended before the cue (box break at cue line) - assert any("y el ocaso llega." in ln for ln in prefix) - - -def test_mode_switch_and_flash_shake(script): - block = scene_block(script, "talk") - i_nvl = block.index("# talk_0016") - # nvl cue at 0016: sprites hidden (nothing changes the bg), director spoke in nvl mode - assert block[i_nvl + 1].startswith("c_director_nvl ") - assert "nvl clear" in block[i_nvl:] - # lyric voice lines in nvl are grouped into one page - pages = [ln for ln in block if ln.startswith("c_poet_voice_nvl")] - assert pages == ['c_poet_voice_nvl "Callan los pájaros;\\nla noche cae."'] - # cue 3: leave nvl, flash + shake, tint reset - i_cue = block.index("# talk_0019") - assert block[i_cue - 4 : i_cue] == [ - "nvl hide dissolve", - "show bg theatre at tint_none", - "with vn_flash", - "show layer master at vn_shake", - ] - - -def test_expression_mapping(script): - block = scene_block(script, "talk") - # first line of the first box is joyful -> director "pleased" - assert "show director pleased at vn_left" in block - # poet angry -> indignant (split box); director stays pleased/neutral as per his own lines - assert "show poet indignant at vn_right" in block - # poet melancholic -> neutral - assert "show poet neutral at vn_right" in block - - -def test_stable_positions(script): - block = scene_block(script, "talk") - shows = [ln for ln in block if ln.startswith("show poet ")] - assert shows and all(ln.endswith("at vn_right") for ln in shows) - assert not any("vn_center" in ln for ln in block) # annotated centre was never used - - -def test_sprite_false_never_shown(script): - assert "show lord" not in script - assert "show poet_voice" not in script - assert "c_lord " in script # still speaks, with name and colour - - -def test_characters_and_images(project): - chars = (project / "game/characters.rpy").read_text(encoding="utf-8") - assert 'define c_director = Character("El Director", who_color="#c9a25b")' in chars - assert 'define c_director_nvl = Character("El Director", kind=nvl' in chars - assert "define c_narrator = Character(None, what_color=" in chars - assert "what_italic=True" in chars - nameless_nvl = next(ln for ln in chars.split("\n") if ln.startswith("define c_poet_voice_nvl")) - assert "None" in nameless_nvl and "nvl_thought" in nameless_nvl - images = (project / "game/images.rpy").read_text(encoding="utf-8") - assert 'image bg dedication = "images/bg/dedication.webp"' in images - assert 'image director pleased = "images/sprites/director_pleased.webp"' in images - assert (project / "game/images/sprites/poet_indignant.webp").is_file() - assert (project / "game/images/bg/theatre.webp").is_file() - assert not (project / "game/images/sprites/lord_neutral.webp").exists() - - -def test_title_card_images(project): - images = (project / "game/images.rpy").read_text(encoding="utf-8") - assert 'image card_talk = Text("CONVERSACIÓN", size=60, text_align=0.5)' in images - assert 'image card_end = Text("Continuará…"' in images - - -def test_options_substitution(project): - options = (project / "game/options.rpy").read_text(encoding="utf-8") - assert 'config.name = _("Mini")' in options - assert 'build.name = "mini-vn"' in options - assert "@@" not in options - gui = (project / "game/gui.rpy").read_text(encoding="utf-8") - assert 'gui.main_menu_background = "bg dedication"' in gui - assert (project / "game/gui/textbox.png").is_file() - assert (project / "game/fonts/RobotoSlab-Regular.ttf").is_file() - - -def test_music_only_when_audio_exists(work, annotated, tmp_path): - out = tmp_path / "p" - renpy_gen.generate(work, annotated, out) - assert "play music" not in (out / "game/script.rpy").read_text(encoding="utf-8") - (out / "game/audio").mkdir() - (out / "game/audio/sacred.ogg").write_bytes(b"OggS") - renpy_gen.generate(work, annotated, out) - text = (out / "game/script.rpy").read_text(encoding="utf-8") - assert 'play music "audio/sacred.ogg" fadeout 1.0 fadein 1.0' in text - assert "stop music fadeout 1.0" in text # mood "none" on the Lord's first line - assert (out / "game/audio/sacred.ogg").is_file() # regeneration keeps user audio - - -def test_unknown_cue_target_fails(work, annotated): - broken = json.loads(json.dumps(annotated)) - broken["scenes"][1]["lines"] = broken["scenes"][1]["lines"][:5] - with pytest.raises(ValueError, match="unknown line ids"): - renpy_gen.render_script(work, broken, set()) - - -def test_unknown_speaker_fails(work, annotated): - broken = json.loads(json.dumps(annotated)) - broken["scenes"][1]["lines"][1]["ann"]["speaker"] = "ghost" - with pytest.raises(ValueError, match="ghost"): - renpy_gen.render_script(work, broken, set()) - - -def tree(root: Path) -> dict[str, bytes]: - return { - str(p.relative_to(root)): p.read_bytes() for p in sorted(root.rglob("*")) if p.is_file() - } - - -def test_deterministic(work, annotated, tmp_path): - a, b = tmp_path / "a", tmp_path / "b" - renpy_gen.generate(work, annotated, a) - renpy_gen.generate(work, annotated, b) - renpy_gen.generate(work, annotated, b) # regenerating over an existing tree - assert tree(a) == tree(b) - - -def test_from_parsed_annotations(): - work = load_work(ROOT / "works/faust") - parsed = json.loads((ROOT / "works/faust/data/parsed.json").read_text(encoding="utf-8")) - annotated = renpy_gen.annotations_from_parsed(work, parsed) - validate(annotated, "annotated") - teatro = next(s for s in annotated["scenes"] if s["id"] == "prologo_teatro") - stage = [ln["ann"]["on_stage"] for ln in teatro["lines"] if ln["kind"] == "verse"] - assert stage[0] == [{"character": "director", "position": "left"}] - assert {e["character"]: e["position"] for e in stage[-1]} == { - "director": "left", - "poet": "right", - "clown": "center", - } - dedication = annotated["scenes"][0]["lines"][0]["ann"] - assert dedication["speaker"] == "poet_voice" and dedication["on_stage"] == [] - cielo = next(s for s in annotated["scenes"] if s["id"] == "prologo_cielo") - assert cielo["lines"][0]["ann"]["on_stage"] == [] - # the real project generates (cues all resolve) without writing anything - renpy_gen.render_script(work, annotated, set()) - - -@pytest.mark.skipif(not SDK.exists(), reason="Ren'Py SDK not installed in tools/renpy-sdk") -def test_renpy_lint(work, annotated, tmp_path): - out = tmp_path / "mini" - renpy_gen.generate(work, annotated, out) - env = {**os.environ, "HOME": str(tmp_path / "home")} - (tmp_path / "home").mkdir() - result = subprocess.run( - [str(SDK), str(out), "lint"], capture_output=True, text=True, env=env, timeout=300 - ) - report = result.stdout + result.stderr - assert result.returncode == 0, report - assert "Traceback" not in report and "error" not in report.lower(), report - - -def _with_cfg(work, **changes): - data = json.loads(json.dumps(work.data)) - for key, value in changes.items(): - data[key] = value - return type(work)(root=work.root, data=data) - - -def test_pinned_cast(work, annotated): - data = json.loads(json.dumps(work.data)) - data["staging"]["talk"]["cast"] = {"poet": "left", "director": "center"} - pinned = type(work)(root=work.root, data=data) - block = scene_block(renpy_gen.render_script(pinned, annotated, set()), "talk") - first_box = block.index("# talk_0002 .. talk_0005") - assert "show poet neutral at vn_left" in block[first_box:] - assert any(ln.startswith("show director") and ln.endswith("vn_center") for ln in block) - assert not any("vn_right" in ln for ln in block) # annotation position overridden - - -def test_stage_direction_keeps_on_stage(work, annotated): - ann = json.loads(json.dumps(annotated)) - direction = next(ln for ln in ann["scenes"][1]["lines"] if ln["id"] == "talk_0010") - direction["ann"]["on_stage"] = [] - block = scene_block(renpy_gen.render_script(work, ann, set()), "talk") - i = block.index('c_narrator "Se aleja."') - assert not any(ln.startswith("hide ") for ln in block[i - 3 : i]) - - -def test_cue_move(work, annotated): - data = json.loads(json.dumps(work.data)) - data["cues"][0]["move"] = {"poet": "left"} - moved = type(work)(root=work.root, data=data) - block = scene_block(renpy_gen.render_script(moved, annotated, set()), "talk") - # sprites are hidden by that cue's hide_all, so nothing to slide; position is updated - assert "with vn_move" not in block - data["cues"][0].pop("hide_all") - data["cues"][0]["move"] = {"poet": "left"} - moved = type(work)(root=work.root, data=data) - block = scene_block(renpy_gen.render_script(moved, annotated, set()), "talk") - i = block.index("with vn_move") - assert block[i - 1].startswith("show poet ") and block[i - 1].endswith("vn_left") - - -def test_overrides(work, annotated): - ov = [{"from": "talk_0011", "to": "talk_0013", "emotion": "angry"}] - block = scene_block( - renpy_gen.render_script(_with_cfg(work, overrides=ov), annotated, set()), "talk" - ) - assert "show poet indignant at vn_right" in block[block.index("# talk_0011 .. talk_0013") :] - - -@pytest.mark.parametrize( - "change, match", - [ - ({"overrides": [{"from": "talk_0011", "to": "nope", "emotion": "angry"}]}, "unknown line"), - ({"overrides": [{"from": "talk_0011", "to": "talk_0012", "emotion": "mad"}]}, "emotion"), - ({"overrides": [{"from": "talk_0011", "to": "lyric_0001", "emotion": "angry"}]}, "range"), - ({"overrides": [{"from": "talk_0012", "to": "talk_0011", "emotion": "angry"}]}, "range"), - ], -) -def test_invalid_overrides(work, annotated, change, match): - with pytest.raises(ValueError, match=match): - renpy_gen.render_script(_with_cfg(work, **change), annotated, set()) - - -def test_invalid_staging_cast_and_move(work, annotated): - data = json.loads(json.dumps(work.data)) - data["staging"]["talk"]["cast"] = {"ghost": "left"} - with pytest.raises(ValueError, match="ghost"): - renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set()) - data = json.loads(json.dumps(work.data)) - data["staging"]["talk"]["cast"] = {"poet": "up"} - with pytest.raises(ValueError, match="position"): - renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set()) - data = json.loads(json.dumps(work.data)) - data["cues"][0]["move"] = {"poet": "nowhere"} - with pytest.raises(ValueError, match="position"): - renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set()) - - -def test_every_gui_image_exists(project): - """Every gui/... path the template screens reference resolves to a shipped file.""" - import re - - game = project / "game" - text = "".join((game / n).read_text(encoding="utf-8") for n in ("gui.rpy", "screens.rpy")) - text = "\n".join(ln for ln in text.split("\n") if not ln.lstrip().startswith("#")) - refs = set(re.findall(r'"(gui/[^"]+\.png)"', text)) - assert len(refs) > 20 - missing = [] - for ref in sorted(refs): - # Ren'Py's prefix search ends with the un-prefixed name - candidates = [ref.replace("[prefix_]", "")] - if ref.endswith("confirm_frame.png"): - candidates.append("gui/frame.png") # listed fallback in screens.rpy - if not any((game / c).is_file() for c in candidates): - missing.append(ref) - assert not missing - # button_properties() backgrounds fall back to gui/button/background.png - assert (game / "gui/button/background.png").is_file() - assert (game / "gui/phone/button/background.png").is_file() - - -def test_with_test_flag(work, annotated, tmp_path): - plain, tested = tmp_path / "a", tmp_path / "b" - renpy_gen.generate(work, annotated, plain) - renpy_gen.generate(work, annotated, tested, with_test=True) - assert not (plain / "game/e2e_test.rpy").exists() - assert "testcase default" in (tested / "game/e2e_test.rpy").read_text(encoding="utf-8") - renpy_gen.generate(work, annotated, tested) # flag off removes it again - assert not (tested / "game/e2e_test.rpy").exists() - - -def run_e2e(project: Path, home: Path) -> str: - home.mkdir(exist_ok=True) - for name in ("traceback.txt", "errors.txt"): - (project / name).unlink(missing_ok=True) - env = { - **os.environ, - "HOME": str(home), - "SDL_VIDEODRIVER": "dummy", - "SDL_AUDIODRIVER": "dummy", - "RENPY_RENDERER": "sw", - } - result = subprocess.run( - [str(SDK), str(project), "test"], capture_output=True, text=True, env=env, timeout=900 - ) - report = result.stdout + result.stderr - for name in ("traceback.txt", "errors.txt"): - assert not (project / name).exists(), (project / name).read_text(encoding="utf-8") - assert result.returncode == 0, report - assert "Traceback" not in report and "FAIL" not in report, report - return report - - -@pytest.mark.skipif(not SDK.exists(), reason="Ren'Py SDK not installed in tools/renpy-sdk") -def test_e2e_playthrough_mini(work, annotated, tmp_path): - out = tmp_path / "mini" - renpy_gen.generate(work, annotated, out, with_test=True) - run_e2e(out, tmp_path / "home") - - -@pytest.mark.skipif(not SDK.exists(), reason="Ren'Py SDK not installed in tools/renpy-sdk") -@pytest.mark.skipif( - not (ROOT / "works/faust/data/annotated.json").is_file(), reason="no annotated.json" -) -def test_e2e_playthrough_faust(tmp_path): - faust = load_work(ROOT / "works/faust") - data = json.loads((ROOT / "works/faust/data/annotated.json").read_text(encoding="utf-8")) - out = tmp_path / "faust" - renpy_gen.generate(faust, data, out, with_test=True) - run_e2e(out, tmp_path / "home") diff --git a/tests/test_schema.py b/tests/test_schema.py deleted file mode 100644 index 6c0f0dd..0000000 --- a/tests/test_schema.py +++ /dev/null @@ -1,27 +0,0 @@ -import pytest - -from vnpipe.schema import SchemaError, validate - - -def test_valid_instance_passes(): - validate( - { - "work": "x", - "source_sha256": "a" * 64, - "scenes": [{"id": "s", "heading": "H", "lines": []}], - }, - "parsed", - ) - - -def test_reports_all_problems(): - with pytest.raises(SchemaError) as exc: - validate({"work": 1, "source_sha256": "bad", "scenes": []}, "parsed") - message = str(exc.value) - assert "3 problem(s)" in message - assert "/work" in message and "/source_sha256" in message and "/scenes" in message - - -def test_unknown_schema(): - with pytest.raises(FileNotFoundError): - validate({}, "nope") diff --git a/tests/test_text.py b/tests/test_text.py deleted file mode 100644 index 9ef493a..0000000 --- a/tests/test_text.py +++ /dev/null @@ -1,229 +0,0 @@ -import argparse -import json -from pathlib import Path - -import pytest - -from vnpipe import text -from vnpipe.config import load_work -from vnpipe.schema import validate - -ROOT = Path(__file__).resolve().parent.parent -FIXTURE = Path(__file__).parent / "fixtures" / "mini_raw.txt" -RAW = ROOT / "works/faust/data/raw/pg68566.txt" - -CFG = { - "work": {"id": "mini"}, - "scope": {"start_marker": "DEDICATORIA", "end_marker": "(_Llaman._)", "end_occurrence": 1}, - "speakers": { - "EL DIRECTOR": "director", - "EL POETA": "poet", - "MEFISTÓFELES": "mephisto", - "EL SEÑOR": "lord", - "FAUSTO": "faust", - "EL ESPÍRITU": "spirit", - }, - "scenes": [ - {"heading": "DEDICATORIA", "id": "dedicatoria"}, - {"heading": "PRÓLOGO EN EL TEATRO", "id": "prologo_teatro"}, - {"heading": "PRÓLOGO EN EL CIELO", "id": "prologo_cielo"}, - {"heading": "DE NOCHE", "id": "noche"}, - ], -} -SHA = "0" * 64 - - -@pytest.fixture(scope="module") -def raw() -> str: - return FIXTURE.read_text(encoding="utf-8") - - -@pytest.fixture(scope="module") -def parsed(raw): - return text.parse(text.clean(raw, CFG["scope"]), CFG, SHA) - - -def scene(parsed, scene_id): - return next(s for s in parsed["scenes"] if s["id"] == scene_id) - - -def test_scope_cut(raw): - lines = text.clean(raw, CFG["scope"]) - joined = "\n".join(t for _, t in lines) - assert lines[0][1] == "DEDICATORIA" - assert lines[0][0] == 8 # first whole-line match, not the indented TOC entry - assert "Gutenberg" not in joined - assert "TEODORO LLORENTE" not in joined - assert "Llaman" not in joined - assert "WAGNER" not in joined - assert "Ilustración" not in joined - assert "\n\n\n" not in joined - - -def test_scope_missing_marker(raw): - with pytest.raises(text.ParseError): - text.clean(raw, {**CFG["scope"], "start_marker": "NOPE"}) - with pytest.raises(text.ParseError): - text.clean(raw, {**CFG["scope"], "end_occurrence": 5}) - - -def test_crlf_is_normalised(raw): - crlf = raw.replace("\n", "\r\n") - assert text.clean(crlf, CFG["scope"]) == text.clean(raw, CFG["scope"]) - - -def test_scenes_in_order_with_ids(parsed): - assert [s["id"] for s in parsed["scenes"]] == [ - "dedicatoria", - "prologo_teatro", - "prologo_cielo", - "noche", - ] - first = scene(parsed, "noche")["lines"][0] - assert first["id"] == "noche_0001" - - -def test_dedicatoria_has_no_speaker(parsed): - lines = scene(parsed, "dedicatoria")["lines"] - assert all(ln["speaker"] is None and ln["kind"] == "verse" for ln in lines) - assert [ln["stanza"] for ln in lines] == [0, 0, 0, 0, 1, 1] - assert [ln["indent"] for ln in lines] == [2, 0, 0, 0, 2, 0] - - -def test_cast_list_detection(parsed): - teatro = scene(parsed, "prologo_teatro")["lines"][0] - assert teatro["kind"] == "cast" - assert teatro["text"] == "EL DIRECTOR, EL POETA DRAMÁTICO, EL GRACIOSO" - assert teatro["speaker"] is None - cielo = scene(parsed, "prologo_cielo")["lines"][0] - assert cielo["kind"] == "cast" - assert cielo["text"] == ( - "EL SEÑOR, los EJÉRCITOS CELESTIALES. Después MEFISTÓFELES. " - "Los tres ARCÁNGELES se adelantan" - ) - - -def test_setting_is_joined_direction(parsed): - first = scene(parsed, "noche")["lines"][0] - assert first["kind"] == "direction" - assert first["text"] == ( - "En un aposento gótico, estrecho, con elevada bóveda, FAUSTO " - "intranquilo sentado a su pupitre." - ) - - -def test_stanza_counting(parsed): - lines = [ln for ln in scene(parsed, "prologo_teatro")["lines"] if ln["speaker"] == "director"] - assert [ln["stanza"] for ln in lines] == [0, 0, 0, 1, 1] - assert {ln["speech"] for ln in lines} == {0} - - -def test_split_verse_indentation(parsed): - poet = [ln for ln in scene(parsed, "prologo_teatro")["lines"] if ln["speaker"] == "poet"] - assert poet[0]["indent"] == 26 - assert poet[1]["indent"] == 0 - assert poet[0]["speech"] == 1 - - -def test_indented_speaker_heading(parsed): - lines = scene(parsed, "prologo_cielo")["lines"] - mephisto = [ln for ln in lines if ln["text"] in ("¿A Fausto", "el Doctor?")] - assert [ln["speaker"] for ln in mephisto] == ["mephisto", "mephisto"] - assert [ln["indent"] for ln in mephisto] == [19, 0] - assert [ln["speech"] for ln in lines if ln["speaker"]] == [0, 1, 1, 2, 3, 3] - - -def test_speaker_note(parsed): - solo = [ln for ln in scene(parsed, "prologo_cielo")["lines"] if ln["speaker_note"]] - assert {ln["speaker_note"] for ln in solo} == {"solo"} - assert {ln["speaker"] for ln in solo} == {"mephisto"} - noche = scene(parsed, "noche")["lines"] - terrified = [ln for ln in noche if ln["speaker_note"] == "aterrado"] - assert len(terrified) == 2 - assert terrified[0]["speaker"] == "faust" - - -def test_multiline_stage_direction(parsed): - directions = [ln for ln in scene(parsed, "noche")["lines"] if ln["speaker"] is None][1:] - assert len(directions) == 1 - assert directions[0]["kind"] == "direction" - assert directions[0]["text"] == ( - "Toma el libro y pronuncia misteriosamente el nombre del Espíritu. " - "Enciéndese una luz rojiza y trémula. El Espíritu aparece en ella." - ) - assert directions[0]["src_line"] == 86 - inline = [ln for ln in scene(parsed, "prologo_cielo")["lines"] if ln["kind"] == "direction"] - assert inline[0]["text"] == "El cielo se cierra y los Arcángeles se dispersan." - - -def test_italics_stripped(parsed): - texts = [ln["text"] for ln in scene(parsed, "noche")["lines"]] - assert "la Razón lo nombra" in texts - assert not any("_" in t for s in parsed["scenes"] for t in (ln["text"] for ln in s["lines"])) - - -def test_src_lines_point_to_raw(raw, parsed): - raw_lines = raw.split("\n") - for s in parsed["scenes"]: - for ln in s["lines"]: - if ln["kind"] == "verse": - assert raw_lines[ln["src_line"] - 1].strip().replace("_", "") == ln["text"] - - -def test_unknown_speaker_fails(raw): - cfg = {**CFG, "speakers": {k: v for k, v in CFG["speakers"].items() if k != "FAUSTO"}} - with pytest.raises(text.ParseError, match="FAUSTO"): - text.parse(text.clean(raw, CFG["scope"]), cfg, SHA) - - -def test_unknown_scene_heading_fails(raw): - cfg = {**CFG, "scenes": CFG["scenes"][:3]} - with pytest.raises(text.ParseError, match="DE NOCHE"): - text.parse(text.clean(raw, CFG["scope"]), cfg, SHA) - - -def test_deterministic_and_schema_valid(raw, parsed): - again = text.parse(text.clean(raw, CFG["scope"]), CFG, SHA) - assert json.dumps(again) == json.dumps(parsed) - validate(parsed, "parsed") - - -def test_build_hashes_raw_bytes(): - data = FIXTURE.read_bytes() - _, result = text.build(data, CFG) - import hashlib - - assert result["source_sha256"] == hashlib.sha256(data).hexdigest() - - -@pytest.mark.skipif(not RAW.is_file(), reason="raw Gutenberg file not downloaded") -def test_real_file_integration(): - work = load_work(ROOT / "works/faust") - _, parsed = text.build(RAW.read_bytes(), work.data) - assert [s["id"] for s in parsed["scenes"]] == [ - "dedicatoria", - "prologo_teatro", - "prologo_cielo", - "noche", - ] - known = set(work.speakers.values()) - for s in parsed["scenes"]: - assert s["lines"] - assert {ln["speaker"] for ln in s["lines"]} - {None} <= known - - -@pytest.mark.skipif(not RAW.is_file(), reason="raw Gutenberg file not downloaded") -def test_cli_parse_is_byte_identical(tmp_path): - import shutil - - work_dir = tmp_path / "faust" - (work_dir / "data/raw").mkdir(parents=True) - shutil.copy(ROOT / "works/faust/work.toml", work_dir / "work.toml") - shutil.copy(RAW, work_dir / "data/raw/pg68566.txt") - args = argparse.Namespace(work=work_dir) - assert text.cmd_parse(args) == 0 - first = (work_dir / "data/parsed.json").read_bytes() - assert text.cmd_parse(args) == 0 - assert (work_dir / "data/parsed.json").read_bytes() == first - assert first.endswith(b"\n") - assert (work_dir / "data/play.txt").read_text(encoding="utf-8").startswith("DEDICATORIA\n") diff --git a/uv.lock b/uv.lock index 7dc12da..04b87fd 100644 --- a/uv.lock +++ b/uv.lock @@ -20,6 +20,29 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "faust-vn" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "vnpipe" }, +] + +[package.dev-dependencies] +dev = [ + { name = "pytest" }, + { name = "ruff" }, +] + +[package.metadata] +requires-dist = [{ name = "vnpipe", editable = "/home/dasemu/Hacking/Darío/vnpipe" }] + +[package.metadata.requires-dev] +dev = [ + { name = "pytest", specifier = ">=8.3" }, + { name = "ruff", specifier = ">=0.8" }, +] + [[package]] name = "iniconfig" version = "2.3.1" @@ -334,18 +357,12 @@ wheels = [ [[package]] name = "vnpipe" version = "0.1.0" -source = { editable = "." } +source = { editable = "/home/dasemu/Hacking/Darío/vnpipe" } dependencies = [ { name = "jsonschema" }, { name = "pillow" }, ] -[package.dev-dependencies] -dev = [ - { name = "pytest" }, - { name = "ruff" }, -] - [package.metadata] requires-dist = [ { name = "jsonschema", specifier = ">=4.23" },