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.

test(triposg): add the request-policy module and the tests main.py and the image already reference

nirholas3c422130d692
diff --git a/workers/model-triposg/request_policy.py b/workers/model-triposg/request_policy.py
new file mode 100644
index 000000000..21481a0e7
--- /dev/null
+++ b/workers/model-triposg/request_policy.py
@@ -0,0 +1,123 @@
+"""Request policy for the TripoSG worker: mode routing, prompt gating, and the
+per-mode sampler settings.
+
+This module is deliberately free of torch, CUDA, and the TripoSG source tree, so
+every decision that shapes a generation can be imported and unit tested on any
+machine with no GPU and no model weights (see test_request_policy.py). main.py
+imports every public name here; nothing in this file touches the GPU.
+
+Two modes share the one /infer endpoint and they are NOT interchangeable:
+
+ image one photo, the full 50-step rectified-flow sampler at guidance 7.0.
+ scribble a drawing plus a text prompt, the CFG-distilled sampler (16 steps,
+ guidance 0). Prompt-conditioned, so an empty prompt is a caller
+ error (422), not a silent fall back to image mode: without the
+ prompt the scribble pipeline has nothing to condition on and
+ returns a blob.
+
+The numbers below are upstream's own inference defaults
+(scripts/inference_triposg.py and scripts/inference_triposg_scribble.py in
+github.com/VAST-AI-Research/TripoSG), not tuned guesses.
+"""
+
+from __future__ import annotations
+
+IMAGE_MODE = "image"
+SCRIBBLE_MODE = "scribble"
+MODES = (IMAGE_MODE, SCRIBBLE_MODE)
+
+IMAGE_STEPS = 50
+IMAGE_GUIDANCE = 7.0
+
+# CFG-distilled checkpoint: few steps, and guidance MUST stay 0 (the distilled
+# model already bakes in the guided trajectory; a non-zero scale double-applies
+# it and the geometry blows out).
+SCRIBBLE_STEPS = 16
+SCRIBBLE_GUIDANCE = 0.0
+DEFAULT_SCRIBBLE_CONFIDENCE = 0.4
+# Octree depths for the scribble decoder. Flash decoding is off because the
+# distilled checkpoint's latents decode wrong through it upstream.
+SCRIBBLE_OCTREE_DEPTH = 8
+
+
+class PromptRequired(ValueError):
+ """Scribble mode was requested with no prompt. main.py maps this to 422."""
+
+
+def resolve_mode(raw) -> str:
+ """Normalize the caller's `mode`. Anything unrecognized (including None and
+ a non-string) falls back to image mode, which is the safe default: it needs
+ no prompt and accepts any photo."""
+ if isinstance(raw, str) and raw.strip().lower() in MODES:
+ return raw.strip().lower()
+ return IMAGE_MODE
+
+
+def resolve_prompt(mode: str, raw) -> str:
+ """Trim the prompt and enforce the scribble-mode requirement. Image mode
+ ignores the prompt entirely (the image pipeline takes no text), so it is
+ returned as an empty string there rather than being carried into a call
+ that would reject it."""
+ prompt = raw.strip() if isinstance(raw, str) else ""
+ if mode == SCRIBBLE_MODE:
+ if not prompt:
+ raise PromptRequired(
+ "scribble mode is prompt-conditioned: supply a prompt naming what the sketch depicts"
+ )
+ return prompt
+ return ""
+
+
+def clamp_confidence(value) -> float:
+ """Sketch-adherence scale, clamped to the 0..1 the cross-attention scale
+ accepts. A non-numeric value falls back to the default rather than failing
+ the generation."""
+ try:
+ num = float(value)
+ except (TypeError, ValueError):
+ return DEFAULT_SCRIBBLE_CONFIDENCE
+ if num != num: # NaN
+ return DEFAULT_SCRIBBLE_CONFIDENCE
+ return max(0.0, min(1.0, num))
+
+
+def pipeline_settings(mode: str, *, prompt: str = "", scribble_confidence=None) -> dict:
+ """Exact keyword arguments for the mode's pipeline call, minus the image and
+ the RNG generator (which main.py supplies). Keeping them here means the two
+ samplers can never drift apart unnoticed: a change to either is a change to
+ a tested value."""
+ if mode == SCRIBBLE_MODE:
+ confidence = clamp_confidence(
+ DEFAULT_SCRIBBLE_CONFIDENCE if scribble_confidence is None else scribble_confidence
+ )
+ return {
+ "prompt": prompt,
+ "num_inference_steps": SCRIBBLE_STEPS,
+ "guidance_scale": SCRIBBLE_GUIDANCE,
+ "attention_kwargs": {
+ "cross_attention_scale": 1.0,
+ "cross_attention_2_scale": confidence,
+ },
+ "use_flash_decoder": False,
+ "dense_octree_depth": SCRIBBLE_OCTREE_DEPTH,
+ "hierarchical_octree_depth": SCRIBBLE_OCTREE_DEPTH,
+ }
+ return {
+ "num_inference_steps": IMAGE_STEPS,
+ "guidance_scale": IMAGE_GUIDANCE,
+ }
+
+
+def should_decimate(face_count: int, target_faces) -> bool:
+ """Decimation runs only when the caller asked for a budget AND the mesh is
+ over it. Running a quadric collapse on an already-small mesh costs seconds
+ and can only lose detail, so an under-budget mesh is exported as generated."""
+ if not target_faces:
+ return False
+ try:
+ target = int(target_faces)
+ except (TypeError, ValueError):
+ return False
+ if target <= 0:
+ return False
+ return int(face_count) > target
diff --git a/workers/model-triposg/test_app_contract.py b/workers/model-triposg/test_app_contract.py
new file mode 100644
index 000000000..d2e29c8b3
--- /dev/null
+++ b/workers/model-triposg/test_app_contract.py
@@ -0,0 +1,134 @@
+"""Smoke test for the served contract, run INSIDE the built image (it needs
+torch, diffusers, FastAPI, and the cloned TripoSG tree on PYTHONPATH):
+
+ docker build -t model-triposg workers/model-triposg
+ docker run --rm model-triposg python3 test_app_contract.py
+
+It needs no GPU, no weights, and no GCP credentials: the ASGI lifespan (which
+opens the GCS client and starts the model load) is deliberately not run, so
+every assertion below is about request handling, not inference.
+
+What it proves, and why each line earns its place:
+
+ 1. The whole import chain resolves. Revisions 00001 and 00002 of this service
+ died at import time on a bad transitive resolve of transformers / diffusers
+ / peft, crashing before the container could bind $PORT, which reads as an
+ opaque Cloud Run startup-probe failure. Importing the two pipelines and the
+ preprocessing helpers here turns that into a build-time test failure.
+ 2. The auth boundary rejects a wrong bearer on both authenticated routes.
+ 3. The scribble prompt gate returns 422 instead of silently generating a blob.
+ 4. The unauthenticated probe surfaces (/ and /health) answer, which is what
+ the platform's liveness probes read.
+ 5. The real sketch preprocessing flattens alpha onto white, and the image
+ fetcher refuses a non-https or private-network source (the SSRF guard).
+"""
+
+from __future__ import annotations
+
+import base64
+import io
+import os
+import sys
+
+os.environ.setdefault("API_KEY", "smoke-test-key")
+os.environ.setdefault("GCS_BUCKET", "smoke-test-bucket")
+
+KEY = os.environ["API_KEY"]
+
+PASSED = 0
+
+
+def check(name: str, condition: bool, detail: str = "") -> None:
+ global PASSED
+ if not condition:
+ print(f"FAIL {name} {detail}")
+ sys.exit(1)
+ PASSED += 1
+ print(f"ok {name}")
+
+
+def png_data_uri(color=(20, 20, 20, 255), size=(24, 24)) -> str:
+ from PIL import Image
+
+ img = Image.new("RGBA", size, color)
+ buf = io.BytesIO()
+ img.save(buf, format="PNG")
+ return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
+
+
+def main() -> int:
+ # 1. Import chain: the pipelines and preprocessing helpers the loader uses.
+ from triposg.pipelines.pipeline_triposg import TripoSGPipeline
+ from triposg.pipelines.pipeline_triposg_scribble import TripoSGScribblePipeline
+ from briarmbg import BriaRMBG
+ from image_process import prepare_image
+
+ check("triposg pipelines import", all(
+ callable(getattr(cls, "from_pretrained", None))
+ for cls in (TripoSGPipeline, TripoSGScribblePipeline)
+ ))
+ check("preprocessing helpers import", callable(prepare_image) and BriaRMBG is not None)
+
+ import main as service
+ from fastapi.testclient import TestClient
+
+ client = TestClient(service.app)
+ auth = {"authorization": f"Bearer {KEY}"}
+
+ # 2. Unauthenticated probe surfaces.
+ root = client.get("/")
+ check("GET / is 200", root.status_code == 200, root.text)
+ check("GET / names the service", root.json()["service"] == "model-triposg", root.text)
+ check("GET / lists both modes", root.json()["modes"] == ["image", "scribble"], root.text)
+
+ health = client.get("/health")
+ check("GET /health is 200", health.status_code == 200, health.text)
+ body = health.json()
+ check("health reports ok with no load error", body["ok"] is True and body["load_error"] is None, health.text)
+ check("health reports not-ready before the load", body["ready"] is False, health.text)
+ check("health reports gpu availability", isinstance(body["gpu_available"], bool), health.text)
+
+ # 3. Auth boundary.
+ bad = client.post("/infer", json={"images": [png_data_uri()]}, headers={"authorization": "Bearer wrong"})
+ check("POST /infer rejects a wrong bearer", bad.status_code == 401, bad.text)
+ bad_task = client.get("/tasks/whatever", headers={"authorization": "Bearer wrong"})
+ check("GET /tasks rejects a wrong bearer", bad_task.status_code == 401, bad_task.text)
+
+ # 4. Request validation, all of it decided before any GPU or GCS work.
+ no_prompt = client.post(
+ "/infer", json={"images": [png_data_uri()], "mode": "scribble"}, headers=auth
+ )
+ check("scribble without a prompt is 422", no_prompt.status_code == 422, no_prompt.text)
+ check(
+ "the 422 explains the prompt gate",
+ "prompt" in no_prompt.json()["detail"],
+ no_prompt.text,
+ )
+
+ no_images = client.post("/infer", json={"images": []}, headers=auth)
+ check("an empty images list is 422", no_images.status_code == 422, no_images.text)
+
+ over_budget = client.post(
+ "/infer", json={"images": [png_data_uri()], "target_polycount": 12}, headers=auth
+ )
+ check("a below-floor target_polycount is 422", over_budget.status_code == 422, over_budget.text)
+
+ # 5. Real preprocessing and the SSRF guard.
+ sketch = service._prepare_sketch(png_data_uri(color=(0, 0, 0, 0)))
+ check("sketch preprocessing returns RGB", sketch.mode == "RGB")
+ check("transparent sketch pixels flatten to white", sketch.getpixel((0, 0)) == (255, 255, 255))
+
+ for refused in ("http://example.com/a.png", "https://127.0.0.1/a.png", "ftp://x/a.png"):
+ try:
+ service._decode_image_bytes(refused)
+ except ValueError:
+ continue
+ check(f"refuses {refused}", False, "the fetch was not refused")
+ check("refuses non-https and private-network image sources", True)
+
+ print(f"\n{PASSED} passed")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/workers/model-triposg/test_request_policy.py b/workers/model-triposg/test_request_policy.py
new file mode 100644
index 000000000..f03037c3a
--- /dev/null
+++ b/workers/model-triposg/test_request_policy.py
@@ -0,0 +1,127 @@
+"""Unit tests for request_policy.py: pure decision logic, no torch, no CUDA, no
+weights, no TripoSG source tree. Runs anywhere:
+
+ python3 workers/model-triposg/test_request_policy.py
+
+(also collectable by pytest if it is installed). These pin the two things a
+caller can get wrong and the two the worker must never get wrong: mode routing,
+the scribble prompt gate, the CFG-distilled sampler settings, and the
+decimation guard.
+"""
+
+from __future__ import annotations
+
+import sys
+
+from request_policy import (
+ DEFAULT_SCRIBBLE_CONFIDENCE,
+ IMAGE_GUIDANCE,
+ IMAGE_MODE,
+ IMAGE_STEPS,
+ PromptRequired,
+ SCRIBBLE_MODE,
+ SCRIBBLE_STEPS,
+ clamp_confidence,
+ pipeline_settings,
+ resolve_mode,
+ resolve_prompt,
+ should_decimate,
+)
+
+
+def test_mode_defaults_to_image():
+ assert resolve_mode(None) == IMAGE_MODE
+ assert resolve_mode("") == IMAGE_MODE
+ assert resolve_mode("photo") == IMAGE_MODE
+ assert resolve_mode(7) == IMAGE_MODE
+
+
+def test_mode_accepts_both_documented_modes():
+ assert resolve_mode("image") == IMAGE_MODE
+ assert resolve_mode("scribble") == SCRIBBLE_MODE
+ assert resolve_mode(" Scribble ") == SCRIBBLE_MODE
+
+
+def test_scribble_without_prompt_is_a_caller_error():
+ for empty in (None, "", " ", 0):
+ try:
+ resolve_prompt(SCRIBBLE_MODE, empty)
+ except PromptRequired:
+ continue
+ raise AssertionError(f"empty prompt {empty!r} was accepted in scribble mode")
+
+
+def test_scribble_prompt_is_trimmed():
+ assert resolve_prompt(SCRIBBLE_MODE, " a brass steampunk owl ") == "a brass steampunk owl"
+
+
+def test_image_mode_drops_the_prompt():
+ # The image pipeline takes no text; carrying a prompt into it would be a
+ # TypeError at call time, and silently honouring it would be a lie.
+ assert resolve_prompt(IMAGE_MODE, "a brass steampunk owl") == ""
+
+
+def test_confidence_is_clamped_and_never_fails_a_generation():
+ assert clamp_confidence(0.4) == 0.4
+ assert clamp_confidence(-3) == 0.0
+ assert clamp_confidence(9) == 1.0
+ assert clamp_confidence("0.75") == 0.75
+ assert clamp_confidence(None) == DEFAULT_SCRIBBLE_CONFIDENCE
+ assert clamp_confidence("later") == DEFAULT_SCRIBBLE_CONFIDENCE
+ assert clamp_confidence(float("nan")) == DEFAULT_SCRIBBLE_CONFIDENCE
+
+
+def test_image_settings_are_the_full_sampler():
+ settings = pipeline_settings(IMAGE_MODE)
+ assert settings == {
+ "num_inference_steps": IMAGE_STEPS,
+ "guidance_scale": IMAGE_GUIDANCE,
+ }
+ # No prompt and no attention kwargs reach the image pipeline.
+ assert "prompt" not in settings
+ assert "attention_kwargs" not in settings
+
+
+def test_scribble_settings_keep_guidance_at_zero():
+ settings = pipeline_settings(SCRIBBLE_MODE, prompt="a brass steampunk owl", scribble_confidence=0.9)
+ assert settings["num_inference_steps"] == SCRIBBLE_STEPS
+ # The distilled checkpoint bakes guidance in; a non-zero scale double-applies it.
+ assert settings["guidance_scale"] == 0.0
+ assert settings["prompt"] == "a brass steampunk owl"
+ assert settings["attention_kwargs"]["cross_attention_2_scale"] == 0.9
+ assert settings["attention_kwargs"]["cross_attention_scale"] == 1.0
+ assert settings["use_flash_decoder"] is False
+ assert settings["dense_octree_depth"] == settings["hierarchical_octree_depth"] == 8
+
+
+def test_scribble_settings_clamp_the_confidence_they_are_given():
+ settings = pipeline_settings(SCRIBBLE_MODE, prompt="owl", scribble_confidence=42)
+ assert settings["attention_kwargs"]["cross_attention_2_scale"] == 1.0
+ default = pipeline_settings(SCRIBBLE_MODE, prompt="owl")
+ assert default["attention_kwargs"]["cross_attention_2_scale"] == DEFAULT_SCRIBBLE_CONFIDENCE
+
+
+def test_decimation_only_runs_when_asked_and_over_budget():
+ assert should_decimate(500_000, 100_000) is True
+ assert should_decimate(50_000, 100_000) is False
+ assert should_decimate(50_000, 50_000) is False
+ assert should_decimate(500_000, None) is False
+ assert should_decimate(500_000, 0) is False
+ assert should_decimate(500_000, "nope") is False
+
+
+def main() -> int:
+ tests = [(name, fn) for name, fn in sorted(globals().items()) if name.startswith("test_") and callable(fn)]
+ for name, fn in tests:
+ try:
+ fn()
+ except AssertionError as exc:
+ print(f"FAIL {name} {exc}")
+ return 1
+ print(f"ok {name}")
+ print(f"\n{len(tests)} passed")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())