Upload folder using huggingface_hub
Browse files- .gitattributes +3 -0
- ARCHITECTURE.md +68 -0
- app.py +15 -4
- assets/anchor_gravel.wav +3 -0
- assets/anchor_nasal.wav +3 -0
- assets/anchor_sharp.wav +3 -0
- game/model.py +59 -11
- game/voice.py +96 -0
- modal_factory.py +39 -0
- requirements.txt +2 -0
.gitattributes
CHANGED
|
@@ -39,3 +39,6 @@ assets/voice_caught_2.wav filter=lfs diff=lfs merge=lfs -text
|
|
| 39 |
assets/voice_escaped_0.wav filter=lfs diff=lfs merge=lfs -text
|
| 40 |
assets/voice_escaped_1.wav filter=lfs diff=lfs merge=lfs -text
|
| 41 |
assets/voice_escaped_2.wav filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
assets/voice_escaped_0.wav filter=lfs diff=lfs merge=lfs -text
|
| 40 |
assets/voice_escaped_1.wav filter=lfs diff=lfs merge=lfs -text
|
| 41 |
assets/voice_escaped_2.wav filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
assets/anchor_gravel.wav filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
assets/anchor_nasal.wav filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
assets/anchor_sharp.wav filter=lfs diff=lfs merge=lfs -text
|
ARCHITECTURE.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# EYEWITNESS — cómo funciona (mapa del sistema)
|
| 2 |
+
|
| 3 |
+
## El principio de diseño
|
| 4 |
+
|
| 5 |
+
**Author the ground truth, don't detect it.** El motor compone cada cara desde un
|
| 6 |
+
vocabulario cerrado de 12 atributos (`game/face.py: VOCAB`), así que siempre sabe la
|
| 7 |
+
verdad exacta. Los modelos solo *traducen* — nunca tienen que reconocer nada.
|
| 8 |
+
|
| 9 |
+
## Flujo de una partida
|
| 10 |
+
|
| 11 |
+
```
|
| 12 |
+
intro ──ROLL──▶ glimpse (3s, CSS animation-delay oculta la cara)
|
| 13 |
+
──I SAW HIM──▶ testimony (texto libre EN/ES)
|
| 14 |
+
──SEND──▶ [PARSER] testimonio → JSON de atributos
|
| 15 |
+
├── Tier B: MiniCPM5-1B fine-tuneado (ZeroGPU, frases sucias)
|
| 16 |
+
└── Tier A: matcher de sinónimos (backstop literal, siempre gana donde matchea)
|
| 17 |
+
──▶ sketch (dibuja SOLO lo que dijiste) + lineup (gr.Gallery PNG)
|
| 18 |
+
└── lineup.py: distractores desde TUS errores
|
| 19 |
+
· lo que dijiste MAL → plantado en distractores
|
| 20 |
+
· lo que NO mencionaste → ejes de confusión
|
| 21 |
+
· lo que acertaste → poda la rueda (p=0.72, afinado por simulación)
|
| 22 |
+
──click──▶ verdict: sello + cita con voz (VoxCPM2 pre-render, en memoria) +
|
| 23 |
+
tabla transparente dijiste/verdad + póster SE BUSCA (PIL) ──▶ next case
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
Rangos: ROOKIE (3s, rueda 4) → DETECTIVE (2s, 6) → INSPECTOR (1.5s, 6 + disfraz) → CHIEF (1s, 8 + disfraz).
|
| 27 |
+
"Disfraz" = el culpable cambia UN atributo saliente entre el crimen y la rueda.
|
| 28 |
+
|
| 29 |
+
## Ficheros
|
| 30 |
+
|
| 31 |
+
| Fichero | Qué hace |
|
| 32 |
+
|---|---|
|
| 33 |
+
| `app.py` | UI Gradio: una sola etapa `@gr.render` dirigida por `gr.State` dict (screen=intro/glimpse/testimony/lineup/verdict) |
|
| 34 |
+
| `game/face.py` | VOCAB + FaceSpec + renderer SVG paramétrico (estilo retrato robot) |
|
| 35 |
+
| `game/render.py` | SVG→PIL compartido (Gallery y póster) |
|
| 36 |
+
| `game/casegen.py` | Casos: crimen + culpable + parámetros por rango; carga banco Modal si existe |
|
| 37 |
+
| `game/parser.py` | Tier A: sinónimos EN+ES, matching longest-first |
|
| 38 |
+
| `game/model.py` | Tier B: MiniCPM5-1B slot-filling (gated: solo ZeroGPU/CUDA/env), merge con prioridad Tier A |
|
| 39 |
+
| `game/lineup.py` | Distractores derivados de errores (la mecánica firma) |
|
| 40 |
+
| `game/scoring.py` | Nota ponderada por saliencia + rating con humor |
|
| 41 |
+
| `game/poster.py` | Póster SE BUSCA compartible (PIL) |
|
| 42 |
+
| `modal_factory.py` | Build-time en Modal: banco de casos (llama.cpp+GGUF) + banco de voces (VoxCPM2, anchor a 48kHz) |
|
| 43 |
+
| `train/gen_dataset.py` | Dataset sintético: spec→testimonio ruidoso bilingüe (verdad por construcción) |
|
| 44 |
+
| `train/train_modal.py` | LoRA en Modal → publica `Fcabla/MiniCPM5-1B-eyewitness` |
|
| 45 |
+
| `tests/test_engine.py` | QA: testimonios límite, equidad por simulación (400 partidas), bounds |
|
| 46 |
+
| `deploy.sh` | Sube el Space a la org (idempotente) |
|
| 47 |
+
|
| 48 |
+
## Modelos en runtime (~3.4B total)
|
| 49 |
+
|
| 50 |
+
- `Fcabla/MiniCPM5-1B-eyewitness` (1.08B, LoRA del MiniCPM5-1B) — parser de testimonios.
|
| 51 |
+
Variable de Space `EYEWITNESS_MODEL_ID` lo selecciona; sin ella usa el base.
|
| 52 |
+
- VoxCPM2 (2.29B) — SOLO build-time hoy (banco pre-renderizado); el wav viaja en memoria
|
| 53 |
+
como (48000, int16 array) porque gr.Audio con rutas revienta en el Space.
|
| 54 |
+
|
| 55 |
+
## Infra
|
| 56 |
+
|
| 57 |
+
- **Space**: `build-small-hackathon/eyewitness`, ZeroGPU (H200 slice), gating por env.
|
| 58 |
+
- **GitHub**: `fcabla/eyewitness` (público).
|
| 59 |
+
- **Dataset**: `build-small-hackathon/eyewitness-testimonies`.
|
| 60 |
+
- **Modal**: apps `eyewitness-factory` (casos+voces) y `eyewitness-train` (LoRA, A10G).
|
| 61 |
+
|
| 62 |
+
## Limitaciones conocidas (candidatas a iteración)
|
| 63 |
+
|
| 64 |
+
1. La voz del veredicto es de un banco de 6 líneas fijas — no referencia TUS errores,
|
| 65 |
+
y el timbre no siempre casa con la cara del sospechoso.
|
| 66 |
+
2. El 1B trabaja una sola vez por ronda (parse) — su papel es invisible para el jurado.
|
| 67 |
+
3. El glimpse es vulnerable a inspeccionar el DOM (la cara sigue en el HTML borroso).
|
| 68 |
+
4. El parser puede alucinar atributos no mencionados (mitigado: Tier A manda donde habló).
|
app.py
CHANGED
|
@@ -46,11 +46,17 @@ def verdict_voice(correct: bool) -> tuple[int, "np.ndarray"] | None:
|
|
| 46 |
return w.getframerate(), np.frombuffer(frames, dtype=np.int16)
|
| 47 |
|
| 48 |
try: # Tier B (deployed): MiniCPM5-1B slot-filler. Falls back to Tier A locally.
|
| 49 |
-
from game.model import parse_testimony_model, model_enabled
|
| 50 |
HAS_MODEL = model_enabled()
|
| 51 |
except Exception:
|
| 52 |
HAS_MODEL = False
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
# ------------------------------------------------------------------ helpers
|
| 56 |
def svg_uri(svg: str) -> str:
|
|
@@ -285,8 +291,12 @@ with gr.Blocks(title="EYEWITNESS") as demo:
|
|
| 285 |
truth_img = svg_uri(render_face_svg(case.culprit, width=240))
|
| 286 |
picked_img = svg_uri(render_face_svg(s["lineup"][s["picked"]], width=240))
|
| 287 |
head = "ARREST CONFIRMED" if correct else "WRONG ARREST"
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
with gr.Column(elem_classes=["ew-card"]):
|
| 291 |
gr.HTML(f"""
|
| 292 |
<div class="ew-verdict {'ew-good' if correct else 'ew-bad'}">
|
|
@@ -300,7 +310,8 @@ with gr.Blocks(title="EYEWITNESS") as demo:
|
|
| 300 |
<div class="ew-line">{line} · Memory accuracy: <b>{report.weighted_pct}%</b></div>
|
| 301 |
</div>
|
| 302 |
{report_table_html(report)}""")
|
| 303 |
-
voice =
|
|
|
|
| 304 |
if voice:
|
| 305 |
# minimal kwargs: the Space's gradio build rejects newer
|
| 306 |
# Audio options like show_download_button
|
|
|
|
| 46 |
return w.getframerate(), np.frombuffer(frames, dtype=np.int16)
|
| 47 |
|
| 48 |
try: # Tier B (deployed): MiniCPM5-1B slot-filler. Falls back to Tier A locally.
|
| 49 |
+
from game.model import parse_testimony_model, model_enabled, culprit_taunt
|
| 50 |
HAS_MODEL = model_enabled()
|
| 51 |
except Exception:
|
| 52 |
HAS_MODEL = False
|
| 53 |
|
| 54 |
+
try: # live VoxCPM2 verdict voice (anchored per suspect); bank is the fallback
|
| 55 |
+
from game.voice import speak as live_speak
|
| 56 |
+
except Exception:
|
| 57 |
+
def live_speak(line, seed):
|
| 58 |
+
return None
|
| 59 |
+
|
| 60 |
|
| 61 |
# ------------------------------------------------------------------ helpers
|
| 62 |
def svg_uri(svg: str) -> str:
|
|
|
|
| 291 |
truth_img = svg_uri(render_face_svg(case.culprit, width=240))
|
| 292 |
picked_img = svg_uri(render_face_svg(s["lineup"][s["picked"]], width=240))
|
| 293 |
head = "ARREST CONFIRMED" if correct else "WRONG ARREST"
|
| 294 |
+
# live, personalized taunt from the witness's actual mistakes;
|
| 295 |
+
# canned quote is the fallback at every step of the cascade
|
| 296 |
+
taunt = culprit_taunt(report.rows, correct) if HAS_MODEL else None
|
| 297 |
+
quote = (f"“{taunt}”" if taunt else
|
| 298 |
+
("“Okay, okay. It was me. Take me in.”" if correct
|
| 299 |
+
else "“Wrong guy. I walked RIGHT past you. Twice.”"))
|
| 300 |
with gr.Column(elem_classes=["ew-card"]):
|
| 301 |
gr.HTML(f"""
|
| 302 |
<div class="ew-verdict {'ew-good' if correct else 'ew-bad'}">
|
|
|
|
| 310 |
<div class="ew-line">{line} · Memory accuracy: <b>{report.weighted_pct}%</b></div>
|
| 311 |
</div>
|
| 312 |
{report_table_html(report)}""")
|
| 313 |
+
voice = (live_speak(taunt, case.seed) if taunt else None) \
|
| 314 |
+
or verdict_voice(correct)
|
| 315 |
if voice:
|
| 316 |
# minimal kwargs: the Space's gradio build rejects newer
|
| 317 |
# Audio options like show_download_button
|
assets/anchor_gravel.wav
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5eb01a91212d7a273017e737c66f2153379a96c1d41f6abc479bb180f627698a
|
| 3 |
+
size 737324
|
assets/anchor_nasal.wav
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:86526805963118b0a28b0d10a57e38682dcdb2b86ab4277ef704069d8269012e
|
| 3 |
+
size 706604
|
assets/anchor_sharp.wav
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:66ab81b94810b12b393461599c59b707cadbf2cb6a3380ee059390a584301c05
|
| 3 |
+
size 814124
|
game/model.py
CHANGED
|
@@ -30,9 +30,12 @@ except Exception: # local dev
|
|
| 30 |
def _gpu(fn):
|
| 31 |
return fn
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
_lock = threading.Lock()
|
| 34 |
-
|
| 35 |
-
_tokenizer = None
|
| 36 |
|
| 37 |
|
| 38 |
def model_enabled() -> bool:
|
|
@@ -54,20 +57,20 @@ def model_enabled() -> bool:
|
|
| 54 |
return False
|
| 55 |
|
| 56 |
|
| 57 |
-
def _load():
|
| 58 |
-
|
| 59 |
-
if _model is None:
|
| 60 |
with _lock:
|
| 61 |
-
if
|
| 62 |
import torch
|
| 63 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 68 |
device_map="cuda" if torch.cuda.is_available() else "cpu",
|
| 69 |
)
|
| 70 |
-
|
|
|
|
| 71 |
|
| 72 |
|
| 73 |
def _schema_block() -> str:
|
|
@@ -100,13 +103,58 @@ def _generate(testimony: str) -> str:
|
|
| 100 |
safe = json.dumps(testimony, ensure_ascii=False)[1:-1]
|
| 101 |
prompt = PROMPT.format(schema=_schema_block(), testimony=safe)
|
| 102 |
messages = [{"role": "user", "content": prompt}]
|
| 103 |
-
text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 104 |
enc = tok(text, return_tensors="pt").to(model.device)
|
| 105 |
out = model.generate(**enc, max_new_tokens=220, do_sample=False,
|
| 106 |
pad_token_id=tok.eos_token_id)
|
| 107 |
return tok.decode(out[0][enc["input_ids"].shape[1]:], skip_special_tokens=True)
|
| 108 |
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
def parse_testimony_model(testimony: str) -> dict[str, str | None]:
|
| 111 |
"""Model first, Tier A as per-slot backstop. Validated against VOCAB."""
|
| 112 |
base = _tier_a(testimony)
|
|
|
|
| 30 |
def _gpu(fn):
|
| 31 |
return fn
|
| 32 |
|
| 33 |
+
# the LoRA fine-tune only knows slot-filling (catastrophic forgetting — it
|
| 34 |
+
# babbles dataset phrasings on open prompts); creative lines use the base model
|
| 35 |
+
TAUNT_MODEL_ID = os.environ.get("EYEWITNESS_TAUNT_MODEL_ID", "openbmb/MiniCPM5-1B")
|
| 36 |
+
|
| 37 |
_lock = threading.Lock()
|
| 38 |
+
_models: dict[str, tuple] = {}
|
|
|
|
| 39 |
|
| 40 |
|
| 41 |
def model_enabled() -> bool:
|
|
|
|
| 57 |
return False
|
| 58 |
|
| 59 |
|
| 60 |
+
def _load(model_id: str = MODEL_ID):
|
| 61 |
+
if model_id not in _models:
|
|
|
|
| 62 |
with _lock:
|
| 63 |
+
if model_id not in _models:
|
| 64 |
import torch
|
| 65 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 66 |
+
tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 67 |
+
mdl = AutoModelForCausalLM.from_pretrained(
|
| 68 |
+
model_id, trust_remote_code=True,
|
| 69 |
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 70 |
device_map="cuda" if torch.cuda.is_available() else "cpu",
|
| 71 |
)
|
| 72 |
+
_models[model_id] = (mdl, tok)
|
| 73 |
+
return _models[model_id]
|
| 74 |
|
| 75 |
|
| 76 |
def _schema_block() -> str:
|
|
|
|
| 103 |
safe = json.dumps(testimony, ensure_ascii=False)[1:-1]
|
| 104 |
prompt = PROMPT.format(schema=_schema_block(), testimony=safe)
|
| 105 |
messages = [{"role": "user", "content": prompt}]
|
| 106 |
+
text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
|
| 107 |
enc = tok(text, return_tensors="pt").to(model.device)
|
| 108 |
out = model.generate(**enc, max_new_tokens=220, do_sample=False,
|
| 109 |
pad_token_id=tok.eos_token_id)
|
| 110 |
return tok.decode(out[0][enc["input_ids"].shape[1]:], skip_special_tokens=True)
|
| 111 |
|
| 112 |
|
| 113 |
+
TAUNT_PROMPT = """You are the culprit in a comedy detective game. Outcome: you were {outcome}.
|
| 114 |
+
The witness just described you to a sketch artist. Their wrong claims: {wrong}.
|
| 115 |
+
What they failed to notice: {missed}. What they got right: {right}.
|
| 116 |
+
Speak ONE smug in-character line (under 25 words) mocking their SPECIFIC mistakes.
|
| 117 |
+
Plain text only, no quotes, no emoji, no hashtags, no explanations, exactly one sentence.
|
| 118 |
+
|
| 119 |
+
Example (wrong claim "said my hat was beanie (it was fedora)"): A beanie? Detective, this fedora has more class than your entire memory.
|
| 120 |
+
|
| 121 |
+
Line:"""
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@_gpu
|
| 125 |
+
def _generate_taunt(outcome: str, wrong: str, missed: str, right: str) -> str:
|
| 126 |
+
model, tok = _load(TAUNT_MODEL_ID)
|
| 127 |
+
prompt = TAUNT_PROMPT.format(outcome=outcome, wrong=wrong, missed=missed, right=right)
|
| 128 |
+
messages = [{"role": "user", "content": prompt}]
|
| 129 |
+
text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
|
| 130 |
+
enc = tok(text, return_tensors="pt").to(model.device)
|
| 131 |
+
out = model.generate(**enc, max_new_tokens=60, do_sample=True, temperature=0.8,
|
| 132 |
+
top_p=0.9, pad_token_id=tok.eos_token_id)
|
| 133 |
+
return tok.decode(out[0][enc["input_ids"].shape[1]:], skip_special_tokens=True)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def culprit_taunt(report_rows: list, correct: bool) -> str | None:
|
| 137 |
+
"""Personalized verdict line from the witness's actual mistakes. None on any
|
| 138 |
+
failure or low-quality output — callers fall back to the canned quote."""
|
| 139 |
+
wrong = [f"said my {label.lower()} was {said} (it was {truth})"
|
| 140 |
+
for label, said, truth, v in report_rows if v == "miss"][:3]
|
| 141 |
+
missed = [label.lower() for label, _s, _t, v in report_rows if v == "silent"][:3]
|
| 142 |
+
right = [label.lower() for label, _s, _t, v in report_rows if v == "hit"][:2]
|
| 143 |
+
try:
|
| 144 |
+
raw = _generate_taunt(
|
| 145 |
+
"caught red-handed" if correct else "wrongly let go — they arrested someone else",
|
| 146 |
+
"; ".join(wrong) or "none",
|
| 147 |
+
", ".join(missed) or "nothing",
|
| 148 |
+
", ".join(right) or "nothing",
|
| 149 |
+
).strip().strip('"').split("\n")[0].strip()
|
| 150 |
+
except Exception:
|
| 151 |
+
return None
|
| 152 |
+
# quality gate: reject JSON leakage (slot-filling fine-tune habit) and degenerate output
|
| 153 |
+
if not raw or raw.startswith("{") or len(raw) < 15 or len(raw) > 220:
|
| 154 |
+
return None
|
| 155 |
+
return raw
|
| 156 |
+
|
| 157 |
+
|
| 158 |
def parse_testimony_model(testimony: str) -> dict[str, str | None]:
|
| 159 |
"""Model first, Tier A as per-slot backstop. Validated against VOCAB."""
|
| 160 |
base = _tier_a(testimony)
|
game/voice.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Live verdict voice: VoxCPM2 clones a designed anchor and speaks the 1B's line.
|
| 2 |
+
|
| 3 |
+
Anchor wavs (assets/anchor_*.wav, built on Modal) give each suspect a stable,
|
| 4 |
+
face-plausible voice; the case seed picks one deterministically. Every failure
|
| 5 |
+
path returns None — callers degrade to the pre-rendered bank, then to text.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import threading
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
ASSETS = Path(__file__).resolve().parent.parent / "assets"
|
| 13 |
+
|
| 14 |
+
# transcript of every anchor recording — cloning requires the exact prompt text
|
| 15 |
+
ANCHOR_TEXTS = {
|
| 16 |
+
"gravel": "Deep, gravelly male voice, slow and self-satisfied. Okay, okay. It was me. Take me in.",
|
| 17 |
+
"sharp": "Sharp, fast female voice, mocking and theatrical. Okay, okay. It was me. Take me in.",
|
| 18 |
+
"nasal": "Thin, nasal male voice, whiny and indignant. Okay, okay. It was me. Take me in.",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
import spaces
|
| 23 |
+
_gpu = spaces.GPU(duration=40)
|
| 24 |
+
except Exception:
|
| 25 |
+
def _gpu(fn):
|
| 26 |
+
return fn
|
| 27 |
+
|
| 28 |
+
_lock = threading.Lock()
|
| 29 |
+
_tts = None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _available_anchors() -> list[str]:
|
| 33 |
+
return sorted(n for n in ANCHOR_TEXTS if (ASSETS / f"anchor_{n}.wav").exists())
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def voice_enabled() -> bool:
|
| 37 |
+
import os
|
| 38 |
+
if not _available_anchors():
|
| 39 |
+
return False
|
| 40 |
+
if os.environ.get("EYEWITNESS_FORCE_VOICE") == "1":
|
| 41 |
+
return True
|
| 42 |
+
if os.environ.get("SPACES_ZERO_GPU"):
|
| 43 |
+
try:
|
| 44 |
+
import spaces # noqa: F401
|
| 45 |
+
return True
|
| 46 |
+
except Exception:
|
| 47 |
+
return False
|
| 48 |
+
try:
|
| 49 |
+
import torch
|
| 50 |
+
return torch.cuda.is_available()
|
| 51 |
+
except Exception:
|
| 52 |
+
return False
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _load():
|
| 56 |
+
global _tts
|
| 57 |
+
if _tts is None:
|
| 58 |
+
with _lock:
|
| 59 |
+
if _tts is None:
|
| 60 |
+
from voxcpm import VoxCPM
|
| 61 |
+
_tts = VoxCPM.from_pretrained("openbmb/VoxCPM2")
|
| 62 |
+
return _tts
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def anchor_for_seed(seed: int) -> str:
|
| 66 |
+
names = _available_anchors()
|
| 67 |
+
return names[seed % len(names)]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@_gpu
|
| 71 |
+
def _render(line: str, anchor: str):
|
| 72 |
+
tts = _load()
|
| 73 |
+
wav = tts.generate(
|
| 74 |
+
text=line,
|
| 75 |
+
prompt_wav_path=str(ASSETS / f"anchor_{anchor}.wav"),
|
| 76 |
+
prompt_text=ANCHOR_TEXTS[anchor],
|
| 77 |
+
)
|
| 78 |
+
return tts.tts_model.sample_rate, wav
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def speak(line: str, seed: int) -> tuple[int, "np.ndarray"] | None:
|
| 82 |
+
"""(sample_rate, int16 samples) for gr.Audio, or None on any failure."""
|
| 83 |
+
import numpy as np
|
| 84 |
+
|
| 85 |
+
if not voice_enabled() or not line:
|
| 86 |
+
return None
|
| 87 |
+
try:
|
| 88 |
+
sr, wav = _render(line, anchor_for_seed(seed))
|
| 89 |
+
wav = np.asarray(wav)
|
| 90 |
+
if wav.size < sr // 4 or wav.size > sr * 20: # degenerate render guard
|
| 91 |
+
return None
|
| 92 |
+
if wav.dtype != np.int16:
|
| 93 |
+
wav = (np.clip(wav, -1.0, 1.0) * 32767).astype(np.int16)
|
| 94 |
+
return int(sr), wav
|
| 95 |
+
except Exception:
|
| 96 |
+
return None
|
modal_factory.py
CHANGED
|
@@ -158,3 +158,42 @@ def probe_voice() -> dict:
|
|
| 158 |
@app.local_entrypoint()
|
| 159 |
def probe():
|
| 160 |
print(probe_voice.remote())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
@app.local_entrypoint()
|
| 159 |
def probe():
|
| 160 |
print(probe_voice.remote())
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
VOICE_ANCHORS = {
|
| 164 |
+
# designed once, cloned at runtime so each suspect keeps a consistent voice
|
| 165 |
+
"gravel": "Deep, gravelly male voice, slow and self-satisfied. Okay, okay. It was me. Take me in.",
|
| 166 |
+
"sharp": "Sharp, fast female voice, mocking and theatrical. Okay, okay. It was me. Take me in.",
|
| 167 |
+
"nasal": "Thin, nasal male voice, whiny and indignant. Okay, okay. It was me. Take me in.",
|
| 168 |
+
}
|
| 169 |
+
ANCHOR_TEXT = "Okay, okay. It was me. Take me in."
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@app.function(image=voice_image, gpu="A10G", timeout=1200)
|
| 173 |
+
def build_voice_anchors() -> dict[str, bytes]:
|
| 174 |
+
"""Three reference voices for runtime cloning (voice/face match)."""
|
| 175 |
+
import io
|
| 176 |
+
|
| 177 |
+
import soundfile as sf
|
| 178 |
+
from voxcpm import VoxCPM
|
| 179 |
+
|
| 180 |
+
tts = VoxCPM.from_pretrained("openbmb/VoxCPM2")
|
| 181 |
+
sr = tts.tts_model.sample_rate
|
| 182 |
+
out: dict[str, bytes] = {}
|
| 183 |
+
for name, styled_text in VOICE_ANCHORS.items():
|
| 184 |
+
# best-of-3: keep the longest render that stays in budget (style adherence varies)
|
| 185 |
+
takes = [tts.generate(text=styled_text) for _ in range(3)]
|
| 186 |
+
takes = [t for t in takes if len(t) / sr < 9.0] or takes
|
| 187 |
+
wav = max(takes, key=len)
|
| 188 |
+
buf = io.BytesIO()
|
| 189 |
+
sf.write(buf, wav, sr, format="WAV")
|
| 190 |
+
out[name] = buf.getvalue()
|
| 191 |
+
return out
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@app.local_entrypoint()
|
| 195 |
+
def anchors_only():
|
| 196 |
+
for name, blob in build_voice_anchors.remote().items():
|
| 197 |
+
with open(f"assets/anchor_{name}.wav", "wb") as f:
|
| 198 |
+
f.write(blob)
|
| 199 |
+
print("anchors complete -> assets/")
|
requirements.txt
CHANGED
|
@@ -4,3 +4,5 @@ transformers
|
|
| 4 |
accelerate
|
| 5 |
torch
|
| 6 |
spaces
|
|
|
|
|
|
|
|
|
| 4 |
accelerate
|
| 5 |
torch
|
| 6 |
spaces
|
| 7 |
+
voxcpm
|
| 8 |
+
numpy
|