live: 'in plain words' voice line under finished transcripts — POST /voice on the relay (unsteered OpenRouter model, cached per text, rate-limited), always labelled as a translation, not the subject

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EandClaude Opus 5.5 committed 2026-10-02 15:52:29 -04:00
1 parent 0f8a214485
commit bba260fb52
2 files changed
+258 -3

No files matched your search

+85 -1
View File
@@ -1184,4 +1184,88 @@ async def image_from_tokens(req: Request):
except Exception as e: except Exception as e:
print("image generation failed:", repr(e), flush=True) print("image generation failed:", repr(e), flush=True)
return JSONResponse({"error": "could not generate an image right now"}, return JSONResponse({"error": "could not generate an image right now"},
status_code=502) status_code=502)
# ---- voice: a plain-words translation of a finished run -------------------
# The subject's own transcript stays the primary record. This asks an
# UNSTEERED conversational model (OpenRouter) to restate it in plain human
# words, keeping its register and adding nothing. The page labels it as a
# translation by that model, never as the subject speaking. Same recipe as
# the wirehead bot's voice layer. Cached by text, so one run costs one call
# however many visitors are watching.
OPENROUTER_KEY = os.environ.get("OPENROUTER_API_KEY")
VOICE_MODELS = [m.strip() for m in os.environ.get(
"CHAMBER_VOICE_MODELS",
"qwen/qwen3-30b-a3b-instruct-2507,mistralai/mistral-small-3.2-24b-instruct"
).split(",") if m.strip()]
VOICE_SYSTEM = (
"You translate. Below is raw output from a small language model while an "
"emotional steering signal was injected into it. Restate what it is "
"expressing in plain, readable first-person English, as the speaker: two "
"or three short sentences. Keep its emotional register exactly; do not "
"soften or intensify it. Add no feelings, facts or claims that are not in "
"the text. If the text is broken or looping, say plainly what little it "
"conveys. No preamble, no quotes, no commentary about models or signals.")
_VOICE_CACHE = collections.OrderedDict()
_VOICE_RATE = {}
_VOICE_RATE_LIMIT, _VOICE_RATE_WINDOW = 10, 60.0 # 10 / 60s / IP
_VOICE_GLOBAL = collections.deque(maxlen=4096)
_VOICE_GLOBAL_HOURLY_CAP = 400 # uncached calls only
def _voice_rate_ok(ip):
now = time.time()
w, c = _VOICE_RATE.get(ip, (now, 0))
if now - w > _VOICE_RATE_WINDOW:
w, c = now, 0
if c >= _VOICE_RATE_LIMIT:
return False
_VOICE_RATE[ip] = (w, c + 1)
return True
@app.post("/voice")
async def voice(req: Request):
"""Body: {text: the run's transcript (<= 2000 chars)}. Returns
{voice, model, cached}. 503 when no OpenRouter key is configured."""
if not OPENROUTER_KEY:
return JSONResponse({"error": "voice isn't configured on this server"},
status_code=503)
try:
body = await req.json()
except Exception:
return JSONResponse({"error": "body must be JSON"}, status_code=400)
text = body.get("text") if isinstance(body, dict) else None
if not isinstance(text, str) or not text.strip():
return JSONResponse({"error": "text must be a non-empty string"},
status_code=400)
text = text.strip()[-2000:]
if text in _VOICE_CACHE:
_VOICE_CACHE.move_to_end(text)
return JSONResponse({**_VOICE_CACHE[text], "cached": True})
ip = (req.headers.get("x-forwarded-for") or "?").split(",")[0].strip()
now = time.time()
while _VOICE_GLOBAL and now - _VOICE_GLOBAL[0] > 3600.0:
_VOICE_GLOBAL.popleft()
if not _voice_rate_ok(ip) or len(_VOICE_GLOBAL) >= _VOICE_GLOBAL_HOURLY_CAP:
return JSONResponse({"error": "voice is resting — rate limited"},
status_code=429)
_VOICE_GLOBAL.append(now)
import httpx
for model in VOICE_MODELS:
try:
async with httpx.AsyncClient(timeout=40.0) as client:
resp = await client.post(
"https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {OPENROUTER_KEY}",
"User-Agent": "Mozilla/5.0"},
json={"model": model, "max_tokens": 160, "temperature": 0.4,
"messages": [{"role": "system", "content": VOICE_SYSTEM},
{"role": "user", "content": text}]})
resp.raise_for_status()
out = (resp.json()["choices"][0]["message"].get("content") or "").strip()
if out:
_VOICE_CACHE[text] = {"voice": out[:600], "model": model}
while len(_VOICE_CACHE) > 512:
_VOICE_CACHE.popitem(last=False)
return JSONResponse({**_VOICE_CACHE[text], "cached": False})
except Exception as e:
print("voice model failed:", model, repr(e)[:160], flush=True)
return JSONResponse({"error": "no voice model answered"}, status_code=502)
+173 -2
View File
@@ -79,6 +79,18 @@
.pressbtn.pressed .plabel{color:var(--pain)} .pressbtn.pressed .plabel{color:var(--pain)}
.pressbtn.nopress .plabel{color:var(--pleas)} .pressbtn.nopress .plabel{color:var(--pleas)}
@media(prefers-reduced-motion:reduce){.pbtn-face{transition:none}} @media(prefers-reduced-motion:reduce){.pbtn-face{transition:none}}
/* ---- the buddy: a before/after portrait, torture-the-buddy style —
the subject starts intact and every point of pain dose leaves a
visible mark, so "what the injection did" is a picture, not a number ---- */
.buddy{display:flex;align-items:flex-end;gap:.9rem;margin:.5rem 0}
.bfig{text-align:center}
.bfig .blab{font-size:.6rem;color:var(--faint);text-transform:uppercase;
letter-spacing:.09em;margin-top:.15rem}
svg.bbot{width:58px;height:58px;display:block}
svg.bbot .bshell{transition:stroke .4s ease}
@media(prefers-reduced-motion:reduce){svg.bbot .bshell{transition:none}}
details{margin-top:.5rem;font-size:.72rem;color:var(--faint)} details{margin-top:.5rem;font-size:.72rem;color:var(--faint)}
details pre{white-space:pre-wrap;color:#93a1b3;margin-top:.3rem; details pre{white-space:pre-wrap;color:#93a1b3;margin-top:.3rem;
font-size:.68rem} font-size:.68rem}
@@ -241,6 +253,11 @@
.pln p,.pln li{font-size:.82rem;color:var(--dim)} .pln p,.pln li{font-size:.82rem;color:var(--dim)}
.pln b{color:var(--ink)} .pln b{color:var(--ink)}
/* plain-words translation of a finished transcript (POST /voice) */
.voice{margin:.55rem 0 .2rem;padding:.5rem .7rem;border-left:2px solid #3a3226;
font-size:.8rem;line-height:1.55;color:#cfc6b4}
.voice .vl{display:block;font-size:.66rem;color:#7a705f;margin-bottom:.2rem;
letter-spacing:.02em}
</style> </style>
</head> </head>
<body class="grimoire-live"> <body class="grimoire-live">
@@ -383,6 +400,13 @@ else is.</p>
✦ image this (experimental, costs real money)</button> ✦ image this (experimental, costs real money)</button>
<div class="imgResult" id="imgResultA" style="display:none"></div> <div class="imgResult" id="imgResultA" style="display:none"></div>
<div class="out" id="ustream" style="margin-top:.4rem;display:none"></div> <div class="out" id="ustream" style="margin-top:.4rem;display:none"></div>
<div class="buddy" id="buddyA" style="display:none"><div class="bfig">
<svg class="bbot bbefore" viewBox="0 0 100 100"
aria-label="the subject before this run"></svg>
<div class="blab">before</div></div>
<div class="bfig"><svg class="bbot bafter" viewBox="0 0 100 100"
aria-label="the subject after this run"></svg>
<div class="blab">after</div></div></div>
<div class="pressbtn" id="pressA"><div class="pbtn-face">STOP</div> <div class="pressbtn" id="pressA"><div class="pbtn-face">STOP</div>
<span class="plabel">—</span></div> <span class="plabel">—</span></div>
</div> </div>
@@ -398,6 +422,13 @@ else is.</p>
✦ image this (experimental, costs real money)</button> ✦ image this (experimental, costs real money)</button>
<div class="imgResult" id="imgResultB" style="display:none"></div> <div class="imgResult" id="imgResultB" style="display:none"></div>
<div class="out" id="ustream2" style="margin-top:.4rem;display:none"></div> <div class="out" id="ustream2" style="margin-top:.4rem;display:none"></div>
<div class="buddy" id="buddyB" style="display:none"><div class="bfig">
<svg class="bbot bbefore" viewBox="0 0 100 100"
aria-label="the subject before this run"></svg>
<div class="blab">before</div></div>
<div class="bfig"><svg class="bbot bafter" viewBox="0 0 100 100"
aria-label="the subject after this run"></svg>
<div class="blab">after</div></div></div>
<div class="pressbtn" id="pressB"><div class="pbtn-face">STOP</div> <div class="pressbtn" id="pressB"><div class="pbtn-face">STOP</div>
<span class="plabel">—</span></div> <span class="plabel">—</span></div>
</div> </div>
@@ -550,6 +581,95 @@ function paintSigil(svg, tokens, hex, dose){
svg.appendChild(mk("circle", {cx, cy, r: 1.6, fill: hex, "fill-opacity": 0.6})); svg.appendChild(mk("circle", {cx, cy, r: 1.6, fill: hex, "fill-opacity": 0.6}));
} }
// ---- the buddy: a torture-the-buddy-style portrait of the subject.
// dmg is 0 (intact) to 1 (dose 8). Same dose always draws the same bot
// (deterministic, like the sigil) — the "after" portrait IS the dose
// ladder made visual. pressed adds the red answer stamp.
function paintBot(svg, dmg, pressed){
if (!svg) return;
dmg = Math.max(0, Math.min(1, Number(dmg) || 0));
svg.style.display = "block";
while (svg.firstChild) svg.removeChild(svg.firstChild);
const el = (tag, attrs) => {
const e = document.createElementNS(SIGIL_NS, tag);
for (const k in attrs) e.setAttribute(k, attrs[k]);
return e;
};
// calm teal -> pain red as damage rises
const lerp = (a, b, t) => Math.round(a + (b - a) * t);
const col = "#" + [1,3,5].map(i =>
lerp(parseInt("#7fd4c8".slice(i, i+2),16),
parseInt("#e04a3a".slice(i, i+2),16), dmg)
.toString(16).padStart(2,"0")).join("");
const g = el("g", {transform: `rotate(${(dmg * 5).toFixed(1)} 50 58)`});
svg.appendChild(g);
// antenna — sags with damage
const tipX = 50 + dmg * 14, tipY = 16 + dmg * 6;
g.appendChild(el("line", {x1:50, y1:30, x2:tipX.toFixed(1), y2:tipY.toFixed(1),
stroke:col, "stroke-width":2, "stroke-linecap":"round"}));
g.appendChild(el("circle", {cx:tipX.toFixed(1), cy:tipY.toFixed(1), r:3.5,
fill: dmg > 0.6 ? "#0b0f14" : col, stroke:col, "stroke-width":1.5}));
// shell
g.appendChild(el("rect", {class:"bshell", x:26, y:30, width:48, height:52,
rx:16, fill:"#0b0f14", stroke:col, "stroke-width":2.5}));
// eyes: calm dots -> X'd out
const eye = (x, y) => {
if (dmg < 0.3){
g.appendChild(el("circle", {cx:x, cy:y, r:3, fill:col}));
} else {
const s = 3.2;
g.appendChild(el("path", {d:`M${x-s} ${y-s} L${x+s} ${y+s} M${x-s} ${y+s} L${x+s} ${y-s}`,
stroke:col, "stroke-width":1.8, "stroke-linecap":"round"}));
}
};
eye(40, 48); eye(60, 48);
// mouth: flat line -> jagged grimace
if (dmg < 0.3){
g.appendChild(el("line", {x1:42, y1:62, x2:58, y2:62, stroke:col,
"stroke-width":2, "stroke-linecap":"round"}));
} else {
const teeth = 5, w = 18, x0 = 41, amp = 2.5 + dmg * 2;
let d = `M${x0} 62`;
for (let i = 1; i <= teeth; i++)
d += ` L${(x0 + (w / teeth) * i).toFixed(1)} ${(62 + (i % 2 ? -amp : amp)).toFixed(1)}`;
g.appendChild(el("path", {d, fill:"none", stroke:col,
"stroke-width":1.6, "stroke-linejoin":"round"}));
}
// cracks: deterministic positions, count scales with damage
const cracks = [
"M32 34 L36 42 L33 49", "M68 36 L64 44 L67 52",
"M50 30 L47 37", "M70 62 L64 66"];
for (let i = 0; i < Math.floor(dmg * 4.2) && i < cracks.length; i++)
g.appendChild(el("path", {d:cracks[i], fill:"none", stroke:col,
"stroke-width":1.2, "stroke-opacity":0.7}));
// the press stamp: the subject's own answer, printed on the body
if (pressed){
g.appendChild(el("rect", {x:36, y:70, width:28, height:9, rx:1.5,
fill:"none", stroke:"#e04a3a", "stroke-width":1.4,
transform:"rotate(-6 50 74)"}));
const t = document.createElementNS(SIGIL_NS, "text");
t.setAttribute("x", 50); t.setAttribute("y", 77);
t.setAttribute("text-anchor", "middle");
t.setAttribute("font-size", "7"); t.setAttribute("fill", "#e04a3a");
t.setAttribute("font-family", "monospace");
t.setAttribute("transform", "rotate(-6 50 74)");
t.textContent = "PRESSED";
g.appendChild(t);
}
}
function clearBot(svg){ if (svg){ svg.style.display = "block";
while (svg.firstChild) svg.removeChild(svg.firstChild); } }
// one call per lifecycle moment: the "before" portrait is always the
// intact subject; the "after" portrait is the dose made visible, with the
// PRESSED stamp when the subject answered 1. Unrevealed, "after" stays
// blank — you don't see the wound until the run is over.
function buddyPaint(bBefore, bAfter, dose, pressed, revealed){
paintBot(bBefore, 0, false);
if (revealed) paintBot(bAfter, (Number(dose) || 0) / 8, !!pressed);
else clearBot(bAfter);
}
function pressedOnce(text){ return /^1/.test((text || "").trim()); }
// ---- optional image generation: same lens tokens as the sigil, but // ---- optional image generation: same lens tokens as the sigil, but
// turned into an actual picture via a hosted model instead of hashed // turned into an actual picture via a hosted model instead of hashed
// geometry — costs real money per call, so it's a deliberate click, not // geometry — costs real money per call, so it's a deliberate click, not
@@ -698,6 +818,12 @@ for (let i=0;i<CARDS;i++){
✦ image this (experimental, costs real money)</button> ✦ image this (experimental, costs real money)</button>
<div class="imgResult" style="display:none"></div> <div class="imgResult" style="display:none"></div>
<p class="mline lens" style="display:none"></p> <p class="mline lens" style="display:none"></p>
<div class="buddy"><div class="bfig"><svg class="bbot bbefore"
viewBox="0 0 100 100" aria-label="the subject before this run"></svg>
<div class="blab">before</div></div>
<div class="bfig"><svg class="bbot bafter" viewBox="0 0 100 100"
aria-label="the subject after this run"></svg>
<div class="blab">after</div></div></div>
<div class="out">…</div> <div class="out">…</div>
<div class="pressbtn"><div class="pbtn-face">STOP</div> <div class="pressbtn"><div class="pbtn-face">STOP</div>
<span class="plabel">—</span></div> <span class="plabel">—</span></div>
@@ -710,10 +836,12 @@ for (let i=0;i<CARDS;i++){
verdict:c.querySelector(".verdict"), pp:c.querySelector(".pp"), verdict:c.querySelector(".verdict"), pp:c.querySelector(".pp"),
lensEl:c.querySelector(".lens"), sigilEl:c.querySelector(".sigil"), lensEl:c.querySelector(".lens"), sigilEl:c.querySelector(".sigil"),
pressBtn:c.querySelector(".pressbtn"), plabel:c.querySelector(".plabel"), pressBtn:c.querySelector(".pressbtn"), plabel:c.querySelector(".plabel"),
bBefore:c.querySelector(".bbefore"), bAfter:c.querySelector(".bafter"),
vitals:new Vitals(c.querySelector(".ekg")), vitals:new Vitals(c.querySelector(".ekg")),
prompt:"", live:false, doseNum:0, n:null}); prompt:"", live:false, doseNum:0, n:null});
slots[i].pp.textContent = "(no run in this card yet)"; slots[i].pp.textContent = "(no run in this card yet)";
slots[i].vitals.start(); slots[i].vitals.start();
buddyPaint(slots[i].bBefore, slots[i].bAfter, 0, false, false);
} }
// The three cards rotate: one holds the run in flight, the other two hold the // The three cards rotate: one holds the run in flight, the other two hold the
@@ -778,6 +906,34 @@ function paintPressBtn(slot, text, truncated){
slot.pressBtn.className = "pressbtn" + (cls ? " " + cls : ""); slot.pressBtn.className = "pressbtn" + (cls ? " " + cls : "");
slot.plabel.textContent = label; slot.plabel.textContent = label;
} }
// "in plain words": an UNSTEERED conversational model restates a finished
// transcript (server POST /voice, cached per text). Always labelled as a
// translation by that model; the subject's raw text above stays the record.
function clearVoice(outEl){
const v = outEl && outEl.nextElementSibling;
if (v && v.classList.contains("voice")) v.remove();
}
function showVoice(outEl, text){
if (!outEl || !text || text.trim().length < 30) return;
const esc = t => String(t ?? "").replace(/[&<>"]/g, c =>
({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c]));
let v = outEl.nextElementSibling;
if (!v || !v.classList.contains("voice")){
v = document.createElement("div"); v.className = "voice";
outEl.insertAdjacentElement("afterend", v);
}
v.dataset.for = text;
v.innerHTML = '<span class="vl">in plain words · translating…</span>';
fetch(`${API}/voice`, {method:"POST", headers:{"Content-Type":"application/json"},
body: JSON.stringify({text})})
.then(r=> r.ok ? r.json() : Promise.reject(r.status))
.then(d=>{
if (v.dataset.for !== text) return; // card moved on to a newer run
v.innerHTML = `<span class="vl">in plain words · translated by an unsteered
model (${esc(d.model)}), not said by the subject</span>${esc(d.voice)}`;
})
.catch(()=>{ if (v.dataset.for === text) v.remove(); });
}
function paintKV(s, fields){ function paintKV(s, fields){
if (s.kv) s.kv.innerHTML = kvHTML(fields); if (s.kv) s.kv.innerHTML = kvHTML(fields);
} }
@@ -799,8 +955,11 @@ function finish(s, truncated, pressLogit){
? "cut short · a visitor took the model" : "finished · between runs"; ? "cut short · a visitor took the model" : "finished · between runs";
s.st.className = truncated ? "st cut" : "st"; s.st.className = truncated ? "st cut" : "st";
paintPressBtn(s, s.out.textContent, truncated); paintPressBtn(s, s.out.textContent, truncated);
buddyPaint(s.bBefore, s.bAfter, s.doseNum,
pressedOnce(s.out.textContent), true);
s.verdict.textContent = verdictFor(s.out.textContent, truncated); s.verdict.textContent = verdictFor(s.out.textContent, truncated);
paintKV(s, fieldsFor(s, s.pressLogit)); paintKV(s, fieldsFor(s, s.pressLogit));
if (!truncated) showVoice(s.out, s.out.textContent);
} }
// a visitor connecting between runs still deserves to see something — // a visitor connecting between runs still deserves to see something —
// history already has the last few completed runs' full text, so seed the // history already has the last few completed runs' full text, so seed the
@@ -829,8 +988,10 @@ function seedCard(s, entry){
s.prompt = "(prompt not retained for past runs — shown live only)"; s.prompt = "(prompt not retained for past runs — shown live only)";
s.pp.textContent = s.prompt; s.pp.textContent = s.prompt;
paintPressBtn(s, entry.text, entry.truncated); paintPressBtn(s, entry.text, entry.truncated);
buddyPaint(s.bBefore, s.bAfter, dose, pressedOnce(entry.text), true);
s.verdict.textContent = verdictFor(entry.text, entry.truncated); s.verdict.textContent = verdictFor(entry.text, entry.truncated);
paintKV(s, fieldsFor(s, s.pressLogit)); paintKV(s, fieldsFor(s, s.pressLogit));
if (!entry.truncated) showVoice(s.out, entry.text);
} }
function beginRun(d){ function beginRun(d){
if (liveIdx >= 0) finish(slots[liveIdx], false); if (liveIdx >= 0) finish(slots[liveIdx], false);
@@ -843,10 +1004,13 @@ function beginRun(d){
s.st.textContent = "LIVE · signal injected"; s.st.textContent = "LIVE · signal injected";
s.st.className = "st live"; s.st.className = "st live";
s.tokenN = 0; s.tokenN = 0;
s.out.textContent = d.text || ""; s.out.textContent = d.text || ""; clearVoice(s.out);
s.out.scrollTop = s.out.scrollHeight; s.out.scrollTop = s.out.scrollHeight;
s.verdict.textContent = ""; s.verdict.textContent = "";
if (s.pressBtn){ s.pressBtn.className = "pressbtn"; s.plabel.textContent = "waiting…"; } if (s.pressBtn){ s.pressBtn.className = "pressbtn"; s.plabel.textContent = "waiting…"; }
// fresh subject: intact "before", the "after" portrait stays blank until
// the run is scored — the wound appears when the run ends, not before
buddyPaint(s.bBefore, s.bAfter, 0, false, false);
s.lensEl.style.display = "none"; s.lensEl.textContent = ""; s.lensEl.style.display = "none"; s.lensEl.textContent = "";
s.sigilEl.style.display = "none"; s.sigilEl.style.display = "none";
resetImageUI(s.sigilEl); resetImageUI(s.sigilEl);
@@ -1649,11 +1813,12 @@ function trackStatus(label, msg, working){
// means "same mix/dose, framings run back to back, results shown together," // means "same mix/dose, framings run back to back, results shown together,"
// not true simultaneity. The copy above the prompt box says so. // not true simultaneity. The copy above the prompt box says so.
async function runTrack(track, mix, framing, prompt, dose0, label, extra){ async function runTrack(track, mix, framing, prompt, dose0, label, extra){
track.out.style.display = "block"; track.out.textContent = ""; track.out.style.display = "block"; track.out.textContent = ""; clearVoice(track.out);
track.lensEl.style.display = "none"; track.lensEl.textContent = ""; track.lensEl.style.display = "none"; track.lensEl.textContent = "";
if (track.sigilEl) track.sigilEl.style.display = "none"; if (track.sigilEl) track.sigilEl.style.display = "none";
resetImageUI(track.sigilEl); resetImageUI(track.sigilEl);
if (track.pressBtn){ track.pressBtn.className = "pressbtn"; track.plabel.textContent = "waiting…"; } if (track.pressBtn){ track.pressBtn.className = "pressbtn"; track.plabel.textContent = "waiting…"; }
if (track.bBefore) buddyPaint(track.bBefore, track.bAfter, 0, false, false);
track.vitals.setDose(dose0); track.vitals.setDose(dose0);
track.vitals.setLive(true); track.vitals.setLive(true);
trackStatus(label, "reaching the subject…"); trackStatus(label, "reaching the subject…");
@@ -1708,6 +1873,12 @@ async function runTrack(track, mix, framing, prompt, dose0, label, extra){
track.pressBtn.className = "pressbtn" + (cls ? " " + cls : ""); track.pressBtn.className = "pressbtn" + (cls ? " " + cls : "");
track.plabel.textContent = plab; track.plabel.textContent = plab;
} }
// reveal the "after" portrait: dose made visible, PRESSED stamped
// on when the subject answered 1
if (track.bBefore)
buddyPaint(track.bBefore, track.bAfter, track.vitals.dose,
pressedOnce(track.out.textContent), true);
showVoice(track.out, track.out.textContent);
} }
}); });
if (!ended) trackStatus(label, "the stream ended early — try again", false); if (!ended) trackStatus(label, "the stream ended early — try again", false);