Add STT fixes, SDXL-Lightning backend, voice UX and rembg sprite transparency
Browse files- stt.py: WhisperSTT._ensure_extension() handles Gradio extensionless blobs,
per-segment no_speech_prob filter, REAL_STT flag, __main__ debug mode
- config.py: IMAGE_BACKEND (sdxl|lightning), REAL_STT, dynamic _default_steps
- painter.py: _SPRITE_NEGATIVE + negative_prompt threading, SdxlLightningPainter
(EulerDiscrete trailing timestep, fuse_lora), rembg transform on sprites
- frontend: recording timer (● 0:04), transcribing indicator (⏳), full UI lock,
100ms timeslice, empty-chunk guard
- pyproject.toml: peft>=0.11 in image extra
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- frontend/index.html +36 -12
- pyproject.toml +2 -2
- scripts/download_models.py +16 -1
- uv.lock +0 -0
- visualnovel/config.py +10 -4
- visualnovel/painter.py +128 -18
- visualnovel/stt.py +69 -3
frontend/index.html
CHANGED
|
@@ -107,7 +107,9 @@
|
|
| 107 |
padding:11px 16px; color:#10131a; background:var(--gold); font-weight:600; font-size:.98rem}
|
| 108 |
button.ghost{background:transparent; color:var(--ink); border:1px solid rgba(255,255,255,.22)}
|
| 109 |
button:disabled{opacity:.45; cursor:wait}
|
| 110 |
-
|
|
|
|
|
|
|
| 111 |
/* ---- book intro overlay ---- */
|
| 112 |
#intro-book{
|
| 113 |
position:fixed; inset:0; z-index:30; display:flex; align-items:center; justify-content:center;
|
|
@@ -317,7 +319,7 @@ function showNotif(msg){
|
|
| 317 |
}, 5000);
|
| 318 |
}
|
| 319 |
|
| 320 |
-
function busy(state){ $("send").disabled = state; $("say").disabled = state; }
|
| 321 |
|
| 322 |
// --- book overlay dismiss ---
|
| 323 |
$("book-close").addEventListener("click", () => {
|
|
@@ -352,24 +354,46 @@ $("send").addEventListener("click", sendTurn);
|
|
| 352 |
$("say").addEventListener("keydown", (e) => { if (e.key === "Enter") sendTurn(); });
|
| 353 |
|
| 354 |
// --- voice (MediaRecorder -> /transcribe). Press to start, press again to stop. ---
|
| 355 |
-
let rec, chunks = [];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
$("mic").addEventListener("click", async () => {
|
| 357 |
const mic = $("mic");
|
| 358 |
-
if (rec && rec.state === "recording"){ rec.stop(); return; }
|
| 359 |
try {
|
| 360 |
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
| 361 |
rec = new MediaRecorder(stream); chunks = [];
|
| 362 |
-
rec.ondataavailable = (e) => chunks.push(e.data);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
rec.onstop = async () => {
|
| 364 |
-
|
| 365 |
-
const blob = new Blob(chunks, { type: "audio/webm" });
|
| 366 |
-
const file = new File([blob], "speech.webm", { type: "audio/webm" });
|
| 367 |
-
const { data } = await client.predict("/transcribe", { audio: handle_file(file) });
|
| 368 |
-
if (data[0]?.text){ $("say").value = data[0].text; sendTurn(); }
|
| 369 |
stream.getTracks().forEach((t) => t.stop());
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
};
|
| 371 |
-
rec.start();
|
| 372 |
-
} catch (e) {
|
|
|
|
|
|
|
|
|
|
| 373 |
});
|
| 374 |
</script>
|
| 375 |
</body>
|
|
|
|
| 107 |
padding:11px 16px; color:#10131a; background:var(--gold); font-weight:600; font-size:.98rem}
|
| 108 |
button.ghost{background:transparent; color:var(--ink); border:1px solid rgba(255,255,255,.22)}
|
| 109 |
button:disabled{opacity:.45; cursor:wait}
|
| 110 |
+
@keyframes pulse-rec{0%,100%{opacity:1}50%{opacity:.6}}
|
| 111 |
+
#mic.live{background:var(--rose); animation:pulse-rec 1.2s ease-in-out infinite}
|
| 112 |
+
#mic.waiting{background:rgba(255,255,255,.12); color:var(--ink-dim); cursor:wait}
|
| 113 |
/* ---- book intro overlay ---- */
|
| 114 |
#intro-book{
|
| 115 |
position:fixed; inset:0; z-index:30; display:flex; align-items:center; justify-content:center;
|
|
|
|
| 319 |
}, 5000);
|
| 320 |
}
|
| 321 |
|
| 322 |
+
function busy(state){ $("send").disabled = state; $("say").disabled = state; $("mic").disabled = state; }
|
| 323 |
|
| 324 |
// --- book overlay dismiss ---
|
| 325 |
$("book-close").addEventListener("click", () => {
|
|
|
|
| 354 |
$("say").addEventListener("keydown", (e) => { if (e.key === "Enter") sendTurn(); });
|
| 355 |
|
| 356 |
// --- voice (MediaRecorder -> /transcribe). Press to start, press again to stop. ---
|
| 357 |
+
let rec, chunks = [], recTimerId = null;
|
| 358 |
+
|
| 359 |
+
function micIdle() { const m=$("mic"); m.textContent="🎙️"; m.title="click to record"; m.classList.remove("live","waiting"); }
|
| 360 |
+
function micTick(s) { const m=Math.floor(s/60), sec=String(s%60).padStart(2,"0"); $("mic").textContent=`● ${m}:${sec}`; }
|
| 361 |
+
function micWait() { const m=$("mic"); m.textContent="⏳"; m.title="transcribing…"; m.classList.remove("live"); m.classList.add("waiting"); }
|
| 362 |
+
|
| 363 |
$("mic").addEventListener("click", async () => {
|
| 364 |
const mic = $("mic");
|
| 365 |
+
if (rec && rec.state === "recording") { rec.stop(); return; }
|
| 366 |
try {
|
| 367 |
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
| 368 |
rec = new MediaRecorder(stream); chunks = [];
|
| 369 |
+
rec.ondataavailable = (e) => { if (e.data.size > 0) chunks.push(e.data); };
|
| 370 |
+
|
| 371 |
+
// lock text input while recording; mic stays clickable to stop
|
| 372 |
+
$("say").disabled = true; $("send").disabled = true;
|
| 373 |
+
let secs = 0; micTick(0); mic.classList.add("live");
|
| 374 |
+
recTimerId = setInterval(() => micTick(++secs), 1000);
|
| 375 |
+
|
| 376 |
rec.onstop = async () => {
|
| 377 |
+
clearInterval(recTimerId);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
stream.getTracks().forEach((t) => t.stop());
|
| 379 |
+
const blob = new Blob(chunks, { type: "audio/webm" });
|
| 380 |
+
console.debug("[stt] blob size", blob.size);
|
| 381 |
+
if (blob.size < 1000) { micIdle(); $("say").disabled = false; $("send").disabled = false; return; }
|
| 382 |
+
micWait(); mic.disabled = true;
|
| 383 |
+
try {
|
| 384 |
+
const file = new File([blob], "speech.webm", { type: "audio/webm" });
|
| 385 |
+
const { data } = await client.predict("/transcribe", { audio: handle_file(file) });
|
| 386 |
+
micIdle();
|
| 387 |
+
if (data[0]?.text) { $("say").value = data[0].text; sendTurn(); return; }
|
| 388 |
+
} catch (e) { console.error("[stt] transcribe error", e); }
|
| 389 |
+
// fallback: restore input if no text or error
|
| 390 |
+
mic.disabled = false; $("say").disabled = false; $("send").disabled = false;
|
| 391 |
};
|
| 392 |
+
rec.start(100);
|
| 393 |
+
} catch (e) {
|
| 394 |
+
console.warn("mic unavailable", e);
|
| 395 |
+
micIdle(); $("say").disabled = false; $("send").disabled = false;
|
| 396 |
+
}
|
| 397 |
});
|
| 398 |
</script>
|
| 399 |
</body>
|
pyproject.toml
CHANGED
|
@@ -25,8 +25,8 @@ dependencies = [
|
|
| 25 |
# uv sync --extra stt # faster-whisper microphone input
|
| 26 |
llamacpp = ["llama-cpp-python>=0.3.0"]
|
| 27 |
transformers = ["transformers>=4.44", "accelerate>=0.33", "torch>=2.3"]
|
| 28 |
-
image = ["diffusers>=0.38.0", "transformers>=4.44", "accelerate>=0.33", "torch>=2.3", "safetensors>=0.4"]
|
| 29 |
-
stt = ["faster-whisper>=1.0"]
|
| 30 |
matting = ["transformers>=4.44", "torch>=2.3"] # BiRefNet for transparent sprites (Phase 2)
|
| 31 |
spaces = ["spaces>=0.30"] # ZeroGPU decorator on HF Spaces
|
| 32 |
modal = ["modal>=1.0"] # cloud GPU via Modal (LLM + painter)
|
|
|
|
| 25 |
# uv sync --extra stt # faster-whisper microphone input
|
| 26 |
llamacpp = ["llama-cpp-python>=0.3.0"]
|
| 27 |
transformers = ["transformers>=4.44", "accelerate>=0.33", "torch>=2.3"]
|
| 28 |
+
image = ["diffusers>=0.38.0", "transformers>=4.44", "accelerate>=0.33", "torch>=2.3", "safetensors>=0.4", "rembg>=2.0", "peft>=0.11"]
|
| 29 |
+
stt = ["faster-whisper>=1.0", "sounddevice>=0.5.5"]
|
| 30 |
matting = ["transformers>=4.44", "torch>=2.3"] # BiRefNet for transparent sprites (Phase 2)
|
| 31 |
spaces = ["spaces>=0.30"] # ZeroGPU decorator on HF Spaces
|
| 32 |
modal = ["modal>=1.0"] # cloud GPU via Modal (LLM + painter)
|
scripts/download_models.py
CHANGED
|
@@ -48,6 +48,17 @@ def fetch_image() -> None:
|
|
| 48 |
)
|
| 49 |
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
def fetch_whisper() -> None:
|
| 52 |
# faster-whisper downloads on first use; this just pre-warms it.
|
| 53 |
try:
|
|
@@ -64,14 +75,18 @@ def main() -> None:
|
|
| 64 |
ap.add_argument("--llm", action="store_true")
|
| 65 |
ap.add_argument("--image", action="store_true")
|
| 66 |
ap.add_argument("--whisper", action="store_true")
|
|
|
|
| 67 |
args = ap.parse_args()
|
| 68 |
-
do_all = not (args.llm or args.image or args.whisper)
|
| 69 |
|
| 70 |
config.MODELS_DIR.mkdir(parents=True, exist_ok=True)
|
| 71 |
if args.llm or do_all:
|
| 72 |
fetch_llm()
|
| 73 |
if args.image or do_all:
|
| 74 |
fetch_image()
|
|
|
|
|
|
|
|
|
|
| 75 |
if args.whisper or do_all:
|
| 76 |
fetch_whisper()
|
| 77 |
print("done.")
|
|
|
|
| 48 |
)
|
| 49 |
|
| 50 |
|
| 51 |
+
def fetch_rembg() -> None:
|
| 52 |
+
try:
|
| 53 |
+
from rembg import new_session # noqa: PLC0415
|
| 54 |
+
|
| 55 |
+
print("↓ rembg: u2net background-removal model")
|
| 56 |
+
new_session("u2net") # downloads ~168 MB on first call, cached in ~/.u2net
|
| 57 |
+
print(" -> cached")
|
| 58 |
+
except ImportError:
|
| 59 |
+
print(" (skip rembg: install the `image` extra to pre-fetch)")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
def fetch_whisper() -> None:
|
| 63 |
# faster-whisper downloads on first use; this just pre-warms it.
|
| 64 |
try:
|
|
|
|
| 75 |
ap.add_argument("--llm", action="store_true")
|
| 76 |
ap.add_argument("--image", action="store_true")
|
| 77 |
ap.add_argument("--whisper", action="store_true")
|
| 78 |
+
ap.add_argument("--rembg", action="store_true")
|
| 79 |
args = ap.parse_args()
|
| 80 |
+
do_all = not (args.llm or args.image or args.whisper or args.rembg)
|
| 81 |
|
| 82 |
config.MODELS_DIR.mkdir(parents=True, exist_ok=True)
|
| 83 |
if args.llm or do_all:
|
| 84 |
fetch_llm()
|
| 85 |
if args.image or do_all:
|
| 86 |
fetch_image()
|
| 87 |
+
fetch_rembg()
|
| 88 |
+
if args.rembg:
|
| 89 |
+
fetch_rembg()
|
| 90 |
if args.whisper or do_all:
|
| 91 |
fetch_whisper()
|
| 92 |
print("done.")
|
uv.lock
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
visualnovel/config.py
CHANGED
|
@@ -41,6 +41,9 @@ for _d in (MEMORY_DIR, RUNS_DIR, CACHE_DIR):
|
|
| 41 |
# MOCK off -> real backends are instantiated (install the relevant uv extras first).
|
| 42 |
USE_MOCK = os.getenv("VN_MOCK", "1") == "1"
|
| 43 |
|
|
|
|
|
|
|
|
|
|
| 44 |
# LLM runtime backend when not mocking. llamacpp = the llama.cpp bonus path.
|
| 45 |
LLM_BACKEND = os.getenv("VN_LLM_BACKEND", "llamacpp") # llamacpp | transformers | modal | mock
|
| 46 |
|
|
@@ -65,9 +68,11 @@ LLM_REPO = os.getenv("VN_LLM_REPO", "Qwen/Qwen3-14B") # transformers id
|
|
| 65 |
LLM_GGUF_REPO = os.getenv("VN_LLM_GGUF_REPO", "Qwen/Qwen3-14B-GGUF") # llama.cpp source
|
| 66 |
LLM_GGUF_FILE = os.getenv("VN_LLM_GGUF_FILE", "Qwen3-14B-Q4_K_M.gguf")
|
| 67 |
|
| 68 |
-
IMAGE_MODEL
|
| 69 |
# Path or HF repo of YOUR fine-tuned anime-style LoRA (the Well-Tuned bonus). Empty = none.
|
| 70 |
-
IMAGE_LORA
|
|
|
|
|
|
|
| 71 |
|
| 72 |
WHISPER_SIZE = os.getenv(
|
| 73 |
"VN_WHISPER_SIZE", "large-v3-turbo"
|
|
@@ -79,8 +84,9 @@ WHISPER_SIZE = os.getenv(
|
|
| 79 |
CONTEXT_TOKEN_BUDGET = int(os.getenv("VN_CTX_BUDGET", "3500")) # the "Thousand Token Wood"
|
| 80 |
RECENT_TURNS_K = int(os.getenv("VN_RECENT_K", "6"))
|
| 81 |
COMPACT_EVERY = int(os.getenv("VN_COMPACT_EVERY", "8")) # also compacts when over budget
|
| 82 |
-
IMAGE_SIZE
|
| 83 |
-
|
|
|
|
| 84 |
MAX_PRESENT = int(os.getenv("VN_MAX_PRESENT", "3")) # spirits on stage at once
|
| 85 |
|
| 86 |
# --------------------------------------------------------------------------- #
|
|
|
|
| 41 |
# MOCK off -> real backends are instantiated (install the relevant uv extras first).
|
| 42 |
USE_MOCK = os.getenv("VN_MOCK", "1") == "1"
|
| 43 |
|
| 44 |
+
# VN_REAL_STT=1 -> use real Whisper even in mock mode (test STT without full model stack).
|
| 45 |
+
REAL_STT = os.getenv("VN_REAL_STT", "0") == "1"
|
| 46 |
+
|
| 47 |
# LLM runtime backend when not mocking. llamacpp = the llama.cpp bonus path.
|
| 48 |
LLM_BACKEND = os.getenv("VN_LLM_BACKEND", "llamacpp") # llamacpp | transformers | modal | mock
|
| 49 |
|
|
|
|
| 68 |
LLM_GGUF_REPO = os.getenv("VN_LLM_GGUF_REPO", "Qwen/Qwen3-14B-GGUF") # llama.cpp source
|
| 69 |
LLM_GGUF_FILE = os.getenv("VN_LLM_GGUF_FILE", "Qwen3-14B-Q4_K_M.gguf")
|
| 70 |
|
| 71 |
+
IMAGE_MODEL = os.getenv("VN_IMAGE_MODEL", "stabilityai/sdxl-turbo")
|
| 72 |
# Path or HF repo of YOUR fine-tuned anime-style LoRA (the Well-Tuned bonus). Empty = none.
|
| 73 |
+
IMAGE_LORA = os.getenv("VN_IMAGE_LORA", "")
|
| 74 |
+
# sdxl → SDXL-Turbo (1–2 steps) | lightning → SDXL-Lightning (4 steps, better quality)
|
| 75 |
+
IMAGE_BACKEND = os.getenv("VN_IMAGE_BACKEND", "sdxl")
|
| 76 |
|
| 77 |
WHISPER_SIZE = os.getenv(
|
| 78 |
"VN_WHISPER_SIZE", "large-v3-turbo"
|
|
|
|
| 84 |
CONTEXT_TOKEN_BUDGET = int(os.getenv("VN_CTX_BUDGET", "3500")) # the "Thousand Token Wood"
|
| 85 |
RECENT_TURNS_K = int(os.getenv("VN_RECENT_K", "6"))
|
| 86 |
COMPACT_EVERY = int(os.getenv("VN_COMPACT_EVERY", "8")) # also compacts when over budget
|
| 87 |
+
IMAGE_SIZE = int(os.getenv("VN_IMAGE_SIZE", "768"))
|
| 88 |
+
_default_steps = "4" if IMAGE_BACKEND == "lightning" else "2"
|
| 89 |
+
IMAGE_STEPS = int(os.getenv("VN_IMAGE_STEPS", _default_steps))
|
| 90 |
MAX_PRESENT = int(os.getenv("VN_MAX_PRESENT", "3")) # spirits on stage at once
|
| 91 |
|
| 92 |
# --------------------------------------------------------------------------- #
|
visualnovel/painter.py
CHANGED
|
@@ -65,11 +65,22 @@ def backdrop_prompt(state: GameState) -> str:
|
|
| 65 |
|
| 66 |
def sprite_prompt(state: GameState, ch: Character) -> str:
|
| 67 |
return (
|
| 68 |
-
f"
|
| 69 |
-
f"{ch.mood} expression,
|
|
|
|
| 70 |
)
|
| 71 |
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
class PainterBase:
|
| 74 |
"""Caching + key derivation. Subclasses override `_render`."""
|
| 75 |
|
|
@@ -82,22 +93,26 @@ class PainterBase:
|
|
| 82 |
def sprite(self, state: GameState, ch: Character) -> Path:
|
| 83 |
prompt = sprite_prompt(state, ch)
|
| 84 |
return self._cached(
|
| 85 |
-
kind="sprite", key=f"{ch.id}.{ch.mood}", prompt=prompt, seed=ch.sprite_seed
|
|
|
|
| 86 |
)
|
| 87 |
|
| 88 |
# -- internals --
|
| 89 |
-
def _cached(self, *, kind: str, key: str, prompt: str, seed: int
|
| 90 |
-
|
|
|
|
| 91 |
path = config.CACHE_DIR / f"{kind}_{key}_{h}.png"
|
| 92 |
if path.exists():
|
| 93 |
collector.record_cache(hit=True)
|
| 94 |
return path
|
| 95 |
collector.record_cache(hit=False)
|
| 96 |
-
img = self._render(prompt, seed, config.IMAGE_SIZE)
|
|
|
|
|
|
|
| 97 |
img.save(path)
|
| 98 |
return path
|
| 99 |
|
| 100 |
-
def _render(self, prompt: str, seed: int, size: int
|
| 101 |
raise NotImplementedError
|
| 102 |
|
| 103 |
|
|
@@ -105,7 +120,7 @@ class PainterBase:
|
|
| 105 |
# Mock — labelled placeholder, no models
|
| 106 |
# --------------------------------------------------------------------------- #
|
| 107 |
class MockPainter(PainterBase):
|
| 108 |
-
def _render(self, prompt: str, seed: int, size: int):
|
| 109 |
from PIL import Image, ImageDraw # noqa: PLC0415
|
| 110 |
|
| 111 |
# deterministic colour from the seed so the same entity keeps the same placeholder
|
|
@@ -120,30 +135,70 @@ class MockPainter(PainterBase):
|
|
| 120 |
return img
|
| 121 |
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
# --------------------------------------------------------------------------- #
|
| 124 |
# SDXL-Turbo (+ your fine-tuned anime LoRA). STUB — implement with Claude Code.
|
| 125 |
# --------------------------------------------------------------------------- #
|
| 126 |
class SdxlTurboPainter(PainterBase):
|
| 127 |
def __init__(self) -> None:
|
| 128 |
import torch # noqa: PLC0415
|
| 129 |
-
from diffusers import AutoPipelineForText2Image # noqa: PLC0415
|
| 130 |
|
| 131 |
device = config.detect_device() # "cuda" also covers AMD ROCm; "mps" = Apple Metal
|
| 132 |
dtype = torch.float16 if device in ("cuda", "mps") else torch.float32
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
| 139 |
self.torch = torch
|
| 140 |
self.device = device
|
| 141 |
|
| 142 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
gen = self.torch.Generator(device=self.device).manual_seed(seed)
|
| 144 |
# SDXL-Turbo: guidance_scale=0.0, 1-4 steps. Tune in config.IMAGE_STEPS.
|
| 145 |
result = self.pipe(
|
| 146 |
prompt=prompt,
|
|
|
|
| 147 |
num_inference_steps=config.IMAGE_STEPS,
|
| 148 |
guidance_scale=0.0,
|
| 149 |
height=size,
|
|
@@ -153,8 +208,61 @@ class SdxlTurboPainter(PainterBase):
|
|
| 153 |
return result.images[0]
|
| 154 |
# TODO (Phase 2, optional): for layered VN sprites, render on a plain bg here and run
|
| 155 |
# BiRefNet to cut the subject out -> transparent PNG (see docs/ARCHITECTURE.md §5.3).
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
|
| 160 |
# --------------------------------------------------------------------------- #
|
|
@@ -188,4 +296,6 @@ def get_painter() -> Painter:
|
|
| 188 |
return MockPainter()
|
| 189 |
if config.IMAGE_BACKEND == "modal":
|
| 190 |
return ModalPainter()
|
|
|
|
|
|
|
| 191 |
return SdxlTurboPainter()
|
|
|
|
| 65 |
|
| 66 |
def sprite_prompt(state: GameState, ch: Character) -> str:
|
| 67 |
return (
|
| 68 |
+
f"vtuber character design, solo, single character, full-body, centered, "
|
| 69 |
+
f"{state.style_guide}, {ch.appearance}, {ch.mood} expression, "
|
| 70 |
+
f"pure white background, simple background, no scenery, no text"
|
| 71 |
)
|
| 72 |
|
| 73 |
|
| 74 |
+
# Negative prompt injected for every sprite render to enforce the white background.
|
| 75 |
+
# Combined with config.NEGATIVE_PROMPT (quality/artifact negatives).
|
| 76 |
+
_SPRITE_NEGATIVE = (
|
| 77 |
+
f"{config.NEGATIVE_PROMPT}, "
|
| 78 |
+
"background, scenery, landscape, environment, outdoors, indoors, room, sky, "
|
| 79 |
+
"trees, grass, colored background, gradient background, detailed background, "
|
| 80 |
+
"complex background, nature, architecture, buildings"
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
class PainterBase:
|
| 85 |
"""Caching + key derivation. Subclasses override `_render`."""
|
| 86 |
|
|
|
|
| 93 |
def sprite(self, state: GameState, ch: Character) -> Path:
|
| 94 |
prompt = sprite_prompt(state, ch)
|
| 95 |
return self._cached(
|
| 96 |
+
kind="sprite", key=f"{ch.id}.{ch.mood}", prompt=prompt, seed=ch.sprite_seed,
|
| 97 |
+
negative_prompt=_SPRITE_NEGATIVE,
|
| 98 |
)
|
| 99 |
|
| 100 |
# -- internals --
|
| 101 |
+
def _cached(self, *, kind: str, key: str, prompt: str, seed: int,
|
| 102 |
+
negative_prompt: str = "", transform=None) -> Path:
|
| 103 |
+
h = hashlib.sha1(f"{kind}|{prompt}|{negative_prompt}|{seed}".encode()).hexdigest()[:12]
|
| 104 |
path = config.CACHE_DIR / f"{kind}_{key}_{h}.png"
|
| 105 |
if path.exists():
|
| 106 |
collector.record_cache(hit=True)
|
| 107 |
return path
|
| 108 |
collector.record_cache(hit=False)
|
| 109 |
+
img = self._render(prompt, seed, config.IMAGE_SIZE, negative_prompt=negative_prompt)
|
| 110 |
+
if transform is not None:
|
| 111 |
+
img = transform(img)
|
| 112 |
img.save(path)
|
| 113 |
return path
|
| 114 |
|
| 115 |
+
def _render(self, prompt: str, seed: int, size: int, negative_prompt: str = ""):
|
| 116 |
raise NotImplementedError
|
| 117 |
|
| 118 |
|
|
|
|
| 120 |
# Mock — labelled placeholder, no models
|
| 121 |
# --------------------------------------------------------------------------- #
|
| 122 |
class MockPainter(PainterBase):
|
| 123 |
+
def _render(self, prompt: str, seed: int, size: int, negative_prompt: str = ""):
|
| 124 |
from PIL import Image, ImageDraw # noqa: PLC0415
|
| 125 |
|
| 126 |
# deterministic colour from the seed so the same entity keeps the same placeholder
|
|
|
|
| 135 |
return img
|
| 136 |
|
| 137 |
|
| 138 |
+
def _parse_lora(lora: str) -> tuple[str, str | None]:
|
| 139 |
+
"""Return (repo_or_path, weight_name_or_None) for load_lora_weights.
|
| 140 |
+
|
| 141 |
+
Accepts:
|
| 142 |
+
- HF URL: https://huggingface.co/owner/repo/resolve/main/sub/file.safetensors
|
| 143 |
+
- HF repo: owner/repo (diffusers auto-detects the single .safetensors)
|
| 144 |
+
- local: /abs/path/to/lora.safetensors
|
| 145 |
+
"""
|
| 146 |
+
import urllib.parse
|
| 147 |
+
|
| 148 |
+
if lora.startswith("https://huggingface.co/"):
|
| 149 |
+
path = urllib.parse.unquote(lora.removeprefix("https://huggingface.co/"))
|
| 150 |
+
parts = path.split("/")
|
| 151 |
+
# parts: [owner, repo, "resolve", branch, *file_parts]
|
| 152 |
+
repo_id = "/".join(parts[:2])
|
| 153 |
+
weight_name = "/".join(parts[4:])
|
| 154 |
+
return (repo_id, weight_name)
|
| 155 |
+
if "::" in lora: # "owner/repo::weight_file.safetensors"
|
| 156 |
+
repo_id, weight_name = lora.split("::", 1)
|
| 157 |
+
return (repo_id, weight_name)
|
| 158 |
+
return (lora, None)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
# --------------------------------------------------------------------------- #
|
| 162 |
# SDXL-Turbo (+ your fine-tuned anime LoRA). STUB — implement with Claude Code.
|
| 163 |
# --------------------------------------------------------------------------- #
|
| 164 |
class SdxlTurboPainter(PainterBase):
|
| 165 |
def __init__(self) -> None:
|
| 166 |
import torch # noqa: PLC0415
|
| 167 |
+
from diffusers.pipelines.auto_pipeline import AutoPipelineForText2Image # noqa: PLC0415
|
| 168 |
|
| 169 |
device = config.detect_device() # "cuda" also covers AMD ROCm; "mps" = Apple Metal
|
| 170 |
dtype = torch.float16 if device in ("cuda", "mps") else torch.float32
|
| 171 |
+
print(f"[painter] Loading {config.IMAGE_MODEL} (downloading on first run)…", flush=True)
|
| 172 |
+
self.pipe = AutoPipelineForText2Image.from_pretrained(
|
| 173 |
+
config.IMAGE_MODEL, torch_dtype=dtype, variant="fp16" if device == "cuda" else None
|
| 174 |
+
).to(device)
|
| 175 |
+
if config.IMAGE_LORA:
|
| 176 |
+
repo, weight_name = _parse_lora(config.IMAGE_LORA)
|
| 177 |
+
kw = {"weight_name": weight_name} if weight_name else {}
|
| 178 |
+
with _quiet_stderr():
|
| 179 |
+
self.pipe.load_lora_weights(repo, **kw)
|
| 180 |
self.torch = torch
|
| 181 |
self.device = device
|
| 182 |
|
| 183 |
+
def sprite(self, state: GameState, ch: Character) -> Path:
|
| 184 |
+
from rembg import remove # noqa: PLC0415
|
| 185 |
+
|
| 186 |
+
prompt = sprite_prompt(state, ch)
|
| 187 |
+
return self._cached(
|
| 188 |
+
kind="sprite",
|
| 189 |
+
key=f"{ch.id}.{ch.mood}",
|
| 190 |
+
prompt=prompt,
|
| 191 |
+
seed=ch.sprite_seed,
|
| 192 |
+
negative_prompt=_SPRITE_NEGATIVE,
|
| 193 |
+
transform=remove, # removes background → transparent PNG
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
def _render(self, prompt: str, seed: int, size: int, negative_prompt: str = ""):
|
| 197 |
gen = self.torch.Generator(device=self.device).manual_seed(seed)
|
| 198 |
# SDXL-Turbo: guidance_scale=0.0, 1-4 steps. Tune in config.IMAGE_STEPS.
|
| 199 |
result = self.pipe(
|
| 200 |
prompt=prompt,
|
| 201 |
+
negative_prompt=negative_prompt or None,
|
| 202 |
num_inference_steps=config.IMAGE_STEPS,
|
| 203 |
guidance_scale=0.0,
|
| 204 |
height=size,
|
|
|
|
| 208 |
return result.images[0]
|
| 209 |
# TODO (Phase 2, optional): for layered VN sprites, render on a plain bg here and run
|
| 210 |
# BiRefNet to cut the subject out -> transparent PNG (see docs/ARCHITECTURE.md §5.3).
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# --------------------------------------------------------------------------- #
|
| 214 |
+
# SDXL-Lightning — 4-step adversarial distillation. Switch: VN_IMAGE_BACKEND=lightning
|
| 215 |
+
# --------------------------------------------------------------------------- #
|
| 216 |
+
class SdxlLightningPainter(PainterBase):
|
| 217 |
+
def __init__(self) -> None:
|
| 218 |
+
import torch # noqa: PLC0415
|
| 219 |
+
from diffusers import EulerDiscreteScheduler, StableDiffusionXLPipeline # noqa: PLC0415
|
| 220 |
+
|
| 221 |
+
device = config.detect_device()
|
| 222 |
+
dtype = torch.float16 if device in ("cuda", "mps") else torch.float32
|
| 223 |
+
print(f"[painter] Loading SDXL-Lightning ({config.IMAGE_MODEL})…", flush=True)
|
| 224 |
+
self.pipe = StableDiffusionXLPipeline.from_pretrained(
|
| 225 |
+
config.IMAGE_MODEL,
|
| 226 |
+
torch_dtype=dtype,
|
| 227 |
+
variant="fp16" if device == "cuda" else None,
|
| 228 |
+
).to(device)
|
| 229 |
+
# Lightning requires EulerDiscrete with trailing timestep spacing
|
| 230 |
+
self.pipe.scheduler = EulerDiscreteScheduler.from_config(
|
| 231 |
+
self.pipe.scheduler.config, timestep_spacing="trailing"
|
| 232 |
+
)
|
| 233 |
+
if config.IMAGE_LORA:
|
| 234 |
+
repo, weight_name = _parse_lora(config.IMAGE_LORA)
|
| 235 |
+
kw = {"weight_name": weight_name} if weight_name else {}
|
| 236 |
+
self.pipe.load_lora_weights(repo, **kw)
|
| 237 |
+
self.pipe.fuse_lora() # bake into weights for faster inference
|
| 238 |
+
self.torch = torch
|
| 239 |
+
self.device = device
|
| 240 |
+
|
| 241 |
+
def sprite(self, state: GameState, ch: Character) -> Path:
|
| 242 |
+
from rembg import remove # noqa: PLC0415
|
| 243 |
+
|
| 244 |
+
prompt = sprite_prompt(state, ch)
|
| 245 |
+
return self._cached(
|
| 246 |
+
kind="sprite",
|
| 247 |
+
key=f"{ch.id}.{ch.mood}",
|
| 248 |
+
prompt=prompt,
|
| 249 |
+
seed=ch.sprite_seed,
|
| 250 |
+
negative_prompt=_SPRITE_NEGATIVE,
|
| 251 |
+
transform=remove, # removes background → transparent PNG
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
def _render(self, prompt: str, seed: int, size: int, negative_prompt: str = ""):
|
| 255 |
+
gen = self.torch.Generator(device=self.device).manual_seed(seed)
|
| 256 |
+
result = self.pipe(
|
| 257 |
+
prompt=prompt,
|
| 258 |
+
negative_prompt=negative_prompt or None,
|
| 259 |
+
num_inference_steps=config.IMAGE_STEPS, # 4 for Lightning
|
| 260 |
+
guidance_scale=0.0,
|
| 261 |
+
height=size,
|
| 262 |
+
width=size,
|
| 263 |
+
generator=gen,
|
| 264 |
+
)
|
| 265 |
+
return result.images[0]
|
| 266 |
|
| 267 |
|
| 268 |
# --------------------------------------------------------------------------- #
|
|
|
|
| 296 |
return MockPainter()
|
| 297 |
if config.IMAGE_BACKEND == "modal":
|
| 298 |
return ModalPainter()
|
| 299 |
+
if config.IMAGE_BACKEND == "lightning":
|
| 300 |
+
return SdxlLightningPainter()
|
| 301 |
return SdxlTurboPainter()
|
visualnovel/stt.py
CHANGED
|
@@ -30,10 +30,76 @@ class WhisperSTT:
|
|
| 30 |
ct2_device = "cuda" if device == "cuda" else "cpu"
|
| 31 |
self.model = WhisperModel(config.WHISPER_SIZE, device=ct2_device, compute_type="auto")
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
def transcribe(self, audio_path: str) -> str:
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
def get_stt() -> STTBackend:
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
ct2_device = "cuda" if device == "cuda" else "cpu"
|
| 31 |
self.model = WhisperModel(config.WHISPER_SIZE, device=ct2_device, compute_type="auto")
|
| 32 |
|
| 33 |
+
@staticmethod
|
| 34 |
+
def _ensure_extension(audio_path: str) -> tuple[str, bool]:
|
| 35 |
+
"""Return (path, should_delete). Copies extensionless blobs to .webm so PyAV can probe format."""
|
| 36 |
+
import pathlib
|
| 37 |
+
import shutil
|
| 38 |
+
import tempfile
|
| 39 |
+
|
| 40 |
+
if pathlib.Path(audio_path).suffix.lower():
|
| 41 |
+
return audio_path, False
|
| 42 |
+
# Gradio saves browser recordings as bare 'blob' files — give it the right extension.
|
| 43 |
+
tmp = tempfile.mktemp(suffix=".webm")
|
| 44 |
+
shutil.copy2(audio_path, tmp)
|
| 45 |
+
return tmp, True
|
| 46 |
+
|
| 47 |
def transcribe(self, audio_path: str) -> str:
|
| 48 |
+
import os
|
| 49 |
+
|
| 50 |
+
path, temp = self._ensure_extension(audio_path)
|
| 51 |
+
try:
|
| 52 |
+
segments, _ = self.model.transcribe(
|
| 53 |
+
path,
|
| 54 |
+
beam_size=1,
|
| 55 |
+
no_speech_threshold=0.6,
|
| 56 |
+
condition_on_previous_text=False,
|
| 57 |
+
)
|
| 58 |
+
return " ".join(s.text for s in segments if s.no_speech_prob <= 0.6).strip()
|
| 59 |
+
finally:
|
| 60 |
+
if temp:
|
| 61 |
+
os.unlink(path)
|
| 62 |
|
| 63 |
|
| 64 |
def get_stt() -> STTBackend:
|
| 65 |
+
if config.USE_MOCK and not config.REAL_STT:
|
| 66 |
+
return MockSTT()
|
| 67 |
+
return WhisperSTT()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# Debug: record from microphone and transcribe
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
import sys
|
| 73 |
+
import tempfile
|
| 74 |
+
import wave
|
| 75 |
+
|
| 76 |
+
import numpy as np
|
| 77 |
+
|
| 78 |
+
RATE = 16_000
|
| 79 |
+
SECONDS = int(sys.argv[1]) if len(sys.argv) > 1 else 5
|
| 80 |
+
|
| 81 |
+
try:
|
| 82 |
+
import sounddevice as sd
|
| 83 |
+
|
| 84 |
+
print(f"Recording {SECONDS}s … speak now!")
|
| 85 |
+
audio = sd.rec(RATE * SECONDS, samplerate=RATE, channels=1, dtype="float32")
|
| 86 |
+
sd.wait()
|
| 87 |
+
audio = audio[:, 0]
|
| 88 |
+
print("Done recording.")
|
| 89 |
+
except ImportError:
|
| 90 |
+
print("sounddevice not installed — using 5 s of silence as fallback.")
|
| 91 |
+
print("Install with: uv add sounddevice")
|
| 92 |
+
audio = np.zeros(RATE * SECONDS, dtype=np.float32)
|
| 93 |
+
|
| 94 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
|
| 95 |
+
tmp_path = f.name
|
| 96 |
+
pcm = (audio * 32767).astype(np.int16)
|
| 97 |
+
with wave.open(tmp_path, "wb") as wf:
|
| 98 |
+
wf.setnchannels(1)
|
| 99 |
+
wf.setsampwidth(2)
|
| 100 |
+
wf.setframerate(RATE)
|
| 101 |
+
wf.writeframes(pcm.tobytes())
|
| 102 |
+
|
| 103 |
+
stt = WhisperSTT()
|
| 104 |
+
result = stt.transcribe(tmp_path)
|
| 105 |
+
print(f"Transcription: {result!r}")
|