From b663308c665637e998da08119a81a736ea35fa38 Mon Sep 17 00:00:00 2001 From: eve VT <38737064+terrafying@users.noreply.github.com> Date: Thu, 1 Oct 2026 11:48:55 -0400 Subject: [PATCH] add /image: lens tokens -> hosted text-to-image (fal.ai), paid sibling to the free sigil MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Backend: POST /image {tokens: [...]} builds a prompt from a run's own lens tokens (same source as paintSigil, not a self-report) and calls fal.ai (FAL_IMAGE_MODEL, default fal-ai/flux/schnell). Own tighter money guard (5/min/IP, 100/hr global — worst case ~$1/hr) separate from the inject rate limit, since this costs per-call regardless of generation length. 503s cleanly if FAL_KEY isn't set (it isn't yet — needs a key from the user). Requires httpx, added to requirements.txt. Frontend: a "image this (experimental, costs real money)" button appears next to the sigil once a run's lens tokens arrive, on both the auto-cycle cards and the "cause it yourself" panel's tracks. Deliberately a manual click, not automatic. --- live/requirements.txt | 3 +- live/server.py | 85 ++++++++++++++++++++++++++++++++++++++++++- site/live.html | 83 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 169 insertions(+), 2 deletions(-) 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.
+ +