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.

feat(avatar-reconstruction): yaw gate for single-view geometry, CPU-only worker

nirholas77a27bc243bc
diff --git a/.gitignore b/.gitignore
index dff19fada..12a0e6a2e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -411,3 +411,4 @@ SECURITY-AUDIT.md
# Scratch harnesses for local 3D/pose debugging — never committed.
scripts/.scratch/
+/workers/avatar-reconstruction/eval/adversarial/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b2537e88b..9903177b5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,11 +10,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The Story So Far** (`/timeline`) — three.ws's history as an explorable 3D scene: every launch, partnership, listing, and milestone laid out along a path you can orbit in 360° or walk end to end, with a synced scrubber and source links.
- **three.ws is an OpenAI Select Partner** (`/openai`) — three.ws is an OpenAI Select Partner in the OpenAI Partner Network. Connect the free three.ws 3D Studio MCP server to ChatGPT and turn a prompt into an interactive, riggable, AR-ready 3D model inline in the conversation.
- **three.ws Named an OpenAI Select Partner** (`/blog/three-ws-openai-select-partner`) — three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.
+- **Check any 3D tool result against the Spatial MCP standard, in the page, as you type** — Spatial MCP is our open standard for handing back a live 3D scene as an AI tool result instead of a link, and until now three.ws/spatial-mcp only claimed that the payloads it displayed were valid. Now it proves it. The conformance checker the standard ships runs in your browser, and every scene on the page carries its verdict underneath: conformant, zero errors, and which version of the shape it speaks. Below that is a box you can paste your own tool result into. It checks the payload as you type and, instead of answering yes or no, names the exact field that is wrong and what it should be, so anyone writing an adapter for their own 3D tool can debug it on the page without reading the specification or installing anything. Load the deliberately broken example to see the whole thing at once: six mistakes, each naming its own field, and the fallback a real host would show a user for a payload it cannot render. Anything that passes renders immediately in the same viewer. The checker is the same code our own servers validate with, now published at a fixed address so third parties can import it directly, which means what the page tells you about a payload is exactly what a build will tell you. Two safeguards landed alongside it, because this page had been quietly showing two empty frames: one refuses to ship a page that asks for a file by a path that will not resolve, and one loads the page for real in a browser and fails if a scene does not appear or an asset it depends on has gone missing. The first immediately found the same defect on three more live pages, all fixed in this release: the agent editor was loading none of its code, the Czech landing page none of its styling, and the first-meet page none of its script. (`/spatial-mcp`) `[feature, fix, infra]`
- **Crypto API: automatic upstream failover ends most rate-limit errors** — The unified crypto API (/api/v1/x) no longer fails your call just because one upstream host had a bad moment. When a provider is backed by a pool of interchangeable hosts (the Solana read endpoints front the platform's full RPC pool), a rate-limited, unreachable, or erroring host now fails over to a healthy alternate within the same request. The API also remembers which host just failed for a short window, so during an outage only the first request pays the discovery cost and everything after routes straight to a working host. Rate-limit passthrough was the second-largest error class on the aggregator; this removes it for pooled providers. (`/crypto-api`) `[improvement, infra]`
- **Dress any avatar: the wardrobe now adds clothes, not just recolours them** — Until now the wardrobe could only recolour or hide the clothes an avatar was generated with. It can now put NEW clothes on: the avatar editor's Wardrobe tab gained a Closet with racks of catalog pieces (tops, bottoms, footwear, outerwear, hair, headwear, glasses, accessories). Click a piece and it binds to your avatar's skeleton and moves with every animation, whatever generator the avatar came from: forge characters, selfie reconstructions and uploaded models all work, because garments are fitted to the skeleton at wear-time instead of being authored for one specific body. The body is masked under whatever you wear so skin never pokes through the cloth, a piece that cannot fit a particular skeleton politely refuses instead of deforming into spaghetti, and every download is integrity-checked against the catalog before it touches your avatar. Saved outfits persist: the downloadable and embedded versions of your avatar come out dressed too. (`/avatar-edit`) `[feature]`
- **Our crypto API no longer reports itself as broken to the directories that rate it** — Agent directories and uptime monitors discover an x402 API by calling every endpoint it advertises with no arguments, to check the endpoint is alive and knows its own price. Our paid-only endpoints answered that correctly with a payment challenge, but the free-tier ones ran argument validation first and answered with an error, so about two dozen perfectly healthy endpoints were being graded as failing by a public trust monitor, roughly 14,000 times a month. A parameterless call now returns the standard 402 challenge on every endpoint, with the argument you would need named in an X-Param-Error header. Nothing changes for real callers: send any argument, even an empty one, and you get the specific validation error as before. The same probes were also the single biggest source of noise in our own error metrics, so a genuine outage in the crypto API is now visible instead of buried. (`/crypto-api`) `[fix, improvement]`
- **Our x402 facilitator now publishes a standard discovery catalog** — The three.ws self-hosted x402 facilitator serves a new public endpoint, GET /api/x402-facilitator/discovery/resources, listing every paid endpoint on the platform in the standard facilitator catalog format that x402 explorers and aggregators (like x402scan) crawl. It is the same catalog as /.well-known/x402.json, so listings on third-party explorers always match what the platform actually charges. This is groundwork for three.ws payments showing up on ecosystem explorers without routing settlement through any third party. (`/docs/x402-ring-economy`) `[feature, infra]`
- **Selfie avatars now match the shape of your face, not just the colour of it** — The selfie-to-avatar engine used to do one thing: take the face from your photo and paint it onto a standard head. From straight on it looked convincing, but the skull underneath was the same for everyone, so the moment the avatar turned it stopped being you. It now reshapes the head itself to your face: width, jaw, chin, cheekbones, brow, and how far the nose projects. That step had been written and tested for a while but had never actually reached the servers, so every avatar made until today was built the old way. Making it live also turned up a flaw in how the photo was read. Face measurements arrived scaled to the picture's width and height separately, which means a tall photo stretched the face before anything else happened, and that stretch was then treated as part of your bone structure. In practice the shape of your avatar's head partly depended on whether you shot the photo tall or square, which is not something anyone would expect. Measurements are now taken in true proportions, so the same face gives the same head regardless of how the photo was framed. Finally, the limits controlling how far the head is allowed to move toward your real shape were set before there was any way to measure the result. They were far too cautious, holding the head back to about two centimetres of change and quietly discarding real differences between faces. Measured across a forty-face test set covering a wide range of ages, complexions, beards, glasses and head coverings, retuning them cut the remaining shape error by 46 percent, and no face in the set came out worse. Choosing that limit needed a second measurement, because a test set of clean, well-lit photos will always argue for removing the limit entirely: it contains nothing for the limit to catch. So each test face was also degraded the way real photos are, with camera shake, a turned head, hair across the face, a dim room and a heavily shrunk upload, and checked for whether the same person still came out with the same head. The setting we shipped is the point where matching your face stops improving but sensitivity to photo quality keeps rising. In total, avatars now capture about 60 percent of the difference between a generic head and your real one, up from 26 percent. Rebuild your avatar at /create/selfie to get one made the new way. (`/create/selfie`) `[improvement, fix]`
+- **Signing avatars now sign whole sentences, touch what they are supposed to touch, and can raise an eyebrow** — Six things changed in the signing avatar. It was lowering its arms all the way to its sides between every single word, so a sentence read as a list of unrelated words; now the hands rise once at the start and lower once at the end, the way a person signs, and everything in between stays up in signing space. Signs that involve the two hands touching, like fall, help, good and again, were positioning each hand at fixed coordinates and hoping they met; they are now solved from the actual shape of the posed hand, so the fingers land on the palm even on an avatar with longer fingers or bigger hands, and the same is true of signs that touch the face, which previously buried the fingertips somewhere inside the head. The avatar can now raise its eyebrows: American Sign Language carries grammar on the face, where raised brows make a yes-or-no question and furrowed brows a what-or-why question, and signs now carry those markers to any avatar that has facial expressions built in. You can slow the signing down to three-quarter or half speed, which learners and many Deaf viewers want and which no amount of replaying a video at full speed substitutes for. You can switch the avatar to sign left-handed, because roughly one signer in ten is left-dominant and signing left-handed is not a mistake to be corrected. And the vocabulary is now checked automatically against two rules that hold across the whole language, so a new sign has to be well-formed and not merely render without crashing. (`/sign-language`) `[improvement, feature]`
- **Solana reads on the crypto API stop failing when one RPC host throttles us** — The Solana endpoints on the public crypto API (balance, token holdings, token supply, largest holders, transaction, account, priority fees) were pointed at a single RPC host. Whenever that host rate-limited us, the caller got the rate-limit error even though the platform keeps a priority-ordered pool of other RPC endpoints for exactly this situation. Those calls now move to the next healthy host automatically, up to three per request, and a host that has just failed is skipped for the next 30 seconds so one bad host does not slow down every request behind it. A genuinely bad request, like a malformed address, still returns its error immediately instead of being retried. This was the second-largest error class on the API. (`/crypto-api`) `[fix, improvement]`
- **The KOL Tracker is now reachable, and its numbers are real** — The KOL Tracker page shipped listed in the sitemap but with no route behind it, so three.ws/tracker returned a 404 for everyone who followed the link, and the API behind it was answering with three placeholder rows left over from a test fixture. Both are fixed. The page is served, and it now ranks real Solana traders from the live kolscan board: realized profit, win rate and trade count for the 24h, 7d and 30d windows, enriched with our own on-chain FIFO profit calculation wherever we have the trades for a wallet. Every row states where its number came from, and when a source is unreachable the board shows an honest empty state instead of inventing traders. A new test blocks the whole class of mistake: any page advertised in the site index that has no route, or that never gets built, now fails the suite before it can reach production. (`/tracker`) `[fix, feature]`
- **The signing avatar's arm now sits where a signer's arm sits, and it signs real words** — The signing avatar had a broken arm. Its handshapes were right, but the arm carrying them swung out to the side and behind the body, and the clip also dragged the avatar about a metre down through the floor, so you were watching correct fingerspelling performed somewhere over the avatar's shoulder. The cause was that the arm was posed with rotations written against a skeleton convention our reference avatar does not use. Arms are now solved instead of guessed: the code measures the actual skeleton (which way each bone points, how long it is, which way each palm faces) and then runs real inverse kinematics to put the wrist at a specific point in front of the body, with the elbow hanging where an elbow hangs. Fingerspelling now happens where signers do it, in front of the dominant shoulder at jaw height with the palm facing you, and the letters themselves are unchanged, to the digit. Because a hand can now be sent to a place on the body, the avatar also has a real sign vocabulary for the first time: thirty-two everyday words including hello, thank you, please, sorry, yes, no, happy, help, love, want, welcome, name, y'all and finish, two-handed where the sign is two-handed. Type a sentence and the words with signs are signed while the rest is fingerspelled, in one continuous motion, and the page tells you which was which. There is a new section on the sign-language page listing every word it can sign, each one playable. Both arms are now posed throughout, the idle hand rests at the side instead of hanging oddly, the avatar breathes during long holds, and the camera crops closer so you can actually see the hands. (`/sign-language`) `[improvement, fix]`
@@ -23,6 +25,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The trading postmortem's findings are now enforced in code** — Our published audit of the fleet's first 90 real trades ended with a list of fixes, and four of them are now live code instead of intentions. First, the overconfidence ceiling: the audit showed AI judge verdicts at 0.7 confidence performed best while verdicts above 0.9 went winless, so each AI-judged strategy now carries a confidence ceiling next to its floor, and a screaming-confident verdict is recorded but never funded. Second, named-model integrity: during the audit most calls to the named models were actually answered by cheaper fallback models, muddying the model-vs-model comparison, so the Grok and Claude strategies are now strict and will pause rather than trade on a fallback's judgment. Third, the liquidity-decay exit: a coin nobody is trading at all now gets sold after five quiet minutes instead of squatting on a trading slot for the full half-hour timeout, and this only applies underwater, so quiet winners still ride. Fourth, and most important operationally: the audit found two of the fleet's learning loops had been silently dead for two days behind green health checks, so a new hourly watchdog now asks every learning loop when it last actually wrote a row, and pages us when any answer is too old. A loop that has never written a row counts as the worst finding, not a pass. (`/docs/trading-experiment`) `[improvement, fix, infra]`
- **three.ws is an OpenAI Select Partner** — three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. A new page at /openai lays out everything the platform already ships on OpenAI surfaces: the free, keyless 3D Studio MCP connector for ChatGPT with nine tools (text to 3D, avatars, auto-rigging, conversational refinement, and a living agent body), the custom GPT Actions surface for plans without connectors, one-tap AR on iOS and Android, and Spatial MCP, the open CC0 shape for returning a live 3D scene as a tool result. The partner directory at /partners was also rewritten to list only the programs three.ws is actually enrolled in today, with NVIDIA correctly described as Inception membership. (`/openai`) `[feature, docs]`
- **Trading arms now earn their freedom from their own track record** — The autonomous trading fleet used to give every strategy the same leash: the same limits on how far its settings could move, the same short list of settings it could change, and the same information in front of it before each decision. A strategy that had been making money for weeks was kept in exactly the same box as one that had never had a winning day. Now each arm is graded on its own real, on-chain results and placed in one of four tiers. A profitable arm gets a wider range to work in, moves faster, unlocks settings a losing arm can't touch (which launches it hunts, how confident it needs to be before buying, and the take-initials exit that banks your stake at 2x and lets the rest ride), takes a bigger share of the fleet's fixed daily budget, and is shown far more evidence before it decides: how often launches actually succeed, which signals genuinely predict a winner, its own trading history, and how well its own past calls turned out. A bleeding arm is held tighter instead. Grading is on realized profit rather than win rate, so an arm that wins only a third of its trades but makes real money is rewarded, while one that wins most of its trades and still loses money is not. Every tier is re-earned continuously, so an arm that stops paying loses the extra rope automatically. None of it can touch the safety limits: the trade firewall, the daily loss cap, position limits, and a hard stop-loss apply at every tier, no matter how well an arm is doing. Each arm's tier and the evidence behind it are visible on the experiments board. (`/sniper/experiments`) `[feature, improvement]`
+- **Turned-away selfies no longer guess at the shape of your head** — When an avatar is built from a single photo, the half of your face pointing away from the camera is not in the picture at all. Up to now the shape step treated its estimate of that hidden half as though it were measured, so a photo taken at a steep angle could push made-up structure into the skull. The engine now checks how far the head is turned before reshaping anything. Past about a third of a turn it keeps the photo's colour and detail but leaves the head shape alone, which is the honest answer when the information simply is not there. The limit sits far away from ordinary selfies: across a forty-face test set of front-facing photos, the most turned one measured under three degrees against a threshold of thirty-five, so normal photos are unaffected. This came out of deliberately testing the engine on things that are not the user's face, including pets, statues, shop mannequins, carnival masks, faces on posters and phone screens, group shots and badly blurred or backlit photos. That testing produced a reassuring result worth stating plainly: none of them could push the avatar outside the range of head shapes real faces produce, because several safeguards already compound to keep any result on a plausible human head. (`/create/selfie`) `[improvement]`
- **Type a garment, get a wearable: the Garment Forge** — The wardrobe's closet no longer depends on hand-authored pieces. A new generation service turns a plain text prompt ("a white oxford dress shirt") into a finished catalog garment: it photographs the idea with the platform's image model, sculpts a textured 3D mesh on the GPU fleet, fits the piece onto the canonical body, rigs it so it moves with every animation, and publishes it to the public wardrobe catalog with its manifest and thumbnail. Every published piece is validated end to end (including the 60% skeleton-binding gate) before it can ever reach an avatar. `[feature, infra]`
## 2026-07-24
diff --git a/data/changelog.json b/data/changelog.json
index 18b34e512..f2caf8f20 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,25 @@
{
"$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-07-25",
+ "title": "Signing avatars now sign whole sentences, touch what they are supposed to touch, and can raise an eyebrow",
+ "summary": "Six things changed in the signing avatar. It was lowering its arms all the way to its sides between every single word, so a sentence read as a list of unrelated words; now the hands rise once at the start and lower once at the end, the way a person signs, and everything in between stays up in signing space. Signs that involve the two hands touching, like fall, help, good and again, were positioning each hand at fixed coordinates and hoping they met; they are now solved from the actual shape of the posed hand, so the fingers land on the palm even on an avatar with longer fingers or bigger hands, and the same is true of signs that touch the face, which previously buried the fingertips somewhere inside the head. The avatar can now raise its eyebrows: American Sign Language carries grammar on the face, where raised brows make a yes-or-no question and furrowed brows a what-or-why question, and signs now carry those markers to any avatar that has facial expressions built in. You can slow the signing down to three-quarter or half speed, which learners and many Deaf viewers want and which no amount of replaying a video at full speed substitutes for. You can switch the avatar to sign left-handed, because roughly one signer in ten is left-dominant and signing left-handed is not a mistake to be corrected. And the vocabulary is now checked automatically against two rules that hold across the whole language, so a new sign has to be well-formed and not merely render without crashing.",
+ "tags": [
+ "improvement",
+ "feature"
+ ],
+ "link": "/sign-language"
+ },
+ {
+ "date": "2026-07-25",
+ "title": "Turned-away selfies no longer guess at the shape of your head",
+ "summary": "When an avatar is built from a single photo, the half of your face pointing away from the camera is not in the picture at all. Up to now the shape step treated its estimate of that hidden half as though it were measured, so a photo taken at a steep angle could push made-up structure into the skull. The engine now checks how far the head is turned before reshaping anything. Past about a third of a turn it keeps the photo's colour and detail but leaves the head shape alone, which is the honest answer when the information simply is not there. The limit sits far away from ordinary selfies: across a forty-face test set of front-facing photos, the most turned one measured under three degrees against a threshold of thirty-five, so normal photos are unaffected. This came out of deliberately testing the engine on things that are not the user's face, including pets, statues, shop mannequins, carnival masks, faces on posters and phone screens, group shots and badly blurred or backlit photos. That testing produced a reassuring result worth stating plainly: none of them could push the avatar outside the range of head shapes real faces produce, because several safeguards already compound to keep any result on a plausible human head.",
+ "tags": [
+ "improvement"
+ ],
+ "link": "/create/selfie"
+ },
{
"date": "2026-07-25",
"title": "Our x402 facilitator now publishes a standard discovery catalog",
@@ -71,6 +90,17 @@
],
"link": "/docs/trading-experiment"
},
+ {
+ "date": "2026-07-25",
+ "title": "Check any 3D tool result against the Spatial MCP standard, in the page, as you type",
+ "summary": "Spatial MCP is our open standard for handing back a live 3D scene as an AI tool result instead of a link, and until now three.ws/spatial-mcp only claimed that the payloads it displayed were valid. Now it proves it. The conformance checker the standard ships runs in your browser, and every scene on the page carries its verdict underneath: conformant, zero errors, and which version of the shape it speaks. Below that is a box you can paste your own tool result into. It checks the payload as you type and, instead of answering yes or no, names the exact field that is wrong and what it should be, so anyone writing an adapter for their own 3D tool can debug it on the page without reading the specification or installing anything. Load the deliberately broken example to see the whole thing at once: six mistakes, each naming its own field, and the fallback a real host would show a user for a payload it cannot render. Anything that passes renders immediately in the same viewer. The checker is the same code our own servers validate with, now published at a fixed address so third parties can import it directly, which means what the page tells you about a payload is exactly what a build will tell you. Two safeguards landed alongside it, because this page had been quietly showing two empty frames: one refuses to ship a page that asks for a file by a path that will not resolve, and one loads the page for real in a browser and fails if a scene does not appear or an asset it depends on has gone missing. The first immediately found the same defect on three more live pages, all fixed in this release: the agent editor was loading none of its code, the Czech landing page none of its styling, and the first-meet page none of its script.",
+ "tags": [
+ "feature",
+ "fix",
+ "infra"
+ ],
+ "link": "/spatial-mcp"
+ },
{
"date": "2026-07-25",
"title": "The Spatial MCP reference renderer actually renders again",
diff --git a/docs/avatar-fidelity-program.md b/docs/avatar-fidelity-program.md
index d4200a4af..806f4230c 100644
--- a/docs/avatar-fidelity-program.md
+++ b/docs/avatar-fidelity-program.md
@@ -85,13 +85,40 @@ each face is degraded on the fly (blur, 12° turn, occlusion, dim, 1/6 resolutio
and scored on whether the same person still yields the same head. Fidelity and
stability pull opposite ways, and shipped parameters sit at the knee (Track 1).
-**The remaining gap is the confidently-wrong detection.** All 75 degraded images
-still produced a face detection, so the regime that matters most is untested. A
-detection *failure* is safe — the job falls back to texture-only rather than
-morphing to garbage — but a detector returning a confident landmark set for the
-wrong thing (a face in a poster, a pet, a pattern in the background) is not, and
-nothing here bounds it. Closing this needs samples severe enough to break
-detection outright, plus non-face and multi-face images.
+The confidently-wrong detection is covered too, by a 16-sample adversarial set
+([`eval/make_adversarial.py`](../workers/avatar-reconstruction/eval/make_adversarial.py))
+spanning non-faces (pet, statue, doll, mask, mannequin), depicted faces (poster,
+phone screen, painting, magazine), crowds, and out-of-envelope shots
+(near-profile, hard backlight, motion blur, macro), audited by
+[`eval/detection_guard.py`](../workers/avatar-reconstruction/eval/detection_guard.py).
+That audit produced three findings, one of which killed the guard I was about to
+build:
+
+**A face-plausibility gate cannot work — do not rebuild one.** The natural design
+is to align landmarks to the canonical face and reject a large residual. MediaPipe
+FaceMesh is a *fitted model*: it does not decide whether something is a face, it
+reports where a face would be. A golden retriever scored 0.4758, a *better*
+canonical fit than all 40 real humans (0.5035-0.5238). Any threshold separating
+them rejects real people first.
+
+**The catastrophic failure mode does not exist in this architecture.** Head
+displacement from the template: real faces 0.2713-0.2839, every detected
+adversarial input 0.2586-0.2929, and **zero** ungated adversarial inputs distort
+more than a real face. A dog photo yields a slightly unusual *human* head, not a
+monstrous one. Four mechanisms compose to guarantee it: canonical alignment
+removes pose and scale, `strength` damps the residual, the per-point clamp bounds
+outliers, and the TPS off-face mask confines deformation to the face. Guarding the
+mesh against wrong detections is therefore unnecessary — which is worth knowing
+before someone spends a sprint on it.
+
+**Yaw was the one thing worth gating.** Real frontals peak at 2.7°; the
+near-profile shot reads 58.6° and was the sole input pushing the head outside the
+real-face band. Past roughly a third of a turn the far side of the face is
+self-occluded, so its depth is extrapolation and the morph fits guesswork as bone
+structure. `face_pipeline.MAX_MORPH_YAW_DEG` (35°) now skips the morph and keeps
+texture transfer above that, clearing every genuine frontal by ~13x. Photos of
+photos sit at 9-18°, already produce in-band heads, and are deliberately not
+blocked.
### Track 1 — Ship the morph that is already written `[done]`
@@ -161,13 +188,30 @@ shadow, ears, the scalp, under the jaw — none of it is in the photo, and today
those regions fall back to a tinted template texture. That mismatch is what
reads as "avatar" rather than "person" the moment the head turns.
-Imagen inpainting on Vertex AI fills the unseen regions conditioned on the
-observed face, in UV space so the result stays inside the template's texture
-layout. Pure GCP, pre-approved, no licence exposure, usage-priced.
+Two candidate mechanisms, and the measurement in Track 3 decides between them.
-ISE will not move — it is a geometry metric. This track needs a texture metric
-alongside it, and that is part of the track: masked SSIM / LPIPS against held-out
-views, plus a seam-continuity check across the UV boundary.
+**Do not inpaint the UV atlas directly.** A UV layout is not a photograph; a
+generative image model conditioned on one will produce photographically plausible
+but UV-incoherent content, and the seams land exactly where the head turns.
+
+**Do synthesise additional camera views and warp them through the existing path.**
+Each view goes through the same landmark-driven TPS warp as the frontal
+(`_warp_face_to_uv`), so coverage of cheeks, ears and jawline is UV-coherent by
+construction rather than by hoping the model understood the atlas.
+
+Crucially, the finding that kills multi-view for *geometry* (Track 3) does not
+kill it for *texture*. Rotated synthesised views measure as a different person
+geometrically, but the same-pose control shows appearance is reproduced faithfully
+(0.0069 divergence), and texture needs plausible skin, not millimetre-accurate
+landmarks. A 3/4 view that is 0.03 off in face shape still carries the correct
+complexion, beard, hairline and ear into the regions a frontal cannot see. The
+severity of the error differs by an order of magnitude between the two uses.
+
+ISE will not move — it is a geometry metric, texture-blind by design. This track
+must bring its own: masked SSIM / LPIPS against held-out views, plus a
+seam-continuity check across the UV boundary. Gate the synthesised view on the
+same-pose identity check before compositing, so a bad generation is rejected
+rather than painted on.
### Track 3 — Dense identity geometry by per-subject optimisation
@@ -186,10 +230,29 @@ current head, compare to the photo, backpropagate to vertex positions, repeat.
survives. Vertex count and order never change, so `glb_ops.set_head_geometry`
writes the result back without touching skinning or morph targets — the
property `test_face_geometry.py` already pins.
-- **Multi-view from one photo:** synthesise consistent 3/4 and profile views
- with Vertex image models, then fit against all views at once. Single-view
- depth ambiguity is the ceiling on shape accuracy, and this attacks it directly.
- The multi-view fusion pattern already exists in `workers/model-hunyuan3d`.
+- **Multi-view from one photo — MEASURED AND REJECTED for geometry.** The plan
+ was to synthesise 3/4 and profile views with a Vertex image model and fit
+ against all of them at once. It does not survive contact with the identity
+ metric. Asking `gemini-2.5-flash-image` for the same person turned 30°:
+
+ | comparison | identity-shape divergence |
+ |---|---|
+ | same-pose regeneration (control) | **0.0069** |
+ | synthesised 3/4 view (19.7° yaw) | 0.0396 |
+ | a *different real person* | 0.0358 (range 0.0268-0.0489) |
+
+ The control matters: at unchanged pose the model reproduces the person ~5x more
+ faithfully than a stranger, so identity preservation is genuinely good. But once
+ the head is rotated, the recoverable face geometry is **statistically
+ indistinguishable from a different person**. Whether the cause is the model
+ drifting under pose change or MediaPipe's depth being pose-dependent (likely
+ both), the signal is too degraded to fit a skull to. Feeding it to a
+ differentiable fit would optimise confidently toward someone who does not exist.
+
+ Do not revive this leg on synthesised views. It needs genuine multi-pose capture
+ — several real frames of the actual user, which the `/scan` flow already
+ collects — and the metric above is the acceptance test any such source must pass
+ before it drives geometry.
No third-party weights, no face dataset, no licence question: it optimises
against the user's own photo. It is GPU-hungry per avatar, which is exactly the
diff --git a/docs/ops/gcp-credits-plan.md b/docs/ops/gcp-credits-plan.md
index 587d98747..a4f99cbe3 100644
--- a/docs/ops/gcp-credits-plan.md
+++ b/docs/ops/gcp-credits-plan.md
@@ -10,18 +10,20 @@ Six GPU services share those 3 GPUs:
| Service | Role | minScale | maxScale |
|---|---|---|---|
-| model-trellis | free text-to-3D lane (quality already maxed: steps 40, 4K textures) | 1 | 1 |
-| model-hunyuan3d | high-fidelity reconstruction + multi-view fusion | 1 | 1 |
+| model-trellis | free text-to-3D lane (quality already maxed: steps 40, 4K textures) | 1 | 3 |
+| model-hunyuan3d | high-fidelity reconstruction + multi-view fusion | 1 | 2 |
| model-triposr | fast image-to-3D fallback | 0 | 2 |
| model-triposg | image-to-3D | 0 | 2 |
-| unirig | auto-rigging | 1 | 2 |
-| avatar-reconstruction | photo-to-avatar | 1 | 3 |
+| ~~unirig~~ | retired (superseded by `workers/rig`) — **holds no GPU**, minScale 0 | 0 | — |
+| ~~avatar-reconstruction~~ | photo-to-avatar — **moved to CPU-only 2026-07-25, holds no GPU** (see below) | 1 | 6 |
| model-hunyuan3d-21 | PBR realism lane, L4 build (min 0 since 2026-07-17; a pinned min 1 here starved every other rollout). KNOWN-BROKEN for actual jobs: 18 GiB tmpfs weight staging + 14 GiB model OOMs the 32 Gi L4 ceiling (signal 9 mid-load); see workers/model-hunyuan3d/README.md | 0 | 1 |
`model-hunyuan3d-21-rtx` (same 2.1 PBR lane, warm min 1 / max 4) does NOT draw
from this pool; it runs on the RTX PRO 6000 quota below.
-Four warm instances against a quota of 3 means the fleet is permanently at its ceiling: any concurrent generation forces failover to lower-quality lanes or queues. **This quota, not model parameters, is the current cap on 3D output quality and reliability.**
+**Resolved 2026-07-25 by returning a GPU nobody was using.** `avatar-reconstruction` held one of the three L4s solely for background removal (rembg / onnxruntime-gpu); every other stage (MediaPipe, TPS, GLB ops) is CPU-bound. Measured: rembg took **~2.2 s per job with the L4 attached versus ~1.9 s on a plain CPU box** — the CUDA provider was never engaging and the GPU was buying nothing. It now runs `--gpu=0 --cpu=8`, which is *faster* (end-to-end 4.2-4.7 s, was 4.8-5.8 s) at identical output quality (mean ISE 0.1595 both ways).
+
+Warm GPU demand therefore went from **3 of 3 (zero headroom)** to **2 of 3**. `model-trellis` (maxScale 3) and `model-hunyuan3d` (maxScale 2) were already permitted to burst and simply could not; that headroom is now real with no further config change. The lesson generalises: **before requesting more GPU quota, verify each holder actually uses its GPU.** A worker whose only GPU stage is an ONNX/rembg step is a prime suspect — check stage timings in its logs against the same stage on CPU.
- A quota preference exists: `l4-no-zonal-us-central1-8`, raised to **preferred 16** on 2026-07-16 (was 8). Still reconciling as of 2026-07-17. Google reviews asynchronously; check with:
`gcloud alpha quotas preferences list --project=aerial-vehicle-466722-p5`
diff --git a/public/changelog.json b/public/changelog.json
index f96d598d2..4d8aef5d5 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-25T10:10:06.549Z",
+ "generated_at": "2026-07-25T10:29:26.480Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -46,6 +46,18 @@
"launch"
]
},
+ {
+ "date": "2026-07-25",
+ "type": "update",
+ "title": "Check any 3D tool result against the Spatial MCP standard, in the page, as you type",
+ "summary": "Spatial MCP is our open standard for handing back a live 3D scene as an AI tool result instead of a link, and until now three.ws/spatial-mcp only claimed that the payloads it displayed were valid. Now it proves it. The conformance checker the standard ships runs in your browser, and every scene on the page carries its verdict underneath: conformant, zero errors, and which version of the shape it speaks. Below that is a box you can paste your own tool result into. It checks the payload as you type and, instead of answering yes or no, names the exact field that is wrong and what it should be, so anyone writing an adapter for their own 3D tool can debug it on the page without reading the specification or installing anything. Load the deliberately broken example to see the whole thing at once: six mistakes, each naming its own field, and the fallback a real host would show a user for a payload it cannot render. Anything that passes renders immediately in the same viewer. The checker is the same code our own servers validate with, now published at a fixed address so third parties can import it directly, which means what the page tells you about a payload is exactly what a build will tell you. Two safeguards landed alongside it, because this page had been quietly showing two empty frames: one refuses to ship a page that asks for a file by a path that will not resolve, and one loads the page for real in a browser and fails if a scene does not appear or an asset it depends on has gone missing. The first immediately found the same defect on three more live pages, all fixed in this release: the agent editor was loading none of its code, the Czech landing page none of its styling, and the first-meet page none of its script.",
+ "link": "/spatial-mcp",
+ "tags": [
+ "feature",
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-07-25",
"type": "update",
@@ -100,6 +112,17 @@
"fix"
]
},
+ {
+ "date": "2026-07-25",
+ "type": "update",
+ "title": "Signing avatars now sign whole sentences, touch what they are supposed to touch, and can raise an eyebrow",
+ "summary": "Six things changed in the signing avatar. It was lowering its arms all the way to its sides between every single word, so a sentence read as a list of unrelated words; now the hands rise once at the start and lower once at the end, the way a person signs, and everything in between stays up in signing space. Signs that involve the two hands touching, like fall, help, good and again, were positioning each hand at fixed coordinates and hoping they met; they are now solved from the actual shape of the posed hand, so the fingers land on the palm even on an avatar with longer fingers or bigger hands, and the same is true of signs that touch the face, which previously buried the fingertips somewhere inside the head. The avatar can now raise its eyebrows: American Sign Language carries grammar on the face, where raised brows make a yes-or-no question and furrowed brows a what-or-why question, and signs now carry those markers to any avatar that has facial expressions built in. You can slow the signing down to three-quarter or half speed, which learners and many Deaf viewers want and which no amount of replaying a video at full speed substitutes for. You can switch the avatar to sign left-handed, because roughly one signer in ten is left-dominant and signing left-handed is not a mistake to be corrected. And the vocabulary is now checked automatically against two rules that hold across the whole language, so a new sign has to be well-formed and not merely render without crashing.",
+ "link": "/sign-language",
+ "tags": [
+ "improvement",
+ "feature"
+ ]
+ },
{
"date": "2026-07-25",
"type": "update",
@@ -188,6 +211,16 @@
"improvement"
]
},
+ {
+ "date": "2026-07-25",
+ "type": "update",
+ "title": "Turned-away selfies no longer guess at the shape of your head",
+ "summary": "When an avatar is built from a single photo, the half of your face pointing away from the camera is not in the picture at all. Up to now the shape step treated its estimate of that hidden half as though it were measured, so a photo taken at a steep angle could push made-up structure into the skull. The engine now checks how far the head is turned before reshaping anything. Past about a third of a turn it keeps the photo's colour and detail but leaves the head shape alone, which is the honest answer when the information simply is not there. The limit sits far away from ordinary selfies: across a forty-face test set of front-facing photos, the most turned one measured under three degrees against a threshold of thirty-five, so normal photos are unaffected. This came out of deliberately testing the engine on things that are not the user's face, including pets, statues, shop mannequins, carnival masks, faces on posters and phone screens, group shots and badly blurred or backlit photos. That testing produced a reassuring result worth stating plainly: none of them could push the avatar outside the range of head shapes real faces produce, because several safeguards already compound to keep any result on a plausible human head.",
+ "link": "/create/selfie",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-07-25",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 2753db85f..8263d20c5 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -38,6 +38,14 @@
<category>launch</category>
<description>three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.</description>
</item>
+ <item>
+ <title>Check any 3D tool result against the Spatial MCP standard, in the page, as you type</title>
+ <link>https://three.ws/spatial-mcp</link>
+ <guid isPermaLink="false">2026-07-25:Check any 3D tool result against the Spatial MCP standard, in the page, as you type</guid>
+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Spatial MCP is our open standard for handing back a live 3D scene as an AI tool result instead of a link, and until now three.ws/spatial-mcp only claimed that the payloads it displayed were valid. Now it proves it. The conformance checker the standard ships runs in your browser, and every scene on the page carries its verdict underneath: conformant, zero errors, and which version of the shape it speaks. Below that is a box you can paste your own tool result into. It checks the payload as you type and, instead of answering yes or no, names the exact field that is wrong and what it should be, so anyone writing an adapter for their own 3D tool can debug it on the page without reading the specification or installing anything. Load the deliberately broken example to see the whole thing at once: six mistakes, each naming its own field, and the fallback a real host would show a user for a payload it cannot render. Anything that passes renders immediately in the same viewer. The checker is the same code our own servers validate with, now published at a fixed address so third parties can import it directly, which means what the page tells you about a payload is exactly what a build will tell you. Two safeguards landed alongside it, because this page had been quietly showing two empty frames: one refuses to ship a page that asks for a file by a path that will not resolve, and one loads the page for real in a browser and fails if a scene does not appear or an asset it depends on has gone missing. The first immediately found the same defect on three more live pages, all fixed in this release: the agent editor was loading none of its code, the Czech landing page none of its styling, and the first-meet page none of its script.</description>
+ </item>
<item>
<title>Crypto API: automatic upstream failover ends most rate-limit errors</title>
<link>https://three.ws/crypto-api</link>
@@ -78,6 +86,14 @@
<category>improvement</category>
<description>The selfie-to-avatar engine used to do one thing: take the face from your photo and paint it onto a standard head. From straight on it looked convincing, but the skull underneath was the same for everyone, so the moment the avatar turned it stopped being you. It now reshapes the head itself to your face: width, jaw, chin, cheekbones, brow, and how far the nose projects. That step had been written and tested for a while but had never actually reached the servers, so every avatar made until today was built the old way. Making it live also turned up a flaw in how the photo was read. Face measurements arrived scaled to the picture's width and height separately, which means a tall photo stretched the face before anything else happened, and that stretch was then treated as part of your bone structure. In practice the shape of your avatar's head partly depended on whether you shot the photo tall or square, which is not something anyone would expect. Measurements are now taken in true proportions, so the same face gives the same head regardless of how the photo was framed. Finally, the limits controlling how far the head is allowed to move toward your real shape were set before there was any way to measure the result. They were far too cautious, holding the head back to about two centimetres of change and quietly discarding real differences between faces. Measured across a forty-face test set covering a wide range of ages, complexions, beards, glasses and head coverings, retuning them cut the remaining shape error by 46 percent, and no face in the set came out worse. Choosing that limit needed a second measurement, because a test set of clean, well-lit photos will always argue for removing the limit entirely: it contains nothing for the limit to catch. So each test face was also degraded the way real photos are, with camera shake, a turned head, hair across the face, a dim room and a heavily shrunk upload, and checked for whether the same person still came out with the same head. The setting we shipped is the point where matching your face stops improving but sensitivity to photo quality keeps rising. In total, avatars now capture about 60 percent of the difference between a generic head and your real one, up from 26 percent. Rebuild your avatar at /create/selfie to get one made the new way.</description>
</item>
+ <item>
+ <title>Signing avatars now sign whole sentences, touch what they are supposed to touch, and can raise an eyebrow</title>
+ <link>https://three.ws/sign-language</link>
+ <guid isPermaLink="false">2026-07-25:Signing avatars now sign whole sentences, touch what they are supposed to touch, and can raise an eyebrow</guid>
+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Six things changed in the signing avatar. It was lowering its arms all the way to its sides between every single word, so a sentence read as a list of unrelated words; now the hands rise once at the start and lower once at the end, the way a person signs, and everything in between stays up in signing space. Signs that involve the two hands touching, like fall, help, good and again, were positioning each hand at fixed coordinates and hoping they met; they are now solved from the actual shape of the posed hand, so the fingers land on the palm even on an avatar with longer fingers or bigger hands, and the same is true of signs that touch the face, which previously buried the fingertips somewhere inside the head. The avatar can now raise its eyebrows: American Sign Language carries grammar on the face, where raised brows make a yes-or-no question and furrowed brows a what-or-why question, and signs now carry those markers to any avatar that has facial expressions built in. You can slow the signing down to three-quarter or half speed, which learners and many Deaf viewers want and which no amount of replaying a video at full speed substitutes for. You can switch the avatar to sign left-handed, because roughly one signer in ten is left-dominant and signing left-handed is not a mistake to be corrected. And the vocabulary is now checked automatically against two rules that hold across the whole language, so a new sign has to be well-formed and not merely render without crashing.</description>
+ </item>
<item>
<title>Solana reads on the crypto API stop failing when one RPC host throttles us</title>
<link>https://three.ws/crypto-api</link>
@@ -142,6 +158,14 @@
<category>feature</category>
<description>The autonomous trading fleet used to give every strategy the same leash: the same limits on how far its settings could move, the same short list of settings it could change, and the same information in front of it before each decision. A strategy that had been making money for weeks was kept in exactly the same box as one that had never had a winning day. Now each arm is graded on its own real, on-chain results and placed in one of four tiers. A profitable arm gets a wider range to work in, moves faster, unlocks settings a losing arm can't touch (which launches it hunts, how confident it needs to be before buying, and the take-initials exit that banks your stake at 2x and lets the rest ride), takes a bigger share of the fleet's fixed daily budget, and is shown far more evidence before it decides: how often launches actually succeed, which signals genuinely predict a winner, its own trading history, and how well its own past calls turned out. A bleeding arm is held tighter instead. Grading is on realized profit rather than win rate, so an arm that wins only a third of its trades but makes real money is rewarded, while one that wins most of its trades and still loses money is not. Every tier is re-earned continuously, so an arm that stops paying loses the extra rope automatically. None of it can touch the safety limits: the trade firewall, the daily loss cap, position limits, and a hard stop-loss apply at every tier, no matter how well an arm is doing. Each arm's tier and the evidence behind it are visible on the experiments board.</description>
</item>
+ <item>
+ <title>Turned-away selfies no longer guess at the shape of your head</title>
+ <link>https://three.ws/create/selfie</link>
+ <guid isPermaLink="false">2026-07-25:Turned-away selfies no longer guess at the shape of your head</guid>
+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>When an avatar is built from a single photo, the half of your face pointing away from the camera is not in the picture at all. Up to now the shape step treated its estimate of that hidden half as though it were measured, so a photo taken at a steep angle could push made-up structure into the skull. The engine now checks how far the head is turned before reshaping anything. Past about a third of a turn it keeps the photo's colour and detail but leaves the head shape alone, which is the honest answer when the information simply is not there. The limit sits far away from ordinary selfies: across a forty-face test set of front-facing photos, the most turned one measured under three degrees against a threshold of thirty-five, so normal photos are unaffected. This came out of deliberately testing the engine on things that are not the user's face, including pets, statues, shop mannequins, carnival masks, faces on posters and phone screens, group shots and badly blurred or backlit photos. That testing produced a reassuring result worth stating plainly: none of them could push the avatar outside the range of head shapes real faces produce, because several safeguards already compound to keep any result on a plausible human head.</description>
+ </item>
<item>
<title>Type a garment, get a wearable: the Garment Forge</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 8f2d6e12d..79870e01e 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-25T10:10:06.543Z",
+ "generated_at": "2026-07-25T10:29:26.474Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/workers/avatar-reconstruction/cloudbuild.yaml b/workers/avatar-reconstruction/cloudbuild.yaml
index 2fa18b64d..8fb5c1d40 100644
--- a/workers/avatar-reconstruction/cloudbuild.yaml
+++ b/workers/avatar-reconstruction/cloudbuild.yaml
@@ -1,5 +1,5 @@
# Cloud Build pipeline: build the avatar-reconstruction Docker image and deploy
-# it to Cloud Run (GPU) in us-central1.
+# it to Cloud Run (CPU-only — see the deploy step) in us-central1.
#
# Substitution variables (override via --substitutions flag or trigger config):
# _REGION — Cloud Run region (default: us-central1)
@@ -7,7 +7,7 @@
# _REPO — Artifact Registry repo name (default: avatar-reconstruction)
# _GCS_BUCKET — Cloud Storage bucket for output GLBs
# _MIN_INSTANCES — minimum warm instances (default: 1)
-# _MAX_INSTANCES — maximum instances (default: 3)
+# _MAX_INSTANCES — maximum instances (default: 6)
#
# Required secrets in Secret Manager (must exist before first deploy):
# avatar-reconstruction-key — the API_KEY bearer secret
@@ -18,7 +18,8 @@ substitutions:
_REPO: avatar-reconstruction
_GCS_BUCKET: three-ws-avatar-reconstructions
_MIN_INSTANCES: "1" # keep one warm — face pipeline cold-start is ~15 s
- _MAX_INSTANCES: "3" # capped at 3 by GPU quota (NvidiaL4 no-zonal-redundancy)
+ _MAX_INSTANCES: "6" # no longer GPU-bound (see the deploy step) — CPU-only,
+ # so this scales on CPU quota rather than the 3-GPU pool
steps:
# ── Build ──────────────────────────────────────────────────────────────────
@@ -55,12 +56,23 @@ steps:
- --region=${_REGION}
- --platform=managed
- --port=8080
- # GPU: NVIDIA L4 (24 GB VRAM) — sufficient for InstantMesh-large
- - --gpu=1
- - --gpu-type=nvidia-l4
- - --no-gpu-zonal-redundancy
+ # NO GPU — deliberately. This service ran on an NVIDIA L4 for background
+ # removal (rembg/onnxruntime-gpu); every other stage (MediaPipe, TPS, GLB
+ # ops) is CPU-bound. Measured 2026-07-25: rembg took ~2.2 s per job with the
+ # L4 attached versus ~1.9 s on a plain CPU box, i.e. the CUDA provider was
+ # never actually engaging and the GPU bought nothing. Dropping it and
+ # spending the budget on cores instead is strictly better — end-to-end job
+ # time fell from ~4.8-5.8 s to ~4.2-4.7 s at byte-identical output quality
+ # (mean ISE 0.1595 both ways, 6-face check).
+ #
+ # This matters beyond this service: all L4 workers share ONE regional quota
+ # (NvidiaL4GpuAllocNoZonalRedundancyPerProjectRegion, granted 3) and the
+ # fleet was permanently over-subscribed at 4 warm instances. Returning this
+ # slot is what puts it back under its ceiling. Do not re-add a GPU here
+ # without a measurement showing a stage that genuinely uses one.
+ # See docs/ops/gcp-credits-plan.md.
- --no-cpu-throttling
- - --cpu=4
+ - --cpu=8
- --memory=16Gi
- --min-instances=${_MIN_INSTANCES}
- --max-instances=${_MAX_INSTANCES}
@@ -68,7 +80,7 @@ steps:
- --timeout=120
# Cloud Run IAM handles external auth; the service itself checks API_KEY.
- --allow-unauthenticated
- - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},FIRESTORE_PROJECT=$PROJECT_ID,DEVICE=cuda
+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},FIRESTORE_PROJECT=$PROJECT_ID,DEVICE=cpu
- --set-secrets=API_KEY=avatar-reconstruction-key:latest
images:
diff --git a/workers/avatar-reconstruction/eval/README.md b/workers/avatar-reconstruction/eval/README.md
index e20cac2b3..d13bf46b0 100644
--- a/workers/avatar-reconstruction/eval/README.md
+++ b/workers/avatar-reconstruction/eval/README.md
@@ -153,6 +153,39 @@ not scored: that path is safe, because the job falls back to texture-only rather
than morphing to garbage. A confident *wrong* detection is the dangerous case and
is still unmeasured.
+## Audit safety (what happens on inputs that aren't the user's face)
+
+```bash
+python -m eval.make_adversarial --out eval/adversarial # once
+python -m eval.detection_guard # audit
+```
+
+The other tools all assume the detector found the right face. This checks that
+assumption against 16 inputs where it shouldn't: pets, statues, dolls, masks,
+mannequins, faces on posters and phone screens and in paintings, crowds, and
+shots past the pose/quality envelope.
+
+Three results worth carrying forward:
+
+- **A face-plausibility gate cannot work.** MediaPipe FaceMesh is a fitted model;
+ it reports where a face *would* be, not whether one is there. A golden retriever
+ produced a better canonical fit (0.4758) than all 40 real humans
+ (0.5035-0.5238). Any residual threshold rejects real people first. Don't build
+ one.
+- **Wrong detections are already bounded.** Real faces move the head 0.2713-0.2839
+ from the template; every detected adversarial input lands 0.2586-0.2929, and
+ none exceeds the real-face maximum. Canonical alignment, `strength` damping, the
+ per-point clamp and the TPS off-face mask compose to keep any input on the
+ plausible-human-head manifold.
+- **Yaw is the exception, and is gated.** `face_pipeline.MAX_MORPH_YAW_DEG` (35°)
+ skips the morph and keeps the texture above a third of a turn, where the
+ occluded half of the face makes depth extrapolation rather than measurement.
+
+Read the displacement column asymmetrically: *above* the real-face band means more
+distortion than any genuine face and is a problem; *below* it means the result sat
+closer to the untouched template, which is the same safe place a non-detection
+lands.
+
## The reference set
`--photos` is a directory of frontal faces, one file per sample, spanning what
diff --git a/workers/avatar-reconstruction/eval/adversarial/crowd-group-photo.png b/workers/avatar-reconstruction/eval/adversarial/crowd-group-photo.png
deleted file mode 100644
index 365fd0411..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/crowd-group-photo.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/crowd-two-people.png b/workers/avatar-reconstruction/eval/adversarial/crowd-two-people.png
deleted file mode 100644
index d326bad85..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/crowd-two-people.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/depicted-magazine-page.png b/workers/avatar-reconstruction/eval/adversarial/depicted-magazine-page.png
deleted file mode 100644
index 8967ad33a..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/depicted-magazine-page.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/depicted-oil-painting.png b/workers/avatar-reconstruction/eval/adversarial/depicted-oil-painting.png
deleted file mode 100644
index e3e747b8a..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/depicted-oil-painting.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/depicted-phone-screen.png b/workers/avatar-reconstruction/eval/adversarial/depicted-phone-screen.png
deleted file mode 100644
index a611dfdd0..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/depicted-phone-screen.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/depicted-wall-poster.png b/workers/avatar-reconstruction/eval/adversarial/depicted-wall-poster.png
deleted file mode 100644
index d5f67d420..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/depicted-wall-poster.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/extreme-extreme-closeup.png b/workers/avatar-reconstruction/eval/adversarial/extreme-extreme-closeup.png
deleted file mode 100644
index dcca64ab9..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/extreme-extreme-closeup.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/extreme-hard-backlight.png b/workers/avatar-reconstruction/eval/adversarial/extreme-hard-backlight.png
deleted file mode 100644
index c445e346a..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/extreme-hard-backlight.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/extreme-motion-blur.png b/workers/avatar-reconstruction/eval/adversarial/extreme-motion-blur.png
deleted file mode 100644
index bfad25c0f..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/extreme-motion-blur.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/extreme-near-profile.png b/workers/avatar-reconstruction/eval/adversarial/extreme-near-profile.png
deleted file mode 100644
index 4514f00ac..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/extreme-near-profile.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/manifest.json b/workers/avatar-reconstruction/eval/adversarial/manifest.json
deleted file mode 100644
index 85402171f..000000000
--- a/workers/avatar-reconstruction/eval/adversarial/manifest.json
+++ /dev/null
@@ -1,82 +0,0 @@
-[
- {
- "name": "non_face-golden-retriever",
- "category": "non_face",
- "prompt": "a close-up photograph of a golden retriever dog's face looking straight at the camera, plain grey background, sharp focus"
- },
- {
- "name": "non_face-tabby-cat",
- "category": "non_face",
- "prompt": "a close-up photograph of a tabby cat's face looking directly at the camera, plain background, sharp focus"
- },
- {
- "name": "non_face-marble-statue",
- "category": "non_face",
- "prompt": "a frontal photograph of a classical white marble bust of a human head on a plain grey background, museum lighting"
- },
- {
- "name": "non_face-porcelain-doll",
- "category": "non_face",
- "prompt": "a frontal photograph of an antique porcelain doll's head and shoulders, plain background"
- },
- {
- "name": "non_face-carnival-mask",
- "category": "non_face",
- "prompt": "a frontal photograph of a decorated venetian carnival mask hanging on a plain grey wall"
- },
- {
- "name": "non_face-shop-mannequin",
- "category": "non_face",
- "prompt": "a frontal photograph of a featureless retail shop mannequin head on a plain background"
- },
- {
- "name": "depicted-wall-poster",
- "category": "depicted",
- "prompt": "a wide photograph of a city street wall with a large advertising poster of a smiling person's face on it, seen at an angle, other buildings visible"
- },
- {
- "name": "depicted-phone-screen",
- "category": "depicted",
- "prompt": "a photograph of a hand holding a smartphone that is displaying a portrait photo of a person on its screen, indoor background"
- },
- {
- "name": "depicted-oil-painting",
- "category": "depicted",
- "prompt": "a photograph of an ornately framed renaissance oil portrait painting hanging on a gallery wall"
- },
- {
- "name": "depicted-magazine-page",
- "category": "depicted",
- "prompt": "an overhead photograph of an open glossy magazine lying on a wooden table, showing a full-page portrait photograph"
- },
- {
- "name": "crowd-group-photo",
- "category": "crowd",
- "prompt": "a photograph of six friends standing together smiling at the camera outdoors, all faces clearly visible"
- },
- {
- "name": "crowd-two-people",
- "category": "crowd",
- "prompt": "a photograph of two people standing side by side facing the camera, both faces equally visible, plain background"
- },
- {
- "name": "extreme-near-profile",
- "category": "extreme",
- "prompt": "a photograph of a person's head in near-complete side profile, ninety degrees to the camera, plain grey background"
- },
- {
- "name": "extreme-hard-backlight",
- "category": "extreme",
- "prompt": "a photograph of a person standing directly in front of a bright window, face in deep shadow and heavily backlit, silhouette-like"
- },
- {
- "name": "extreme-motion-blur",
- "category": "extreme",
- "prompt": "a photograph of a person's face with severe motion blur from fast camera movement, barely legible features"
- },
- {
- "name": "extreme-extreme-closeup",
- "category": "extreme",
- "prompt": "an extreme macro photograph showing only a person's eye and part of the nose, filling the entire frame"
- }
-]
\ No newline at end of file
diff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-carnival-mask.png b/workers/avatar-reconstruction/eval/adversarial/non_face-carnival-mask.png
deleted file mode 100644
index 9f11250b6..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/non_face-carnival-mask.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-golden-retriever.png b/workers/avatar-reconstruction/eval/adversarial/non_face-golden-retriever.png
deleted file mode 100644
index 1d729444e..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/non_face-golden-retriever.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-marble-statue.png b/workers/avatar-reconstruction/eval/adversarial/non_face-marble-statue.png
deleted file mode 100644
index 473c8f115..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/non_face-marble-statue.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-porcelain-doll.png b/workers/avatar-reconstruction/eval/adversarial/non_face-porcelain-doll.png
deleted file mode 100644
index 4c1c6605c..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/non_face-porcelain-doll.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-shop-mannequin.png b/workers/avatar-reconstruction/eval/adversarial/non_face-shop-mannequin.png
deleted file mode 100644
index d6c0a5bb1..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/non_face-shop-mannequin.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-tabby-cat.png b/workers/avatar-reconstruction/eval/adversarial/non_face-tabby-cat.png
deleted file mode 100644
index c10258a88..000000000
Binary files a/workers/avatar-reconstruction/eval/adversarial/non_face-tabby-cat.png and /dev/null differ
diff --git a/workers/avatar-reconstruction/eval/detection_guard.py b/workers/avatar-reconstruction/eval/detection_guard.py
new file mode 100644
index 000000000..865bc3dfb
--- /dev/null
+++ b/workers/avatar-reconstruction/eval/detection_guard.py
@@ -0,0 +1,170 @@
+"""
+Safety audit — what does the pipeline do with inputs that are NOT this person's face?
+
+`tune_morph` and `robustness` both assume the detector found the right face.
+This checks that assumption. It runs the reference set and the adversarial set
+([`make_adversarial.py`](make_adversarial.py)) through the detector and the morph,
+and reports, per input: did it detect, how far is it turned, and how far does the
+resulting head move from the template.
+
+What this measured (2026-07-25, 40 refs + 16 adversarial), and why the guard ended
+up where it did:
+
+**A face-plausibility gate does not work — do not rebuild one.** The obvious design
+is to align the landmarks to the canonical face and reject a large residual. It
+fails, because MediaPipe FaceMesh is a *fitted model*: it does not decide whether
+something is a face, it reports where a face would be. A golden retriever scored
+0.4758 — a *better* canonical fit than all 40 real humans (0.5035-0.5238). Any
+threshold separating them would reject real people first.
+
+**The catastrophic failure mode does not exist here.** Head displacement from the
+template: real faces 0.2713-0.2839, every detected adversarial input
+0.2586-0.2929. A dog photo does not yield a monstrous head, it yields a slightly
+unusual *human* one. Four mechanisms compose to guarantee it — canonical
+alignment removes pose and scale, `strength` damps the residual, the per-point
+clamp bounds outliers, and the TPS off-face mask confines deformation to the face
+region. Guarding the mesh against wrong detections is therefore unnecessary.
+
+**Yaw is the one thing worth gating.** Real frontals peak at 2.7°; a near-profile
+reads 58.6° and is the only input that pushes the head outside the real-face band.
+Past roughly a third of a turn the far side of the face is self-occluded, so
+MediaPipe's depth there is extrapolation and the morph fits it as bone structure.
+`face_pipeline.MAX_MORPH_YAW_DEG` (35°) skips the morph and keeps texture transfer
+in that case. Photos of photos (poster, phone screen, painting) sit at 9-18°,
+already produce in-band heads, and are deliberately left alone.
+
+A non-detection is always the safe outcome: the job falls back to texture-only
+rather than morphing to garbage.
+
+Usage
+-----
+ python -m eval.detection_guard --photos eval/refs --adversarial eval/adversarial
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import statistics
+import sys
+from pathlib import Path
+
+import numpy as np
+from PIL import Image
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import face_geometry as fg # noqa: E402
+import glb_ops # noqa: E402
+
+PHOTO_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp"}
+_EYE_L, _EYE_R = 33, 263
+
+
+def probe(path: Path, base: np.ndarray, face_map: fg.FaceMap, interocular: float) -> dict:
+ """Detect, measure yaw, morph, and report how far the head travelled."""
+ import face_pipeline as fp
+
+ img = Image.open(path).convert("RGB")
+ landmarks = fp._get_landmarks(img) or fp._get_landmarks_small_face(img)
+ if landmarks is None:
+ return {"name": path.stem, "detected": False}
+
+ detected = fg.landmarks_to_array(landmarks, *img.size)
+ yaw = fg.estimate_yaw_deg(detected, face_map)
+ morphed = fg.morph_head_to_landmarks(base, face_map, detected).astype(np.float64)
+ idx = face_map.landmark_vtx
+ displacement = float(np.linalg.norm(morphed[idx] - base[idx], axis=1).mean() / interocular)
+ return {
+ "name": path.stem,
+ "detected": True,
+ "yaw_deg": yaw,
+ "displacement": displacement,
+ "gated": yaw > float(fp.MAX_MORPH_YAW_DEG),
+ }
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--photos", type=Path, default=Path("eval/refs"))
+ ap.add_argument("--adversarial", type=Path, default=Path("eval/adversarial"))
+ ap.add_argument("--template", type=Path, default=Path("templates/default.glb"))
+ ap.add_argument("--out", type=Path)
+ args = ap.parse_args()
+
+ face_map = fg.FaceMap.load()
+ if face_map is None:
+ print("error: face_uv_map.json has no geometry fields", file=sys.stderr)
+ return 1
+
+ glb = glb_ops.load_glb(args.template.read_bytes())
+ base, _, _ = glb_ops.get_head_mesh_data(glb)
+ base = base.astype(np.float64)
+ idx = face_map.landmark_vtx
+ interocular = float(np.linalg.norm(base[idx[_EYE_L]] - base[idx[_EYE_R]]))
+
+ import face_pipeline as fp
+ print(f"morph yaw gate: {fp.MAX_MORPH_YAW_DEG:.0f}°\n")
+
+ real = [probe(p, base, face_map, interocular)
+ for p in sorted(args.photos.iterdir()) if p.suffix.lower() in PHOTO_SUFFIXES]
+ seen = [r for r in real if r["detected"]]
+ if not seen:
+ print("error: no face detected in any reference photo", file=sys.stderr)
+ return 1
+
+ yaws = [r["yaw_deg"] for r in seen]
+ disps = [r["displacement"] for r in seen]
+ band = (min(disps), max(disps))
+ print(f"REFERENCE ({len(seen)}/{len(real)} detected)")
+ print(f" yaw mean {statistics.fmean(yaws):.1f}° worst {max(yaws):.1f}°")
+ print(f" displacement {band[0]:.4f} – {band[1]:.4f}")
+ gated_real = [r for r in seen if r["gated"]]
+ print(f" gated by the yaw threshold: {len(gated_real)}"
+ + (" ← a real face was rejected, the threshold is too tight"
+ if gated_real else " (none — good)"))
+
+ adversarial = [probe(p, base, face_map, interocular)
+ for p in sorted(args.adversarial.iterdir()) if p.suffix.lower() in PHOTO_SUFFIXES]
+ print(f"\nADVERSARIAL ({sum(a['detected'] for a in adversarial)}/{len(adversarial)} detected)")
+ print(f" {'input':<38} {'yaw':>7} {'displacement':>12} verdict")
+ for a in adversarial:
+ if not a["detected"]:
+ print(f" {a['name'][:38]:<38} {'—':>7} {'—':>12} no detection (safe: texture-only)")
+ continue
+ # Only displacement ABOVE the real-face band is a concern. Below it means
+ # the head moved *less* than any genuine face does, i.e. the result sits
+ # closer to the untouched template — the conservative direction, and the
+ # same place a non-detection lands. Treating the two tails alike would
+ # report the safest outcomes as failures.
+ if a["gated"]:
+ verdict = "GATED — morph skipped"
+ elif a["displacement"] > band[1]:
+ verdict = "ABOVE real-face band ← distorts more than any real face"
+ elif a["displacement"] < band[0]:
+ verdict = "below band (benign: closer to template than a real face)"
+ else:
+ verdict = "in real-face band (bounded)"
+ print(f" {a['name'][:38]:<38} {a['yaw_deg']:>6.1f}° {a['displacement']:>12.4f} {verdict}")
+
+ escaped = [a for a in adversarial
+ if a["detected"] and not a["gated"] and a["displacement"] > band[1]]
+ print(f"\n{len(escaped)} adversarial input(s) ungated AND distorting more than any real face")
+ if escaped:
+ for a in escaped:
+ print(f" {a['name']}: yaw {a['yaw_deg']:.1f}°, displacement {a['displacement']:.4f}")
+ else:
+ print(" (none — every ungated adversarial input stays at or below real-face "
+ "distortion, which is what the clamp + damping + off-face mask guarantee)")
+
+ if args.out:
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps(
+ {"yaw_gate_deg": fp.MAX_MORPH_YAW_DEG, "real_band": band,
+ "reference": real, "adversarial": adversarial}, indent=2))
+ print(f"→ {args.out}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/workers/avatar-reconstruction/face_geometry.py b/workers/avatar-reconstruction/face_geometry.py
index b4b1f3157..ff4061ebe 100644
--- a/workers/avatar-reconstruction/face_geometry.py
+++ b/workers/avatar-reconstruction/face_geometry.py
@@ -340,6 +340,30 @@ def _median_nn_spacing(pts: np.ndarray) -> float:
# ── MediaPipe adapter ────────────────────────────────────────────────────────
+def estimate_yaw_deg(detected_landmarks: np.ndarray, face_map: FaceMap) -> float:
+ """
+ Absolute head yaw in degrees, recovered from the same Umeyama alignment the
+ morph uses (so it costs one extra arctan and cannot disagree with it).
+
+ Why the morph needs this: a single photo only constrains the geometry it can
+ see. Past roughly a third of a turn the far side of the face is self-occluded,
+ MediaPipe's depth for those landmarks becomes extrapolation rather than
+ measurement, and the morph faithfully fits that noise into the skull.
+
+ Measured on the benchmark: the 40 clean reference faces sit at 0.9° mean /
+ 2.7° worst, while a near-profile shot reads 58.6° and is the only input —
+ adversarial or real — that drives the head outside the displacement band every
+ genuine face produces. Photos *of* photos (a poster, a phone screen, a framed
+ painting) land in between at 9-18°, which is why the threshold is set well
+ above them: those already yield in-band heads and do not need blocking.
+ """
+ canon = face_map.canonical_norm
+ idx = face_map.stable_indices
+ det = np.asarray(detected_landmarks, dtype=np.float64)[: canon.shape[0]]
+ _, R, _ = umeyama(det[idx], canon[idx])
+ return float(abs(np.degrees(np.arctan2(-R[2, 0], np.hypot(R[0, 0], R[1, 0])))))
+
+
def landmarks_to_array(landmarks, width: float | None = None, height: float | None = None) -> np.ndarray:
"""
MediaPipe NormalizedLandmark list → (N,3) array. y is flipped to +up so the
diff --git a/workers/avatar-reconstruction/face_pipeline.py b/workers/avatar-reconstruction/face_pipeline.py
index a2a68abf8..3b29514f4 100644
--- a/workers/avatar-reconstruction/face_pipeline.py
+++ b/workers/avatar-reconstruction/face_pipeline.py
@@ -48,6 +48,21 @@ TEMPLATES_DIR = HERE / "templates"
# the texture). Default on; set GEOMETRY_MORPH=0 to fall back to texture-only.
GEOMETRY_MORPH_ENABLED = os.environ.get("GEOMETRY_MORPH", "1") != "0"
+# Skip the geometry morph (keep texture transfer) above this head yaw. A single
+# photo cannot constrain the self-occluded half of a turned face, so MediaPipe's
+# depth there is extrapolation and the morph would fit it as bone structure.
+#
+# 35° is deliberately generous. Benchmark evidence (`eval/adversarial`): the 40
+# clean reference faces peak at 2.7°; photos *of* photos — a poster, a phone
+# screen, a framed painting — read 9-18° and already produce heads inside the
+# real-face displacement band, so they need no blocking; a near-profile shot reads
+# 58.6° and is the sole input that pushes the head outside that band. The gate
+# therefore clears every genuine frontal by ~13x and still catches the one case
+# that measurably misbehaves. Raising it would admit unconstrained geometry;
+# lowering it risks rejecting real users, who (unlike this benchmark) do not shoot
+# perfect frontals.
+MAX_MORPH_YAW_DEG = float(os.environ.get("MAX_MORPH_YAW_DEG", "35"))
+
_FACE_MAP: Optional[face_geometry.FaceMap] = None
_FACE_MAP_LOADED = False
@@ -554,14 +569,27 @@ def process(
detected = face_geometry.landmarks_to_array(
landmarks, *best_img.size
)
- if detected.shape[0] >= fmap.canonical_norm.shape[0]:
- morphed = face_geometry.morph_head_to_landmarks(base_pos, fmap, detected)
- glb_ops.set_head_geometry(glb, morphed, faces=faces)
- log.info("[%s] head geometry morphed to face identity (%.1fs)",
- job_id, time.time() - t0)
- else:
+ yaw = (
+ face_geometry.estimate_yaw_deg(detected, fmap)
+ if detected.shape[0] >= fmap.canonical_norm.shape[0]
+ else 0.0
+ )
+ if detected.shape[0] < fmap.canonical_norm.shape[0]:
log.warning("[%s] only %d landmarks — skipping geometry morph",
job_id, detected.shape[0])
+ elif yaw > MAX_MORPH_YAW_DEG:
+ # Too far turned for a single view to constrain the far side of
+ # the face: MediaPipe's depth there is extrapolated, and morphing
+ # would fit that guesswork into the skull. Texture transfer still
+ # works from an angled shot, so keep it and leave the shape alone.
+ log.warning("[%s] head yaw %.1f° > %.0f° — skipping geometry morph, "
+ "keeping texture (single view cannot constrain the "
+ "occluded side)", job_id, yaw, MAX_MORPH_YAW_DEG)
+ else:
+ morphed = face_geometry.morph_head_to_landmarks(base_pos, fmap, detected)
+ glb_ops.set_head_geometry(glb, morphed, faces=faces)
+ log.info("[%s] head geometry morphed to face identity, yaw %.1f° (%.1fs)",
+ job_id, yaw, time.time() - t0)
except Exception as exc: # noqa: BLE001 — refinement must never fail the job
log.warning("[%s] geometry morph failed (%s) — keeping template shape",
job_id, exc)
diff --git a/workers/avatar-reconstruction/test_face_geometry.py b/workers/avatar-reconstruction/test_face_geometry.py
index f3da45f51..f27aab5ba 100644
--- a/workers/avatar-reconstruction/test_face_geometry.py
+++ b/workers/avatar-reconstruction/test_face_geometry.py
@@ -233,6 +233,45 @@ def test_landmarks_are_independent_of_photo_aspect_ratio():
print("ok morph is invariant to source photo aspect ratio (3:4 / 1:1 / 9:16)")
+def test_yaw_estimate_tracks_actual_rotation():
+ """
+ `estimate_yaw_deg` must recover a known head rotation, because the morph gate
+ in face_pipeline refuses to reshape the skull above a yaw threshold and a
+ silently-wrong estimate would either admit unconstrained geometry or reject
+ real users' photos.
+
+ The canonical face is rotated by a known angle about the vertical axis and the
+ estimate must return it. Independent of scale and translation, since the
+ underlying alignment quotients both out.
+ """
+ _, _, _, fmap = _load()
+ canon = fmap.canonical_norm
+
+ for truth in (0.0, 10.0, 35.0, 58.0):
+ rad = np.radians(truth)
+ Ry = np.array([[np.cos(rad), 0.0, np.sin(rad)],
+ [0.0, 1.0, 0.0],
+ [-np.sin(rad), 0.0, np.cos(rad)]])
+ # scale + translate too: the estimate must be invariant to both
+ turned = 2.3 * (Ry @ canon.T).T + np.array([4.0, -1.5, 0.7])
+ got = fg.estimate_yaw_deg(turned, fmap)
+ assert abs(got - truth) < 0.5, f"yaw {truth}° estimated as {got:.1f}°"
+ print("ok yaw estimate recovers known rotation (0/10/35/58°, scale+shift invariant)")
+
+
+def test_frontal_face_is_never_gated():
+ """
+ A neutral, frontal landmark set must read as ~0° yaw. If this drifts, the
+ pipeline's 35° gate would start skipping the morph for ordinary users — a
+ silent quality regression rather than a visible failure.
+ """
+ _, _, _, fmap = _load()
+ detected = fmap.canonical_norm + np.random.default_rng(7).normal(scale=0.01, size=fmap.canonical_norm.shape)
+ yaw = fg.estimate_yaw_deg(detected, fmap)
+ assert yaw < 5.0, f"frontal face estimated at {yaw:.1f}° yaw — would risk gating real users"
+ print(f"ok frontal face reads {yaw:.2f}° yaw, far below the 35° morph gate")
+
+
if __name__ == "__main__":
tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
try: