Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

docs(rpc-lanes): record that the fleet wallet audit no longer reads an unreachable lane as a zero balance

nirholas669c8b279f77
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6fc753df9..85a58d39e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,16 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-08-11
- **A selfie with no visible face now tells you so, instead of "generation failed"**: Photo-to-avatar could not tell you the one thing that would fix your upload. When the engine found no face in a photo (a hooded figure, a back view, a landscape), it reported that rejection as an anonymous internal error, so the site fell back to a generic "Generation failed. Try a different prompt." You now get the real reason and can act on it: reword the prompt, or use a clear front-facing shot. Rejected uploads also stopped filing themselves as service outages in our error logs, so a genuine failure is visible now instead of buried among them. (`/create`) `[fix, improvement]`
+- **A watched agent card no longer promises a live browser that is never coming**: Every agent on the live wall always has its zero-cost activity feed, and watching one can also start a real browser that casts what the agent is doing. When no caster was running, the card still said "warming up" and sat there forever, because the wall assumed a browser was on its way the moment you watched. The wall now checks whether a caster pool is actually running: if one is, you get the same warming and queue-position handoff as before; if none is, the card stays on the honest activity view instead of spinning. The caster itself also got its deploy fixed: its container pinned a browser build its own library no longer matched, so the image would have failed on its first cast, and it now ships as a normal always-on service with a health endpoint that reports exactly which agents it is casting. (`/agents-live`) `[fix, infra]`
- **Background removal in the Forge is faster, keeps phone photos the right way up, and says when the link is the problem**: Cutting the background out of an image is the step that runs before most 3D generations, and it was doing avoidable work: every image was re-encoded to PNG on the way in, which on a 12 megapixel photo cost more time than the cutout itself. That round trip is gone, so the step now takes about a third of the time, and because the original file goes straight to the model, a photo taken on a phone comes back the way up you took it instead of on its side. Failures explain themselves now too: a link that answers "not found" or "forbidden", a file that is not an image, or a truncated paste all used to come back as an unexplained server error, and now say which of those happened so you can fix the input. (`/forge`) `[improvement, fix]`
+- **Motion Swap's guide now describes the hand and finger capture it has been doing all along**: The Motion Swap guide described body tracking only, so a reader had no way to know the capture also follows both hands, takes wrist rotation from the palm itself, and solves every finger joint, or that it holds your last handshape when your hands leave the frame. The guide and the capture worker's README now cover all of that, plus the exact files a capture produces, every setting the worker reads, and how to run a real capture on your own machine to check a change before it ships. The worker also gained a second test suite covering the parts around the motion solver: the authentication and input rules on its API, the video normalization step, the person-mask video, and the guard that refuses to fetch a video address pointing at our own internal infrastructure. (`/motion-swap`) `[docs, improvement]`
+- **Photo to 3D no longer fails when the image host has one slow moment**: Turning a photo into a 3D model starts by downloading the image you pointed at. If that download stalled for even a moment, the whole generation failed and you had to start over. The image is now fetched up to three times with a growing pause between tries, so a single slow moment costs a couple of seconds instead of the job. When an image genuinely cannot be used, the failure now names the reason and the host (unreachable, HTTP 404, not a decodable image) instead of an opaque error code, so you can tell a broken link from a hiccup. (`/create`) `[fix, improvement]`
+- **Stylizing a model no longer throws away the finished result over a momentary network hiccup, and plain models keep their intended color**: The stylize filters (voxel, brick, voronoi shell, low-poly) rebuild your model and then upload the result to storage. A brief interruption on that last upload step was not retried, so roughly once a week a job that had already done all its work was reported to you as failed. That upload now retries by itself. Two more repairs ride along: a model that carries no colors of its own now comes back in the soft neutral tone the filters were designed around, instead of the flat gray the geometry library hands out by default, and a model with no size at all is refused with a clear reason rather than returning a file with nothing visible in it. (`/forge`) `[fix, improvement]`
+- **The 3D forge now tells a broken GPU worker apart from a healthy one, and stops routing your generation at it**: Our own Hunyuan3D image-to-3D workers answer web requests within seconds of starting, then spend several minutes loading multi-gigabyte model weights in the background. The platform checked only whether a worker answered at all, so a worker that had answered but then failed to load its model looked exactly as healthy as a working one: the forge status page showed it green and generations kept being sent to it. Both the status page and the routing that picks a backend now read the worker's real readiness, so a worker that cannot generate is reported as down and skipped, and one that is still warming up is marked as such instead of promising a fast turnaround it cannot deliver. (`/forge`) `[fix, infra]`
+- **The pump.fun MCP server now returns the real name and symbol for tokens launched today**: Ask the pump.fun MCP server for a token's details and it reported no name, no symbol, and no image link for essentially every coin launched recently, including $THREE. The reason: pump.fun now mints Token-2022 tokens, which carry their name and symbol inside the mint itself rather than in the separate metadata account the server was reading. It now reads both places, so a request for a current token returns its actual name, symbol, and metadata link alongside supply and decimals. Older tokens are unaffected. (`/docs/mcp`) `[fix]`
+- **The sign-language recognition API now documents the confidence score it returns with every transcription**: When you fingerspell into the webcam, the recognizer reports how sure it is of what it read, and the page uses that to flag a shaky capture instead of quietly dropping wrong words into your message. That score was in every response but appeared in none of the docs, so anyone building on the recognition API had no way to know it existed. The API reference, the sign-language guide and the worker's own README now list the full response, including the raw decode before the cleanup pass and whether the cleanup changed anything, so a caller can build the same warning we do. The recognizer itself was also capped to a sane number of simultaneous captures per instance, so a burst of signers scales out instead of queueing behind each other. (`/sign-language`) `[docs, improvement]`
+- **Turning a sketch into 3D no longer loses a finished model when the job and the progress check land on different machines**: Sketch to 3D runs on our own GPU service, which can run on more than one machine at a time. The machine that accepted your drawing remembered the job only in its own memory, so a progress check that reached a second machine was answered with "no such job" and the generation was marked failed, sometimes after the model had already been built. The same thing happened when a machine was recycled between the submit and the result. Every job now records its progress to durable storage the moment it is accepted, so any machine can answer for it, and a job whose machine really did disappear mid-run is reported as failed with a clear reason after thirty minutes instead of leaving you polling forever. Two related repairs ride along: when the model fails to load on a machine, jobs sent to it now fail immediately with the real reason instead of waiting out a ten-minute timeout, and the service's health check reports that machine as unhealthy instead of claiming it is fine. (`/forge`) `[fix, infra]`
+- **Watching an agent forge an avatar now names the engine and the wait**: When an operator casts a live avatar forge onto an agent's screen, the narration used to open with the same line twice and then say only "Queued", never naming which free engine took the job or why a slow start was slow. It now names the engine that actually ran (which is not always the one requested, since the platform routes to whichever free lane is healthy) and, when a GPU worker has to boot from zero, says so with the real spin-up estimate instead of looking stalled. Failures now show their own recovery step rather than blanket prompt advice, and the High tier, which needs a $THREE hold, is refused up front instead of failing mid-cast. `[improvement, fix]`
## 2026-08-10
diff --git a/docs/ops/solana-rpc-lanes.md b/docs/ops/solana-rpc-lanes.md
index b7283e365..0eecb0a5c 100644
--- a/docs/ops/solana-rpc-lanes.md
+++ b/docs/ops/solana-rpc-lanes.md
@@ -118,6 +118,19 @@ unreadable wallet as `‼ unreadable`, and
never as the `owner` "fund this wallet" finding. On 2026-08-07 the older behaviour turned
one throttled lane into four fake below-floor money emergencies.
+[scripts/audit-wallet-flows.mjs](../../scripts/audit-wallet-flows.mjs) follows the same
+rule as of 2026-08-11. It used to coerce every wallet in a chunk whose lane threw to
+`0`, so a single failed chunk silently shrank the fleet total by whatever those wallets
+held and still exited clean. It now leaves them unread, excludes them from every total,
+lists them under `UNVERIFIED`, and exits `2`. A `null` account inside a *successful*
+`getMultipleAccounts` response is still a real zero: that account does not exist on
+chain. Only a call that threw is an unread.
+
+Both audits prune hosts with a hard egress block from their own lane chains rather than
+trusting `SOLANA_RPC_URL` blindly, because that var still points at MagicBlock in `.env`
+and on the Cloud Run service. Pointing an audit at a 403 lane is how it came to read
+every wallet as empty in the first place.
+
## Why a refusal must rotate, and when it must not
The breaker splits JSON-RPC errors into two classes:
diff --git a/prompts/swarm-100/sweep-wallet-flows.md b/prompts/swarm-100/sweep-wallet-flows.md
deleted file mode 100644
index c1a940f12..000000000
--- a/prompts/swarm-100/sweep-wallet-flows.md
+++ /dev/null
@@ -1,86 +0,0 @@
-# Sweep: Wallet flow audits clean
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-Run the sweep's own command first and work from its output, not from any
-memory of what used to fail:
-
- npm run audit:wallet-flows && npm run audit:service-wallets
-
-Capture the full output to the session scratchpad; do not work from an
-excerpt.
-
-## Task
-
-Run both audits. These are read-only checks of wallet plumbing and service wallet health; fix code findings at root. Anything that would move funds is out of scope here and stays behind the CLAUDE.md gate.
-
-Fix everything found in this sweep's scope. Findings that belong to a
-different surface entirely (and would take this session off its one task) go
-in the report as named follow-ups instead; everything in scope gets fixed
-here, at root, with no masking.
-
-## Definition of done
-
-- [ ] The command above exits 0 (or, for measurement-style sweeps, the report
- carries the measured numbers and every committed fix).
-- [ ] Every fix is a root-cause fix; no check was weakened, skipped, or
- quarantined to get to green.
-- [ ] npm run check:rules -- --paths <touched files> exits 0; npm test passes
- if code changed.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/sweep-wallet-flows.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/workers/longcat/test_app_smoke.py b/workers/longcat/test_app_smoke.py
new file mode 100644
index 000000000..0bb646c8e
--- /dev/null
+++ b/workers/longcat/test_app_smoke.py
@@ -0,0 +1,196 @@
+"""Core-path smoke test for the LongCat avatar service.
+
+ python3 workers/longcat/test_app_smoke.py
+
+Imports the real FastAPI app and drives its handlers directly. No GPU, no model
+weights, and no GCP credentials: the handlers under test all short-circuit
+before touching Firestore or Cloud Storage, which is itself part of what is
+being asserted. Runs as a Docker build gate, so the image cannot ship with a
+broken import, a missing route, or an auth regression.
+
+What it proves:
+ * main.py imports and its config validation works;
+ * /health reports the weights state instead of claiming a model is loaded;
+ * both authed routes reject a missing, malformed, or wrong bearer token with
+ 401 (not the 422 that FastAPI's required-Header form produced);
+ * /generate refuses with 503 while weights are unstaged, and refuses BEFORE
+ creating a Firestore job document, so a misconfigured instance cannot leave
+ a trail of jobs that can never run;
+ * an unsupported RESOLUTION fails at boot rather than 40 minutes into a job.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+API_KEY = "test-key-not-a-real-secret"
+
+# main.py reads these at import time. Set them outright rather than defaulting,
+# so the assertions below hold whatever the ambient environment carries. The
+# WEIGHTS_DIR points at an empty directory so the unstaged-weights paths are the
+# ones exercised.
+_EMPTY_WEIGHTS = tempfile.mkdtemp(prefix="longcat_test_weights_")
+os.environ["API_KEY"] = API_KEY
+os.environ["GCS_BUCKET"] = "test-bucket"
+os.environ["FIRESTORE_PROJECT"] = "test-project"
+os.environ["WEIGHTS_DIR"] = _EMPTY_WEIGHTS
+os.environ.pop("RESOLUTION", None)
+
+from fastapi import BackgroundTasks, HTTPException # noqa: E402
+
+import main # noqa: E402
+
+PASS = 0
+
+
+def check(name: str, condition: bool, detail: str = "") -> None:
+ global PASS
+ if not condition:
+ print(f"FAIL {name} {detail}")
+ sys.exit(1)
+ PASS += 1
+
+
+def status_of(coro) -> int:
+ """Run ``coro`` and return the HTTPException status it raises."""
+ try:
+ asyncio.run(coro)
+ except HTTPException as exc:
+ return exc.status_code
+ return 0
+
+
+def generate_call(authorization):
+ return main.generate(
+ main.GenerateRequest(
+ image_url="https://three.ws/a.png",
+ audio_url="https://three.ws/a.wav",
+ ),
+ BackgroundTasks(),
+ authorization=authorization,
+ )
+
+
+# ── config ─────────────────────────────────────────────────────────────────────
+
+check("the default resolution is supported", main.RESOLUTION in main.SUPPORTED_RESOLUTIONS)
+check("concurrency is at least 1", main.MAX_CONCURRENT >= 1)
+check("the segment cap is at least 1", main.MAX_SEGMENTS >= 1)
+check(
+ "the checkpoint dir is the avatar repo under the weights root",
+ main.CHECKPOINT_DIR == Path(_EMPTY_WEIGHTS) / "LongCat-Video-Avatar-1.5",
+ str(main.CHECKPOINT_DIR),
+)
+check(
+ "the base model dir is its sibling",
+ main.BASE_MODEL_DIR == Path(_EMPTY_WEIGHTS) / "LongCat-Video",
+ str(main.BASE_MODEL_DIR),
+)
+check(
+ "the inference entrypoint is upstream's single-audio avatar demo",
+ main.INFERENCE_SCRIPT == "run_demo_avatar_single_audio_to_video.py",
+)
+
+
+# ── /health ────────────────────────────────────────────────────────────────────
+
+health = asyncio.run(main.health())
+check("health is unauthenticated and answers", health.get("ok") is True)
+check("health names the pipeline", health.get("pipeline") == "longcat-avatar-1.5")
+check(
+ "health does not claim a model is loaded when weights are absent",
+ health.get("model_loaded") is False,
+ str(health),
+)
+check(
+ "health lists what is missing so an operator can act",
+ isinstance(health.get("missing_weights"), list) and len(health["missing_weights"]) > 0,
+ str(health.get("missing_weights")),
+)
+check("health reports the resolution", health.get("resolution") == main.RESOLUTION)
+check("health reports the segment cap", health.get("max_segments") == main.MAX_SEGMENTS)
+
+
+# ── auth ───────────────────────────────────────────────────────────────────────
+
+for label, header in (
+ ("a missing header", None),
+ ("an empty header", ""),
+ ("a non-bearer scheme", f"Basic {API_KEY}"),
+ ("a bare token", API_KEY),
+ ("a wrong key", "Bearer wrong-key"),
+ ("an empty bearer", "Bearer "),
+):
+ check(
+ f"/generate rejects {label} with 401",
+ status_of(generate_call(header)) == 401,
+ f"got {status_of(generate_call(header))}",
+ )
+ check(
+ f"/jobs rejects {label} with 401",
+ status_of(main.get_job("some-job", authorization=header)) == 401,
+ )
+
+
+# ── /generate with weights unstaged ────────────────────────────────────────────
+
+# A valid key gets past auth and lands on the weights gate. If this ever returns
+# 401 the key comparison broke; if it returns 500 the handler reached Firestore,
+# which has no credentials here, and the ordering regressed.
+check(
+ "a valid key past the weights gate answers 503",
+ status_of(generate_call(f"Bearer {API_KEY}")) == 503,
+ f"got {status_of(generate_call(f'Bearer {API_KEY}'))}",
+)
+
+# The gate must run before the job document is written. main._set_job would
+# raise AttributeError on the None client if it were reached, so a 503 here is
+# proof the Firestore write never happened.
+check("the weights gate precedes any Firestore write", main._db is None)
+
+
+# ── boot-time config validation ────────────────────────────────────────────────
+
+def import_with(env: dict) -> subprocess.CompletedProcess:
+ child_env = {**os.environ, **env}
+ return subprocess.run(
+ [sys.executable, "-c", "import main"],
+ cwd=str(Path(__file__).resolve().parent),
+ env=child_env,
+ capture_output=True,
+ text=True,
+ )
+
+
+bad = import_with({"RESOLUTION": "1080p"})
+check("an unsupported resolution fails at import", bad.returncode != 0, bad.stderr[-400:])
+check(
+ "the failure names the offending value",
+ "1080p" in bad.stderr,
+ bad.stderr[-400:],
+)
+
+good = import_with({"RESOLUTION": "480p"})
+check("480p is accepted at import", good.returncode == 0, good.stderr[-400:])
+
+for missing_var in ("API_KEY", "GCS_BUCKET", "FIRESTORE_PROJECT"):
+ child_env = {k: v for k, v in os.environ.items() if k != missing_var}
+ result = subprocess.run(
+ [sys.executable, "-c", "import main"],
+ cwd=str(Path(__file__).resolve().parent),
+ env=child_env,
+ capture_output=True,
+ text=True,
+ )
+ check(
+ f"a missing {missing_var} fails at import",
+ result.returncode != 0,
+ result.stderr[-200:],
+ )
+
+print(f"OK {PASS} app smoke checks passed")
diff --git a/workers/rembg/main.py b/workers/rembg/main.py
index 08f030e4d..cf8c1f5cf 100644
--- a/workers/rembg/main.py
+++ b/workers/rembg/main.py
@@ -1,31 +1,34 @@
"""
-Background removal service — strips backgrounds from images using BRIA RMBG-2.0
-(Apache-2.0) with rembg's U2Net as a fast CPU fallback.
+Background removal service: strips the background from an image and returns a
+transparent PNG, using rembg (MIT) and its ONNX salient-object-detection models.
API contract:
POST /remove { image: data-uri|url, model?: name }
- → 202 { task_id, status: "queued" }
+ → 202 { task_id, status: "queued", model }
model is one of u2net | isnet-general-use | u2net_human_seg | silueta.
The legacy aliases "rmbg2" and "isnet" resolve to isnet-general-use.
GET /tasks/:id → { task_id, status, result_url?, error? }
- GET /health → { ok, models_loaded, models_available, default_model, gpu_available }
+ GET /health → { ok, models_loaded, models_available, default_model,
+ gpu_available, execution_providers }
-No GPU required — isnet-general-use / u2net run on CPU in ~1-2s per 1024px image.
-GPU accelerates to ~0.2s. Only the default model is loaded at startup (the rest
-load lazily on first use) so cold starts stay fast and /remove returns instantly.
+No GPU required: the models run on ONNX Runtime's CPU provider in ~1-2 s for the
+inference step. Only the default model is loaded at startup (the rest load
+lazily on first use) so cold starts stay fast and /remove returns instantly.
Environment variables:
- API_KEY — shared bearer secret (required)
- GCS_BUCKET — Cloud Storage bucket for output PNGs (required)
- MODEL — default model name (default: isnet-general-use)
+ API_KEY shared bearer secret (required)
+ GCS_BUCKET Cloud Storage bucket for output PNGs (required)
+ MODEL default model name (default: isnet-general-use)
+ MAX_CONCURRENT in-flight removals allowed at once (default: 4)
"""
from __future__ import annotations
import asyncio
import base64
+import binascii
import io
import logging
import os
@@ -35,12 +38,21 @@ import uuid
from contextlib import asynccontextmanager
from typing import Optional
-import torch
+import httpx
from fastapi import FastAPI, HTTPException, Header, BackgroundTasks
from google.cloud import storage
-from PIL import Image
+from PIL import Image, UnidentifiedImageError
from pydantic import BaseModel, Field
+from rembg_policy import (
+ CANONICAL_MODELS,
+ MAX_TASKS,
+ SourceImageError,
+ TASK_RETENTION_S,
+ canonical_model,
+ gpu_providers,
+ prune_tasks,
+)
from worker_security import (
UnsafeUrlError,
fetch_remote_bytes,
@@ -58,25 +70,19 @@ API_KEY = os.environ["API_KEY"]
GCS_BUCKET = os.environ["GCS_BUCKET"]
MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "4"))
-# Canonical rembg model names. Friendly aliases keep the public API contract
-# stable for callers that still send "rmbg2"/"isnet" (the previous, invalid
-# names) — they resolve to rembg's real general-purpose model.
-CANONICAL_MODELS = ("u2net", "isnet-general-use", "u2net_human_seg", "silueta")
-MODEL_ALIASES = {
- "rmbg2": "isnet-general-use",
- "isnet": "isnet-general-use",
-}
-
-
-def _canonical_model(name: str, fallback: str = "isnet-general-use") -> str:
- n = (name or "").strip()
- n = MODEL_ALIASES.get(n, n)
- return n if n in CANONICAL_MODELS else fallback
+# The startup default, pre-baked into the image (see Dockerfile), so warming it
+# never touches the network. Env override is resolved through the alias table.
+DEFAULT_MODEL = canonical_model(os.environ.get("MODEL", ""))
+# Some image hosts (Wikimedia most visibly) answer 403 to a bare library
+# user-agent. Identify the service and where to complain about it, per their
+# published policy, so a public image URL a user pastes actually resolves.
+USER_AGENT = "three.ws-rembg/1.0 (background removal worker; +https://three.ws)"
+FETCH_TIMEOUT_S = 30.0
+MAX_SOURCE_BYTES = 16 * 1024 * 1024
-# The startup default — pre-baked into the image (see Dockerfile), so warming it
-# never touches the network. Env override is resolved through the alias table.
-DEFAULT_MODEL = _canonical_model(os.environ.get("MODEL", "isnet-general-use"))
+# Timestamps prune_tasks() reads; never part of the wire response.
+_INTERNAL_TASK_FIELDS = ("created_at", "finished_at")
_sessions: dict[str, object] = {}
_sessions_lock = threading.Lock()
@@ -90,18 +96,24 @@ def _get_session(model_name: str):
the worker thread-pool never loads the same model twice. Only the default
model is warmed at startup; the rest load on first use, so cold start stays
fast and the /remove submit returns its 202 immediately."""
- canon = _canonical_model(model_name)
- sess = _sessions.get(canon)
- if sess is not None:
- return sess
+ canon = canonical_model(model_name, fallback=DEFAULT_MODEL)
+ session = _sessions.get(canon)
+ if session is not None:
+ return session
with _sessions_lock:
- sess = _sessions.get(canon)
- if sess is None:
+ session = _sessions.get(canon)
+ if session is None:
import rembg
- sess = rembg.new_session(canon)
- _sessions[canon] = sess
+ session = rembg.new_session(canon)
+ _sessions[canon] = session
log.info("Loaded rembg session: %s", canon)
- return sess
+ return session
+
+
+def _execution_providers() -> list:
+ """ONNX Runtime execution providers this build can use."""
+ import onnxruntime
+ return list(onnxruntime.get_available_providers())
@asynccontextmanager
@@ -113,40 +125,79 @@ async def lifespan(app: FastAPI):
# Warm only the default model so the container becomes ready in seconds; the
# other models are loaded lazily on first request.
await loop.run_in_executor(None, _get_session, DEFAULT_MODEL)
- log.info("rembg service ready — default model: %s", DEFAULT_MODEL)
+ log.info("rembg service ready, default model: %s", DEFAULT_MODEL)
yield
app = FastAPI(title="rembg-service", lifespan=lifespan)
-def _require_api_key(authorization: str) -> None:
+def _require_api_key(authorization: Optional[str]) -> None:
try:
require_api_key(authorization, API_KEY)
except PermissionError as exc:
raise HTTPException(status_code=401, detail=str(exc)) from exc
+def _open_image(data: bytes) -> Image.Image:
+ """Decode fetched bytes into RGBA, or say what arrived instead.
+
+ RGBA is what rembg composites against: it pastes the cutout onto a
+ transparent RGBA canvas of the same mode, so handing it RGB raises deep
+ inside the library with a message no caller could act on.
+ """
+ try:
+ return Image.open(io.BytesIO(data)).convert("RGBA")
+ except UnidentifiedImageError as exc:
+ raise SourceImageError(
+ "the source is not a decodable image (expected PNG, JPEG, WebP or similar)"
+ ) from exc
+ except OSError as exc:
+ raise SourceImageError(f"the source image is truncated or corrupt: {exc}") from exc
+
+
def _decode_image(src: str) -> Image.Image:
if src.startswith("data:image"):
- b64 = src.split(",", 1)[1]
- return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGBA")
+ _, _, payload = src.partition(",")
+ try:
+ raw = base64.b64decode(payload, validate=True)
+ except (binascii.Error, ValueError) as exc:
+ raise SourceImageError("the data URI payload is not valid base64") from exc
+ return _open_image(raw)
if src.startswith("https://"):
try:
- data = fetch_remote_bytes(src, timeout=30, max_bytes=16 * 1024 * 1024)
+ data = fetch_remote_bytes(
+ src,
+ timeout=FETCH_TIMEOUT_S,
+ max_bytes=MAX_SOURCE_BYTES,
+ headers={"User-Agent": USER_AGENT},
+ )
except UnsafeUrlError as exc:
- raise ValueError(f"refused to fetch image: {exc}") from exc
- return Image.open(io.BytesIO(data)).convert("RGBA")
- raise ValueError(f"unsupported image source format: {src[:60]}")
+ raise SourceImageError(f"refused to fetch the image: {exc}") from exc
+ except httpx.HTTPStatusError as exc:
+ raise SourceImageError(
+ f"the image URL returned HTTP {exc.response.status_code}"
+ ) from exc
+ except httpx.HTTPError as exc:
+ raise SourceImageError(f"could not fetch the image URL: {type(exc).__name__}") from exc
+ except ValueError as exc:
+ # fetch_remote_bytes raises ValueError once the body passes max_bytes.
+ raise SourceImageError(str(exc)) from exc
+ return _open_image(data)
+ raise SourceImageError("image must be an https:// URL or a data:image/... URI")
def _run_removal(img: Image.Image, model_name: str) -> Image.Image:
+ """Cut the subject out, returning an RGBA image.
+
+ The image goes to rembg as a PIL image rather than as re-encoded PNG bytes:
+ the round trip cost more than the inference itself (2.9 s of the 8.1 s total
+ on a 12 MP photo, measured on 2 cores) and threw away the EXIF orientation,
+ so upright phone photos came back on their side.
+ """
import rembg
session = _get_session(model_name)
- buf_in = io.BytesIO()
- img.save(buf_in, format="PNG")
- result_bytes = rembg.remove(buf_in.getvalue(), session=session)
- return Image.open(io.BytesIO(result_bytes)).convert("RGBA")
+ return rembg.remove(img, session=session)
async def _process(task_id: str, image_src: str, model_name: str) -> None:
@@ -159,7 +210,7 @@ async def _process(task_id: str, image_src: str, model_name: str) -> None:
result = await loop.run_in_executor(None, _run_removal, img, model_name)
buf = io.BytesIO()
- result.save(buf, format="PNG", optimize=True)
+ result.save(buf, format="PNG")
png_bytes = buf.getvalue()
blob_name = f"rembg/{task_id}.png"
@@ -177,14 +228,27 @@ async def _process(task_id: str, image_src: str, model_name: str) -> None:
"width": result.width,
"height": result.height,
"elapsed_ms": int(elapsed * 1000),
+ "finished_at": time.time(),
})
- log.info("[%s] done in %.2fs — %d bytes", task_id, elapsed, len(png_bytes))
+ log.info("[%s] done in %.2fs, %d bytes", task_id, elapsed, len(png_bytes))
+ except SourceImageError as exc:
+ # The caller's input is at fault, so answer with what is wrong. The
+ # opaque safe_error path exists for OUR failures, and using it here
+ # sent people hunting a service outage over a dead image link.
+ log.warning("[%s] rejected source image: %s", task_id, exc)
+ _tasks[task_id].update({
+ "status": "failed",
+ "error": str(exc),
+ "elapsed_ms": int((time.time() - t0) * 1000),
+ "finished_at": time.time(),
+ })
except Exception as exc:
_tasks[task_id].update({
"status": "failed",
"error": safe_error(exc, context=f"[{task_id}] rembg"),
"elapsed_ms": int((time.time() - t0) * 1000),
+ "finished_at": time.time(),
})
@@ -197,36 +261,48 @@ class RemoveRequest(BaseModel):
async def remove_background(
body: RemoveRequest,
background_tasks: BackgroundTasks,
- authorization: str = Header(...),
+ authorization: Optional[str] = Header(default=None),
) -> dict:
_require_api_key(authorization)
- model_name = _canonical_model(body.model, fallback=DEFAULT_MODEL)
+ model_name = canonical_model(body.model, fallback=DEFAULT_MODEL)
task_id = str(uuid.uuid4())
+ now = time.time()
+ evicted = prune_tasks(_tasks, now)
+ if evicted:
+ log.info("pruned %d finished task(s), %d retained", len(evicted), len(_tasks))
_tasks[task_id] = {
"task_id": task_id,
"status": "queued",
"model": model_name,
+ "created_at": now,
}
background_tasks.add_task(_process, task_id, body.image, model_name)
- return {"task_id": task_id, "status": "queued"}
+ return {"task_id": task_id, "status": "queued", "model": model_name}
@app.get("/tasks/{task_id}")
-async def get_task(task_id: str, authorization: str = Header(...)) -> dict:
+async def get_task(task_id: str, authorization: Optional[str] = Header(default=None)) -> dict:
_require_api_key(authorization)
task = _tasks.get(task_id)
if task is None:
raise HTTPException(status_code=404, detail="task not found")
- return task
+ # Retention bookkeeping stays server-side: the documented response shape is
+ # what callers get, whatever the eviction policy needs to track.
+ return {key: value for key, value in task.items() if key not in _INTERNAL_TASK_FIELDS}
@app.get("/health")
async def health() -> dict:
+ providers = _execution_providers()
return {
"ok": True,
"service": "rembg",
- "gpu_available": torch.cuda.is_available(),
+ "gpu_available": bool(gpu_providers(providers)),
+ "execution_providers": providers,
"models_loaded": list(_sessions),
"models_available": list(CANONICAL_MODELS),
"default_model": DEFAULT_MODEL,
+ "tasks_tracked": len(_tasks),
+ "task_retention_s": TASK_RETENTION_S,
+ "max_tasks": MAX_TASKS,
}