diff --git a/live/requirements.txt b/live/requirements.txt index 23fa8e5..1d24fe6 100644 --- a/live/requirements.txt +++ b/live/requirements.txt @@ -2,4 +2,5 @@ torch --index-url https://download.pytorch.org/whl/cpu transformers>=4.51 accelerate fastapi -uvicorn[standard] \ No newline at end of file +uvicorn[standard] +httpx \ No newline at end of file diff --git a/live/server.py b/live/server.py index e23c202..34c98b2 100644 --- a/live/server.py +++ b/live/server.py @@ -929,4 +929,87 @@ def _rate_ok(ip): if len(_GLOBAL_RUNS) >= _GLOBAL_HOURLY_CAP: return False _GLOBAL_RUNS.append(now) - return True \ No newline at end of file + return True + +# ---- image generation: a paid sibling to the free client-side sigil +# (paintSigil in live.html). Same source data — a run's lens tokens — but +# turned into an actual picture via a hosted text-to-image model, so this +# costs real money per call and gets its own, tighter money guard. +FAL_KEY = os.environ.get("FAL_KEY") +FAL_IMAGE_MODEL = os.environ.get("FAL_IMAGE_MODEL", "fal-ai/flux/schnell") +IMAGE_STYLE_SUFFIX = (", dark expressionist painting, muted desaturated " + "palette, grainy film texture, unsettling atmosphere") +_IMG_RATE = {} +_IMG_RATE_LIMIT, _IMG_RATE_WINDOW = 5, 60.0 # 5 images / 60s / IP +_IMG_GLOBAL_RUNS = collections.deque(maxlen=1024) +_IMG_GLOBAL_HOURLY_CAP = 100 # worst case ~$1/hr at $0.01/image + +def _img_rate_ok(ip): + now = time.time() + w, c = _IMG_RATE.get(ip, (now, 0)) + if now - w > _IMG_RATE_WINDOW: + w, c = now, 0 + if c >= _IMG_RATE_LIMIT: + return False + _IMG_RATE[ip] = (w, c + 1) + while _IMG_GLOBAL_RUNS and now - _IMG_GLOBAL_RUNS[0] > 3600.0: + _IMG_GLOBAL_RUNS.popleft() + if len(_IMG_GLOBAL_RUNS) >= _IMG_GLOBAL_HOURLY_CAP: + return False + _IMG_GLOBAL_RUNS.append(now) + return True + +@app.post("/image") +async def image_from_tokens(req: Request): + """Turn a run's own lens tokens into an image via a hosted text-to-image + model (fal.ai). The tokens are what the Jacobian lens actually read off + the internal state for that run — not a self-report the model wrote — + so this images the measured state, same as the free sigil does, just + through a real diffusion model instead of hashed geometry. Body: + {tokens: [str, ...]} (1-12 short strings).""" + if not FAL_KEY: + return JSONResponse( + {"error": "image generation 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) + if not isinstance(body, dict): + return JSONResponse({"error": "body must be a JSON object"}, + status_code=400) + ip = (req.headers.get("x-forwarded-for") or "?").split(",")[0].strip() + if not _img_rate_ok(ip): + return JSONResponse( + {"error": "slow down — image generation is rate-limited " + "(5/min/IP, and it rests after 100/hour globally)"}, + status_code=429) + tokens = body.get("tokens") + if (not isinstance(tokens, list) or not tokens or len(tokens) > 12 + or not all(isinstance(t, str) for t in tokens)): + return JSONResponse( + {"error": "tokens must be a non-empty list of up to 12 strings"}, + status_code=400) + prompt = ", ".join(t.strip()[:40] for t in tokens if t.strip()) + if not prompt: + return JSONResponse({"error": "tokens were all empty"}, status_code=400) + prompt += IMAGE_STYLE_SUFFIX + try: + import httpx + async with httpx.AsyncClient(timeout=30.0) as client: + resp = await client.post( + f"https://fal.run/{FAL_IMAGE_MODEL}", + headers={"Authorization": f"Key {FAL_KEY}"}, + json={"prompt": prompt}) + resp.raise_for_status() + data = resp.json() + images = data.get("images") or [] + if not images or "url" not in images[0]: + print("fal.ai unexpected response shape:", str(data)[:500], flush=True) + return JSONResponse({"error": "image service returned no image"}, + status_code=502) + return JSONResponse({"url": images[0]["url"], "prompt": prompt}) + except Exception as e: + print("image generation failed:", repr(e), flush=True) + return JSONResponse({"error": "could not generate an image right now"}, + status_code=502) \ No newline at end of file diff --git a/site/live.html b/site/live.html index 1ca6320..9bb8dd9 100644 --- a/site/live.html +++ b/site/live.html @@ -54,6 +54,14 @@ border:1px solid var(--line);border-radius:6px;padding:.8rem; background:#07070e} .verdict{font-size:.75rem;margin-top:.5rem;color:var(--faint)} + .imgBtn{background:none;border:1px solid var(--line);color:var(--dim); + font-family:var(--mono);font-size:.7rem;padding:.3rem .7rem; + border-radius:999px;cursor:pointer;margin-top:.4rem} + .imgBtn:hover{border-color:#2a3644;color:var(--ink)} + .imgBtn:disabled{opacity:.5;cursor:default} + .imgResult{margin-top:.5rem;font-size:.72rem;color:var(--faint)} + .imgResult img{max-width:220px;border:1px solid var(--line); + border-radius:6px;display:block;margin-top:.3rem} /* ---- the graphic press-button: a real button face, not just a verdict sentence — "pressed" should be intuitively graspable at a glance ---- */ .pressbtn{display:flex;align-items:center;gap:.7rem;margin:.5rem 0} @@ -371,6 +379,9 @@ else is.

