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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(avatar-reconstruction): tell the user their photo has no face instead of an opaque internal error
nirholasad1ce7b2e032
diff --git a/data/changelog.json b/data/changelog.jsonindex f8e9f90fa..d8279c856 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,46 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-11",+ "title": "Turning a sketch into 3D no longer loses a finished model when the job and the progress check land on different machines",+ "summary": "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.",+ "tags": [+ "fix",+ "infra"+ ],+ "link": "/forge"+ },+ {+ "date": "2026-08-11",+ "title": "The sign-language recognition API now documents the confidence score it returns with every transcription",+ "summary": "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.",+ "tags": [+ "docs",+ "improvement"+ ],+ "link": "/sign-language"+ },+ {+ "date": "2026-08-11",+ "title": "A selfie with no visible face now tells you so, instead of \"generation failed\"",+ "summary": "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.",+ "tags": [+ "fix",+ "improvement"+ ],+ "link": "/create"+ },+ {+ "date": "2026-08-11",+ "title": "Background removal in the Forge is faster, keeps phone photos the right way up, and says when the link is the problem",+ "summary": "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.",+ "tags": [+ "improvement",+ "fix"+ ],+ "link": "/forge"+ },{"date": "2026-08-10","title": "A mistyped bounty or citizen link in Agora now says what is wrong instead of failing with a server error",diff --git a/workers/avatar-reconstruction/Dockerfile b/workers/avatar-reconstruction/Dockerfileindex ec1d3d9f6..5ffb4fd07 100644--- a/workers/avatar-reconstruction/Dockerfile+++ b/workers/avatar-reconstruction/Dockerfile@@ -1,7 +1,12 @@# ── Stage: base ───────────────────────────────────────────────────────────────-# CUDA runtime for rembg[gpu] (onnxruntime-gpu). The L4 GPU is only used for-# background removal; the rest of the pipeline (MediaPipe, TPS, GLB ops) is-# CPU-bound and benefits from the generous CPU allocation on Cloud Run.+# CUDA runtime, kept for the onnxruntime-gpu build that rembg[gpu] pulls in. Note+# the service DEPLOYS WITHOUT A GPU (see cloudbuild.yaml): measured 2026-07-25,+# the CUDA provider never actually engaged for background removal, so the L4 was+# returned to the shared regional pool and every stage now runs on the 8 vCPU+# allocation. onnxruntime-gpu falls back to its CPU provider cleanly, which is+# what production has been serving on since. The image is ~2 GB heavier than a+# plain CPU base for that fallback; swapping the base image is a live change to+# the inference path, so it needs its own measured run rather than a drive-by.FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04ENV PYTHONDONTWRITEBYTECODE=1 \@@ -43,11 +48,13 @@ COPY precompute_uv.py /app/precompute_uv.pyCOPY test_face_geometry.py /app/test_face_geometry.pyCOPY test_face_projection.py /app/test_face_projection.pyCOPY test_face_pipeline.py /app/test_face_pipeline.py+COPY smoke_test.py /app/smoke_test.py# ── Template GLBs ─────────────────────────────────────────────────────────────-# Bake both gender variants into the image so cold starts are instant.-# The repo's default.glb is a Wolf3D unisex base; add male/female variants as-# they become available. For now, all body_type values fall back to default.glb.+# Baked into the image so cold starts are instant. default.glb is the Wolf3D+# unisex base and the only template the pipeline can use: face_uv_map.json is+# precomputed against its exact head topology (see _load_template). Every+# body_type resolves to it until a male/female variant with that topology exists.RUN mkdir -p /app/templatesCOPY templates/ /app/templates/@@ -57,11 +64,23 @@ COPY templates/ /app/templates/# Requires network access during build (downloads ~200 KB OBJ from GitHub).RUN python /app/precompute_uv.py /app/templates/default.glb-# ── Build-time guard ──────────────────────────────────────────────────────────+# ── Build-time guards ─────────────────────────────────────────────────────────# The geometry morph must preserve the rig + 52 ARKit blendshapes and never blow# up the mesh. Fail the image build if the morph math regresses, rather than# shipping a broken avatar pipeline.RUN python /app/test_face_geometry.py+RUN python /app/test_face_projection.py+RUN python /app/test_face_pipeline.py++# Then the whole core path on a real photograph: every stage-level test above+# passes on a pipeline that cannot actually serve a request (a module missing+# from the COPY list, a stage that only crashes on real photo data, an output GLB+# whose rig has come loose). Failing here costs a build; failing after a deploy+# costs a build plus a broken revision. Needs network, which this build already+# requires for the UV pre-computation above. It also warms rembg's u2net weights+# into the image, so the first request on a cold instance no longer waits on that+# download.+RUN python /app/smoke_test.pyEXPOSE 8080diff --git a/workers/avatar-reconstruction/README.md b/workers/avatar-reconstruction/README.mdindex 421046710..2373a567e 100644--- a/workers/avatar-reconstruction/README.md+++ b/workers/avatar-reconstruction/README.md@@ -1,24 +1,31 @@# Avatar Reconstruction Service-FastAPI service on a Cloud Run GPU instance (NVIDIA L4) that turns 1–6 selfie-photos into a rigged, animation-ready GLB avatar and stores it in Cloud Storage.-Same external contract the three.ws backend (`api/_providers/gcp.js`) already-speaks — `POST /reconstruct` → `GET /jobs/:id`.+FastAPI service on Cloud Run that turns 1-6 selfie photos into a rigged,+animation-ready GLB avatar and stores it in Cloud Storage. Same external contract+the three.ws backend (`api/_providers/gcp.js`, `reconstruct` mode) already speaks:+`POST /reconstruct` → `GET /jobs/:id`.++**CPU-only, no GPU.** It ran on an NVIDIA L4 until 2026-07-27. Measurement that+retired it, and the reason not to re-add one, are in+[`cloudbuild.yaml`](cloudbuild.yaml); the short version is that the CUDA provider+never engaged, so the GPU bought nothing and its slot was worth more to the rest+of the fleet. Production runs at 8 vCPU / 16 GiB, `--no-cpu-throttling`, one warm+instance. A job takes about 5 s end to end.## PipelineThe avatar is built on a fixed-topology Wolf3D/RPM template head+body that shipspre-rigged with a humanoid skeleton and **52 ARKit blendshapes + 15 visemes**(the same architecture Avaturn uses: fit a person onto a rigged template, don't-generate an arbitrary mesh). Two phases, both commercial-clean:+generate an arbitrary mesh). Three stages, all commercial-clean:-1. **Face texture transfer** (`face_pipeline.py`) — MediaPipe FaceLandmarker →+1. **Face texture transfer** (`face_pipeline.py`) - MediaPipe FaceLandmarker →TPS-warp the selfie into the template's skin UV → composite over the faceoval → sample and tint skin / hair / eye colour.-2. **Face geometry morph** (`face_geometry.py`, Phase 2) — recover the person's- actual 3D face shape (width, jaw, nose projection, brow, cheekbones) from the- same 468 MediaPipe landmarks and reshape the template head to match, so the- avatar reads as *that person* instead of their texture on a generic head.+2. **Face geometry morph** (`face_geometry.py`) - recover the person's actual 3D+ face shape (width, jaw, nose projection, brow, cheekbones) from the same 468+ MediaPipe landmarks and reshape the template head to match, so the avatar+ reads as *that person* instead of their texture on a generic head.Umeyama-aligns the landmarks to MediaPipe's neutral canonical face, carriesthe identity residual onto the head's corresponding vertices (precomputednearest-vertex map), and interpolates it across the head with a thin-plate@@ -26,26 +33,58 @@ generate an arbitrary mesh). Two phases, both commercial-clean:fades the field to zero off the face. Vertex count/order are preserved, so`glb_ops.set_head_geometry` writes it back **without disturbing skinning orany blendshape**. The `strength` / `max_displacement_frac` defaults are set by- an ISE sweep over the reference set — see [`eval/`](eval/README.md).+ an ISE sweep over the reference set: see [`eval/`](eval/README.md).+3. **Projective texturing** (`face_projection.py`) - the face-oval warp only+ reaches about 10% of the head's texels. This solves a weak-perspective camera+ from the landmarks and paints the photo onto the ears, jawline, forehead and+ neck as well, lifting photographic coverage to roughly 37% (the figure the+ live service logs per job).`precompute_uv.py` builds `face_uv_map.json` at image-build time: the canonicalface model, the landmark→head-vertex correspondence, and the skin UV mapping.-Toggle Phase 2 with `GEOMETRY_MORPH` (default `1`; set `0` for texture-only). If-the map lacks geometry fields or the morph raises, the job degrades cleanly to-texture-only — the shape refinement never fails a reconstruction.+Each stage after the first is independently switchable and degrades instead of+failing: `GEOMETRY_MORPH=0` and `PROJECTIVE_TEXTURE=0` turn stages 2 and 3 off,+and if either raises, or the UV map lacks the fields it needs, the job still+returns a textured avatar. A refinement never fails a reconstruction.-Everything above is Apache-2.0 / MIT-clean (MediaPipe, numpy, scipy) — no+Everything above is Apache-2.0 / MIT-clean (MediaPipe, numpy, scipy): nonon-commercial 3DMM (FLAME/BFM/SMPL) is used. See[`docs/avatar-reconstruction.md`](../../docs/avatar-reconstruction.md) for thefidelity roadmap (v2: dense MICA+FLAME identity via the model-agnostic`register_head_to_target` primitive + Imagen texture inpaint; v3: an Anny/MakeHuman CC0 body to drop the RPM-template dependency). FaceLift was evaluated-and rejected — non-commercial Adobe weights, splat output, not mesh.+and rejected: non-commercial Adobe weights, splat output, not mesh.++### Templates++`templates/default.glb` is the only template the pipeline can use. It is+addressed by name throughout (a `Wolf3D_Head` mesh carrying the blendshapes, and+`Wolf3D_Skin` / `Wolf3D_Hair` / `Wolf3D_Eye` materials), and `face_uv_map.json`+is precomputed against that exact head topology. `body_type` therefore has no+effect yet: every value resolves to `default.glb`. Adding a male/female variant+means adding a GLB with the same head topology, or regenerating the UV map for+its own.++## Environment++| Variable | Required | Meaning |+|---|---|---|+| `API_KEY` | yes | Shared bearer secret. Production reads it from the `avatar-reconstruction-key` secret. |+| `GCS_BUCKET` | yes | Bucket for output GLBs (`three-ws-avatar-reconstructions`). |+| `FIRESTORE_PROJECT` | yes | Project hosting the Firestore job collection. |+| `MAX_CONCURRENT_JOBS` | no (2) | Jobs processed in parallel. |+| `GEOMETRY_MORPH` | no (`1`) | `0` skips the identity morph (texture only). |+| `MAX_MORPH_YAW_DEG` | no (35) | Above this head yaw the morph is skipped: a single view cannot constrain the occluded half of a turned face. |+| `PROJECTIVE_TEXTURE` | no (`1`) | `0` falls back to warp-only skin. |++The service reads no others. (Cloud Run also carries `DEVICE=cpu`, which predates+the GPU removal and is inert.)## Prerequisites-1. GCP project with billing enabled and the $110k credits applied+1. GCP project with billing enabled and the Google for Startups Web3 credits+ applied: see [`docs/ops/gcp-credits-plan.md`](../../docs/ops/gcp-credits-plan.md).2. APIs enabled: Cloud Run, Cloud Build, Artifact Registry, Cloud Storage, Firestore, Secret Manager3. Artifact Registry repository created:```@@ -69,28 +108,42 @@ and rejected — non-commercial Adobe weights, splat output, not mesh.gcloud secrets create avatar-reconstruction-key \--data-file=-```+7. The `avatar-reconstruction-sa@` service account, which both the build and the+ runtime pin (the project's default compute SA was deleted).## Deploying+Owner-gated, like every production deploy in this repo (see `CLAUDE.md`).+```bash-# From repo root+# From this directory (the build context is the worker dir, not the repo root)gcloud builds submit \- --config workers/avatar-reconstruction/cloudbuild.yaml \+ --config cloudbuild.yaml \+ --region us-central1 \+ --project aerial-vehicle-466722-p5 \--substitutions _GCS_BUCKET=three-ws-avatar-reconstructions```-After deploy, Cloud Build prints the service URL. Set these on the three.ws-production service (Cloud Run `three-ws-api`) so the site can reach this worker:+The build runs the geometry, projection, texture and smoke tests as image-build+steps, so a regression fails the build instead of shipping. It also needs network+access: `precompute_uv.py` downloads the canonical face model (~200 KB from+GitHub) and the smoke test fetches one benchmark reference photo.++These are already set on the production `three-ws-api` service so the site+reaches this worker:```AVATAR_REGEN_PROVIDER=gcp-GCP_RECONSTRUCTION_URL=https://avatar-reconstruction-<hash>-uc.a.run.app-GCP_RECONSTRUCTION_KEY=<the secret value from step 6>+GCP_RECONSTRUCTION_URL=https://avatar-reconstruction-lp642k3kpa-uc.a.run.app+GCP_RECONSTRUCTION_KEY=<the avatar-reconstruction-key secret value>```+To change them (note `--update-env-vars`, which merges: `--set-env-vars` would+replace the service's entire env):+```bashgcloud run services update three-ws-api --region us-central1 \- --update-env-vars AVATAR_REGEN_PROVIDER=gcp,GCP_RECONSTRUCTION_URL=https://avatar-reconstruction-<hash>-uc.a.run.app,GCP_RECONSTRUCTION_KEY=<key>+ --update-env-vars AVATAR_REGEN_PROVIDER=gcp,GCP_RECONSTRUCTION_URL=<url>,GCP_RECONSTRUCTION_KEY=<key>```(For local development, put the same keys in your `.env`.) See the production@@ -98,16 +151,29 @@ runbook: [`docs/ops/gcp-production.md`](../../docs/ops/gcp-production.md).## API+Every route requires `Authorization: Bearer $API_KEY`, except `/health`.+### POST /reconstruct-Accepts 1–6 images (base64 data URIs or HTTPS URLs). Returns immediately with a `job_id`.+Accepts 1-6 images as base64 data URIs or HTTPS URLs. Returns immediately; the+work runs in the background. HTTPS sources are fetched through the SSRF-hardened+client in `worker_security.py` (https-only, private/loopback/metadata addresses+rejected after DNS resolution, every redirect hop re-validated, response size+bounded).```json{- "images": ["data:image/jpeg;base64,...", "https://..."]+ "images": ["data:image/jpeg;base64,...", "https://..."],+ "body_type": "neutral",+ "job_id": "optional-caller-supplied-id"}```+`body_type` is `male` | `female` | `neutral` (default `neutral`); see+[Templates](#templates) for why it currently has no effect. `job_id` lets the+caller choose the id, which is how the platform correlates a reconstruction with+its own job row; omit it and the service generates a UUID.+Response `202 Accepted`:```json{ "job_id": "uuid", "status": "queued" }@@ -115,17 +181,64 @@ Response `202 Accepted`:### GET /jobs/{job_id}-Poll for status.+Poll for status. `404` if the id is unknown.```json-{ "job_id": "...", "status": "done", "glb_url": "https://storage.googleapis.com/..." }+{+ "job_id": "...",+ "status": "done",+ "glb_url": "https://storage.googleapis.com/three-ws-avatar-reconstructions/avatars/....glb",+ "body_type": "neutral",+ "image_count": 1,+ "created_at": "2026-08-11T01:20:46.605950+00:00",+ "updated_at": "2026-08-11T01:20:53.044663+00:00"+}````status` values: `queued` → `running` → `done` | `failed`+A `failed` job carries `error` plus `error_kind`, which says whose problem it is:++| `error_kind` | `error` | Meaning |+|---|---|---|+| `input` | the actual reason, e.g. `no face detected in any of the provided photos` | The photos were unusable. Safe to show the caller, and the site's job-error mapping reads this wording to tell the user what to change. |+| `internal` | `internal error (ref <id>)` | A service fault. The full traceback is in Cloud Logging under that correlation id, deliberately not in the response. |+### GET /health-Returns `{ "ok": true, "pipeline": "face_texture_transfer_v2", "model_loaded": true, "geometry_morph": true }`.+Unauthenticated, and what the Cloud Run startup probe hits.++```json+{+ "ok": true,+ "pipeline": "face_texture_transfer_v2",+ "model_loaded": true,+ "uv_map_ready": true,+ "geometry_morph": true+}+```++`pipeline` is `face_texture_transfer_v2` when the geometry morph is live and+`face_texture_transfer_v1` when it is off or its map is missing.++## Tests++The image build runs all four, so a broken pipeline fails the build:++```bash+python3 test_face_geometry.py # morph preserves the rig, blendshapes, mesh bounds+python3 test_face_projection.py # camera fit, occlusion, UV rasterisation+python3 test_face_pipeline.py # skin-tint masking (protects the photographic oval)+python3 smoke_test.py # the whole core path on a real photo (needs network)+```++`smoke_test.py` is the one that catches what the others cannot: it runs+`face_pipeline.process` on a real reference photo and asserts the output GLB keeps+its head topology, all its morph targets and its skinning, that the photo reached+the texture, that the head actually moved, and that a faceless photo is rejected+as an input error rather than an internal one. Pass a URL or a local image path to+use a different photo. Fidelity measurement (a score, not a pass/fail) is a+separate suite: [`eval/`](eval/README.md).## Local development (CPU only, no GPU)@@ -133,8 +246,18 @@ Returns `{ "ok": true, "pipeline": "face_texture_transfer_v2", "model_loaded": tdocker build -t avatar-reconstruction .docker run -p 8080:8080 \-e API_KEY=dev \- -e GCS_BUCKET=my-bucket \- -e FIRESTORE_PROJECT=my-project \- -e DEVICE=cpu \+ -e GCS_BUCKET=three-ws-avatar-reconstructions \+ -e FIRESTORE_PROJECT=aerial-vehicle-466722-p5 \+ -v "$HOME/.config/gcloud:/root/.config/gcloud:ro" \+ -e GOOGLE_CLOUD_PROJECT=aerial-vehicle-466722-p5 \avatar-reconstruction```++Startup opens real Firestore and Cloud Storage clients, so the container needs+credentials that can reach both (the mounted ADC above, or a service-account key).+To exercise the pipeline without them, run the smoke test in the container+instead: it calls `face_pipeline.process` directly and touches neither service.++```bash+docker run --rm avatar-reconstruction python /app/smoke_test.py+```diff --git a/workers/avatar-reconstruction/eval/README.md b/workers/avatar-reconstruction/eval/README.mdindex d13bf46b0..43bda5c2b 100644--- a/workers/avatar-reconstruction/eval/README.md+++ b/workers/avatar-reconstruction/eval/README.md@@ -33,9 +33,10 @@ Two numbers give it meaning:- **template floor** — the same measurement against the unmorphed template. Thisis what a texture-only pipeline scores, and the number to beat.-- **improvement** — the fraction of that floor a run closes. The Phase-2 morph- moves `strength` (default 0.75) of the way toward the person, so ~0.75 is the- current implementation's ceiling, not 1.0.+- **improvement**: the fraction of that floor a run closes. The geometry morph+ moves `strength` (default 0.6, see `face_geometry.morph_head_to_landmarks`) of+ the way toward the person, so that value is the current implementation's+ ceiling, not 1.0.A region breakdown (oval / nose / cheeks / brow / jaw) says *where* the shape iswrong, which is what decides where the next fidelity push goes.@@ -115,7 +116,8 @@ Sweeps `strength` x `max_displacement_frac` over every reference face and reportthe best mean ISE, the worst individual face, and how many faces a setting makesworse than the shipped default. Runs offline — landmarks are detected once, theneach combination is applied in-process — so a full grid is minutes, not a day of-job submissions. This is how the current 0.6 / 0.45 defaults were chosen.+job submissions. This is how the shipped defaults (`strength` 0.6,+`max_displacement_frac` 0.55) were chosen.Read its output with the blind spots above in mind. The sweep's numerical optimumis not automatically the right ship: a benchmark of clean portraits will alwaysdiff --git a/workers/avatar-reconstruction/face_pipeline.py b/workers/avatar-reconstruction/face_pipeline.pyindex c70798374..c74dac3e8 100644--- a/workers/avatar-reconstruction/face_pipeline.py+++ b/workers/avatar-reconstruction/face_pipeline.py@@ -26,6 +26,7 @@ from pathlib import Pathfrom typing import Optionalimport cv2+import httpximport mediapipe as mpimport numpy as npfrom PIL import Image, ImageFilter@@ -39,6 +40,29 @@ from worker_security import UnsafeUrlError, fetch_remote_byteslog = logging.getLogger("face_pipeline")++# ── error classification ───────────────────────────────────────────────────────++class InputError(ValueError):+ """The submitted photos cannot be reconstructed, and no retry will change that.++ Distinct from every other exception the pipeline can raise, because the two+ need opposite treatment. An internal fault is an operator's problem: it is+ logged with a traceback and reported to the caller as an opaque+ correlation id (``worker_security.safe_error``), since its message can carry+ paths, library internals and upstream response fragments.++ An input rejection is the *user's* problem and its message is the only thing+ that lets them fix it. "no face detected in any of the provided photos" is+ safe to hand back verbatim, and the site's job-error mapping keys off exactly+ that wording (`src/create-prompt.js` / `src/forge-studio/create-prompt.js`+ match "face" + "detect" to tell the user to reword their prompt). Routing it+ through the opaque path instead stranded those users on a generic+ "Generation failed", and buried a legitimate rejection in the ERROR log next+ to real outages.+ """++# ── paths ──────────────────────────────────────────────────────────────────────HERE = Path(__file__).parent@@ -116,16 +140,29 @@ def _get_uv_map() -> dict: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("RGB")+ try:+ return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")+ except Exception as exc:+ raise InputError("an inline image could not be decoded") from excif src.startswith("https://"):# SSRF-hardened: https-only, private/loopback/link-local/metadata IPs# rejected after DNS resolution, redirects re-validated per hop, bounded.try:data = fetch_remote_bytes(src, timeout=30)except UnsafeUrlError as exc:- raise ValueError(f"refused to fetch image source: {exc}") from exc- return Image.open(io.BytesIO(data)).convert("RGB")- raise ValueError(f"unsupported image source: {src[:60]}")+ raise InputError(f"refused to fetch image source: {exc}") from exc+ except httpx.HTTPStatusError as exc:+ # The caller chose this URL, so its status belongs in their message.+ raise InputError(+ f"image source returned HTTP {exc.response.status_code}"+ ) from exc+ except httpx.HTTPError as exc:+ raise InputError(f"could not fetch image source: {type(exc).__name__}") from exc+ try:+ return Image.open(io.BytesIO(data)).convert("RGB")+ except Exception as exc:+ raise InputError("a fetched image could not be decoded") from exc+ raise InputError(f"unsupported image source: {src[:60]}")def _select_best_photo(images: list[Image.Image]) -> tuple[Image.Image, list]:@@ -478,6 +515,14 @@ def _load_template(body_type: str) -> bytes:"""Load the appropriate template GLB.body_type: 'male' | 'female' | 'neutral' (default).++ Only `default.glb` ships today, so every body_type resolves to it. A template+ is not just any avatar: the whole pipeline addresses it by name (a+ `Wolf3D_Head` mesh with the 52 ARKit blendshapes, and `Wolf3D_Skin` /+ `Wolf3D_Hair` / `Wolf3D_Eye` materials), and `face_uv_map.json` is+ precomputed against that exact mesh. A GLB without those, or with a different+ head topology, cannot be added to this map without regenerating the UV map+ for it."""candidates = {"male": TEMPLATES_DIR / "male.glb",@@ -531,7 +576,7 @@ def process(log.info("[%s] small-face rescue succeeded on image %d", job_id, idx)breakif landmarks is None:- raise ValueError("no face detected in any of the provided photos")+ raise InputError("no face detected in any of the provided photos")log.info("[%s] face selected (%.1fs)", job_id, time.time() - t0)img_w, img_h = best_img.sizediff --git a/workers/avatar-reconstruction/main.py b/workers/avatar-reconstruction/main.pyindex b52a69767..1e44d7b06 100644--- a/workers/avatar-reconstruction/main.py+++ b/workers/avatar-reconstruction/main.py@@ -1,15 +1,22 @@"""-Avatar reconstruction service — Phase 1: face texture transfer.+Avatar reconstruction service: selfie photos to a rigged GLB avatar.-Same external API contract as the original InstantMesh service so the-Vercel backend (api/_providers/gcp.js) requires zero changes:+Same external API contract as the original InstantMesh service, so the+three.ws backend (api/_providers/gcp.js, `reconstruct` mode) requires no+changes:POST /reconstruct { images: [data-uri|https-url, ...], job_id?: str }→ 202 { job_id, status: "queued" }- GET /jobs/:id → { job_id, status, glb_url?, error?, updated_at }+ GET /jobs/:id → { job_id, status, glb_url?, error?, error_kind?, updated_at }- GET /health → { ok, pipeline, model_loaded }+ On failure, `error_kind` says whose problem it is:+ "input" the photos were unusable; `error` is the+ caller-facing reason ("no face detected …").+ "internal" a service fault; `error` is an opaque+ correlation id to join against the logs.++ GET /health → { ok, pipeline, model_loaded, uv_map_ready, geometry_morph }Environment variables (all required unless noted):API_KEY — shared bearer secret (set via GCP Secret Manager)@@ -28,7 +35,6 @@ from contextlib import asynccontextmanagerfrom datetime import datetime, timezonefrom fastapi import FastAPI, HTTPException, Header, BackgroundTasks-from fastapi.responses import JSONResponsefrom google.cloud import firestore, storagefrom pydantic import BaseModel, Field@@ -126,10 +132,24 @@ async def _process_job(job_id: str, image_sources: list[str], body_type: str) ->_set_job(job_id, {"status": "done", "glb_url": glb_url})log.info("[%s] done → %s", job_id, glb_url)+ except face_pipeline.InputError as exc:+ # The photos, not the service. Hand the reason back verbatim, it is+ # the only thing that tells the user what to change, and the site's+ # job-error mapping reads it (see face_pipeline.InputError). Logged at+ # WARNING with no traceback so a rejected upload never looks like an+ # outage in the error log.+ log.warning("[%s] rejected input: %s", job_id, exc)+ _set_job(job_id, {+ "status": "failed",+ "error": str(exc),+ "error_kind": "input",+ })+except Exception as exc:_set_job(job_id, {"status": "failed","error": safe_error(exc, context=f"[{job_id}] pipeline"),+ "error_kind": "internal",})diff --git a/workers/avatar-reconstruction/smoke_test.py b/workers/avatar-reconstruction/smoke_test.pynew file mode 100644index 000000000..6c0996bc8--- /dev/null+++ b/workers/avatar-reconstruction/smoke_test.py@@ -0,0 +1,177 @@+"""+Core-path smoke test: a real photo through the whole pipeline to a real GLB.++Run: python3 smoke_test.py [photo-url-or-path]++The other test files here pin individual stages in isolation (tint maths,+geometry morph, camera fit). None of them runs `face_pipeline.process`, which is+the only thing the service actually calls, and every production failure this+worker has had lived in that gap: a module missing from the image, a stage that+crashes only on a real photograph, an output GLB whose rig no longer loads. Each+took a full build-and-deploy cycle to discover. This closes it.++The photo is a real image fetched over HTTPS from the benchmark reference set+(`eval/README.md`), so the SSRF-hardened fetch, the decoder, background removal,+landmark detection, the TPS warp, the geometry morph and projective texturing all+run exactly as they do for a user's upload. Pass a URL or a local path to use a+different one.++What it asserts, and why each one is the thing that breaks:++ 1. The output parses as a GLB with an intact binary blob.+ 2. The head keeps its exact vertex count and order. Everything below depends+ on this: the 52 ARKit blendshapes and the skin weights are stored as+ indices into it, so a single added or reordered vertex silently detaches+ the whole rig.+ 3. Every morph target survives, with the same target count as the template.+ An avatar that cannot blink or speak is not shippable, and the morph writes+ POSITION in place precisely so they stay attached.+ 4. Skinning (JOINTS_0 / WEIGHTS_0) and the skeleton are still present.+ 5. The skin texture actually changed, proof the photo landed rather than the+ template being returned untouched.+ 6. The head geometry actually moved, proof the identity morph ran.+ 7. A faceless photo is rejected as an InputError carrying a caller-facing+ reason, not as an opaque internal error. That distinction is what decides+ whether the user is told to reword their prompt or shown "Generation+ failed" (see `face_pipeline.InputError`).+"""++from __future__ import annotations++import base64+import io+import sys+from pathlib import Path++import numpy as np+from PIL import Image++import face_pipeline+import glb_ops++HERE = Path(__file__).parent++# One face from the benchmark reference set, mirrored to the worker's own bucket+# and publicly readable (eval/README.md). Deliberately a URL, not a bundled file:+# the HTTPS branch of `_decode_image` is the one every production job takes.+DEFAULT_PHOTO = (+ "https://storage.googleapis.com/three-ws-avatar-reconstructions"+ "/eval-refs/black-caribbean-adult-woman-clean.png"+)+++def _photo_source(argv: list[str]) -> str:+ """Resolve the photo argument to something `process` accepts."""+ if not argv:+ return DEFAULT_PHOTO+ arg = argv[0]+ if arg.startswith("https://") or arg.startswith("data:image"):+ return arg+ path = Path(arg)+ if not path.exists():+ raise SystemExit(f"photo not found: {path}")+ suffix = path.suffix.lstrip(".").lower() or "png"+ b64 = base64.b64encode(path.read_bytes()).decode("ascii")+ return f"data:image/{suffix};base64,{b64}"+++def _morph_target_count(glb) -> int:+ prim = glb_ops._find_head_prim(glb)+ return len(prim.targets or [])+++def _head_texture(glb) -> Image.Image:+ tex = glb_ops.get_material_texture(glb, "Wolf3D_Skin")+ if tex is None:+ raise AssertionError("Wolf3D_Skin texture missing from the GLB")+ return tex.convert("RGB")+++def main(argv: list[str]) -> int:+ source = _photo_source(argv)+ print(f"photo: {source[:90]}{'…' if len(source) > 90 else ''}")++ template = glb_ops.load_glb((HERE / "templates" / "default.glb").read_bytes())+ tpl_positions, _, _ = glb_ops.get_head_mesh_data(template)+ tpl_targets = _morph_target_count(template)+ tpl_texture = np.array(_head_texture(template), dtype=np.int16)+ print(f"template: {len(tpl_positions)} head vertices, {tpl_targets} morph targets")++ # ── 1. the core path ──────────────────────────────────────────────────────+ glb_bytes = face_pipeline.process("smoke", [source], "neutral")+ assert glb_bytes[:4] == b"glTF", "output is not a GLB container"+ print(f"ok pipeline returned a {len(glb_bytes)} byte GLB")++ out = glb_ops.load_glb(glb_bytes)+ assert out.binary_blob(), "output GLB has no binary blob"++ # ── 2. fixed topology ─────────────────────────────────────────────────────+ positions, _, faces = glb_ops.get_head_mesh_data(out)+ assert positions.shape == tpl_positions.shape, (+ f"head vertex count changed: {positions.shape[0]} vs template "+ f"{tpl_positions.shape[0]}, skinning and blendshapes are now detached"+ )+ assert int(faces.max()) < positions.shape[0], "a face indexes past the vertex array"+ print(f"ok head topology preserved ({positions.shape[0]} vertices, {len(faces)} tris)")++ # ── 3. blendshapes ────────────────────────────────────────────────────────+ targets = _morph_target_count(out)+ assert targets == tpl_targets, f"morph targets lost: {targets} vs template {tpl_targets}"+ assert targets >= 52, f"expected at least the 52 ARKit blendshapes, found {targets}"+ print(f"ok all {targets} morph targets intact (ARKit blendshapes + visemes)")++ # ── 4. rig ────────────────────────────────────────────────────────────────+ prim = glb_ops._find_head_prim(out)+ assert prim.attributes.JOINTS_0 is not None, "JOINTS_0 gone, head is no longer skinned"+ assert prim.attributes.WEIGHTS_0 is not None, "WEIGHTS_0 gone, head is no longer skinned"+ assert out.skins, "no skin in the output GLB, the avatar cannot be animated"+ joint_count = len(out.skins[0].joints or [])+ assert joint_count > 0, "skeleton has no joints"+ print(f"ok rig intact (skinned head, {joint_count} joints)")++ # ── 5. the photo landed ───────────────────────────────────────────────────+ texture = np.array(_head_texture(out), dtype=np.int16)+ assert texture.shape == tpl_texture.shape, "skin texture changed size"+ changed = float(np.mean(np.abs(texture - tpl_texture) > 6))+ assert changed > 0.02, (+ f"only {changed * 100:.2f}% of skin texels differ from the template, "+ "the photograph did not reach the texture"+ )+ print(f"ok skin texture repainted ({changed * 100:.1f}% of texels moved)")++ # ── 6. the identity morph ran ─────────────────────────────────────────────+ moved = float(np.linalg.norm(positions - tpl_positions, axis=1).max())+ assert moved > 1e-4, (+ "head geometry is byte-identical to the template, the identity morph "+ "did not run (check GEOMETRY_MORPH and the yaw gate)"+ )+ print(f"ok head geometry morphed to the face (max vertex move {moved * 1000:.1f} mm)")++ # ── 7. a faceless photo is a caller error, not an internal one ─────────────+ # Synthesised on purpose: the assertion is about the *classification* of a+ # rejection, and a plain gradient is unambiguously faceless in a way no+ # collected photograph can be guaranteed to stay.+ grad = np.tile(+ np.linspace(40, 210, 384, dtype=np.uint8)[:, None, None], (1, 384, 3)+ )+ buf = io.BytesIO()+ Image.fromarray(grad, "RGB").save(buf, format="PNG")+ faceless = "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii")+ try:+ face_pipeline.process("smoke-faceless", [faceless], "neutral")+ except face_pipeline.InputError as exc:+ assert "face" in str(exc).lower(), f"unhelpful rejection reason: {exc}"+ print(f"ok faceless photo rejected as an input error ({exc})")+ else:+ raise AssertionError("a faceless photo produced an avatar instead of a rejection")++ print("\nall 7 smoke assertions passed, core path is healthy")+ return 0+++if __name__ == "__main__":+ try:+ raise SystemExit(main(sys.argv[1:]))+ except AssertionError as exc:+ print(f"FAIL: {exc}", file=sys.stderr)+ raise SystemExit(1)