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.

fix(avatar-reconstruction): stop tinting the one region with real photographic colour

nirholas11c19e07ffc1
diff --git a/docs/avatar-fidelity-program.md b/docs/avatar-fidelity-program.md
index 806f4230c..974c677ca 100644
--- a/docs/avatar-fidelity-program.md
+++ b/docs/avatar-fidelity-program.md
@@ -188,7 +188,39 @@ 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.
-Two candidate mechanisms, and the measurement in Track 3 decides between them.
+**Measure the opportunity first — it is bigger than it looks.** Of the head
+mesh's UV surface, only **19.2% is the face oval** the selfie actually covers.
+The other **80.8%** — ears, scalp, neck, under-jaw — is template texture the
+camera never saw, personalised solely by a global skin-tone tint. That is the
+real prize here, and it also bounds what the mechanisms below can achieve.
+
+**A landmark-driven warp cannot reach most of it.** MediaPipe's 468 landmarks are
+face-only: there are no ear, scalp or neck points, and `_warp_face_to_uv` masks
+to the face-oval polygon accordingly. So warping extra synthesised views through
+the existing path improves *lateral cheek and jaw* fidelity (where a frontal is
+foreshortened) but cannot texture the other 80.8%, because no correspondence
+exists there. Anyone picking this up should not expect the view-warp route to
+fill the scalp.
+
+**The mechanism that does reach it is projective texturing off the mesh we
+already have.** The head geometry is known (the morph just produced it), so a
+synthesised view can be projected through an estimated camera pose onto the mesh
+and resolved to UV by rasterisation plus a visibility test — no landmarks needed,
+and ears/scalp/neck fall out naturally. This is the recommended build, and it
+shares its camera-pose machinery with Track 3.
+
+Already fixed on the way in: the skin tint was being applied to the *whole*
+texture, including the face oval that had just been composited from the user's
+photograph — shifting the only region with true photographic colour toward an
+average of itself by ~1.4% of range. It is now masked to the regions the photo
+could not cover, which is what its own comment always said it was for
+(`test_face_pipeline.py` pins the mask behaviour, including that the tint still
+reaches every unprotected pixel — a mask that over-protected would leave a
+template-coloured neck against a photographic face, a worse artefact than the
+one being fixed).
+
+Two candidate mechanisms for the remainder, and the measurement in Track 3
+decides between them.
**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
diff --git a/workers/avatar-reconstruction/face_pipeline.py b/workers/avatar-reconstruction/face_pipeline.py
index 3b29514f4..ec80df91c 100644
--- a/workers/avatar-reconstruction/face_pipeline.py
+++ b/workers/avatar-reconstruction/face_pipeline.py
@@ -338,14 +338,32 @@ def _extract_eye_colour(img_rgb: np.ndarray, landmarks: list, img_w: int, img_h:
return patch.reshape(-1, 3).mean(axis=0)
-def _tint_texture(base: Image.Image, target_rgb: np.ndarray, strength: float = 0.35) -> Image.Image:
+def _tint_texture(
+ base: Image.Image,
+ target_rgb: np.ndarray,
+ strength: float = 0.35,
+ protect_mask: Optional[np.ndarray] = None,
+) -> Image.Image:
"""
Colour-grade a texture toward target_rgb.
Blends the texture's luminance with target colour at given strength.
+
+ `protect_mask` (float 0..1, texture-shaped) fades the tint out where it is 1.
+ Pass the face mask when tinting the skin: the face oval has just been
+ composited from the user's actual photograph and is the only region of the
+ model carrying true photographic colour, so shifting it toward a *sampled
+ average* of itself can only move it away from the truth. The tint exists to
+ pull the template's neck/ears/scalp toward the person's complexion — regions
+ the camera never saw — and that is exactly where it should apply.
"""
arr = np.array(base.convert("RGB"), dtype=np.float32)
mean = arr.mean(axis=(0, 1))
shift = (target_rgb - mean) * strength
+ if protect_mask is not None:
+ # Broadcast (h,w) → (h,w,1) so the tint fades smoothly across the mask's
+ # feathered edge rather than leaving a hard seam at the oval boundary.
+ weight = np.clip(1.0 - protect_mask.astype(np.float32), 0.0, 1.0)[..., None]
+ shift = shift * weight
tinted = np.clip(arr + shift, 0, 255).astype(np.uint8)
return Image.fromarray(tinted)
@@ -537,9 +555,14 @@ def process(
new_skin = _composite_face_onto_skin(skin_tex, warped_face, face_mask_uv)
log.info("[%s] face composited onto skin texture (%.1fs)", job_id, time.time() - t0)
- # 8. Skin-tone tint: ensure neck/hands roughly match face colour.
+ # 8. Skin-tone tint: pull the neck, ears and scalp toward the person's
+ # complexion. Only ~19% of the head's UV surface is the face oval the selfie
+ # actually covers; the other ~81% is template texture, and this tint is all
+ # that personalises it. Protect the oval itself — those pixels came straight
+ # from the photograph, so tinting them toward an average of themselves can
+ # only degrade the one region with true photographic colour.
skin_tone = _extract_skin_tone(img_arr, landmarks, img_w, img_h)
- new_skin = _tint_texture(new_skin, skin_tone, strength=0.25)
+ new_skin = _tint_texture(new_skin, skin_tone, strength=0.25, protect_mask=face_mask_uv)
glb_ops.set_material_texture(glb, "Wolf3D_Skin", new_skin)
diff --git a/workers/avatar-reconstruction/test_face_pipeline.py b/workers/avatar-reconstruction/test_face_pipeline.py
new file mode 100644
index 000000000..712e5b10a
--- /dev/null
+++ b/workers/avatar-reconstruction/test_face_pipeline.py
@@ -0,0 +1,113 @@
+"""
+Unit tests for the texture stage of the selfie → avatar pipeline.
+
+Run: python3 test_face_pipeline.py (asserts; exits non-zero on failure)
+
+Scope note: only ~19% of the head's UV surface is the face oval the selfie
+actually covers. The other ~81% — ears, scalp, neck, under-jaw — is template
+texture that the camera never saw, and the skin tint is currently the only thing
+personalising it. That asymmetry is why the tint's mask behaviour matters enough
+to pin: it must reach everything the photo could not, and nothing the photo did.
+"""
+
+import sys
+
+import numpy as np
+from PIL import Image
+
+import face_pipeline as fp
+
+
+def _flat(rgb, size=64):
+ return Image.fromarray(np.full((size, size, 3), rgb, dtype=np.uint8))
+
+
+def test_tint_moves_texture_toward_target():
+ """Baseline: with no mask, the tint shifts the whole texture toward target."""
+ base = _flat((100, 100, 100))
+ out = np.array(_tint(base, np.array([200.0, 200.0, 200.0]), 0.5).convert("RGB"), dtype=np.float32)
+ # mean 100, target 200, strength 0.5 → +50
+ assert abs(out.mean() - 150.0) < 1.0, f"expected ~150, got {out.mean():.1f}"
+ print("ok tint shifts an unmasked texture toward the target")
+
+
+def _tint(base, target, strength, protect_mask=None):
+ return fp._tint_texture(base, target, strength=strength, protect_mask=protect_mask)
+
+
+def test_protected_region_keeps_its_photographic_colour():
+ """
+ The face oval is composited straight from the user's photograph and is the
+ only region of the model carrying true photographic colour. Tinting it
+ toward a sampled average of itself can only move it away from the truth, so
+ a fully-protected region must come through untouched.
+ """
+ size = 64
+ base = _flat((100, 100, 100), size)
+ mask = np.zeros((size, size), dtype=np.float32)
+ mask[16:48, 16:48] = 1.0 # "face oval"
+
+ out = np.array(_tint(base, np.array([200.0, 200.0, 200.0]), 0.5, mask).convert("RGB"), dtype=np.float32)
+ inside = out[16:48, 16:48]
+ outside = out[:8, :8]
+
+ assert abs(inside.mean() - 100.0) < 0.51, f"protected region moved: {inside.mean():.1f} (want 100)"
+ assert abs(outside.mean() - 150.0) < 1.0, f"unprotected region not tinted: {outside.mean():.1f} (want 150)"
+ print("ok protected face pixels keep photographic colour; template still tinted")
+
+
+def test_tint_still_reaches_every_unprotected_pixel():
+ """
+ The tint's whole job is the ~81% of the head the camera never saw. A mask
+ that accidentally suppressed it there would leave a template-coloured neck
+ against a photographic face — a worse artefact than the one being fixed.
+ """
+ size = 64
+ base = _flat((100, 100, 100), size)
+ mask = np.zeros((size, size), dtype=np.float32)
+ mask[0:2, 0:2] = 1.0 # tiny protected corner
+
+ out = np.array(_tint(base, np.array([160.0, 160.0, 160.0]), 0.5, mask).convert("RGB"), dtype=np.float32)
+ unprotected = out[4:, 4:]
+ assert unprotected.min() > 100.0, "some unprotected pixels were not tinted at all"
+ assert abs(unprotected.mean() - 130.0) < 1.0, f"unprotected mean {unprotected.mean():.1f}, want ~130"
+ print("ok tint reaches every unprotected pixel (neck/ears/scalp still personalised)")
+
+
+def test_feathered_mask_produces_a_gradient_not_a_seam():
+ """
+ The real mask is feathered. A binary application would leave a visible ring
+ at the oval boundary — the exact place a viewer looks. Intermediate mask
+ values must produce intermediate tinting.
+ """
+ size = 64
+ base = _flat((100, 100, 100), size)
+ mask = np.zeros((size, size), dtype=np.float32)
+ mask[:, :] = np.linspace(0.0, 1.0, size, dtype=np.float32)[None, :]
+
+ out = np.array(_tint(base, np.array([200.0, 200.0, 200.0]), 0.5, mask).convert("RGB"), dtype=np.float32)
+ col_means = out.mean(axis=(0, 2))
+ # Tint strength must fall monotonically as protection rises.
+ assert col_means[0] > col_means[size // 2] > col_means[-1], "tint is not monotonic across the feather"
+ assert abs(col_means[-1] - 100.0) < 1.5, "fully-protected edge was still tinted"
+ print("ok feathered mask yields a smooth gradient, no seam at the oval boundary")
+
+
+def test_none_mask_is_backwards_compatible():
+ """Callers that pass no mask (hair tint) must behave exactly as before."""
+ base = _flat((80, 90, 100))
+ a = np.array(_tint(base, np.array([180.0, 180.0, 180.0]), 0.35).convert("RGB"), dtype=np.float32)
+ b = np.array(_tint(base, np.array([180.0, 180.0, 180.0]), 0.35, None).convert("RGB"), dtype=np.float32)
+ assert np.array_equal(a, b)
+ print("ok omitting the mask is unchanged behaviour (hair tint unaffected)")
+
+
+if __name__ == "__main__":
+ tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
+ try:
+ for t in tests:
+ t()
+ except AssertionError as e:
+ print("FAIL:", e)
+ sys.exit(1)
+ print(f"\nall {len(tests)} face-pipeline tests passed")