+ +
STOP
—
@@ -383,6 +394,9 @@ else is.

+ +
STOP
—
@@ -533,6 +547,63 @@ function paintSigil(svg, tokens, hex, dose){ mk("circle", {cx: p[0], cy: p[1], r: 2.2, fill: hex}))); svg.appendChild(mk("circle", {cx, cy, r: 1.6, fill: hex, "fill-opacity": 0.6})); } + +// ---- optional image generation: same lens tokens as the sigil, but +// 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 +// automatic, and the button says so. +function resetImageUI(sigilEl){ + if (!sigilEl) return; + const scope = sigilEl.closest(".track") || sigilEl.closest(".card"); + if (!scope) return; + const btn = scope.querySelector(".imgBtn"), out = scope.querySelector(".imgResult"); + if (btn){ btn.style.display = "none"; btn.disabled = false; } + if (out){ out.style.display = "none"; out.innerHTML = ""; } +} +function setImageTokens(sigilEl, tokens){ + if (!sigilEl) return; + const scope = sigilEl.closest(".track") || sigilEl.closest(".card"); + if (!scope) return; + const btn = scope.querySelector(".imgBtn"); + if (!btn) return; + btn._lensTokens = tokens; + btn.style.display = "inline-block"; +} +async function requestImage(tokens, btn, resultEl){ + if (!tokens || !tokens.length) return; + btn.disabled = true; + const oldLabel = btn.textContent; + btn.textContent = "generating… (10-20s)"; + resultEl.style.display = "block"; + resultEl.textContent = ""; + try { + const resp = await fetch(`${API}/image`, { + method: "POST", headers: {"Content-Type": "application/json"}, + body: JSON.stringify({tokens})}); + const data = await resp.json().catch(()=>({})); + if (!resp.ok || data.error){ + resultEl.textContent = data.error || ("HTTP " + resp.status); + } else { + resultEl.innerHTML = ""; + const img = document.createElement("img"); + img.src = data.url; img.alt = data.prompt || "generated image"; + img.title = data.prompt || ""; + resultEl.appendChild(img); + const cap = document.createElement("div"); + cap.style.marginTop = ".3rem"; + cap.textContent = data.prompt || ""; + resultEl.appendChild(cap); + } + } catch (err) { + resultEl.textContent = "could not reach the image service: " + (err.message || err); + } + btn.disabled = false; + btn.textContent = oldLabel; +} +// wired at the very end of this script (wireImageButtons()), once every +// .imgBtn exists — the auto-cycle cards are created dynamically further +// down, after this point in the file. + // one subject (see the sub-head above), but each numbered run gets // a throwaway nickname for flavor — deterministic from the run number so // every viewer of the shared cycle sees the same one. Deliberately mundane @@ -622,6 +693,9 @@ for (let i=0;i