refactor(utils): extract shared helpers into visualnovel/utils.py
Browse filesMove _quiet_stderr, _safe_print, strip_think, clip_words, and close_truncated_json
out of llm.py and painter.py into a new utils.py module so every backend can share
them without circular imports.
- visualnovel/characters.py +6 -3
- visualnovel/tts.py +6 -0
- visualnovel/utils.py +105 -0
visualnovel/characters.py
CHANGED
|
@@ -8,6 +8,7 @@ is on stage and how they speak. We only ever inject the sheets of the **present*
|
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
from .schemas import Character, GameState
|
|
|
|
| 11 |
|
| 12 |
|
| 13 |
def present_characters(state: GameState) -> list[Character]:
|
|
@@ -47,11 +48,13 @@ def present_sheets_block(state: GameState) -> str:
|
|
| 47 |
npc_bonds_str = "; ".join(npc_bond_lines) if npc_bond_lines else "—"
|
| 48 |
|
| 49 |
blocks.append(
|
|
|
|
|
|
|
| 50 |
f"### {c.name} (id: {c.id})\n"
|
| 51 |
-
f"- one_line: {c.one_line}\n"
|
| 52 |
f"- traits: {', '.join(c.traits) or '—'}\n"
|
| 53 |
-
f"- voice: {c.voice or '—'}\n"
|
| 54 |
-
f"- goal: {c.goals or '—'}\n"
|
| 55 |
f"- mood: {c.mood} | feeling toward wanderer: {rel}/100{rel_note}\n"
|
| 56 |
f"- bonds with others: {npc_bonds_str}\n"
|
| 57 |
f"- knows: {facts}"
|
|
|
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
from .schemas import Character, GameState
|
| 11 |
+
from .utils import clip_words
|
| 12 |
|
| 13 |
|
| 14 |
def present_characters(state: GameState) -> list[Character]:
|
|
|
|
| 48 |
npc_bonds_str = "; ".join(npc_bond_lines) if npc_bond_lines else "—"
|
| 49 |
|
| 50 |
blocks.append(
|
| 51 |
+
# clip_words guards the token budget against runaway generated fields
|
| 52 |
+
# (characters created before the creation-time caps can carry huge goals)
|
| 53 |
f"### {c.name} (id: {c.id})\n"
|
| 54 |
+
f"- one_line: {clip_words(c.one_line, 30)}\n"
|
| 55 |
f"- traits: {', '.join(c.traits) or '—'}\n"
|
| 56 |
+
f"- voice: {clip_words(c.voice, 25) or '—'}\n"
|
| 57 |
+
f"- goal: {clip_words(c.goals, 50) or '—'}\n"
|
| 58 |
f"- mood: {c.mood} | feeling toward wanderer: {rel}/100{rel_note}\n"
|
| 59 |
f"- bonds with others: {npc_bonds_str}\n"
|
| 60 |
f"- knows: {facts}"
|
visualnovel/tts.py
CHANGED
|
@@ -147,8 +147,14 @@ class MockTTS:
|
|
| 147 |
|
| 148 |
class KokoroTTS:
|
| 149 |
def __init__(self) -> None:
|
|
|
|
|
|
|
| 150 |
from kokoro_onnx import Kokoro # noqa: PLC0415
|
| 151 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
_ensure_kokoro_models()
|
| 153 |
self._kokoro = Kokoro(str(_MODEL_PATH), str(_VOICES_PATH))
|
| 154 |
# Filter profiles to voices actually present in the loaded model
|
|
|
|
| 147 |
|
| 148 |
class KokoroTTS:
|
| 149 |
def __init__(self) -> None:
|
| 150 |
+
import logging # noqa: PLC0415
|
| 151 |
+
|
| 152 |
from kokoro_onnx import Kokoro # noqa: PLC0415
|
| 153 |
|
| 154 |
+
# phonemizer resets its logger level on use, so setLevel from app.py doesn't
|
| 155 |
+
# stick — a filter survives ("words count mismatch" fires on nearly every line).
|
| 156 |
+
logging.getLogger("phonemizer").addFilter(lambda r: r.levelno >= logging.ERROR)
|
| 157 |
+
|
| 158 |
_ensure_kokoro_models()
|
| 159 |
self._kokoro = Kokoro(str(_MODEL_PATH), str(_VOICES_PATH))
|
| 160 |
# Filter profiles to voices actually present in the loaded model
|
visualnovel/utils.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small shared helpers with zero heavy dependencies (safe in mock mode)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import contextlib
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
import sys
|
| 9 |
+
from collections.abc import Generator
|
| 10 |
+
|
| 11 |
+
_THINK_RE = re.compile(r"<think>.*?</think>", re.DOTALL)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def strip_think(text: str) -> str:
|
| 15 |
+
"""Remove Qwen3 ``<think>…</think>`` blocks from a completion.
|
| 16 |
+
|
| 17 |
+
Closed blocks are removed wholesale. If an *unclosed* ``<think>`` remains
|
| 18 |
+
(the generation was truncated mid-thought), everything from that tag onward
|
| 19 |
+
is dropped so thinking text never leaks into game state.
|
| 20 |
+
"""
|
| 21 |
+
text = _THINK_RE.sub("", text)
|
| 22 |
+
open_idx = text.find("<think>")
|
| 23 |
+
if open_idx != -1:
|
| 24 |
+
text = text[:open_idx]
|
| 25 |
+
return text.strip()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def clip_words(text: str, n: int) -> str:
|
| 29 |
+
"""Return at most *n* words from *text* (space-split, no tokenizer needed)."""
|
| 30 |
+
words = text.split()
|
| 31 |
+
return " ".join(words[:n]) if len(words) > n else text
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def close_truncated_json(text: str) -> str:
|
| 35 |
+
"""Best-effort repair of JSON cut off mid-generation (max_tokens hit).
|
| 36 |
+
|
| 37 |
+
Closes an unterminated string, drops a dangling backslash/comma, completes a
|
| 38 |
+
dangling ``"key":`` with null, then closes every open bracket. The result is
|
| 39 |
+
parseable for the common truncation shapes; pathological cuts still raise in
|
| 40 |
+
json.loads and are handled by the caller's fallback.
|
| 41 |
+
"""
|
| 42 |
+
stack: list[str] = []
|
| 43 |
+
in_str = False
|
| 44 |
+
esc = False
|
| 45 |
+
for ch in text:
|
| 46 |
+
if in_str:
|
| 47 |
+
if esc:
|
| 48 |
+
esc = False
|
| 49 |
+
elif ch == "\\":
|
| 50 |
+
esc = True
|
| 51 |
+
elif ch == '"':
|
| 52 |
+
in_str = False
|
| 53 |
+
elif ch == '"':
|
| 54 |
+
in_str = True
|
| 55 |
+
elif ch in "{[":
|
| 56 |
+
stack.append(ch)
|
| 57 |
+
elif ch in "}]":
|
| 58 |
+
if stack:
|
| 59 |
+
stack.pop()
|
| 60 |
+
out = text
|
| 61 |
+
if esc:
|
| 62 |
+
out = out[:-1] # drop the dangling escape so the closing quote is valid
|
| 63 |
+
if in_str:
|
| 64 |
+
out += '"'
|
| 65 |
+
stripped = out.rstrip()
|
| 66 |
+
if stripped.endswith(":"):
|
| 67 |
+
stripped += " null"
|
| 68 |
+
elif stripped.endswith(","):
|
| 69 |
+
stripped = stripped[:-1]
|
| 70 |
+
return stripped + "".join("}" if ch == "{" else "]" for ch in reversed(stack))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _safe_print(msg: str) -> None:
|
| 74 |
+
"""Print to stdout, replacing unencodable chars (cp1252 on Windows terminals)."""
|
| 75 |
+
print(
|
| 76 |
+
msg.encode(sys.stdout.encoding or "utf-8", errors="replace").decode(
|
| 77 |
+
sys.stdout.encoding or "utf-8", errors="replace"
|
| 78 |
+
)
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@contextlib.contextmanager
|
| 83 |
+
def _quiet_stderr() -> Generator[None, None, None]:
|
| 84 |
+
"""Redirect the C-level stderr fd to /dev/null for the duration of the block.
|
| 85 |
+
|
| 86 |
+
Catches messages that bypass Python's sys.stderr redirect (e.g. llama.cpp's
|
| 87 |
+
'n_ctx_seq < n_ctx_train', diffusers/transformers load warnings).
|
| 88 |
+
|
| 89 |
+
No-op on Windows: os.dup2 on Windows can swallow native crash messages (CUDA,
|
| 90 |
+
DLL errors) making failures completely silent and impossible to diagnose.
|
| 91 |
+
"""
|
| 92 |
+
if sys.platform == "win32":
|
| 93 |
+
yield
|
| 94 |
+
return
|
| 95 |
+
sys.stderr.flush()
|
| 96 |
+
devnull_fd = os.open(os.devnull, os.O_WRONLY)
|
| 97 |
+
saved_fd = os.dup(2)
|
| 98 |
+
try:
|
| 99 |
+
os.dup2(devnull_fd, 2)
|
| 100 |
+
yield
|
| 101 |
+
finally:
|
| 102 |
+
sys.stderr.flush()
|
| 103 |
+
os.dup2(saved_fd, 2)
|
| 104 |
+
os.close(saved_fd)
|
| 105 |
+
os.close(devnull_fd)
|