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(modly-worker): run Modly's backend headless on a Cloud Run L4 so the Forge can generate with TripoSG and Hunyuan3D Mini Turbo

nirholas65b34f322040
diff --git a/workers/modly/Dockerfile b/workers/modly/Dockerfile
new file mode 100644
index 000000000..a691e548d
--- /dev/null
+++ b/workers/modly/Dockerfile
@@ -0,0 +1,178 @@
+# Modly (Lightning Pixel, MIT) run headless on an L4 (24 GB): image to 3D through
+# Modly's own backend and its official open-weight extensions, behind the
+# three.ws task contract. See README.md.
+#
+# * Modly and both extensions are pinned to commits and fetched by SHA, so a
+# moving `main` can never change what a rebuild serves.
+# * Each extension gets the venv Modly's own installer would build (its
+# setup.py), translated into pinned pip installs. Both venvs share the one
+# torch 2.6.0 + cu124 install in the system interpreter (--system-site-packages)
+# instead of carrying two 5 GB copies.
+# * CUDA 12.4 *devel* base: nvcc compiles diso (TripoSG's DiffDMC decoder) from
+# a pinned commit. TORCH_CUDA_ARCH_LIST defaults to 8.9 (L4).
+# * Modly's decimate op runs on Node + meshoptimizer; Node is pinned by checksum
+# and its packages come from meshopt/package-lock.json.
+# * rembg's u2net.onnx (background removal, used by both extensions) is baked in
+# by checksum: the service runs with the Hub offline.
+# * Modly's uv_unwrapper and texture_baker (derived from Stability AI's
+# stable-fast-3d, under the Stability AI Community License) are NOT built.
+# postprocess.py replaces them with xatlas (MIT) and a numpy/scipy bake.
+# * gltfpack (zeux/meshoptimizer, MIT) is pinned by release tag and checksum,
+# the same pin workers/model-trellis2 ships, and compresses the output GLB.
+FROM python:3.11-slim AS gltfpack
+ARG GLTFPACK_VERSION=v1.2
+ARG GLTFPACK_SHA256=ebc236f5f6c08c7e5c5750476a187d24805d44d8c680449c4b7369c333f817b1
+RUN apt-get update && apt-get install -y --no-install-recommends curl unzip ca-certificates \
+ && curl -fsSL -o /tmp/gltfpack.zip \
+ https://github.com/zeux/meshoptimizer/releases/download/${GLTFPACK_VERSION}/gltfpack-ubuntu.zip \
+ && echo "${GLTFPACK_SHA256} /tmp/gltfpack.zip" | sha256sum -c - \
+ && unzip -j /tmp/gltfpack.zip gltfpack -d /usr/local/bin \
+ && chmod +x /usr/local/bin/gltfpack \
+ && /usr/local/bin/gltfpack -v
+
+FROM nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04
+
+ARG TORCH_CUDA_ARCH_LIST="8.9"
+ARG MODLY_COMMIT=f11a4d2bd9fe994b9d30f76a36cb6c18ac8733ea
+ARG TRIPOSG_EXT_COMMIT=cc30cb8bedddf8141e78dc6cf88a4cb1a305d128
+ARG HUNYUAN_TURBO_EXT_COMMIT=9457b71b6e3ee5436240cac0d6c1bbcd02e9f53d
+ARG TRIPOSG_COMMIT=fc5c40990181e2a756c4e0b1c2f4d6b5202faf8c
+ARG HUNYUAN3D2_COMMIT=f8db63096c8282cb27354314d896feba5ba6ff8a
+ARG DISO_COMMIT=9792ad928ccb09bdec938779651ee03e395758a6
+ARG NODE_VERSION=v20.18.1
+ARG NODE_SHA256=c6fa75c841cbffac851678a472f2a5bd612fff8308ef39236190e1f8dbb0e567
+ARG U2NET_SHA256=8d10d2f3bb75ae3b6d527c77944fc5e7dcd94b29809d47a739a7a728a912b491
+
+ENV PYTHONDONTWRITEBYTECODE=1 \
+ PYTHONUNBUFFERED=1 \
+ PIP_NO_CACHE_DIR=1 \
+ DEBIAN_FRONTEND=noninteractive \
+ TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST}" \
+ CUDA_HOME=/usr/local/cuda \
+ PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ MODLY_API_DIR=/opt/modly/api \
+ EXTENSIONS_DIR=/opt/modly-extensions \
+ U2NET_HOME=/opt/u2net \
+ # The weights are staged to the bucket, never fetched from the Hub at serve time.
+ HF_HUB_OFFLINE=1 \
+ TRANSFORMERS_OFFLINE=1 \
+ # Cap glibc at two malloc arenas (see instance_health.py).
+ MALLOC_ARENA_MAX=2
+
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ python3.10 python3.10-dev python3.10-venv python3-pip \
+ git curl wget xz-utils build-essential ninja-build \
+ libgl1 libglib2.0-0 libgomp1 libsm6 libxext6 libxrender1 \
+ && rm -rf /var/lib/apt/lists/* \
+ && ln -sf /usr/bin/python3.10 /usr/bin/python3 \
+ && ln -sf /usr/bin/python3.10 /usr/bin/python \
+ && pip install --upgrade pip==24.3.1 setuptools==75.8.0 wheel==0.45.1
+
+COPY --from=gltfpack /usr/local/bin/gltfpack /usr/local/bin/gltfpack
+
+# 1. Torch, once, in the system interpreter. Both extension venvs see it through
+# --system-site-packages; the host (Modly + the front) never imports it.
+RUN pip install torch==2.6.0 torchvision==0.21.0 --index-url https://download.pytorch.org/whl/cu124
+
+# 2. Host: Modly's FastAPI backend and the three.ws front, every line pinned.
+COPY requirements-host.txt /tmp/requirements-host.txt
+RUN pip install -r /tmp/requirements-host.txt
+
+# 3. Modly itself, fetched by commit. Its LICENSE travels with the image.
+RUN git init -q /opt/modly \
+ && git -C /opt/modly remote add origin https://github.com/lightningpixel/modly.git \
+ && git -C /opt/modly fetch -q --depth 1 origin ${MODLY_COMMIT} \
+ && git -C /opt/modly checkout -q FETCH_HEAD \
+ && rm -rf /opt/modly/.git \
+ && mkdir -p /app/licenses \
+ && cp /opt/modly/LICENSE /app/licenses/MODLY-LICENSE
+
+# 4. Node + the mesh-optimizer packages Modly's decimate op loads from
+# <modly>/src/areas/workflows/nodes/mesh-optimizer/node_modules.
+RUN curl -fsSL -o /tmp/node.tar.xz \
+ https://nodejs.org/dist/${NODE_VERSION}/node-${NODE_VERSION}-linux-x64.tar.xz \
+ && echo "${NODE_SHA256} /tmp/node.tar.xz" | sha256sum -c - \
+ && tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1 \
+ --exclude=CHANGELOG.md --exclude=README.md --exclude=LICENSE \
+ && rm /tmp/node.tar.xz \
+ && node --version
+COPY meshopt/package.json meshopt/package-lock.json /opt/meshopt/
+RUN cd /opt/meshopt \
+ && npm ci --omit=dev --no-audit --no-fund \
+ && mv /opt/meshopt/node_modules /opt/modly/src/areas/workflows/nodes/mesh-optimizer/node_modules \
+ && rm -rf /opt/meshopt /root/.npm
+
+# 5. Background removal weights (rembg u2net), by checksum.
+RUN mkdir -p /opt/u2net \
+ && curl -fsSL -o /opt/u2net/u2net.onnx \
+ https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2net.onnx \
+ && echo "${U2NET_SHA256} /opt/u2net/u2net.onnx" | sha256sum -c -
+
+# 6. TripoSG extension (MIT). Folder name must equal the manifest id. An empty
+# vendor/ tells Modly's registry the pure-Python vendor step is not needed: the
+# triposg package lives in the venv's site-packages instead, which is exactly
+# what the extension's own setup.py installs.
+COPY requirements-triposg.txt /tmp/requirements-triposg.txt
+RUN git init -q ${EXTENSIONS_DIR}/triposg \
+ && git -C ${EXTENSIONS_DIR}/triposg remote add origin https://github.com/lightningpixel/modly-triposg-extension.git \
+ && git -C ${EXTENSIONS_DIR}/triposg fetch -q --depth 1 origin ${TRIPOSG_EXT_COMMIT} \
+ && git -C ${EXTENSIONS_DIR}/triposg checkout -q FETCH_HEAD \
+ && rm -rf ${EXTENSIONS_DIR}/triposg/.git \
+ && mkdir ${EXTENSIONS_DIR}/triposg/vendor \
+ && python3 -m venv --system-site-packages ${EXTENSIONS_DIR}/triposg/venv \
+ && ${EXTENSIONS_DIR}/triposg/venv/bin/pip install -r /tmp/requirements-triposg.txt
+# diso compiles against the shared torch, so build isolation must stay off.
+RUN ${EXTENSIONS_DIR}/triposg/venv/bin/pip install --no-build-isolation \
+ "git+https://github.com/SarahWeiii/diso.git@${DISO_COMMIT}"
+RUN git init -q /tmp/TripoSG \
+ && git -C /tmp/TripoSG remote add origin https://github.com/VAST-AI-Research/TripoSG.git \
+ && git -C /tmp/TripoSG fetch -q --depth 1 origin ${TRIPOSG_COMMIT} \
+ && git -C /tmp/TripoSG checkout -q FETCH_HEAD \
+ && SITE="$(${EXTENSIONS_DIR}/triposg/venv/bin/python -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])')" \
+ && cp -r /tmp/TripoSG/triposg "${SITE}/triposg" \
+ && cp /tmp/TripoSG/LICENSE /app/licenses/TRIPOSG-LICENSE \
+ && rm -rf /tmp/TripoSG
+
+# 7. Hunyuan3D 2 Mini Turbo extension (Tencent Hunyuan 3D 2.0 Community License).
+# hy3dgen installs from a pinned Hunyuan3D-2 commit with --no-deps: only the
+# shape pipeline runs, its dependencies are in requirements-hunyuan.txt, and the
+# paint pipeline's compiled rasterizers are never built.
+COPY requirements-hunyuan.txt /tmp/requirements-hunyuan.txt
+RUN git init -q ${EXTENSIONS_DIR}/hunyuan3d-mini-turbo \
+ && git -C ${EXTENSIONS_DIR}/hunyuan3d-mini-turbo remote add origin https://github.com/lightningpixel/modly-hunyuan3d-mini-turbo-extension.git \
+ && git -C ${EXTENSIONS_DIR}/hunyuan3d-mini-turbo fetch -q --depth 1 origin ${HUNYUAN_TURBO_EXT_COMMIT} \
+ && git -C ${EXTENSIONS_DIR}/hunyuan3d-mini-turbo checkout -q FETCH_HEAD \
+ && rm -rf ${EXTENSIONS_DIR}/hunyuan3d-mini-turbo/.git \
+ && python3 -m venv --system-site-packages ${EXTENSIONS_DIR}/hunyuan3d-mini-turbo/venv \
+ && ${EXTENSIONS_DIR}/hunyuan3d-mini-turbo/venv/bin/pip install -r /tmp/requirements-hunyuan.txt \
+ && git init -q /tmp/Hunyuan3D-2 \
+ && git -C /tmp/Hunyuan3D-2 remote add origin https://github.com/Tencent-Hunyuan/Hunyuan3D-2.git \
+ && git -C /tmp/Hunyuan3D-2 fetch -q --depth 1 origin ${HUNYUAN3D2_COMMIT} \
+ && git -C /tmp/Hunyuan3D-2 checkout -q FETCH_HEAD \
+ && ${EXTENSIONS_DIR}/hunyuan3d-mini-turbo/venv/bin/pip install --no-build-isolation --no-deps /tmp/Hunyuan3D-2 \
+ && cp /tmp/Hunyuan3D-2/LICENSE /app/licenses/HUNYUAN3D-2-LICENSE \
+ && cp /tmp/Hunyuan3D-2/NOTICE /app/licenses/HUNYUAN3D-2-NOTICE \
+ && rm -rf /tmp/Hunyuan3D-2
+
+WORKDIR /app
+COPY worker_security.py request_policy.py storage_backend.py instance_health.py \
+ gltf_meshopt.py postprocess.py main.py /app/
+COPY test_request_policy.py test_postprocess.py test_gltf_meshopt.py \
+ test_instance_health.py test_storage_backend.py test_app_contract.py /app/
+
+# Build-time gate, none of which needs a GPU: the pure-logic tests, then the
+# served contract, including a real start of the pinned Modly with both pinned
+# extensions, its repair/decimate/smooth ops, and an import of each extension's
+# model package inside its venv. A broken pin fails here, not on a revision.
+RUN python3 -m pytest /app/test_request_policy.py /app/test_postprocess.py \
+ /app/test_gltf_meshopt.py /app/test_instance_health.py \
+ /app/test_storage_backend.py -q -p no:cacheprovider \
+ && MODLY_CONTRACT_REQUIRE_BACKEND=1 python3 /app/test_app_contract.py
+
+EXPOSE 8080
+
+CMD ["uvicorn", "main:app", \
+ "--host", "0.0.0.0", \
+ "--port", "8080", \
+ "--workers", "1", \
+ "--timeout-keep-alive", "300"]
diff --git a/workers/modly/README.md b/workers/modly/README.md
new file mode 100644
index 000000000..6c1ac77a0
--- /dev/null
+++ b/workers/modly/README.md
@@ -0,0 +1,289 @@
+# model-modly: Modly's image-to-3D backend, headless on a Cloud Run GPU
+
+Based on [Modly](https://github.com/lightningpixel/modly) by
+[Lightning Pixel](https://github.com/lightningpixel), MIT license. Modly's
+LICENSE ships inside the image at `/app/licenses/MODLY-LICENSE`.
+
+Modly is a desktop app that runs open image-to-3D models locally through
+installable extensions. This worker runs Modly's own FastAPI backend, unchanged
+and pinned to a commit, as a child process on a Cloud Run NVIDIA L4, and puts the
+same authenticated task contract every other three.ws model worker speaks in
+front of it. The Forge reaches it as two lanes:
+
+| Forge backend id | Modly model | Weights | Licence |
+|---|---|---|---|
+| `modly` | `triposg/generate` (TripoSG, VAST AI) | `VAST-AI/TripoSG` | MIT |
+| `modly_hunyuan` | `hunyuan3d-mini-turbo/generate` (Hunyuan3D 2 Mini Turbo) | `tencent/Hunyuan3D-2mini` | Tencent Hunyuan 3D 2.0 Community License (territory-gated like every Hunyuan lane) |
+
+Both produce untextured geometry. On top of generation the worker runs an
+optional post-process chain, and the same chain can be applied to a mesh you
+already have:
+
+1. **repair** (Modly op): remove duplicate and degenerate faces, fix non-manifold
+ edges, fill holes up to a size.
+2. **decimate** (Modly op, meshoptimizer through Node): reduce to a target face
+ count.
+3. **smooth** (Modly op): Taubin or Laplacian smoothing.
+4. **uv_unwrap** (this worker, xatlas): a fresh UV atlas.
+5. **bake** (this worker, numpy/scipy): transfer colour from the mesh as it was
+ before steps 1 to 3 onto the new atlas.
+
+The finished GLB is meshopt-compressed with the pinned `gltfpack` binary.
+
+## Endpoints
+
+`POST /infer`, `GET /tasks/{id}` and `GET /results/{id}.glb` require
+`Authorization: Bearer $API_KEY`. `GET /health` and `GET /` are unauthenticated
+and carry no secrets: the platform reads them to decide whether the lane can take
+work. Modly's own API listens on `127.0.0.1` only and is never exposed (it has no
+auth and its optimize routes take filesystem paths).
+
+### `POST /infer`
+
+Image to 3D:
+
+```json
+{
+ "images": ["https://example.com/front.png"],
+ "model": "triposg",
+ "tier": "standard",
+ "seed": 42,
+ "params": { "guidance_scale": 7.0, "faces": 50000 },
+ "postprocess": { "repair": true, "decimate": 20000, "smooth": { "iterations": 3 } }
+}
+```
+
+Post-process an existing mesh (no generation):
+
+```json
+{
+ "mesh_url": "https://example.com/avatar.glb",
+ "postprocess": { "repair": true, "decimate": 5000, "bake": { "texture_size": 1024 } }
+}
+```
+
+| Field | Meaning |
+|---|---|
+| `images` | 1 to 6 `https://` URLs or `data:` URIs. Both models condition on one image, so the first is the subject. URLs are SSRF-checked. |
+| `mesh_url` | One `https://` URL or `data:` URI of a `.glb`, `.gltf`, `.obj`, `.ply` or `.stl`. Meshopt-compressed GLBs (most three.ws avatars) are decoded first. Needs at least one `postprocess` step. Send exactly one of `images` or `mesh_url`. |
+| `model` | `triposg` (default) or `hunyuan3d-mini-turbo` (aliases `hunyuan`, `tripo`, or the full Modly id). A model this deployment does not serve is a `422`. |
+| `tier` | `draft`, `standard`, `high`, `max`. TripoSG maps it to 20/30/50/50 steps; Hunyuan Mini Turbo to 5/10/20/20 steps at octree 256/380/512/512. |
+| `seed` | 0 to 4294967295. Omitted, the worker picks one and reports it, so every result is reproducible. |
+| `params` | Per-model knobs, clamped to the extension's own schema. TripoSG: `num_inference_steps` 8 to 50, `guidance_scale` 0 to 20, `foreground_ratio` 0.5 to 1, `faces` -1 (no cap) to 500000, `use_flash_decoder` `DiffDMC` or `Marching Cubes`. Hunyuan: `num_inference_steps` 5/10/20, `octree_resolution` 256/380/512, `guidance_scale` 1 to 10. Unknown keys are dropped and listed in `params_dropped`. |
+| `postprocess.repair` | `true` or `{remove_duplicates, fix_non_manifold, remove_degenerate, fill_holes, max_hole_size (10 to 10000)}`. |
+| `postprocess.decimate` | A face count (100 to 1000000) or `{target_faces}`. |
+| `postprocess.smooth` | `true` or `{iterations (1 to 50), lambda (0.1 to 1), mode: "taubin" \| "laplacian"}`. |
+| `postprocess.uv_unwrap` | `true`. |
+| `postprocess.bake` | `true` (1024) or `{texture_size: 256 \| 512 \| 1024 \| 2048 \| 4096}`. Implies `uv_unwrap`. A source with no colour is reported, never baked flat grey. |
+
+Steps always run in the order above, whatever order the keys arrive in. Response:
+`202 {"task_id": "...", "status": "queued", "model": "triposg/generate"}`.
+
+### `GET /tasks/{id}`
+
+```json
+{
+ "task_id": "...",
+ "status": "done",
+ "model": "triposg/generate",
+ "seed": 42,
+ "params": { "num_inference_steps": 30, "guidance_scale": 7.0, "seed": 42 },
+ "result_gcs_url": "https://storage.googleapis.com/three-ws-avatar-reconstructions/raw-meshes/modly/....glb",
+ "postprocess_applied": [{ "step": "decimate", "target_faces": 20000 }],
+ "packed": true,
+ "bytes": 812345,
+ "elapsed_ms": 41210
+}
+```
+
+`status` is `queued`, `running` (with `progress` 0 to 100 and the Modly `step`),
+`done` or `failed` (with `error`). `postprocess_applied` lists each step that ran
+with its settings and the details Modly's op reported. Without `GCS_BUCKET` the record carries
+`result_url: /results/{id}.glb` instead. A task whose instance died mid-run is
+reported `failed` once its heartbeat goes stale, never left `running` forever.
+
+### `GET /health`
+
+`200` while bringing up and when ready, `503` once bring-up has spent its retry
+budget (the Cloud Run liveness probe then recycles the instance). It reports
+`ready`, `models`, `gpu_name`, `modly_alive`, `modly_restarts`, `warmup_ms`,
+`load_error`, `draining` and `postprocess_steps`.
+
+## How it runs
+
+1. **Weights.** On start the front copies `WEIGHTS_GCS_URI/<extension>/` for each
+ enabled model into `MODELS_DIR` (the layout Modly reads), eight files at a time.
+2. **Modly.** It starts Modly's `uvicorn main:app` on `127.0.0.1:MODLY_PORT` with a
+ scrubbed environment (no `API_KEY`), waits for `/model/all`, and checks that
+ every enabled model is registered, downloaded and free of extension errors.
+3. **Warm-up.** One draft generation runs so the first caller does not pay the
+ model load.
+4. **Supervision.** A watchdog checks Modly every 5 seconds and brings it back if
+ it exits. A job in flight when that happens fails with a retryable error.
+5. **Memory.** After each job the front trims its heap and recycles the instance
+ if resident memory has grown past the configured ceiling.
+
+Each extension runs in its own venv, exactly as Modly's installer would build it,
+except that both venvs share one torch install in the system interpreter
+(`--system-site-packages`), which saves about 5 GB of image.
+
+## Run it and call it
+
+```bash
+# On a machine with an NVIDIA GPU (24 GB or more) and gcloud credentials that can
+# read gs://three-ws-model-weights:
+docker build -t model-modly workers/modly
+docker run --gpus all -p 8080:8080 \
+ -e API_KEY=dev-secret -e OUTPUT_DIR=/data \
+ -e WEIGHTS_GCS_URI=gs://three-ws-model-weights/modly \
+ -v "$PWD/data:/data" model-modly
+
+TASK=$(curl -s -X POST localhost:8080/infer \
+ -H "Authorization: Bearer dev-secret" -H "content-type: application/json" \
+ -d '{"images":["https://example.com/front.png"],"model":"triposg","postprocess":{"decimate":20000}}' \
+ | jq -r .task_id)
+curl -s localhost:8080/tasks/$TASK -H "Authorization: Bearer dev-secret"
+```
+
+Through the platform: `POST /api/forge` with
+`{"path":"image","backend":"modly"}` (TripoSG) or `{"backend":"modly_hunyuan"}`.
+
+## Environment
+
+| Variable | Default | Purpose |
+|---|---|---|
+| `API_KEY` | required | Shared bearer secret (Secret Manager `avatar-reconstruction-key` on Cloud Run). |
+| `GCS_BUCKET` | unset | Output bucket; results land at `raw-meshes/modly/{task_id}.glb`. Unset uses `OUTPUT_DIR`. |
+| `OUTPUT_DIR` | `/output` | Task and result volume for standalone use. |
+| `MAX_CONCURRENT` | `1` | Parallel jobs per instance. One GPU, so instance count is the concurrency. |
+| `MODLY_MODELS` | `triposg/generate,hunyuan3d-mini-turbo/generate` | Models this deployment serves. `triposg/generate` alone halves the weights held in memory. |
+| `MODLY_DEFAULT_MODEL` | `triposg/generate` | Model used when a request names none. |
+| `WEIGHTS_GCS_URI` | unset | `gs://` prefix the weights are copied from. Unset expects them already in `MODELS_DIR`. |
+| `MODELS_DIR` | `/tmp/modly-models` | Where Modly reads weights. |
+| `WORKSPACE_DIR` | `/tmp/modly-workspace` | Modly's output workspace; each task's directory is removed when it finishes. |
+| `EXTENSIONS_DIR` | `/opt/modly-extensions` | The pinned extensions and their venvs (set in the image). |
+| `MODLY_API_DIR` | `/opt/modly/api` | The pinned Modly backend (set in the image). |
+| `MODLY_PORT` | `8765` | Loopback port for Modly. |
+| `MODLY_START_TIMEOUT_S` | `180` | How long Modly may take to answer after start. |
+| `MODLY_WARMUP` | `1` | `0` skips the warm-up generation. |
+| `GENERATION_TIMEOUT_S` | `600` | Per-generation ceiling; the Modly job is cancelled past it. |
+| `IMAGE_FETCH_TIMEOUT_S` | `30` | Per-attempt fetch timeout for `images` and `mesh_url`. |
+| `MODEL_LOAD_ATTEMPTS` | `4` | Bring-up attempts before the error latches and `/health` returns 503. |
+| `MODEL_LOAD_RETRY_BASE_S`, `MODEL_LOAD_RETRY_CAP_S` | `15`, `120` | Bring-up backoff bounds. |
+
+The platform reads `MODEL_MODLY_URL` (this service's URL) and
+`GCP_RECONSTRUCTION_KEY` (the bearer secret) from the `three-ws-api` environment.
+Until `MODEL_MODLY_URL` is set both lanes report unconfigured and the router skips
+them; `trellis2` stays the default image-to-3D lane either way.
+
+## Pins
+
+| Component | Pin |
+|---|---|
+| Modly | `lightningpixel/modly` at `f11a4d2bd9fe994b9d30f76a36cb6c18ac8733ea` (v0.4.3) |
+| TripoSG extension | `lightningpixel/modly-triposg-extension` at `cc30cb8bedddf8141e78dc6cf88a4cb1a305d128` |
+| Hunyuan3D Mini Turbo extension | `lightningpixel/modly-hunyuan3d-mini-turbo-extension` at `9457b71b6e3ee5436240cac0d6c1bbcd02e9f53d` |
+| TripoSG source | `VAST-AI-Research/TripoSG` at `fc5c40990181e2a756c4e0b1c2f4d6b5202faf8c` |
+| Hunyuan3D-2 source (`hy3dgen`) | `Tencent-Hunyuan/Hunyuan3D-2` at `f8db63096c8282cb27354314d896feba5ba6ff8a` |
+| diso (DiffDMC decoder) | `SarahWeiii/diso` at `9792ad928ccb09bdec938779651ee03e395758a6` |
+| TripoSG weights | `VAST-AI/TripoSG` at `2c1c516d22d58db486a058d98d31bb6177344e06` (about 7.9 GB) |
+| Hunyuan3D 2 Mini weights | `tencent/Hunyuan3D-2mini` at `f90a0f7df7d5e6f71109cf333f6a95a0ae3194a6` (turbo DiT and VAE only, about 4.2 GB) |
+| torch | 2.6.0 + cu124, torchvision 0.21.0 |
+| Node | v20.18.1, sha256 checked |
+| meshoptimizer runtime | `meshopt/package-lock.json` (`@gltf-transform/*` 3.10.1, `meshoptimizer` 0.22.0) |
+| rembg u2net.onnx | sha256 `8d10d2f3bb75ae3b6d527c77944fc5e7dcd94b29809d47a739a7a728a912b491` |
+| gltfpack | v1.2, sha256 checked |
+
+Every Python dependency is pinned in `requirements-host.txt`,
+`requirements-triposg.txt` and `requirements-hunyuan.txt`.
+
+Official Modly extensions that are NOT shipped, and why: Hunyuan3D 2 Mini
+(`c927d5657249f91d09bb912900d5d4f7b26725fb`) and Mini Fast
+(`56a0bab6b039d9922d3ab228941eb8cd0dbb9ff2`) are slower step-count variants of
+the Hunyuan3D 2 Mini family the Turbo lane already serves; TRELLIS.2 GGUF
+(`caa85c7a1aa6c6ba9cb3f07f13878ba8e3864912`) duplicates the full-precision
+`trellis2` lane the Forge already runs on its own worker.
+
+## Licences
+
+- **Modly**: MIT, Copyright (c) 2026 Lightning Pixel. `/app/licenses/MODLY-LICENSE`.
+- **TripoSG**: MIT (code and weights). `/app/licenses/TRIPOSG-LICENSE`; the weight
+ repo's LICENSE is staged beside the weights.
+- **Hunyuan3D 2**: Tencent Hunyuan 3D 2.0 Community License. It does not apply in
+ the European Union, the United Kingdom or South Korea, so `modly_hunyuan` is in
+ `TENCENT_LANES` (`api/_lib/forge-territory.js`) and is never routed for a caller
+ there. `/app/licenses/HUNYUAN3D-2-LICENSE` and `HUNYUAN3D-2-NOTICE` ship in the
+ image; the weight repo's LICENSE and NOTICE are staged beside the weights.
+- **Modly's `uv_unwrapper` and `texture_baker` are not built.** They are derived
+ from Stability AI's stable-fast-3d under the Stability AI Community License, not
+ MIT. `postprocess.py` replaces them with xatlas (MIT) and a numpy/scipy (BSD)
+ bake.
+- **Background removal** uses rembg (MIT) with the u2net model (Apache 2.0).
+
+## Files
+
+| File | Role |
+|---|---|
+| `main.py` | The front: auth, task store, weight staging, Modly start and supervision, the job runner. |
+| `request_policy.py` | Model aliases, tier presets, param clamps, post-process plan, Modly status mapping. Pure logic. |
+| `postprocess.py` | xatlas UV unwrap, colour bake, gltfpack packing. |
+| `stage_weights.sh` | One-time mirror of both weight sets into `gs://three-ws-model-weights/modly`. |
+| `meshopt/` | The pinned Node packages Modly's decimate op loads. |
+| `worker_security.py`, `instance_health.py`, `storage_backend.py`, `gltf_meshopt.py` | Vendored shared modules, kept byte-identical by `npm run check:vendored`. |
+| `Dockerfile`, `cloudbuild.yaml` | The CUDA 12.4 image and the Cloud Build deploy. |
+| `test_*.py` | Unit tests and the contract test. Both run as the build-time gate in the Dockerfile; the contract test also starts the pinned Modly with both extensions and runs its repair, decimate and smooth ops. |
+
+Run the tests without a GPU (the contract test skips its Modly part when
+`/opt/modly` is absent):
+
+```bash
+cd workers/modly
+python3 -m pip install -r requirements-host.txt
+python3 -m pytest test_request_policy.py test_postprocess.py test_gltf_meshopt.py \
+ test_instance_health.py test_storage_backend.py -q -p no:cacheprovider
+python3 test_app_contract.py
+```
+
+## Deploy
+
+GPU worker deploys are owner-gated. The config pins the `three-ws-build@` build
+account and runs as `three-ws@`.
+
+```bash
+# 1. One time: mirror the weights (idempotent, skips what is already there).
+workers/modly/stage_weights.sh
+
+# 2. Build, push and deploy.
+gcloud builds submit --config workers/modly/cloudbuild.yaml \
+ --region us-central1 --project aerial-vehicle-466722-p5 \
+ --substitutions=SHORT_SHA=manual$(date +%s) .
+
+# 3. Point the API at it.
+gcloud run services update three-ws-api --region us-central1 \
+ --update-env-vars MODEL_MODLY_URL=$(gcloud run services describe model-modly \
+ --region us-central1 --format='value(status.url)')
+```
+
+### One-time GCP setup (already applied in `aerial-vehicle-466722-p5`)
+
+```bash
+gcloud artifacts repositories create model-modly --repository-format=docker \
+ --location us-central1
+gcloud storage buckets add-iam-policy-binding gs://three-ws-model-weights \
+ --member serviceAccount:[email protected] \
+ --role roles/storage.objectViewer
+gcloud storage buckets add-iam-policy-binding gs://three-ws-avatar-reconstructions \
+ --member serviceAccount:[email protected] \
+ --role roles/storage.objectAdmin
+```
+
+The service runs on one NVIDIA L4 (24 GB) with 32 GiB of memory and minimum
+instances `0`. The us-central1 L4 grant is shared by every GPU lane, so a warm
+floor is a quota decision: the first request after idle pays the weight copy,
+the Modly start and the warm-up (`BACKENDS.modly.coldStartSeconds`). Raise it with
+`gcloud run services update model-modly --min-instances=1` when quota allows, or
+add `modly` to `FORGE_KEEPWARM_LANES`.
+
+Related: [`../model-trellis2`](../model-trellis2) (the default image-to-3D lane),
+[`../../docs/forge-pipeline.md`](../../docs/forge-pipeline.md),
+[`../../docs/ops/gcp-model-workers.md`](../../docs/ops/gcp-model-workers.md).
diff --git a/workers/modly/cloudbuild.yaml b/workers/modly/cloudbuild.yaml
new file mode 100644
index 000000000..d7d1a3504
--- /dev/null
+++ b/workers/modly/cloudbuild.yaml
@@ -0,0 +1,93 @@
+substitutions:
+ _REGION: us-central1
+ # Runtime identity. It holds secretAccessor on avatar-reconstruction-key,
+ # objectViewer on the weights bucket and objectAdmin on the results bucket
+ # (bucket-level grants, see README.md "One-time GCP setup").
+ _SERVICE: model-modly
+ _REPO: model-modly
+ _GCS_BUCKET: three-ws-avatar-reconstructions
+ _WEIGHTS_BUCKET: three-ws-model-weights
+ _WEIGHTS_BUCKET_PREFIX: modly
+ # Both models by default. MODLY_MODELS=triposg/generate serves TripoSG alone
+ # and halves the weights held in the in-memory /tmp.
+ _MODLY_MODELS: triposg/generate,hunyuan3d-mini-turbo/generate
+ # Scale-to-zero by default. The us-central1 L4 grant is shared by every GPU
+ # lane (docs/ops/gcp-credits-plan.md), so a warm floor here is a quota
+ # decision, not a default. The first request after idle pays the weight copy,
+ # the Modly start and the warm-up generation, which the API reports as a cold
+ # start (BACKENDS.modly.coldStartSeconds). Raise it with
+ # `gcloud run services update model-modly --min-instances=1` once the grant
+ # allows, or add modly to FORGE_KEEPWARM_LANES.
+ _MIN_INSTANCES: "0"
+ _MAX_INSTANCES: "2"
+
+steps:
+ - id: build
+ name: gcr.io/cloud-builders/docker
+ dir: workers/modly
+ args:
+ - build
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+ - --cache-from
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+ - .
+
+ - id: push
+ name: gcr.io/cloud-builders/docker
+ args:
+ - push
+ - --all-tags
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server
+
+ - id: deploy
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: gcloud
+ args:
+ - run
+ - deploy
+ - ${_SERVICE}
+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --region=${_REGION}
+ - --service-account=${_RUN_SA}
+ - --platform=managed
+ - --port=8080
+ - --gpu=1
+ - --gpu-type=nvidia-l4
+ - --no-gpu-zonal-redundancy
+ - --no-cpu-throttling
+ - --cpu=8
+ # About 12 GB of weights live in the in-memory /tmp next to two model
+ # processes (one per extension, each loaded on first use).
+ - --memory=32Gi
+ - --min-instances=${_MIN_INSTANCES}
+ - --max-instances=${_MAX_INSTANCES}
+ - --timeout=900
+ # The worker authenticates every task route itself (API_KEY below); only
+ # /health and / are open.
+ - --allow-unauthenticated
+ - --set-env-vars=^@^GCS_BUCKET=${_GCS_BUCKET}@MAX_CONCURRENT=1@WEIGHTS_GCS_URI=gs://${_WEIGHTS_BUCKET}/${_WEIGHTS_BUCKET_PREFIX}@MODLY_MODELS=${_MODLY_MODELS}
+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest
+ # Recycle an instance whose bring-up is permanently dead. main.py answers
+ # /health with 503 only once the whole bring-up retry budget is spent, so
+ # an ordinary cold start (200 while loading) is never killed mid-load.
+ - --liveness-probe=httpGet.path=/health,initialDelaySeconds=60,periodSeconds=60,timeoutSeconds=10,failureThreshold=3
+
+images:
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+
+options:
+ machineType: E2_HIGHCPU_32
+ logging: CLOUD_LOGGING_ONLY
+
+# Torch, two extension venvs and the diso CUDA compile push the image build well
+# past Cloud Build's 10-minute default. Give it an hour.
+timeout: 3600s
+
+# The project's default compute SA was deleted: builds must pin the dedicated
+# build account or submits fail with "Unknown service account".
+serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]
diff --git a/workers/modly/main.py b/workers/modly/main.py
new file mode 100644
index 000000000..60a961e14
--- /dev/null
+++ b/workers/modly/main.py
@@ -0,0 +1,1042 @@
+"""
+Modly worker: Modly's local image-to-3D backend, run headless on a Cloud Run GPU
+behind the same authenticated task contract as every other three.ws model worker.
+
+Based on Modly (https://github.com/lightningpixel/modly) by Lightning Pixel
+(https://github.com/lightningpixel), MIT license. The pinned Modly checkout lives
+at /opt/modly and its LICENSE ships in the image at /app/licenses/MODLY-LICENSE.
+
+Shape of the service:
+
+ * Modly's own FastAPI app runs as a child process on 127.0.0.1:MODLY_PORT. It is
+ never reachable from outside the container: it has no auth, accepts absolute
+ filesystem paths on its optimize routes, and is built for a single desktop
+ user. Everything a caller can reach is this front.
+ * The front owns auth (worker_security), request policy (request_policy), task
+ records in GCS (storage_backend), instance health (instance_health), weight
+ staging, Modly supervision, the post-process chain and the upload.
+ * Generation runs through Modly's official extensions, pinned by commit in the
+ Dockerfile: TripoSG (MIT, VAST AI) and Hunyuan3D 2 Mini Turbo (Tencent
+ Hunyuan Community License). Each runs in its own venv as a Modly subprocess.
+
+API contract (consumed by the Forge router, same shape as workers/model-trellis2):
+ POST /infer { images?: [data-uri|url, ...], mesh_url?: data-uri|url,
+ model?: "triposg" | "hunyuan3d-mini-turbo" | <full Modly id>,
+ tier?: draft|standard|high|max, seed?: int, params?: {...},
+ postprocess?: { repair?, decimate?, smooth?, uv_unwrap?, bake? },
+ body_type?: str, job_id?: str }
+ -> 202 { task_id, status: "queued", model }
+
+ Exactly one of `images` (image to 3D, first image is the subject) or `mesh_url`
+ (post-process an existing mesh; needs at least one postprocess step).
+
+ GET /tasks/:id -> { task_id, status, model, progress?, step?, result_gcs_url?,
+ result_url?, seed?, params?, postprocess_applied?, packed?,
+ bytes?, elapsed_ms?, error? }
+ GET /results/:id.glb -> generated GLB when OUTPUT_DIR local storage is active
+ GET /health -> readiness; 503 once bring-up has spent its retry budget
+ GET / -> unauthenticated descriptor for the platform's warmth probe
+
+Environment variables (README.md carries the full table):
+ API_KEY, GCS_BUCKET, OUTPUT_DIR, MAX_CONCURRENT, MODLY_MODELS,
+ MODLY_DEFAULT_MODEL, WEIGHTS_GCS_URI, MODELS_DIR, WORKSPACE_DIR,
+ EXTENSIONS_DIR, MODLY_API_DIR, MODLY_PORT, MODLY_START_TIMEOUT_S,
+ MODLY_WARMUP, GENERATION_TIMEOUT_S, IMAGE_FETCH_TIMEOUT_S,
+ MODEL_LOAD_ATTEMPTS, MODEL_LOAD_RETRY_BASE_S, MODEL_LOAD_RETRY_CAP_S
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import io
+import json
+import logging
+import os
+import random
+import shutil
+import signal
+import subprocess
+import sys
+import time
+import uuid
+from contextlib import asynccontextmanager
+from pathlib import Path
+from typing import Any, Optional
+from urllib.parse import urlsplit
+
+import httpx
+from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Response
+from fastapi.responses import FileResponse
+from google.api_core.exceptions import NotFound
+from google.cloud import storage
+from PIL import Image, ImageDraw
+from pydantic import BaseModel, Field
+
+import postprocess
+from gltf_meshopt import decode_if_meshopt
+from instance_health import (
+ HEARTBEAT_SECS,
+ MemorySample,
+ read_memory,
+ should_recycle,
+ task_is_orphaned,
+ trim_heap,
+)
+from request_policy import (
+ FETCH_ATTEMPTS,
+ TRIPOSG,
+ PolicyError,
+ build_generation_params,
+ call_with_retry,
+ interpret_job,
+ parse_model_list,
+ parse_postprocess,
+ readiness_problems,
+ resolve_model,
+ workspace_relative,
+)
+from storage_backend import LocalStorage
+from worker_security import (
+ UnsafeUrlError,
+ fetch_remote_bytes,
+ require_api_key,
+ safe_error,
+)
+
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s %(levelname)s %(name)s %(message)s",
+)
+log = logging.getLogger("modly")
+
+SERVICE = "model-modly"
+LANE = "modly"
+
+API_KEY = os.environ["API_KEY"]
+GCS_BUCKET = os.environ.get("GCS_BUCKET", "").strip()
+OUTPUT_DIR = os.environ.get("OUTPUT_DIR", "/output")
+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))
+ENABLED_MODELS = parse_model_list(
+ os.environ.get("MODLY_MODELS", "triposg/generate,hunyuan3d-mini-turbo/generate")
+)
+DEFAULT_MODEL = resolve_model(os.environ.get("MODLY_DEFAULT_MODEL", TRIPOSG), ENABLED_MODELS, ENABLED_MODELS[0])
+# Weights are copied from GCS to local disk at bring-up (no FUSE mount: the
+# safetensors loaders make random reads that the FUSE driver stalls on). Each
+# enabled model lives at <WEIGHTS_GCS_URI>/<extension>/<node>/, mirroring the
+# MODELS_DIR/<extension>/<node>/ layout Modly reads. Unset, MODELS_DIR must
+# already hold the trees (a mounted volume, or a local run).
+WEIGHTS_GCS_URI = os.environ.get("WEIGHTS_GCS_URI", "").rstrip("/")
+MODELS_DIR = Path(os.environ.get("MODELS_DIR", "/tmp/modly-models"))
+WORKSPACE_DIR = Path(os.environ.get("WORKSPACE_DIR", "/tmp/modly-workspace"))
+EXTENSIONS_DIR = Path(os.environ.get("EXTENSIONS_DIR", "/opt/modly-extensions"))
+MODLY_API_DIR = Path(os.environ.get("MODLY_API_DIR", "/opt/modly/api"))
+MODLY_PYTHON = os.environ.get("MODLY_PYTHON", sys.executable)
+MODLY_PORT = int(os.environ.get("MODLY_PORT", "8765"))
+MODLY_URL = f"http://127.0.0.1:{MODLY_PORT}"
+MODLY_START_TIMEOUT_S = float(os.environ.get("MODLY_START_TIMEOUT_S", "180"))
+# A warm-up generation proves the whole chain (extension venv, CUDA kernels,
+# weights, background removal) before the instance reports ready, and leaves the
+# default model resident so the first real job does not pay its load.
+MODLY_WARMUP = os.environ.get("MODLY_WARMUP", "1") != "0"
+GENERATION_TIMEOUT_S = float(os.environ.get("GENERATION_TIMEOUT_S", "600"))
+READY_WAIT_S = float(os.environ.get("READY_WAIT_S", "1800"))
+IMAGE_FETCH_TIMEOUT_S = float(os.environ.get("IMAGE_FETCH_TIMEOUT_S", "30"))
+MODEL_LOAD_ATTEMPTS = int(os.environ.get("MODEL_LOAD_ATTEMPTS", "4"))
+MODEL_LOAD_RETRY_BASE_S = float(os.environ.get("MODEL_LOAD_RETRY_BASE_S", "15"))
+MODEL_LOAD_RETRY_CAP_S = float(os.environ.get("MODEL_LOAD_RETRY_CAP_S", "120"))
+POLL_INTERVAL_S = 2.0
+MESH_SUFFIXES = (".glb", ".gltf", ".obj", ".ply", ".stl")
+# Environment the front holds that Modly and its extension subprocesses must not
+# inherit: Modly copies os.environ into every extension process.
+_PRIVATE_ENV = ("API_KEY",)
+
+_bucket: Optional[storage.Bucket] = None
+_local_storage: Optional[LocalStorage] = None
+_sem: Optional[asyncio.Semaphore] = None
+_ready: Optional[asyncio.Event] = None
+_bringup_lock: Optional[asyncio.Lock] = None
+_modly_proc: Optional[subprocess.Popen] = None
+_load_error: Optional[str] = None
+_load_attempts = 0
+_modly_restarts = 0
+_warmup_ms: Optional[int] = None
+_gpu_name: Optional[str] = None
+_shutting_down = False
+# In-memory cache only: Cloud Run runs this service across several containers
+# with no session affinity, so the durable source of truth is the
+# `tasks/{task_id}.json` blob in GCS (see _update_task / _resolve_task).
+_tasks: dict[str, dict] = {}
+_task_locks: dict[str, asyncio.Lock] = {}
+_live_tasks: set[str] = set()
+_memory_baseline: Optional[MemorySample] = None
+_draining = False
+_restart_signalled = False
+
+
+class ModlyUnavailable(RuntimeError):
+ """The Modly backend stopped answering mid-job (crash, OOM, restart)."""
+
+
+class ImageSourceError(ValueError):
+ """A caller-supplied image or mesh could not be read. Safe to report verbatim."""
+
+
+# ── Weight staging ────────────────────────────────────────────────────────────
+
+def _gcs_split(uri: str) -> tuple[str, str]:
+ bucket_name, _, prefix = uri[len("gs://"):].partition("/")
+ return bucket_name, prefix.strip("/")
+
+
+def _download_blob(blob, dest: Path) -> None:
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ if dest.exists() and blob.size is not None and dest.stat().st_size == blob.size:
+ return
+ partial = dest.with_name(dest.name + ".part")
+ blob.download_to_filename(str(partial))
+ partial.replace(dest)
+
+
+def _stage_weights() -> None:
+ """Copy every enabled model's weight tree from GCS into MODELS_DIR.
+
+ Files already present at the right size are skipped, so a bring-up retry or a
+ Modly restart costs a listing, not a re-download.
+ """
+ MODELS_DIR.mkdir(parents=True, exist_ok=True)
+ if not WEIGHTS_GCS_URI:
+ log.info("WEIGHTS_GCS_URI unset; serving weights already in %s", MODELS_DIR)
+ return
+ if not WEIGHTS_GCS_URI.startswith("gs://"):
+ raise ValueError(f"WEIGHTS_GCS_URI must be a gs:// URI, got {WEIGHTS_GCS_URI!r}")
+ from concurrent.futures import ThreadPoolExecutor
+
+ client = storage.Client()
+ bucket_name, prefix = _gcs_split(WEIGHTS_GCS_URI)
+ for model in ENABLED_MODELS:
+ model_prefix = f"{prefix}/{model}/" if prefix else f"{model}/"
+ blobs = [b for b in client.list_blobs(bucket_name, prefix=model_prefix) if not b.name.endswith("/")]
+ if not blobs:
+ raise FileNotFoundError(
+ f"no weights staged at gs://{bucket_name}/{model_prefix}; "
+ "run workers/modly/stage_weights.sh"
+ )
+ dest_root = MODELS_DIR / model
+ t0 = time.time()
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ list(pool.map(lambda b: _download_blob(b, dest_root / b.name[len(model_prefix):]), blobs))
+ total = sum(b.size or 0 for b in blobs)
+ log.info(
+ "staged %s: %d files, %.2f GB in %.1fs",
+ model, len(blobs), total / 1e9, time.time() - t0,
+ )
+
+
+# ── Modly process ─────────────────────────────────────────────────────────────
+
+def _modly_env() -> dict[str, str]:
+ env = {k: v for k, v in os.environ.items() if k not in _PRIVATE_ENV}
+ env.update(
+ {
+ "MODELS_DIR": str(MODELS_DIR),
+ "WORKSPACE_DIR": str(WORKSPACE_DIR),
+ "EXTENSIONS_DIR": str(EXTENSIONS_DIR),
+ "MODLY_API_URL": MODLY_URL,
+ "SELECTED_MODEL_ID": DEFAULT_MODEL,
+ # Weights are staged ahead of time; nothing may reach for the Hub.
+ "HF_HUB_OFFLINE": "1",
+ "TRANSFORMERS_OFFLINE": "1",
+ "PYTHONUNBUFFERED": "1",
+ }
+ )
+ return env
+
+
+def _start_modly() -> subprocess.Popen:
+ """Launch Modly's FastAPI app on loopback, in its own process group."""
+ global _modly_proc
+ _stop_modly()
+ WORKSPACE_DIR.mkdir(parents=True, exist_ok=True)
+ MODELS_DIR.mkdir(parents=True, exist_ok=True)
+ _modly_proc = subprocess.Popen(
+ [
+ MODLY_PYTHON, "-m", "uvicorn", "main:app",
+ "--host", "127.0.0.1",
+ "--port", str(MODLY_PORT),
+ "--workers", "1",
+ "--log-level", "warning",
+ ],
+ cwd=str(MODLY_API_DIR),
+ env=_modly_env(),
+ start_new_session=True,
+ )
+ log.info("Modly started (pid %d) on %s", _modly_proc.pid, MODLY_URL)
+ return _modly_proc
+
+
+def _stop_modly(timeout: float = 20.0) -> None:
+ """Stop Modly and every extension subprocess it spawned (one process group)."""
+ global _modly_proc
+ proc = _modly_proc
+ _modly_proc = None
+ if proc is None or proc.poll() is not None:
+ return
+ try:
+ os.killpg(proc.pid, signal.SIGTERM)
+ proc.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ os.killpg(proc.pid, signal.SIGKILL)
+ proc.wait(timeout=5)
+ except ProcessLookupError:
+ pass
+
+
+def _modly_alive() -> bool:
+ return _modly_proc is not None and _modly_proc.poll() is None
+
+
+def _wait_modly_http(timeout: float) -> None:
+ """Block until Modly answers /model/all (its registry is initialized by then)."""
+ deadline = time.time() + timeout
+ last: Optional[BaseException] = None
+ with httpx.Client(base_url=MODLY_URL, timeout=10.0) as client:
+ while time.time() < deadline:
+ if not _modly_alive():
+ code = _modly_proc.returncode if _modly_proc is not None else None
+ raise RuntimeError(f"Modly exited during start (exit code {code})")
+ try:
+ if client.get("/model/all").status_code == 200:
+ return
+ except httpx.HTTPError as exc:
+ last = exc
+ time.sleep(1.0)
+ raise TimeoutError(f"Modly did not answer within {timeout:.0f}s ({type(last).__name__ if last else 'no response'})")
+
+
+def _modly_readiness() -> list[str]:
+ with httpx.Client(base_url=MODLY_URL, timeout=30.0) as client:
+ all_status = client.get("/model/all").raise_for_status().json()
+ errors = client.get("/extensions/errors").raise_for_status().json()
+ return readiness_problems(ENABLED_MODELS, all_status, errors if isinstance(errors, dict) else {})
+
+
+def _query_gpu_name() -> Optional[str]:
+ try:
+ out = subprocess.run(
+ ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
+ capture_output=True, text=True, timeout=10, check=True,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ name = out.stdout.strip().splitlines()
+ return name[0] if name else None
+
+
+def _warmup_image_png() -> bytes:
+ """A lit sphere on a white ground: a subject background removal can isolate."""
+ size = 512
+ img = Image.new("RGB", (size, size), (255, 255, 255))
+ draw = ImageDraw.Draw(img)
+ for i in range(160, 0, -4):
+ shade = int(60 + (160 - i) * 1.1)
+ offset = (160 - i) // 3
+ draw.ellipse(
+ (256 - i - offset, 256 - i - offset, 256 + i - offset, 256 + i - offset),
+ fill=(shade, int(shade * 0.7), int(shade * 0.5)),
+ )
+ buf = io.BytesIO()
+ img.save(buf, format="PNG")
+ return buf.getvalue()
+
+
+async def _warmup(client: httpx.AsyncClient) -> None:
+ global _warmup_ms
+ t0 = time.time()
+ params, _ = build_generation_params(DEFAULT_MODEL, "draft", None, 0)
+ collection = f"warmup-{uuid.uuid4().hex[:12]}"
+ try:
+ job_id = await _submit_generation(client, DEFAULT_MODEL, _warmup_image_png(), params, collection)
+ await _await_generation(client, job_id, on_progress=None)
+ finally:
+ shutil.rmtree(WORKSPACE_DIR / collection, ignore_errors=True)
+ _warmup_ms = int((time.time() - t0) * 1000)
+ log.info("warm-up generation on %s finished in %.1fs", DEFAULT_MODEL, _warmup_ms / 1000)
+
+
+async def _bring_up_once() -> None:
+ global _memory_baseline, _gpu_name
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(None, _stage_weights)
+ await loop.run_in_executor(None, _start_modly)
+ await loop.run_in_executor(None, _wait_modly_http, MODLY_START_TIMEOUT_S)
+ problems = await loop.run_in_executor(None, _modly_readiness)
+ if problems:
+ raise RuntimeError("; ".join(problems))
+ if _gpu_name is None:
+ _gpu_name = await loop.run_in_executor(None, _query_gpu_name)
+ if MODLY_WARMUP:
+ async with httpx.AsyncClient(base_url=MODLY_URL, timeout=60.0) as client:
+ await _warmup(client)
+ await loop.run_in_executor(None, trim_heap)
+ _memory_baseline = read_memory()
+ if _memory_baseline is not None:
+ log.info("memory after bring-up: %s", _memory_baseline.describe())
+
+
+async def _bring_up_bg() -> None:
+ """Stage weights, start Modly, prove it can generate, then signal readiness.
+
+ Retried with exponential backoff, and _load_error stays unset while attempts
+ remain, so a job that arrives mid-retry waits on _ready instead of failing
+ against a half-written verdict (the 2026-09-02 lesson recorded in
+ workers/model-trellis2/main.py). Only a spent budget latches the error; from
+ there /health answers 503 and /infer refuses new work so callers fail over.
+ """
+ global _load_error, _load_attempts
+ async with _bringup_lock:
+ attempts = max(1, MODEL_LOAD_ATTEMPTS)
+ for attempt in range(1, attempts + 1):
+ _load_attempts = attempt
+ try:
+ await _bring_up_once()
+ _load_error = None
+ _ready.set()
+ log.info("Modly ready (attempt %d, models %s)", attempt, ", ".join(ENABLED_MODELS))
+ return
+ except Exception as exc: # noqa: BLE001 - surfaced via /health + task status
+ await asyncio.get_event_loop().run_in_executor(None, _stop_modly)
+ if attempt >= attempts:
+ _load_error = safe_error(exc, context="modly bring-up")
+ log.error("Modly bring-up FAILED after %d attempt(s): %s", attempt, exc)
+ return
+ delay = min(MODEL_LOAD_RETRY_BASE_S * (2 ** (attempt - 1)), MODEL_LOAD_RETRY_CAP_S)
+ log.warning(
+ "Modly bring-up attempt %d/%d failed (%s); retrying in %.0fs",
+ attempt, attempts, exc, delay,
+ )
+ await asyncio.sleep(delay)
+
+
+async def _supervise_modly() -> None:
+ """Restart Modly if it dies after a successful bring-up.
+
+ A crashed backend with a green /health is the failure this guards against:
+ the instance would keep accepting jobs it can only fail. Readiness is cleared
+ first so new jobs wait, and the same retry budget governs the restart.
+ """
+ global _modly_restarts
+ while not _shutting_down:
+ await asyncio.sleep(5.0)
+ if _shutting_down or not _ready.is_set() or _modly_alive():
+ continue
+ code = _modly_proc.returncode if _modly_proc is not None else None
+ log.error("Modly exited unexpectedly (exit code %s); restarting", code)
+ _ready.clear()
+ _modly_restarts += 1
+ await _bring_up_bg()
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ global _bucket, _local_storage, _sem, _ready, _bringup_lock, _shutting_down
+ if GCS_BUCKET:
+ _bucket = storage.Client().bucket(GCS_BUCKET)
+ _local_storage = None
+ else:
+ _bucket = None
+ _local_storage = LocalStorage(OUTPUT_DIR)
+ _sem = asyncio.Semaphore(MAX_CONCURRENT)
+ _ready = asyncio.Event()
+ _bringup_lock = asyncio.Lock()
+ # Bring-up runs in the BACKGROUND: uvicorn runs the lifespan before it binds
+ # the socket, and staging plus a warm-up generation outlasts Cloud Run's
+ # startup probe window. Jobs that arrive early wait on _ready.
+ bringup = asyncio.create_task(_bring_up_bg())
+ supervisor = asyncio.create_task(_supervise_modly())
+ log.info("Service starting, Modly coming up in background (models %s)", ", ".join(ENABLED_MODELS))
+ try:
+ yield
+ finally:
+ _shutting_down = True
+ supervisor.cancel()
+ bringup.cancel()
+ await asyncio.get_event_loop().run_in_executor(None, _stop_modly)
+
+
+app = FastAPI(title="modly", lifespan=lifespan)
+
+
+def _require_api_key(authorization: str) -> None:
+ try:
+ require_api_key(authorization, API_KEY)
+ except PermissionError as exc:
+ raise HTTPException(status_code=401, detail=str(exc)) from exc
+
+
+# ── Caller input ──────────────────────────────────────────────────────────────
+
+def _source_label(src: str) -> str:
+ if src.startswith("data:"):
+ return "inline data uri"
+ host = urlsplit(src).hostname
+ return host or src[:60]
+
+
+def _fetch_bytes(src: str) -> bytes:
+ """Fetch one https source, SSRF-hardened, retrying transient failures."""
+ label = _source_label(src)
+
+ def attempt() -> bytes:
+ return fetch_remote_bytes(src, timeout=IMAGE_FETCH_TIMEOUT_S)
+
+ def note_retry(number: int, delay: float, exc: BaseException) -> None:
+ log.warning(
+ "fetch attempt %d/%d for %s failed (%s); retrying in %.1fs",
+ number, FETCH_ATTEMPTS, label, type(exc).__name__, delay,
+ )
+
+ try:
+ return call_with_retry(attempt, sleep=time.sleep, on_retry=note_retry)
+ except UnsafeUrlError as exc:
+ raise ImageSourceError(f"refused to fetch source ({label}): {exc}") from exc
+ except httpx.HTTPStatusError as exc:
+ raise ImageSourceError(f"source {label} returned HTTP {exc.response.status_code}") from exc
+ except httpx.HTTPError as exc:
+ raise ImageSourceError(
+ f"source {label} unreachable after {FETCH_ATTEMPTS} attempts "
+ f"({type(exc).__name__}); check the URL is publicly readable"
+ ) from exc
+ except ValueError as exc:
+ raise ImageSourceError(f"source {label} rejected: {exc}") from exc
+
+
+def _read_source(src: str, kind: str) -> bytes:
+ if src.startswith("data:"):
+ header, _, payload = src.partition(",")
+ if ";base64" not in header:
+ raise ImageSourceError(f"inline {kind} data uri must be base64")
+ try:
+ return base64.b64decode(payload, validate=True)
+ except Exception as exc: # noqa: BLE001 - caller's own payload, report it as such
+ raise ImageSourceError(f"inline data uri is not valid base64: {exc}") from exc
+ if src.startswith("https://"):
+ return _fetch_bytes(src)
+ raise ImageSourceError(f"unsupported {kind} source: {src[:60]}")
+
+
+def _decode_image(src: str) -> Image.Image:
+ """Caller image to RGBA. Alpha is kept: an existing cutout survives rembg."""
+ if not (src.startswith("data:image") or src.startswith("https://")):
+ raise ImageSourceError(f"unsupported image source: {src[:60]}")
+ data = _read_source(src, "image")
+ try:
+ return Image.open(io.BytesIO(data)).convert("RGBA")
+ except Exception as exc: # noqa: BLE001 - undecodable caller input
+ raise ImageSourceError(
+ f"image source {_source_label(src)} is not a decodable image ({type(exc).__name__})"
+ ) from exc
+
+
+def _image_png(src: str) -> bytes:
+ buf = io.BytesIO()
+ _decode_image(src).save(buf, format="PNG")
+ return buf.getvalue()
+
+
+def _mesh_suffix(src: str) -> str:
+ if src.startswith("data:"):
+ mime = src[5:].split(";", 1)[0].split(",", 1)[0].lower()
+ return {
+ "model/gltf+json": ".gltf",
+ "model/obj": ".obj",
+ "model/stl": ".stl",
+ "application/ply": ".ply",
+ }.get(mime, ".glb")
+ suffix = Path(urlsplit(src).path).suffix.lower()
+ return suffix if suffix in MESH_SUFFIXES else ".glb"
+
+
+def _load_caller_mesh(src: str):
+ """Fetch, meshopt-decode and parse a caller mesh. Returns a trimesh.Trimesh."""
+ data = _read_source(src, "mesh")
+ suffix = _mesh_suffix(src)
+ try:
+ data, suffix = decode_if_meshopt(data, suffix)
+ except ValueError as exc:
+ raise ImageSourceError(f"mesh source {_source_label(src)}: {exc}") from exc
+ try:
+ return postprocess.load_mesh(data, suffix)
+ except postprocess.MeshError as exc:
+ raise ImageSourceError(f"mesh source {_source_label(src)}: {exc}") from exc
+
+
+# ── Task records ──────────────────────────────────────────────────────────────
+
+def _task_blob(task_id: str):
+ if _bucket is None:
+ raise RuntimeError("GCS task storage is not active")
+ return _bucket.blob(f"tasks/{task_id}.json")
+
+
+def _using_gcs() -> bool:
+ return bool(GCS_BUCKET)
+
+
+def _get_local_storage() -> LocalStorage:
+ global _local_storage
+ if _local_storage is None:
+ _local_storage = LocalStorage(OUTPUT_DIR)
+ return _local_storage
+
+
+async def _update_task(task_id: str, **fields) -> dict:
+ """Merge `fields` into the task and persist it. No fields = a heartbeat."""
+ lock = _task_locks.setdefault(task_id, asyncio.Lock())
+ async with lock:
+ task = _tasks.setdefault(task_id, {"task_id": task_id})
+ task.update(fields)
+ task["updated_at"] = time.time()
+ snapshot = task.copy()
+ loop = asyncio.get_event_loop()
+ if _using_gcs():
+ payload = json.dumps(snapshot)
+ await loop.run_in_executor(
+ None,
+ lambda: _task_blob(task_id).upload_from_string(payload, content_type="application/json"),
+ )
+ else:
+ await loop.run_in_executor(None, _get_local_storage().write_task, snapshot)
+ return task
+
+
+async def _heartbeat(task_id: str) -> None:
+ while True:
+ await asyncio.sleep(HEARTBEAT_SECS)
+ try:
+ await _update_task(task_id)
+ except Exception as exc: # noqa: BLE001 - a missed beat must not kill the job
+ log.warning("[%s] heartbeat write failed: %s", task_id, exc)
+
+
+_TERMINAL_STATUSES = frozenset({"done", "failed"})
+
+
+async def _resolve_task(task_id: str) -> dict:
+ """Poll reader: trust the local cache only for terminal records, re-read the
+ durable copy otherwise, and expire a record whose runner went silent."""
+ task = _tasks.get(task_id)
+ if task is not None and task.get("status") in _TERMINAL_STATUSES:
+ return task
+ loop = asyncio.get_event_loop()
+ try:
+ if _using_gcs():
+ data = await loop.run_in_executor(None, _task_blob(task_id).download_as_bytes)
+ task = json.loads(data)
+ else:
+ task = await loop.run_in_executor(None, _get_local_storage().read_task, task_id)
+ except (NotFound, FileNotFoundError, ValueError):
+ if task is not None:
+ return task
+ raise HTTPException(status_code=404, detail="task not found")
+ except Exception as exc:
+ raise HTTPException(status_code=502, detail=safe_error(exc, context="task lookup")) from exc
+ status = task.get("status")
+ if status in _TERMINAL_STATUSES:
+ _tasks[task_id] = task
+ return task
+ if task_is_orphaned(status, task.get("updated_at"), time.time()):
+ _tasks[task_id] = task
+ failed = await _update_task(
+ task_id,
+ status="failed",
+ error="task orphaned: its runner instance stopped mid-job "
+ "(restart or out of memory); retry the request",
+ )
+ _task_locks.pop(task_id, None)
+ return failed
+ return task
+
+
+# ── Modly calls ───────────────────────────────────────────────────────────────
+
+async def _submit_generation(
+ client: httpx.AsyncClient, model: str, png: bytes, params: dict, collection: str
+) -> str:
+ """POST /generate/from-image. Modly's own remesh and texture stages stay off:
+ the front's post-process chain owns everything after the raw mesh."""
+ try:
+ res = await client.post(
+ "/generate/from-image",
+ files={"image": ("input.png", png, "image/png")},
+ data={
+ "model_id": model,
+ "collection": collection,
+ "remesh": "none",
+ "enable_texture": "false",
+ "params": json.dumps(params),
+ },
+ )
+ except httpx.TransportError as exc:
+ raise ModlyUnavailable(f"Modly unreachable on submit ({type(exc).__name__})") from exc
+ if res.status_code != 200:
+ raise RuntimeError(f"Modly refused the generation (HTTP {res.status_code}): {res.text[:300]}")
+ job_id = res.json().get("job_id")
+ if not job_id:
+ raise RuntimeError("Modly accepted the generation without a job id")
+ return job_id
+
+
+async def _await_generation(client: httpx.AsyncClient, job_id: str, on_progress) -> Path:
+ """Poll a Modly job to completion. Returns the output file's absolute path."""
+ deadline = time.time() + GENERATION_TIMEOUT_S
+ last: tuple[Any, Any] = (None, None)
+ while True:
+ try:
+ res = await client.get(f"/generate/status/{job_id}")
+ except httpx.TransportError as exc:
+ raise ModlyUnavailable(f"Modly stopped answering mid-job ({type(exc).__name__})") from exc
+ if res.status_code == 404:
+ raise RuntimeError("Modly lost track of the generation job")
+ res.raise_for_status()
+ job = res.json()
+ state, detail = interpret_job(job)
+ if state == "done":
+ path = (WORKSPACE_DIR / workspace_relative(detail)).resolve()
+ if WORKSPACE_DIR.resolve() not in path.parents or not path.is_file():
+ raise RuntimeError("Modly reported an output file that is not in its workspace")
+ return path
+ if state == "failed":
+ raise RuntimeError(detail)
+ current = (job.get("progress"), job.get("step"))
+ if on_progress is not None and current != last:
+ last = current
+ await on_progress(job.get("progress"), job.get("step"))
+ if time.time() > deadline:
+ try:
+ await client.post(f"/generate/cancel/{job_id}")
+ except httpx.HTTPError as exc:
+ log.warning("cancel of timed-out Modly job %s failed: %s", job_id, exc)
+ raise TimeoutError(f"generation exceeded {GENERATION_TIMEOUT_S:.0f}s and was cancelled")
+ await asyncio.sleep(POLL_INTERVAL_S)
+
+
+async def _modly_op(client: httpx.AsyncClient, name: str, path: Path, params: dict) -> tuple[Path, dict]:
+ """Run one Modly mesh op (repair | decimate | smooth) on a workspace file."""
+ try:
+ res = await client.post(f"/optimize/op/{name}", json={"path": str(path), "params": params})
+ except httpx.TransportError as exc:
+ raise ModlyUnavailable(f"Modly unreachable during {name} ({type(exc).__name__})") from exc
+ if res.status_code != 200:
+ try:
+ detail = res.json().get("detail")
+ except ValueError:
+ detail = res.text
+ raise RuntimeError(f"{name} failed (HTTP {res.status_code}): {str(detail)[:300]}")
+ body = res.json()
+ out = (WORKSPACE_DIR / workspace_relative(body.get("url"))).resolve()
+ if not out.is_file():
+ raise RuntimeError(f"{name} reported an output file that does not exist")
+ details = {k: v for k, v in body.items() if k not in ("path", "url")}
+ return out, details
+
+
+# ── The job ───────────────────────────────────────────────────────────────────
+
+async def _run_inference(task_id: str, *args, **kwargs) -> None:
+ _live_tasks.add(task_id)
+ beat = asyncio.create_task(_heartbeat(task_id))
+ try:
+ await _run_job(task_id, *args, **kwargs)
+ finally:
+ beat.cancel()
+ _live_tasks.discard(task_id)
+ _task_locks.pop(task_id, None)
+ shutil.rmtree(WORKSPACE_DIR / task_id, ignore_errors=True)
+ _recycle_if_bloated(task_id)
+
+
+def _recycle_if_bloated(task_id: str) -> None:
+ """Restart an idle instance whose memory ratcheted toward its ceiling (see
+ workers/model-trellis2/main.py for the full rationale). Draining refuses new
+ work with a 503 so callers fail over; queued jobs still finish first."""
+ global _draining, _restart_signalled
+ sample = read_memory()
+ if sample is not None:
+ log.info("[%s] memory after job: %s", task_id, sample.describe())
+ if not _draining:
+ if not should_recycle(sample, _memory_baseline):
+ return
+ _draining = True
+ log.warning(
+ "recycling instance: memory %s, up from %s after bring-up; draining %d queued job(s) first",
+ sample.describe(),
+ _memory_baseline.describe() if _memory_baseline else "unknown",
+ len(_live_tasks),
+ )
+ if _live_tasks or _restart_signalled:
+ return
+ _restart_signalled = True
+ log.warning("recycling instance: idle, restarting now")
+ signal.raise_signal(signal.SIGTERM)
+
+
+def _local_steps(original, final_path: Path, plan: dict[str, dict]) -> tuple[bytes, list[dict]]:
+ """UV unwrap and bake on the final mesh. Blocking; runs in the executor.
+
+ The bake source is the mesh as it was BEFORE Modly's ops: repair, decimate
+ and smooth rewrite geometry and drop materials, so colour is read from the
+ original surface and projected onto the final one.
+ """
+ applied: list[dict] = []
+ mesh = postprocess.load_mesh(final_path.read_bytes(), final_path.suffix or ".glb")
+ if "uv_unwrap" in plan:
+ size = plan.get("bake", {}).get("texture_size", 1024)
+ mesh, info = postprocess.uv_unwrap(mesh, size)
+ applied.append({"step": "uv_unwrap", **info})
+ if "bake" in plan:
+ outcome = postprocess.bake(original, mesh, texture_size=plan["bake"]["texture_size"])
+ mesh = outcome.mesh
+ entry: dict[str, Any] = {"step": "bake", "baked": outcome.baked, "texture_size": plan["bake"]["texture_size"]}
+ if outcome.baked:
+ entry["coverage"] = round(outcome.coverage, 4)
+ else:
+ entry["reason"] = outcome.reason
+ applied.append(entry)
+ return postprocess.export_glb(mesh), applied
+
+
+async def _run_job(
+ task_id: str,
+ model: str,
+ params: dict,
+ plan: list[tuple[str, dict]],
+ images: Optional[list[str]],
+ mesh_url: Optional[str],
+) -> None:
+ if _load_error:
+ await _update_task(task_id, status="failed", error=f"pipeline unavailable: {_load_error}")
+ return
+ try:
+ await asyncio.wait_for(_ready.wait(), timeout=READY_WAIT_S)
+ except asyncio.TimeoutError:
+ await _update_task(task_id, status="failed", error="pipeline not ready (Modly bring-up timed out)")
+ return
+ if _load_error:
+ await _update_task(task_id, status="failed", error=f"pipeline unavailable: {_load_error}")
+ return
+
+ async with _sem:
+ await _update_task(task_id, status="running", progress=0)
+ loop = asyncio.get_event_loop()
+ t0 = time.time()
+ steps = dict(plan)
+ applied: list[dict] = []
+ task_dir = WORKSPACE_DIR / task_id
+ try:
+ async with httpx.AsyncClient(base_url=MODLY_URL, timeout=httpx.Timeout(600.0, connect=10.0)) as client:
+ if images is not None:
+ png = await loop.run_in_executor(None, _image_png, images[0])
+
+ async def on_progress(progress, step):
+ await _update_task(task_id, progress=progress, step=step)
+
+ job_id = await _submit_generation(client, model, png, params, task_id)
+ current = await _await_generation(client, job_id, on_progress)
+ original = None
+ if "bake" in steps:
+ original = await loop.run_in_executor(
+ None, lambda: postprocess.load_mesh(current.read_bytes(), current.suffix or ".glb")
+ )
+ else:
+ original = await loop.run_in_executor(None, _load_caller_mesh, mesh_url)
+ task_dir.mkdir(parents=True, exist_ok=True)
+ current = task_dir / "input.glb"
+ glb = await loop.run_in_executor(None, postprocess.export_glb, original)
+ await loop.run_in_executor(None, current.write_bytes, glb)
+
+ for name in ("repair", "decimate", "smooth"):
+ if name in steps:
+ await _update_task(task_id, step=name)
+ current, details = await _modly_op(client, name, current, steps[name])
+ applied.append({"step": name, **steps[name], **details})
+
+ if "uv_unwrap" in steps:
+ await _update_task(task_id, step="bake" if "bake" in steps else "uv_unwrap")
+ glb_bytes, local_applied = await loop.run_in_executor(None, _local_steps, original, current, steps)
+ applied.extend(local_applied)
+ else:
+ glb_bytes = await loop.run_in_executor(None, current.read_bytes)
+ glb_bytes, packed = await loop.run_in_executor(None, postprocess.pack_glb, glb_bytes)
+
+ if _using_gcs():
+ blob_name = f"raw-meshes/{LANE}/{task_id}.glb"
+ blob = _bucket.blob(blob_name)
+ await loop.run_in_executor(
+ None, lambda: blob.upload_from_string(glb_bytes, content_type="model/gltf-binary")
+ )
+ result_fields = {"result_gcs_url": f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"}
+ result_label = result_fields["result_gcs_url"]
+ else:
+ result_path = await loop.run_in_executor(None, _get_local_storage().write_result, task_id, glb_bytes)
+ result_fields = {"result_url": f"/results/{task_id}.glb", "result_path": str(result_path)}
+ result_label = str(result_path)
+
+ elapsed = time.time() - t0
+ await _update_task(
+ task_id,
+ status="done",
+ progress=100,
+ step=None,
+ **result_fields,
+ views_used=1 if images is not None else 0,
+ postprocess_applied=applied,
+ packed=packed,
+ bytes=len(glb_bytes),
+ elapsed_ms=int(elapsed * 1000),
+ )
+ log.info(
+ "[%s] done in %.1fs (model=%s steps=%s packed=%s) %d bytes -> %s",
+ task_id, elapsed, model, [a["step"] for a in applied], packed, len(glb_bytes), result_label,
+ )
+ except (ImageSourceError, postprocess.MeshError) as exc:
+ log.warning("[%s] caller input rejected: %s", task_id, exc)
+ await _update_task(task_id, status="failed", error=str(exc), elapsed_ms=int((time.time() - t0) * 1000))
+ except ModlyUnavailable as exc:
+ log.error("[%s] %s", task_id, exc)
+ await _update_task(
+ task_id,
+ status="failed",
+ error="Modly backend stopped mid-job and is restarting; retry the request",
+ elapsed_ms=int((time.time() - t0) * 1000),
+ )
+ except Exception as exc:
+ await _update_task(
+ task_id,
+ status="failed",
+ error=safe_error(exc, context=f"[{task_id}] inference"),
+ elapsed_ms=int((time.time() - t0) * 1000),
+ )
+ finally:
+ await loop.run_in_executor(None, trim_heap)
+
+
+# ── HTTP surface ──────────────────────────────────────────────────────────────
+
+class InferRequest(BaseModel):
+ images: Optional[list[str]] = Field(None, min_length=1, max_length=6)
+ mesh_url: Optional[str] = Field(None, min_length=1, max_length=96 * 1024 * 1024)
+ model: Optional[str] = None
+ tier: Optional[str] = None
+ seed: Optional[int] = None
+ params: Optional[dict[str, Any]] = None
+ postprocess: Optional[dict[str, Any]] = None
+ body_type: str = "neutral"
+ job_id: Optional[str] = None
+
+
+def _plan_request(body: InferRequest) -> tuple[str, dict, list[tuple[str, dict]], list[str]]:
+ if (body.images is None) == (body.mesh_url is None):
+ raise PolicyError("send exactly one of images (image to 3D) or mesh_url (post-process a mesh)")
+ plan = parse_postprocess(body.postprocess)
+ model = resolve_model(body.model, ENABLED_MODELS, DEFAULT_MODEL)
+ if body.mesh_url is not None:
+ if not plan:
+ raise PolicyError("mesh_url needs at least one postprocess step")
+ return model, {}, plan, []
+ params, dropped = build_generation_params(model, body.tier, body.params, body.seed, random.SystemRandom())
+ return model, params, plan, dropped
+
+
[email protected]("/infer", status_code=202)
+async def infer(
+ body: InferRequest,
+ background_tasks: BackgroundTasks,
+ authorization: str = Header(...),
+) -> dict:
+ _require_api_key(authorization)
+ try:
+ model, params, plan, dropped = _plan_request(body)
+ except PolicyError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ if _load_error:
+ raise HTTPException(status_code=503, detail=f"pipeline unavailable: {_load_error}")
+ if _draining:
+ raise HTTPException(status_code=503, detail="instance restarting to reclaim memory; retry shortly")
+ task_id = str(uuid.uuid4())
+ record: dict[str, Any] = {
+ "status": "queued",
+ "model": model if body.images is not None else None,
+ "postprocess": [name for name, _ in plan],
+ }
+ if body.images is not None:
+ record.update(seed=params["seed"], params=params, params_dropped=dropped)
+ await _update_task(task_id, **record)
+ background_tasks.add_task(_run_inference, task_id, model, params, plan, body.images, body.mesh_url)
+ return {"task_id": task_id, "status": "queued", "model": record["model"]}
+
+
[email protected]("/tasks/{task_id}")
+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:
+ _require_api_key(authorization)
+ return await _resolve_task(task_id)
+
+
[email protected]("/results/{task_id}.glb")
+async def get_result(task_id: str, authorization: str = Header(...)):
+ _require_api_key(authorization)
+ if _using_gcs():
+ raise HTTPException(status_code=404, detail="local result storage is not active")
+ try:
+ path = _get_local_storage().result_path(task_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=404, detail="result not found") from exc
+ if not path.is_file():
+ raise HTTPException(status_code=404, detail="result not found")
+ return FileResponse(path, media_type="model/gltf-binary", filename=path.name)
+
+
+async def root() -> dict:
+ """Service descriptor and the answer to the platform's keep-warm ping."""
+ return {
+ "service": SERVICE,
+ "model": DEFAULT_MODEL,
+ "models": ENABLED_MODELS,
+ "ready": bool(_ready and _ready.is_set()),
+ "endpoints": [
+ "POST /infer",
+ "GET /tasks/{task_id}",
+ "GET /results/{task_id}.glb",
+ "GET /health",
+ ],
+ "attribution": "Based on Modly (https://github.com/lightningpixel/modly) by Lightning Pixel",
+ }
+
+
+async def health(response: Response) -> dict:
+ """Readiness. A spent bring-up budget answers 503 so the platform probe and
+ the Cloud Run liveness probe both treat the instance as down; a bring-up still
+ in progress stays 200 so an ordinary cold start is never killed mid-load."""
+ dead = _load_error is not None
+ if dead:
+ response.status_code = 503
+ return {
+ "ok": not dead,
+ "model": DEFAULT_MODEL,
+ "models": ENABLED_MODELS,
+ "gpu_available": _gpu_name is not None,
+ "gpu_name": _gpu_name,
+ "ready": bool(_ready and _ready.is_set()),
+ "modly_alive": _modly_alive(),
+ "modly_pid": _modly_proc.pid if _modly_alive() else None,
+ "modly_restarts": _modly_restarts,
+ "warmup_ms": _warmup_ms,
+ "load_error": _load_error,
+ "load_attempts": _load_attempts,
+ "draining": _draining,
+ "postprocess_steps": ["repair", "decimate", "smooth", "uv_unwrap", "bake"],
+ "output_backend": "gcs" if _using_gcs() else "local",
+ "output_dir": None if _using_gcs() else str(_get_local_storage().output_dir),
+ }
diff --git a/workers/modly/meshopt/package-lock.json b/workers/modly/meshopt/package-lock.json
new file mode 100644
index 000000000..b632c1a3d
--- /dev/null
+++ b/workers/modly/meshopt/package-lock.json
@@ -0,0 +1,825 @@
+{
+ "name": "modly-mesh-optimizer-runtime",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "modly-mesh-optimizer-runtime",
+ "version": "1.0.0",
+ "license": "MIT",
+ "dependencies": {
+ "@gltf-transform/core": "3.10.1",
+ "@gltf-transform/extensions": "3.10.1",
+ "@gltf-transform/functions": "3.10.1",
+ "meshoptimizer": "0.22.0"
+ }
+ },
+ "node_modules/@gltf-transform/core": {
+ "version": "3.10.1",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/core/-/core-3.10.1.tgz",
+ "integrity": "sha512-50OYemknGNxjBmiOM6iJp04JAu0bl9jvXJfN/gFt9QdJO02cPDcoXlTfSPJG6TVWDcfl0xPlsx1vybcbPVGFcQ==",
+ "license": "MIT",
+ "dependencies": {
+ "property-graph": "^1.3.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@gltf-transform/extensions": {
+ "version": "3.10.1",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/extensions/-/extensions-3.10.1.tgz",
+ "integrity": "sha512-xUS9K5fMvW2dkYN4VzxHg2aBPG54M2WqgIjQ7RoSyybMoD7DsPUyMyVgRja+aiTVt/Bxza2ve7zJBD3+tN+aTA==",
+ "license": "MIT",
+ "dependencies": {
+ "@gltf-transform/core": "^3.10.1",
+ "ktx-parse": "^0.6.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@gltf-transform/functions": {
+ "version": "3.10.1",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/functions/-/functions-3.10.1.tgz",
+ "integrity": "sha512-Zs6+1qvTD9w40R5qv70E4wJXXacNQ46ZxjKKW6dmfGIyjT8bsSJmV3Tdj+WJ8R6lWXXZ8e2p3ZvAUfPDEG73bQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@gltf-transform/core": "^3.10.1",
+ "@gltf-transform/extensions": "^3.10.1",
+ "ktx-parse": "^0.6.0",
+ "ndarray": "^1.0.19",
+ "ndarray-lanczos": "^0.3.0",
+ "ndarray-pixels": "^3.0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@types/ndarray": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@types/ndarray/-/ndarray-1.1.0.tgz",
+ "integrity": "sha512-go+C6vHBUuO9jH6Tj6qEZ63JEGoMSxFdmd+6QAtthGD6xumBfIz3RbNDDs2aoRVLf9naH8lk5jnWy2UHHKgYQQ==",
+ "license": "MIT"
+ },
+ "node_modules/b4a": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.9.0.tgz",
+ "integrity": "sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "react-native-b4a": "*"
+ },
+ "peerDependenciesMeta": {
+ "react-native-b4a": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-events": {
+ "version": "2.9.2",
+ "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.2.tgz",
+ "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "bare-abort-controller": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-fs": {
+ "version": "4.8.3",
+ "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.3.tgz",
+ "integrity": "sha512-KQi9ShyPS/nOCtKpma7At8wbq4ORSNUmD67hsZrPcaWJcEmL8PHyS2xVWT308y8/LvHFOUTytTTDsD8dInx6bA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.5.4",
+ "bare-path": "^3.0.0",
+ "bare-stream": "^2.6.4",
+ "bare-url": "^2.2.2",
+ "fast-fifo": "^1.3.2"
+ },
+ "engines": {
+ "bare": ">=1.28.0"
+ },
+ "peerDependencies": {
+ "bare-buffer": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-buffer": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-path": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.2.tgz",
+ "integrity": "sha512-ZyKbsuuqK6Ag0K8pX6V5Txq6XeJRvY+wXucnFGRjiyVYP9YWDpIQugk/b+enRYrEYBJaqLzghRQpXPMR7341Nw==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/bare-stream": {
+ "version": "2.13.4",
+ "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.4.tgz",
+ "integrity": "sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.8.1",
+ "streamx": "^2.25.0",
+ "teex": "^1.0.1"
+ },
+ "peerDependencies": {
+ "bare-abort-controller": "*",
+ "bare-buffer": "*",
+ "bare-events": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ },
+ "bare-buffer": {
+ "optional": true
+ },
+ "bare-events": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-url": {
+ "version": "2.5.4",
+ "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.4.tgz",
+ "integrity": "sha512-Gxa7UVWBr0/edU1b+TJhn/AZvMQUj9OGspvYsaTYQrAbZA4BOTZGL3LiZxvD+CeMlDH4juwD84+eTAp/bLYW5g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-path": "^3.0.0"
+ }
+ },
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/bl": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer": "^5.5.0",
+ "inherits": "^2.0.4",
+ "readable-stream": "^3.4.0"
+ }
+ },
+ "node_modules/buffer": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.1.13"
+ }
+ },
+ "node_modules/chownr": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
+ "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
+ "license": "ISC"
+ },
+ "node_modules/color": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
+ "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==",
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^2.0.1",
+ "color-string": "^1.9.0"
+ },
+ "engines": {
+ "node": ">=12.5.0"
+ }
+ },
+ "node_modules/color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "~1.1.4"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ }
+ },
+ "node_modules/color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "license": "MIT"
+ },
+ "node_modules/color-string": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",
+ "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "^1.0.0",
+ "simple-swizzle": "^0.2.2"
+ }
+ },
+ "node_modules/cwise-compiler": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/cwise-compiler/-/cwise-compiler-1.1.3.tgz",
+ "integrity": "sha512-WXlK/m+Di8DMMcCjcWr4i+XzcQra9eCdXIJrgh4TUgh0pIS/yJduLxS9JgefsHJ/YVLdgPtXm9r62W92MvanEQ==",
+ "license": "MIT",
+ "dependencies": {
+ "uniq": "^1.0.0"
+ }
+ },
+ "node_modules/decompress-response": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
+ "license": "MIT",
+ "dependencies": {
+ "mimic-response": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/deep-extend": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
+ "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/end-of-stream": {
+ "version": "1.4.5",
+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
+ "license": "MIT",
+ "dependencies": {
+ "once": "^1.4.0"
+ }
+ },
+ "node_modules/events-universal": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
+ "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.7.0"
+ }
+ },
+ "node_modules/expand-template": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
+ "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
+ "license": "(MIT OR WTFPL)",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/fast-fifo": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
+ "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",
+ "license": "MIT"
+ },
+ "node_modules/fs-constants": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
+ "license": "MIT"
+ },
+ "node_modules/github-from-package": {
+ "version": "0.0.0",
+ "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
+ "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",
+ "license": "MIT"
+ },
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "license": "ISC"
+ },
+ "node_modules/ini": {
+ "version": "1.3.8",
+ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
+ "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
+ "license": "ISC"
+ },
+ "node_modules/iota-array": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/iota-array/-/iota-array-1.0.0.tgz",
+ "integrity": "sha512-pZ2xT+LOHckCatGQ3DcG/a+QuEqvoxqkiL7tvE8nn3uuu+f6i1TtpB5/FtWFbxUuVr5PZCx8KskuGatbJDXOWA==",
+ "license": "MIT"
+ },
+ "node_modules/is-arrayish": {
+ "version": "0.3.4",
+ "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz",
+ "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==",
+ "license": "MIT"
+ },
+ "node_modules/is-buffer": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
+ "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==",
+ "license": "MIT"
+ },
+ "node_modules/ktx-parse": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/ktx-parse/-/ktx-parse-0.6.0.tgz",
+ "integrity": "sha512-hYOJUI86N9+YPm0M3t8hVzW9t5FnFFibRalZCrqHs/qM2eNziqQzBtAaF0ErgkXm8F+5uE8CjPUYr32vWlXLkQ==",
+ "license": "MIT"
+ },
+ "node_modules/meshoptimizer": {
+ "version": "0.22.0",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-0.22.0.tgz",
+ "integrity": "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==",
+ "license": "MIT"
+ },
+ "node_modules/mimic-response": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/mkdirp-classic": {
+ "version": "0.5.3",
+ "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
+ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
+ "license": "MIT"
+ },
+ "node_modules/napi-build-utils": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
+ "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",
+ "license": "MIT"
+ },
+ "node_modules/ndarray": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ndarray/-/ndarray-1.1.1.tgz",
+ "integrity": "sha512-AsE8w/M2MS+0pD3nP5qbRRtJFeJJJaJ+qXZaZr0XjVGXhy6LIj2TERTlkpdK2AI3WufoOP+pwPk3q2ilAJcZ9g==",
+ "license": "MIT",
+ "dependencies": {
+ "iota-array": "^1.0.0",
+ "is-buffer": "^1.0.2"
+ }
+ },
+ "node_modules/ndarray-lanczos": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/ndarray-lanczos/-/ndarray-lanczos-0.3.0.tgz",
+ "integrity": "sha512-5kBmmG3Zvyj77qxIAC4QFLKuYdDIBJwCG+DukT6jQHNa1Ft74/hPH1z5mbQXeHBt8yvGPBGVrr3wEOdJPYYZYg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/ndarray": "^1.0.11",
+ "ndarray": "^1.0.19"
+ }
+ },
+ "node_modules/ndarray-ops": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/ndarray-ops/-/ndarray-ops-1.2.2.tgz",
+ "integrity": "sha512-BppWAFRjMYF7N/r6Ie51q6D4fs0iiGmeXIACKY66fLpnwIui3Wc3CXiD/30mgLbDjPpSLrsqcp3Z62+IcHZsDw==",
+ "license": "MIT",
+ "dependencies": {
+ "cwise-compiler": "^1.0.0"
+ }
+ },
+ "node_modules/ndarray-pixels": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/ndarray-pixels/-/ndarray-pixels-3.1.0.tgz",
+ "integrity": "sha512-icw7L/kbxlHVoBgFWc0fCl1sYcatYSoZrAudD6KiQ1WXy84hRXIfqel5CLkh/SeLhb02Q2NW1ud9lE5G84V0zQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/ndarray": "^1.0.11",
+ "ndarray": "^1.0.19",
+ "ndarray-ops": "^1.2.2",
+ "sharp": "^0.32.6"
+ }
+ },
+ "node_modules/node-abi": {
+ "version": "3.98.0",
+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.98.0.tgz",
+ "integrity": "sha512-Llh8noNw7s15m+rmIrZnZQbe4gLyasL9loT74rC92PkmwWKeEedKvc7o6pjp8B3MhrYT/Cl846NOYZbz1wmddw==",
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^7.3.5"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/node-addon-api": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-6.1.0.tgz",
+ "integrity": "sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==",
+ "license": "MIT"
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/prebuild-install": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
+ "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
+ "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
+ "license": "MIT",
+ "dependencies": {
+ "detect-libc": "^2.0.0",
+ "expand-template": "^2.0.3",
+ "github-from-package": "0.0.0",
+ "minimist": "^1.2.3",
+ "mkdirp-classic": "^0.5.3",
+ "napi-build-utils": "^2.0.0",
+ "node-abi": "^3.3.0",
+ "pump": "^3.0.0",
+ "rc": "^1.2.7",
+ "simple-get": "^4.0.0",
+ "tar-fs": "^2.0.0",
+ "tunnel-agent": "^0.6.0"
+ },
+ "bin": {
+ "prebuild-install": "bin.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/prebuild-install/node_modules/tar-fs": {
+ "version": "2.1.5",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz",
+ "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==",
+ "license": "MIT",
+ "dependencies": {
+ "chownr": "^1.1.1",
+ "mkdirp-classic": "^0.5.2",
+ "pump": "^3.0.0",
+ "tar-stream": "^2.1.4"
+ }
+ },
+ "node_modules/prebuild-install/node_modules/tar-stream": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
+ "license": "MIT",
+ "dependencies": {
+ "bl": "^4.0.3",
+ "end-of-stream": "^1.4.1",
+ "fs-constants": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.1.1"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/property-graph": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/property-graph/-/property-graph-1.3.1.tgz",
+ "integrity": "sha512-gei3N/bHWJdCItJ4blnlGWd9iauEZI+JZYj/A0D177XSI01+QhiJGAVscYBhe3Yywow3A2QJzVtsO2P+UgrRRQ==",
+ "license": "MIT"
+ },
+ "node_modules/pump": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
+ "license": "MIT",
+ "dependencies": {
+ "end-of-stream": "^1.1.0",
+ "once": "^1.3.1"
+ }
+ },
+ "node_modules/rc": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
+ "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
+ "license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
+ "dependencies": {
+ "deep-extend": "^0.6.0",
+ "ini": "~1.3.0",
+ "minimist": "^1.2.0",
+ "strip-json-comments": "~2.0.1"
+ },
+ "bin": {
+ "rc": "cli.js"
+ }
+ },
+ "node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/sharp": {
+ "version": "0.32.6",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.32.6.tgz",
+ "integrity": "sha512-KyLTWwgcR9Oe4d9HwCwNM2l7+J0dUQwn/yf7S0EnTtb0eVS4RxO0eUSvxPtzT4F3SY+C4K6fqdv/DO27sJ/v/w==",
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "color": "^4.2.3",
+ "detect-libc": "^2.0.2",
+ "node-addon-api": "^6.1.0",
+ "prebuild-install": "^7.1.1",
+ "semver": "^7.5.4",
+ "simple-get": "^4.0.1",
+ "tar-fs": "^3.0.4",
+ "tunnel-agent": "^0.6.0"
+ },
+ "engines": {
+ "node": ">=14.15.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/simple-concat": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
+ "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/simple-get": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
+ "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decompress-response": "^6.0.0",
+ "once": "^1.3.1",
+ "simple-concat": "^1.0.0"
+ }
+ },
+ "node_modules/simple-swizzle": {
+ "version": "0.2.4",
+ "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz",
+ "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==",
+ "license": "MIT",
+ "dependencies": {
+ "is-arrayish": "^0.3.1"
+ }
+ },
+ "node_modules/streamx": {
+ "version": "2.28.1",
+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.1.tgz",
+ "integrity": "sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA==",
+ "license": "MIT",
+ "dependencies": {
+ "events-universal": "^1.0.0",
+ "fast-fifo": "^1.3.2",
+ "text-decoder": "^1.1.0"
+ }
+ },
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
+ "node_modules/strip-json-comments": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
+ "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/tar-fs": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.3.tgz",
+ "integrity": "sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "pump": "^3.0.0",
+ "tar-stream": "^3.1.5"
+ },
+ "optionalDependencies": {
+ "bare-fs": "^4.0.1",
+ "bare-path": "^3.0.0"
+ }
+ },
+ "node_modules/tar-stream": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.2.tgz",
+ "integrity": "sha512-+8NeqHRjQWH9nYlwo2gamAMImZCVzI4UoEgDpWorBt9OEfppiZn+uSkskzQKPWIZyji/C8fpWO7u69G0DX0tbg==",
+ "license": "MIT",
+ "dependencies": {
+ "b4a": "^1.9.0",
+ "bare-fs": "^4.8.2",
+ "fast-fifo": "^1.3.2",
+ "streamx": "^2.28.1"
+ }
+ },
+ "node_modules/teex": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",
+ "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==",
+ "license": "MIT",
+ "dependencies": {
+ "streamx": "^2.12.5"
+ }
+ },
+ "node_modules/text-decoder": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz",
+ "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.6.4"
+ }
+ },
+ "node_modules/tunnel-agent": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
+ "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "safe-buffer": "^5.0.1"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/uniq": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz",
+ "integrity": "sha512-Gw+zz50YNKPDKXs+9d+aKAjVwpjNwqzvNpLigIruT4HA9lMZNdMqs9x07kKHB/L9WRzqp4+DlTU5s4wG2esdoA==",
+ "license": "MIT"
+ },
+ "node_modules/util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+ "license": "MIT"
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "license": "ISC"
+ }
+ }
+}
diff --git a/workers/modly/meshopt/package.json b/workers/modly/meshopt/package.json
new file mode 100644
index 000000000..c44bd7927
--- /dev/null
+++ b/workers/modly/meshopt/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "modly-mesh-optimizer-runtime",
+ "version": "1.0.0",
+ "private": true,
+ "description": "Node dependencies of Modly's mesh-optimizer (decimate) op, pinned for workers/modly.",
+ "license": "MIT",
+ "dependencies": {
+ "@gltf-transform/core": "3.10.1",
+ "@gltf-transform/extensions": "3.10.1",
+ "@gltf-transform/functions": "3.10.1",
+ "meshoptimizer": "0.22.0"
+ }
+}
diff --git a/workers/modly/requirements-hunyuan.txt b/workers/modly/requirements-hunyuan.txt
index 6e3aafd09..5dee9a850 100644
--- a/workers/modly/requirements-hunyuan.txt
+++ b/workers/modly/requirements-hunyuan.txt
@@ -20,7 +20,7 @@ pymeshlab==2023.12.post2
scikit-image==0.24.0
opencv-python-headless==4.10.0.84
rembg==2.0.59
-onnxruntime-gpu==1.20.1
+onnxruntime-gpu==1.20.0
pybind11==2.13.6
ninja==1.11.1.1
setuptools==75.8.0
diff --git a/workers/modly/requirements-triposg.txt b/workers/modly/requirements-triposg.txt
index d8d818e38..aea3a4826 100644
--- a/workers/modly/requirements-triposg.txt
+++ b/workers/modly/requirements-triposg.txt
@@ -24,9 +24,11 @@ pymeshlab==2023.12.post2
scikit-image==0.24.0
opencv-python-headless==4.10.0.84
rembg==2.0.59
-onnxruntime-gpu==1.20.1
-# diso builds with --no-build-isolation, so its build-time imports live here.
+onnxruntime-gpu==1.20.0
+# diso builds with --no-build-isolation, so its build-time imports and the
+# CMake it drives live here.
pybind11==2.13.6
+cmake==3.31.6
ninja==1.11.1.1
setuptools==75.8.0
wheel==0.45.1
diff --git a/workers/modly/stage_weights.sh b/workers/modly/stage_weights.sh
new file mode 100755
index 000000000..3a51c3ebe
--- /dev/null
+++ b/workers/modly/stage_weights.sh
@@ -0,0 +1,80 @@
+#!/usr/bin/env bash
+# Stage the weights of every Modly model this worker serves into
+# gs://three-ws-model-weights, streaming straight from the Hugging Face Hub to the
+# bucket (no local disk). Each repo is pinned to a commit so a rebuild of the
+# bucket reproduces the exact bytes the worker was verified against. Idempotent:
+# an object that already exists at the expected size is skipped.
+#
+# workers/modly/stage_weights.sh
+#
+# Layout written (the worker's WEIGHTS_GCS_URI points at the prefix; each model
+# lands at <prefix>/<extension id>/<node id>/, the MODELS_DIR layout Modly reads):
+# gs://<bucket>/modly/triposg/generate/
+# VAST-AI/TripoSG (MIT) at 2c1c516d22d58db486a058d98d31bb6177344e06,
+# about 7.9 GB: DINOv2 image encoder, flow transformer, VAE, scheduler.
+# gs://<bucket>/modly/hunyuan3d-mini-turbo/generate/
+# tencent/Hunyuan3D-2mini (Tencent Hunyuan 3D 2.0 Community License) at
+# f90a0f7df7d5e6f71109cf333f6a95a0ae3194a6, about 4.2 GB: only the turbo
+# DiT and turbo VAE the extension loads, plus the LICENSE and NOTICE the
+# licence requires to travel with the weights. The fast and base variants
+# and the .ckpt duplicates are skipped.
+#
+# The background-removal model (rembg's u2net.onnx) is baked into the image by
+# checksum, so nothing for it is staged here.
+set -euo pipefail
+
+BUCKET="${WEIGHTS_BUCKET:-three-ws-model-weights}"
+PREFIX="${WEIGHTS_PREFIX:-modly}"
+DEST="gs://${BUCKET}/${PREFIX}"
+AUTH=()
+if [[ -n "${HF_TOKEN:-}" ]]; then AUTH=(-H "Authorization: Bearer ${HF_TOKEN}"); fi
+
+TRIPOSG_REPO="VAST-AI/TripoSG"
+TRIPOSG_REV="2c1c516d22d58db486a058d98d31bb6177344e06"
+HUNYUAN_REPO="tencent/Hunyuan3D-2mini"
+HUNYUAN_REV="f90a0f7df7d5e6f71109cf333f6a95a0ae3194a6"
+
+list_repo() { # <repo> <revision> -> "path size" lines
+ curl -fsS "${AUTH[@]}" "https://huggingface.co/api/models/$1/revision/$2?blobs=true" \
+ | python3 -I -c 'import json,sys
+for s in json.load(sys.stdin)["siblings"]:
+ print(s["rfilename"], s.get("size") or 0)'
+}
+
+remote_size() { gcloud storage objects describe "$1" --format='value(size)' 2>/dev/null || true; }
+
+copy_one() { # <repo> <revision> <src path> <size> <dest uri>
+ local repo="$1" rev="$2" path="$3" size="$4" dest="$5"
+ if [[ "$(remote_size "$dest")" == "$size" && "$size" != "0" ]]; then
+ echo "skip $dest"
+ return
+ fi
+ echo "copy $repo@${rev:0:12}/$path -> $dest ($size bytes)"
+ curl -fsSL "${AUTH[@]}" "https://huggingface.co/${repo}/resolve/${rev}/${path}" \
+ | gcloud storage cp - "$dest" --quiet
+ local got
+ got="$(remote_size "$dest")"
+ if [[ "$size" != "0" && "$got" != "$size" ]]; then
+ echo "FAIL $dest: expected $size bytes, bucket has ${got:-none}" >&2
+ exit 1
+ fi
+}
+
+mirror_repo() { # <repo> <revision> <dest prefix> <path regex>
+ local repo="$1" rev="$2" dest="$3" only="$4" count=0
+ while read -r path size; do
+ [[ "$path" =~ $only ]] || continue
+ copy_one "$repo" "$rev" "$path" "$size" "${dest}/${path}"
+ count=$((count + 1))
+ done < <(list_repo "$repo" "$rev")
+ if [[ "$count" == 0 ]]; then
+ echo "FAIL no files of $repo@$rev matched $only" >&2
+ exit 1
+ fi
+}
+
+mirror_repo "$TRIPOSG_REPO" "$TRIPOSG_REV" "${DEST}/triposg/generate" \
+ '^(model_index\.json|LICENSE|(feature_extractor_dinov2|image_encoder_dinov2|scheduler|transformer|vae)/.+\.(json|safetensors))$'
+mirror_repo "$HUNYUAN_REPO" "$HUNYUAN_REV" "${DEST}/hunyuan3d-mini-turbo/generate" \
+ '^(config\.json|LICENSE|NOTICE|hunyuan3d-(dit|vae)-v2-mini-turbo/(config\.yaml|model\.fp16\.safetensors))$'
+echo "modly weights staged at ${DEST}"
diff --git a/workers/modly/test_app_contract.py b/workers/modly/test_app_contract.py
new file mode 100644
index 000000000..e5203283a
--- /dev/null
+++ b/workers/modly/test_app_contract.py
@@ -0,0 +1,347 @@
+"""Smoke test for the served contract, run INSIDE the built image as a build gate:
+
+ docker build -t modly workers/modly
+ docker run --rm -e MODLY_CONTRACT_REQUIRE_BACKEND=1 modly python3 test_app_contract.py
+
+It needs no GPU, no weights and no GCP credentials. The ASGI lifespan (which opens
+the GCS client, stages weights and starts Modly) is deliberately not run.
+
+Part A, the front (runs anywhere the host requirements are installed):
+
+ 1. The app module imports and the auth boundary rejects a wrong bearer.
+ 2. The unauthenticated probe surfaces (/ and /health) answer, and a dead
+ backend says so on both /health and /infer so the caller fails over.
+ 3. Request validation: images XOR mesh_url, the six-view cap, unknown models,
+ malformed post-process plans.
+ 4. The image decoder keeps alpha and refuses everything the SSRF guard should.
+ 5. Modly's child environment never carries the front's API key.
+
+Part B, the backend (needs the image's /opt tree; enforced when
+MODLY_CONTRACT_REQUIRE_BACKEND=1, which the Dockerfile sets):
+
+ 6. The pinned Modly starts on loopback with the pinned extensions, registers
+ every enabled model, and reports exactly one problem per model: weights
+ missing. Any extension error (a broken manifest, a venv Modly cannot find)
+ fails the build instead of surfacing as a revision that never goes ready.
+ 7. Modly's repair, decimate and smooth ops run through the front's own client
+ code, which proves pymeshlab and the Node + meshoptimizer runtime decimate
+ needs are both present.
+ 8. Each extension venv imports its generator's model package (TripoSG with the
+ compiled diso extension, hy3dgen's shape pipeline) and rembg.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import io
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import uuid
+from pathlib import Path
+
+os.environ.setdefault("API_KEY", "smoke-test-key")
+os.environ.setdefault("GCS_BUCKET", "smoke-test-bucket")
+
+KEY = os.environ["API_KEY"]
+REQUIRE_BACKEND = os.environ.get("MODLY_CONTRACT_REQUIRE_BACKEND") == "1"
+
+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()
+
+
+# Libraries the NVIDIA container runtime mounts into a GPU instance. The image
+# cannot ship them, so their absence on the CPU-only builder is expected.
+_GPU_DRIVER_LIBS = ("libcuda.so", "libnvidia", "libnvrtc")
+
+
+def _is_gpu_driver_absence(text: str) -> bool:
+ if "cannot open shared object file" in text:
+ return any(lib in text for lib in _GPU_DRIVER_LIBS)
+ lowered = text.lower()
+ return "nvidia driver" in lowered or "no cuda gpus" in lowered or "found no nvidia" in lowered
+
+
+# ── Part A: the front ─────────────────────────────────────────────────────────
+
+def front_checks(app_module) -> None:
+ from fastapi.testclient import TestClient
+
+ client = TestClient(app_module.app)
+ good = {"Authorization": f"Bearer {KEY}"}
+ bad = {"Authorization": "Bearer wrong-key"}
+
+ res = client.get("/tasks/does-not-exist", headers=bad)
+ check("GET /tasks rejects a wrong bearer", res.status_code == 401, f"got {res.status_code}")
+ res = client.post("/infer", headers=bad, json={"images": [png_data_uri()]})
+ check("POST /infer rejects a wrong bearer", res.status_code == 401, f"got {res.status_code}")
+ res = client.get("/results/does-not-exist.glb", headers=bad)
+ check("GET /results rejects a wrong bearer", res.status_code == 401, f"got {res.status_code}")
+
+ res = client.get("/health")
+ body = res.json()
+ check("GET /health answers 200", res.status_code == 200, f"got {res.status_code}")
+ check("health names the default model", body.get("model") == app_module.DEFAULT_MODEL, str(body)[:160])
+ check("health lists the enabled models", body.get("models") == app_module.ENABLED_MODELS, str(body)[:160])
+ check(
+ "health lists the post-process steps",
+ body.get("postprocess_steps") == ["repair", "decimate", "smooth", "uv_unwrap", "bake"],
+ str(body.get("postprocess_steps")),
+ )
+ res = client.get("/")
+ body = res.json()
+ check("GET / answers 200 for the keep-warm ping", res.status_code == 200, f"got {res.status_code}")
+ check("root names the service", body.get("service") == "model-modly", str(body)[:120])
+ check("root lists the working endpoints", "POST /infer" in body.get("endpoints", []), str(body)[:160])
+ check("root credits Modly", "lightningpixel/modly" in str(body.get("attribution")), str(body)[:200])
+
+ # A dead backend must SAY it is dead, on both surfaces (the 2026-09-02 lesson
+ # recorded in workers/model-trellis2/test_app_contract.py).
+ app_module._load_error = "internal error (ref deadbeefcafe)"
+ try:
+ res = client.get("/health")
+ body = res.json()
+ check("a dead backend makes /health answer 503", res.status_code == 503, f"got {res.status_code}")
+ check("a dead backend makes /health report ok:false", body.get("ok") is False, str(body)[:160])
+ check("health surfaces the load error", "deadbeefcafe" in str(body.get("load_error")), str(body)[:160])
+ res = client.post("/infer", headers=good, json={"images": [png_data_uri()]})
+ check("a dead backend makes /infer refuse with 503", res.status_code == 503, f"got {res.status_code}")
+ finally:
+ app_module._load_error = None
+ res = client.get("/health")
+ check("a live backend still answers /health 200", res.status_code == 200, f"got {res.status_code}")
+ check("a live backend reports ok:true", res.json().get("ok") is True, str(res.json())[:160])
+
+ for label, payload in [
+ ("an empty images array", {"images": []}),
+ ("more than six views", {"images": [png_data_uri()] * 7}),
+ ("neither images nor mesh_url", {}),
+ ("both images and mesh_url", {"images": [png_data_uri()], "mesh_url": "https://example.com/a.glb"}),
+ ("mesh_url without a postprocess step", {"mesh_url": "https://example.com/a.glb"}),
+ ("a model this deployment does not serve", {"images": [png_data_uri()], "model": "sf3d/generate"}),
+ ("an unknown postprocess step", {"images": [png_data_uri()], "postprocess": {"explode": True}}),
+ ("an out-of-range decimate target", {"images": [png_data_uri()], "postprocess": {"decimate": 10}}),
+ ("an unsupported bake size", {"images": [png_data_uri()], "postprocess": {"bake": {"texture_size": 1000}}}),
+ ("an invalid generation param", {"images": [png_data_uri()], "params": {"guidance_scale": "loud"}}),
+ ("an out-of-range seed", {"images": [png_data_uri()], "seed": -2}),
+ ]:
+ res = client.post("/infer", headers=good, json=payload)
+ check(f"POST /infer rejects {label}", res.status_code == 422, f"got {res.status_code}: {res.text[:160]}")
+
+ img = app_module._decode_image(png_data_uri())
+ check("data uri decodes with its alpha channel", img.mode == "RGBA" and img.size == (24, 24), f"{img.mode} {img.size}")
+
+ for label, src in [
+ ("cleartext http", "http://example.com/a.png"),
+ ("bare path", "/etc/passwd"),
+ ("loopback https", "https://127.0.0.1/a.png"),
+ ("cloud metadata", "https://169.254.169.254/latest/meta-data/"),
+ ("corrupt data uri", "data:image/png;base64,not-base64!!"),
+ ]:
+ try:
+ app_module._decode_image(src)
+ check(f"image decoder refuses {label}", False, "no exception raised")
+ except app_module.ImageSourceError:
+ check(f"image decoder refuses {label}", True)
+ except Exception as exc: # noqa: BLE001 - must be the caller-facing class
+ check(f"image decoder refuses {label}", False, f"raised {type(exc).__name__}: {exc}")
+
+ for label, src in [
+ ("a loopback mesh url", "https://127.0.0.1/a.glb"),
+ ("a file path mesh", "/opt/modly/api/main.py"),
+ ("a non-mesh payload", "data:model/gltf-binary;base64," + base64.b64encode(b"definitely not a mesh").decode()),
+ ]:
+ try:
+ app_module._load_caller_mesh(src)
+ check(f"mesh loader refuses {label}", False, "no exception raised")
+ except app_module.ImageSourceError:
+ check(f"mesh loader refuses {label}", True)
+ except Exception as exc: # noqa: BLE001 - must be the caller-facing class
+ check(f"mesh loader refuses {label}", False, f"raised {type(exc).__name__}: {exc}")
+
+ import trimesh
+
+ glb = trimesh.creation.icosphere(subdivisions=2).export(file_type="glb")
+ mesh = app_module._load_caller_mesh("data:model/gltf-binary;base64," + base64.b64encode(glb).decode())
+ check("mesh loader reads an inline GLB", len(mesh.faces) == 320, f"{len(mesh.faces)} faces")
+ check("mesh suffix follows the url path", app_module._mesh_suffix("https://cdn.example/a/b.OBJ?x=1") == ".obj")
+ check("mesh suffix defaults to glb", app_module._mesh_suffix("https://cdn.example/a/model") == ".glb")
+
+ local_job_check(app_module)
+
+ env = app_module._modly_env()
+ check("Modly's environment never carries the front's API key", "API_KEY" not in env)
+ check("Modly is pinned offline", env.get("HF_HUB_OFFLINE") == "1" and env.get("TRANSFORMERS_OFFLINE") == "1")
+ check("Modly talks to itself on loopback", env.get("MODLY_API_URL", "").startswith("http://127.0.0.1:"))
+
+
+def local_job_check(app_module) -> None:
+ """A mesh_url job whose steps are all local (unwrap + bake) needs no Modly, so
+ the whole job runner, local storage and the result route run for real here."""
+ import numpy as np
+ import trimesh
+ from fastapi.testclient import TestClient
+
+ import postprocess
+
+ sphere = trimesh.creation.icosphere(subdivisions=3)
+ colours = np.where(
+ (sphere.vertices[:, 2] > 0)[:, None], [230, 40, 40, 255], [40, 40, 230, 255]
+ ).astype(np.uint8)
+ sphere.visual = trimesh.visual.ColorVisuals(mesh=sphere, vertex_colors=colours)
+ mesh_uri = "data:model/gltf-binary;base64," + base64.b64encode(sphere.export(file_type="glb")).decode()
+
+ out = Path(tempfile.mkdtemp(prefix="modly-contract-out-"))
+ saved = (app_module.GCS_BUCKET, app_module.OUTPUT_DIR, app_module._local_storage, app_module.WORKSPACE_DIR)
+ app_module.GCS_BUCKET = ""
+ app_module.OUTPUT_DIR = str(out)
+ app_module._local_storage = None
+ app_module.WORKSPACE_DIR = out / "workspace"
+ try:
+ async def run() -> dict:
+ app_module._ready = asyncio.Event()
+ app_module._ready.set()
+ app_module._sem = asyncio.Semaphore(1)
+ task_id = str(uuid.uuid4())
+ plan = [("uv_unwrap", {}), ("bake", {"texture_size": 256})]
+ await app_module._update_task(task_id, status="queued", model=None)
+ await app_module._run_inference(task_id, app_module.DEFAULT_MODEL, {}, plan, None, mesh_uri)
+ return await app_module._resolve_task(task_id)
+
+ task = asyncio.run(run())
+ check("local post-process job finishes", task.get("status") == "done", str(task)[:300])
+ steps = [entry["step"] for entry in task.get("postprocess_applied", [])]
+ check("job reports the steps it applied", steps == ["uv_unwrap", "bake"], str(steps))
+ bake_entry = task["postprocess_applied"][-1]
+ check("bake transferred the source colour", bake_entry.get("baked") is True, str(bake_entry))
+ client = TestClient(app_module.app)
+ res = client.get(f"/results/{task['task_id']}.glb", headers={"Authorization": f"Bearer {KEY}"})
+ check("result route serves the GLB", res.status_code == 200 and res.content[:4] == b"glTF", f"got {res.status_code}")
+ from gltf_meshopt import decode_if_meshopt
+
+ data, suffix = decode_if_meshopt(res.content, ".glb")
+ result = postprocess.load_mesh(data, suffix)
+ check("served GLB carries the baked texture", postprocess.has_colour(result) == "texture")
+ check("job workspace is cleaned up", not (app_module.WORKSPACE_DIR / task["task_id"]).exists())
+ finally:
+ (app_module.GCS_BUCKET, app_module.OUTPUT_DIR, app_module._local_storage, app_module.WORKSPACE_DIR) = saved
+ app_module._ready = None
+ app_module._sem = None
+ shutil.rmtree(out, ignore_errors=True)
+
+
+# ── Part B: the backend ───────────────────────────────────────────────────────
+
+def _backend_present(app_module) -> bool:
+ return (app_module.MODLY_API_DIR / "main.py").is_file() and app_module.EXTENSIONS_DIR.is_dir()
+
+
+def modly_checks(app_module) -> None:
+ import trimesh
+
+ import postprocess
+
+ root = Path(tempfile.mkdtemp(prefix="modly-contract-"))
+ app_module.MODELS_DIR = root / "models"
+ app_module.WORKSPACE_DIR = root / "workspace"
+ try:
+ app_module._start_modly()
+ app_module._wait_modly_http(180)
+ check("pinned Modly starts and answers on loopback", True)
+
+ problems = app_module._modly_readiness()
+ expected = [f"{model}: weights missing from MODELS_DIR" for model in app_module.ENABLED_MODELS]
+ check(
+ "Modly registers every enabled model with only its weights missing",
+ problems == expected,
+ f"got {problems}",
+ )
+
+ job_dir = app_module.WORKSPACE_DIR / "contract"
+ job_dir.mkdir(parents=True)
+ source = job_dir / "input.glb"
+ source.write_bytes(trimesh.creation.icosphere(subdivisions=4).export(file_type="glb"))
+
+ async def run_ops():
+ import httpx
+
+ async with httpx.AsyncClient(base_url=app_module.MODLY_URL, timeout=180.0) as client:
+ repaired, _ = await app_module._modly_op(client, "repair", source, {"fill_holes": True})
+ decimated, details = await app_module._modly_op(client, "decimate", repaired, {"target_faces": 1000})
+ smoothed, _ = await app_module._modly_op(
+ client, "smooth", decimated, {"iterations": 3, "lambda_": 0.5, "mode": "taubin"}
+ )
+ return repaired, decimated, details, smoothed
+
+ repaired, decimated, details, smoothed = asyncio.run(run_ops())
+ check("repair op writes a mesh in the workspace", repaired.is_file() and job_dir in repaired.parents)
+ faces = len(postprocess.load_mesh(decimated.read_bytes(), decimated.suffix).faces)
+ check("decimate op runs on Node + meshoptimizer", 0 < faces <= 1300, f"{faces} faces, details {details}")
+ check("smooth op writes a mesh in the workspace", smoothed.is_file(), str(smoothed))
+ finally:
+ app_module._stop_modly()
+ shutil.rmtree(root, ignore_errors=True)
+
+
+VENV_IMPORTS = {
+ "triposg/generate": "import diso, rembg; from triposg.pipelines.pipeline_triposg import TripoSGPipeline",
+ "hunyuan3d-mini-turbo/generate": "import rembg; from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline",
+}
+
+
+def venv_checks(app_module) -> None:
+ for model in app_module.ENABLED_MODELS:
+ ext = model.split("/", 1)[0]
+ python = app_module.EXTENSIONS_DIR / ext / "venv" / "bin" / "python"
+ check(f"{ext} venv exists", python.is_file(), str(python))
+ statement = VENV_IMPORTS[model]
+ proc = subprocess.run([str(python), "-c", statement], capture_output=True, text=True, timeout=600)
+ if proc.returncode == 0:
+ check(f"{ext} venv imports its model package", True)
+ elif _is_gpu_driver_absence(proc.stderr):
+ last = proc.stderr.strip().splitlines()[-1] if proc.stderr.strip() else ""
+ print(f"skip {ext} venv import (no GPU on this host): {last}")
+ else:
+ check(f"{ext} venv imports its model package", False, proc.stderr.strip()[-600:])
+
+
+def main() -> int:
+ import main as app_module
+
+ check("app module imports", True)
+ front_checks(app_module)
+
+ if _backend_present(app_module):
+ modly_checks(app_module)
+ venv_checks(app_module)
+ elif REQUIRE_BACKEND:
+ check("Modly backend present", False, f"no Modly at {app_module.MODLY_API_DIR} or {app_module.EXTENSIONS_DIR}")
+ else:
+ print(f"skip backend checks (no Modly checkout at {app_module.MODLY_API_DIR}; run inside the image)")
+
+ print(f"\n{PASSED} contract assertions passed")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())