Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(create-3d): Stable Fast 3D as the second local 3D model of the Mac

purple517a3cbcc528
diff --git a/scripts/build-sf3d-wheels.sh b/scripts/build-sf3d-wheels.sh
new file mode 100755
index 00000000..fe4eb3df
--- /dev/null
+++ b/scripts/build-sf3d-wheels.sh
@@ -0,0 +1,81 @@
+#!/bin/bash
+# build-sf3d-wheels.sh: build the two C++ extensions of Stable Fast 3D
+# (texture_baker, uv_unwrapper) into the wheels the app ships in
+# src-tauri/resources/mesh3d/wheels/ (see src-tauri/src/commands/mesh3d_sf3d.rs).
+#
+# A customer's Mac has no compiler, so LU builds these once and the install
+# hands them to pip as files. This script is how they were built, so a new
+# torch or Python pin can build them again.
+#
+# Usage:
+# scripts/build-sf3d-wheels.sh <python> <out-dir>
+#
+# <python> a Python 3.12 with exactly torch==2.10.0, numpy and
+# setuptools==71.1.0 (the pins of mesh3d_sf3d.rs), on Apple Silicon
+# <out-dir> an empty folder; the wheels land there
+#
+# Needs the Xcode command line tools. The source archive is fetched at the
+# pinned commit into a fresh folder, throttled, and checked by sha256 before
+# anything is built. Nothing from it is run except its two setup.py files.
+#
+# What is set, and why:
+# USE_METAL=1 texture_baker gets its Metal kernel for MPS
+# USE_CUDA=0 no CUDA on a Mac
+# USE_NATIVE_ARCH=0 no -march=native: the wheels run on every Apple Silicon
+# CFLAGS=-O3 uv_unwrapper's own flags lose -O3 on a Mac
+# MACOSX_DEPLOYMENT_TARGET=14.0 LU's oldest macOS
+# LDFLAGS find torch's libraries next to the package
+# (@loader_path/../torch/lib) and drop what is not used,
+# so uv_unwrapper does not link a Homebrew libomp
+#
+# The build is not byte for byte the same twice (time stamps in the zip),
+# so the wheels in the tree are the pinned ones and a rebuild gets new sums.
+#
+# Afterwards: put the wheels into src-tauri/resources/mesh3d/wheels/, write
+# their sha256 into WHEELS of mesh3d_sf3d.rs, and run
+# cargo test --lib mesh3d_sf3d
+set -euo pipefail
+
+PY="${1:?the Python to build with}"
+OUT="${2:?an empty folder for the wheels}"
+COMMIT="ff21fc491b4dc5314bf6734c7c0dabd86b5f5bb2"
+SHA256="3674ecf09167764be5471a803cf716b390feccbedc389d8c37aa710b754e2808"
+URL="https://github.com/Stability-AI/stable-fast-3d/archive/${COMMIT}.zip"
+
+mkdir -p "$OUT"
+if [ -n "$(ls -A "$OUT")" ]; then
+ echo "$OUT is not empty" >&2
+ exit 1
+fi
+OUT="$(cd "$OUT" && pwd)"
+
+"$PY" -I -c 'import torch, setuptools, sys; assert torch.__version__.startswith("2.10.0"), torch.__version__; assert sys.version_info[:2] == (3, 12), sys.version' \
+ || { echo "the Python does not have the pinned torch and Python line" >&2; exit 1; }
+
+WORK="$(mktemp -d)"
+trap 'rm -rf "$WORK"' EXIT
+curl -sSL --limit-rate 20M -o "$WORK/src.zip" "$URL"
+GOT="$(shasum -a 256 "$WORK/src.zip" | cut -d' ' -f1)"
+if [ "$GOT" != "$SHA256" ]; then
+ echo "the archive has sha256 $GOT, not $SHA256" >&2
+ exit 1
+fi
+(cd "$WORK" && unzip -q src.zip)
+SRC="$WORK/stable-fast-3d-$COMMIT"
+
+export USE_CUDA=0 USE_NATIVE_ARCH=0 MACOSX_DEPLOYMENT_TARGET=14.0 CFLAGS="-O3"
+export LDFLAGS="-Wl,-rpath,@loader_path/../torch/lib -Wl,-dead_strip_dylibs"
+(cd "$SRC/texture_baker" && USE_METAL=1 "$PY" -I -m pip wheel --no-index --no-build-isolation --no-deps -w "$OUT" .)
+(cd "$SRC/uv_unwrapper" && "$PY" -I -m pip wheel --no-index --no-build-isolation --no-deps -w "$OUT" .)
+
+# Only torch's libraries and the system's may be linked.
+CHECK="$WORK/check"
+mkdir -p "$CHECK"
+for wheel in "$OUT"/*.whl; do (cd "$CHECK" && unzip -qo "$wheel"); done
+BAD="$(otool -L "$CHECK"/*/_C*.so | grep -v ':$' | grep -v '@rpath/lib\(c10\|torch\|torch_cpu\|torch_python\)\.dylib' | grep -v '/usr/lib/' || true)"
+if [ -n "$BAD" ]; then
+ echo "a wheel links something a customer's Mac does not have:" >&2
+ echo "$BAD" >&2
+ exit 1
+fi
+shasum -a 256 "$OUT"/*.whl
diff --git a/scripts/mac-engine-pins.mjs b/scripts/mac-engine-pins.mjs
index 9ea6b004..05cdfa30 100644
--- a/scripts/mac-engine-pins.mjs
+++ b/scripts/mac-engine-pins.mjs
@@ -26,6 +26,8 @@
// mesh3d src-tauri/src/commands/mesh3d.rs PINNED (the TripoSR source is
// not a pip package: Rust fetches
// it by sha256, so pip never sees it)
+// mesh3d-sf3d src-tauri/src/commands/mesh3d_sf3d.rs PINNED (its two own wheels ship in
+// the app, pip gets them as files)
//
// Usage:
// node scripts/mac-engine-pins.mjs # print the lists
@@ -47,6 +49,7 @@ export const SOURCES = {
'mlx-video': 'src-tauri/src/commands/video.rs',
'ltx-2-mlx': 'src-tauri/src/commands/video_ltx2mlx.rs',
mesh3d: 'src-tauri/src/commands/mesh3d.rs',
+ 'mesh3d-sf3d': 'src-tauri/src/commands/mesh3d_sf3d.rs',
}
/** The Python line the app's own interpreter is on, e.g. "3.12". */
@@ -159,6 +162,7 @@ export function readEnginePins(read = (rel) => readFileSync(join(REPO_ROOT, rel)
])
add('ltx-2-mlx', 'second video engine (ltx-2-mlx)', ltxSpecs)
add('mesh3d', '3D engine (TripoSR)', (src) => rustStrArray(src, 'PINNED'))
+ add('mesh3d-sf3d', '3D engine (Stable Fast 3D)', (src) => rustStrArray(src, 'PINNED'))
return engines
}
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 97c6a91f..92de65d4 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -3171,6 +3171,7 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml",
+ "sha1",
"sha2 0.10.9",
"snow",
"socket2 0.5.10",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index d566fda7..4ef77b64 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -113,6 +113,10 @@ qrcode = "0.14"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
rand = "0.8"
sha2 = "0.10"
+# The git object id of a gated Hugging Face file (commands/mesh3d_sf3d.rs).
+# RustCrypto, the sibling of sha2, already in Cargo.lock at 0.10.6 through
+# other crates, so this adds no crate to the build.
+sha1 = "0.10"
# Unpacking the private Python of the voice loop (commands/voice_loop). Both
# are already in Cargo.lock through the updater plugin, so this adds no crate
# to the build.
diff --git a/src-tauri/resources/mesh3d/run_sf3d.py b/src-tauri/resources/mesh3d/run_sf3d.py
new file mode 100644
index 00000000..0e6154ce
--- /dev/null
+++ b/src-tauri/resources/mesh3d/run_sf3d.py
@@ -0,0 +1,332 @@
+"""LU's own runner of Stable Fast 3D: one picture in, one textured GLB out.
+
+The app starts this once per model (`src-tauri/src/commands/mesh3d_sf3d.rs`)
+with `python -I -u run_sf3d.py --lu-mesh3d-job <job.json>` and reads what it
+says on stdout: lines that begin with `LU-MESH3D `, each a JSON object with a
+`phase` (load, shape, paint, save, done, error, note), the same words the
+TripoSR runner uses, so the app reads both the same way.
+
+What it changes against `run.py` of SF3D, and why (read at the pinned commit,
+see mesh3d_sf3d.rs):
+
+1. `rembg` is imported at module level by `sf3d/utils.py` and downloads a
+ model of its own on first use. LU cuts the object out with Apple's Vision
+ before this runs, so a stand-in is put in its place that refuses to work.
+2. `gpytoolbox` and `pynanoinstantmeshes` are imported at module level by
+ `sf3d/models/mesh.py` and only used for the optional remesh, which LU does
+ not offer. Stand-ins that refuse to work take their place.
+3. The image encoder (`Dinov2Model.from_pretrained("facebook/dinov2-large")`)
+ and the CLIP estimator (`open_clip.create_model_and_transforms(...,
+ pretrained="laion2b_s34b_b79k")`) would download weights from the hub
+ when the model is built. SF3D loads `model.safetensors` with
+ `safetensors.torch.load_model`, which is strict: every weight of both
+ encoders is in that file. So both are built empty here, the DINOv2 one from
+ its `config.json` that the app downloads at a fixed revision, the CLIP one
+ from open_clip's own config, and the file fills them. The run is offline
+ (`HF_HUB_OFFLINE=1`).
+4. The two C++ extensions (`texture_baker`, `uv_unwrapper`) come as wheels LU
+ built itself; the app installs them from its own bundle, never compiles.
+
+The weights are read with safetensors: a file that holds anything but tensors
+cannot run code.
+
+`--lu-mesh3d-selftest <out.glb>` runs the native parts without the model: a
+small sphere is unwrapped by `uv_unwrapper`, rasterised by `texture_baker` on
+the CPU (and on MPS when the Mac has it), and written as a textured GLB. With
+`--source <dir>` it also imports SF3D with the stand-ins. The install uses it
+to prove the venv and the wheels.
+"""
+
+import json
+import os
+import shutil
+import sys
+import time
+import traceback
+import types
+
+PREFIX = "LU-MESH3D "
+JOB_FLAG = "--lu-mesh3d-job"
+SELFTEST_FLAG = "--lu-mesh3d-selftest"
+
+DINO_REPO = "facebook/dinov2-large"
+
+# The texture side per step of Detail. The app sends one of these.
+TEXTURES = (512, 1024, 2048)
+
+
+def say(**fields):
+ print(PREFIX + json.dumps(fields), flush=True)
+
+
+# ── Stand-ins for what LU does not use ──────────────────────────────────
+
+
+def refusing_module(name, *functions):
+ def refuse(*_args, **_kwargs):
+ raise RuntimeError(f"{name} is not part of LU's 3D engine")
+
+ module = types.ModuleType(name)
+ for function in functions:
+ setattr(module, function, refuse)
+ return module
+
+
+def install_stand_ins():
+ """Put `rembg`, `gpytoolbox` and `pynanoinstantmeshes` into `sys.modules`
+ before SF3D loads."""
+ for name, functions in (
+ ("rembg", ("remove", "new_session")),
+ ("gpytoolbox", ("subdivide", "decimate", "remesh_botsch")),
+ ("pynanoinstantmeshes", ("remesh",)),
+ ):
+ sys.modules[name] = refusing_module(name, *functions)
+
+
+def import_sf3d(source, dino_config):
+ """SF3D from the pinned source, with both encoders built without a download."""
+ if source not in sys.path:
+ sys.path.insert(0, source)
+ install_stand_ins()
+
+ import open_clip
+ import sf3d.models.tokenizers.dinov2 as dinov2
+ from transformers import Dinov2Config
+
+ def local_dinov2(cls, name, *_args, **_kwargs):
+ if name != DINO_REPO:
+ raise RuntimeError(f"the run is offline and has no config for {name}")
+ return cls(Dinov2Config.from_json_file(dino_config))
+
+ dinov2.Dinov2Model.from_pretrained = classmethod(local_dinov2)
+
+ create = open_clip.create_model_and_transforms
+
+ def clip_without_download(model_name, *args, **kwargs):
+ kwargs["pretrained"] = None
+ return create(model_name, *args, **kwargs)
+
+ open_clip.create_model_and_transforms = clip_without_download
+ unwrap_on_the_cpu()
+
+ from sf3d.system import SF3D
+ from sf3d.utils import resize_foreground
+
+ return SF3D, resize_foreground
+
+
+def unwrap_on_the_cpu():
+ """Run the UV unwrapper on the CPU whatever device the mesh is on.
+
+ Its C++ part has no MPS kernel, and on MPS one of its steps (a QR
+ decomposition that falls back to the CPU) ended the whole process with a
+ Metal assertion on an M5 Pro (13.11.2026), which no `except` can catch.
+ On the CPU the same mesh unwraps in about half a second."""
+ from uv_unwrapper import Unwrapper
+
+ forward = Unwrapper.forward
+ if getattr(forward, "lu_cpu", False):
+ return
+
+ def cpu_forward(self, vertex_positions, vertex_normals, triangle_idxs, island_padding):
+ device = vertex_positions.device
+ uv, indices = forward(self, vertex_positions.cpu(), vertex_normals.cpu(), triangle_idxs.cpu(), island_padding)
+ return uv.to(device), indices.to(device)
+
+ cpu_forward.lu_cpu = True
+ Unwrapper.forward = cpu_forward
+
+
+# ── The picture ─────────────────────────────────────────────────────────
+
+
+def prepare_image(path, foreground_ratio, resize_foreground):
+ """The picture as SF3D takes it: RGBA with the object cropped and padded.
+
+ A picture with transparent pixels (the cutout) is cropped to the object
+ and padded to `foreground_ratio`, as `run.py` does after rembg. A picture
+ without transparency is taken whole, as an object that fills the frame.
+ """
+ import numpy as np
+ from PIL import Image, ImageOps
+
+ image = ImageOps.exif_transpose(Image.open(path)).convert("RGBA")
+ alpha = np.asarray(image)[..., 3]
+ if not (alpha > 127).any():
+ raise ValueError("no object")
+ if (alpha < 255).any():
+ image = resize_foreground(image, foreground_ratio)
+ return image
+
+
+# ── The run ─────────────────────────────────────────────────────────────
+
+
+def pick_device(asked):
+ import torch
+
+ if asked == "cpu":
+ return "cpu"
+ if torch.backends.mps.is_available():
+ return "mps"
+ return "cpu"
+
+
+def texture_for(asked):
+ t = int(asked)
+ return t if t in TEXTURES else 1024
+
+
+def watch_phases(model):
+ """Tell the app when the shape is through and the painting begins."""
+ shape = model.triplane_to_meshes
+
+ def triplane_to_meshes(*args, **kwargs):
+ say(phase="shape", fraction=0.3)
+ meshes = shape(*args, **kwargs)
+ say(phase="shape", fraction=1.0)
+ say(phase="paint")
+ return meshes
+
+ model.triplane_to_meshes = triplane_to_meshes
+
+
+def make(model, image, texture):
+ import torch
+
+ with torch.no_grad():
+ mesh, _glob = model.run_image(image, bake_resolution=texture, remesh="none", vertex_count=-1)
+ return mesh
+
+
+def run(job):
+ started = time.time()
+ say(phase="load")
+ SF3D, resize_foreground = import_sf3d(job["source"], job["dino_config"])
+ model = SF3D.from_pretrained(job["weights_dir"], config_name="config.yaml", weight_name="model.safetensors")
+ device = pick_device(job.get("device", "auto"))
+ if device == "cpu":
+ # SF3D asks for the device itself in a few places (`get_device`).
+ os.environ["SF3D_USE_CPU"] = "1"
+ model.to(device)
+ model.eval()
+ watch_phases(model)
+ say(phase="note", note=f"device {device}", device=device)
+
+ try:
+ image = prepare_image(job["image"], float(job["foreground_ratio"]), resize_foreground)
+ except (ValueError, AssertionError):
+ say(phase="error", error="no object", code="no_object")
+ sys.exit(6)
+
+ texture = texture_for(job["texture"])
+ say(phase="shape", fraction=0.0)
+ try:
+ mesh = make(model, image, texture)
+ except RuntimeError as e:
+ if device == "cpu":
+ raise
+ # An operation MPS cannot run even with the fallback: once more on the
+ # CPU, which is slower and always there.
+ say(phase="note", note="the graphics chip could not run the model, using the CPU: " + str(e)[:200], device="cpu")
+ device = "cpu"
+ os.environ["SF3D_USE_CPU"] = "1"
+ model.to(device)
+ mesh = make(model, image, texture)
+
+ if len(getattr(mesh, "faces", [])) == 0:
+ say(phase="error", error="no object", code="no_object")
+ sys.exit(6)
+
+ say(phase="save")
+ part = os.path.join(job["work"], "model.glb")
+ mesh.export(part, file_type="glb", include_normals=True)
+ os.makedirs(os.path.dirname(job["output"]), exist_ok=True)
+ shutil.move(part, job["output"])
+ say(
+ phase="done",
+ output=job["output"],
+ triangles=int(len(mesh.faces)),
+ vertices=int(len(mesh.vertices)),
+ device=device,
+ texture=texture,
+ seconds=round(time.time() - started, 1),
+ )
+
+
+# ── The self test ───────────────────────────────────────────────────────
+
+
+def bake_sphere(device):
+ """Unwrap and rasterise a small sphere on `device`. Returns the share of
+ texels the bake covered, the number of triangles and the mesh."""
+ import torch
+ import trimesh
+ from texture_baker import TextureBaker
+ from uv_unwrapper import Unwrapper
+
+ sphere = trimesh.creation.icosphere(subdivisions=3, radius=0.5)
+ v = torch.tensor(sphere.vertices, dtype=torch.float32)
+ f = torch.tensor(sphere.faces, dtype=torch.int64)
+ n = torch.tensor(sphere.vertex_normals, dtype=torch.float32)
+ uv, indices = Unwrapper()(v, n, f, 0.02)
+ uv_flat = uv[indices].reshape(-1, 2)
+ faces = torch.arange(uv_flat.shape[0], dtype=torch.int64).reshape(-1, 3)
+ assert float(uv_flat.min()) >= -1e-4 and float(uv_flat.max()) <= 1 + 1e-4, "UVs outside the atlas"
+ baker = TextureBaker()
+ rast = baker.rasterize(uv_flat.to(device), faces.to(device), 128)
+ covered = float(baker.get_mask(rast).float().mean().cpu())
+ assert covered > 0.2, f"the bake covered {covered:.2f} of the texture"
+ return covered, int(faces.shape[0]), v[f].reshape(-1, 3), faces, uv_flat
+
+
+def selftest(out):
+ import numpy as np
+ import torch
+ import trimesh
+ from PIL import Image
+
+ devices = ["cpu"] + (["mps"] if torch.backends.mps.is_available() else [])
+ told = {}
+ for device in devices:
+ covered, triangles, verts, faces, uvs = bake_sphere(device)
+ told[device] = round(covered, 3)
+ texture = Image.fromarray((np.indices((64, 64)).sum(axis=0) % 2 * 255).astype(np.uint8)).convert("RGB")
+ material = trimesh.visual.material.PBRMaterial(baseColorTexture=texture, roughnessFactor=0.8, metallicFactor=0.0)
+ mesh = trimesh.Trimesh(
+ vertices=verts.numpy(),
+ faces=faces.numpy(),
+ visual=trimesh.visual.texture.TextureVisuals(uv=uvs.numpy(), material=material),
+ process=False,
+ )
+ work = os.path.dirname(os.path.abspath(out))
+ part = os.path.join(work, "selftest-part.glb")
+ mesh.export(part, file_type="glb")
+ shutil.move(part, out)
+ with open(out, "rb") as f:
+ assert f.read(4) == b"glTF", "not a GLB"
+ say(phase="selftest", triangles=triangles, covered=told)
+
+
+def main(argv):
+ if SELFTEST_FLAG in argv:
+ out = argv[argv.index(SELFTEST_FLAG) + 1]
+ selftest(out)
+ if "--source" in argv:
+ import_sf3d(argv[argv.index("--source") + 1], "unused")
+ say(phase="selftest", imported="sf3d.system")
+ return
+ with open(argv[argv.index(JOB_FLAG) + 1], encoding="utf-8") as f:
+ job = json.load(f)
+ try:
+ run(job)
+ except SystemExit:
+ raise
+ except BaseException as e:
+ traceback.print_exc()
+ say(phase="error", error=(type(e).__name__ + ": " + str(e))[-600:])
+ sys.exit(5)
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
diff --git a/src-tauri/resources/mesh3d/test_run_sf3d.py b/src-tauri/resources/mesh3d/test_run_sf3d.py
new file mode 100644
index 00000000..b169becf
--- /dev/null
+++ b/src-tauri/resources/mesh3d/test_run_sf3d.py
@@ -0,0 +1,119 @@
+"""Tests of LU's Stable Fast 3D runner without the model.
+
+Run with the engine's venv (it has torch, trimesh, Pillow and LU's two wheels):
+
+ <data_dir>/mesh3d-sf3d/venv/bin/python -I -m unittest discover -s src-tauri/resources/mesh3d -p 'test_run_sf3d.py'
+
+`-I` keeps the folder of the test out of the import path, so the runner is
+loaded by its file path below and nothing else from this folder is.
+"""
+
+import importlib.util
+import json
+import os
+import struct
+import sys
+import tempfile
+import unittest
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.dont_write_bytecode = True
+spec = importlib.util.spec_from_file_location("run_sf3d", os.path.join(HERE, "run_sf3d.py"))
+runner = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(runner)
+
+
+def read_glb_json(path):
+ with open(path, "rb") as f:
+ data = f.read()
+ magic, _version, length = struct.unpack_from("<4sII", data, 0)
+ chunk_len, chunk_type = struct.unpack_from("<I4s", data, 12)
+ assert magic == b"glTF" and length == len(data) and chunk_type == b"JSON"
+ return json.loads(data[20:20 + chunk_len])
+
+
+def crop_like_sf3d(image, ratio):
+ """What `sf3d.utils.resize_foreground` is asked for: an RGBA picture in, an
+ RGBA picture out. The test only checks that it is called."""
+ image.lu_cropped = ratio
+ return image
+
+
+class ThePicture(unittest.TestCase):
+ def picture(self, alpha):
+ from PIL import Image
+
+ image = Image.new("RGBA", (32, 32), (200, 10, 10, alpha))
+ path = os.path.join(tempfile.mkdtemp(), "p.png")
+ image.save(path)
+ return path
+
+ def test_a_cutout_is_cropped_to_its_object(self):
+ from PIL import Image
+
+ image = Image.new("RGBA", (32, 32), (0, 0, 0, 0))
+ image.paste((200, 10, 10, 255), (8, 8, 24, 24))
+ path = os.path.join(tempfile.mkdtemp(), "cut.png")
+ image.save(path)
+ out = runner.prepare_image(path, 0.85, crop_like_sf3d)
+ self.assertEqual(out.mode, "RGBA")
+ self.assertEqual(getattr(out, "lu_cropped", None), 0.85)
+
+ def test_an_opaque_photo_is_taken_whole(self):
+ out = runner.prepare_image(self.picture(255), 0.85, crop_like_sf3d)
+ self.assertEqual(out.mode, "RGBA")
+ self.assertFalse(hasattr(out, "lu_cropped"))
+
+ def test_a_picture_with_nothing_in_it_has_no_object(self):
+ with self.assertRaises(ValueError):
+ runner.prepare_image(self.picture(0), 0.85, crop_like_sf3d)
+
+
+class TheJob(unittest.TestCase):
+ def test_only_the_three_texture_sides(self):
+ self.assertEqual([runner.texture_for(t) for t in (512, 1024, 2048, 4096, 7)], [512, 1024, 2048, 1024, 1024])
+
+ def test_the_stand_ins_refuse_and_say_why(self):
+ runner.install_stand_ins()
+ import gpytoolbox
+ import pynanoinstantmeshes
+ import rembg
+
+ for call in (lambda: rembg.remove(None), lambda: gpytoolbox.remesh_botsch(), lambda: pynanoinstantmeshes.remesh()):
+ with self.assertRaises(RuntimeError) as told:
+ call()
+ self.assertIn("not part of LU", str(told.exception))
+
+
+class TheNativeParts(unittest.TestCase):
+ def test_the_wheels_unwrap_and_bake_and_a_textured_glb_comes_out(self):
+ out = os.path.join(tempfile.mkdtemp(), "self.glb")
+ runner.selftest(out)
+ gltf = read_glb_json(out)
+ self.assertEqual(len(gltf["meshes"]), 1)
+ self.assertTrue(gltf.get("images"), "the texture is in the file")
+ self.assertIn("TEXCOORD_0", gltf["meshes"][0]["primitives"][0]["attributes"])
+
+ def test_the_unwrapper_runs_on_the_cpu_for_a_mesh_on_mps(self):
+ import torch
+
+ runner.unwrap_on_the_cpu()
+ runner.unwrap_on_the_cpu() # twice changes nothing
+ from uv_unwrapper import Unwrapper
+
+ self.assertTrue(getattr(Unwrapper.forward, "lu_cpu", False))
+ if not torch.backends.mps.is_available():
+ self.skipTest("no MPS on this machine")
+ import trimesh
+
+ sphere = trimesh.creation.icosphere(subdivisions=2, radius=0.5)
+ v = torch.tensor(sphere.vertices, dtype=torch.float32, device="mps")
+ n = torch.tensor(sphere.vertex_normals, dtype=torch.float32, device="mps")
+ f = torch.tensor(sphere.faces, dtype=torch.int64, device="mps")
+ uv, indices = Unwrapper()(v, n, f, 0.02)
+ self.assertEqual(uv.device.type, "mps")
+ self.assertEqual(indices.shape[0], f.shape[0])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/src-tauri/resources/mesh3d/wheels/texture_baker-0.0.1-cp312-cp312-macosx_14_0_arm64.whl b/src-tauri/resources/mesh3d/wheels/texture_baker-0.0.1-cp312-cp312-macosx_14_0_arm64.whl
new file mode 100644
index 00000000..1234be0e
Binary files /dev/null and b/src-tauri/resources/mesh3d/wheels/texture_baker-0.0.1-cp312-cp312-macosx_14_0_arm64.whl differ
diff --git a/src-tauri/resources/mesh3d/wheels/uv_unwrapper-0.0.1-cp312-cp312-macosx_14_0_arm64.whl b/src-tauri/resources/mesh3d/wheels/uv_unwrapper-0.0.1-cp312-cp312-macosx_14_0_arm64.whl
new file mode 100644
index 00000000..276092c8
Binary files /dev/null and b/src-tauri/resources/mesh3d/wheels/uv_unwrapper-0.0.1-cp312-cp312-macosx_14_0_arm64.whl differ
diff --git a/src-tauri/src/commands/mesh3d.rs b/src-tauri/src/commands/mesh3d.rs
index 2c69e3db..cc60c4dd 100644
--- a/src-tauri/src/commands/mesh3d.rs
+++ b/src-tauri/src/commands/mesh3d.rs
@@ -42,6 +42,7 @@
//! - the encoder config, Apache 2.0: <https://huggingface.co/facebook/dino-vitb16>
//! at `DINO_REVISION`
+use crate::commands::mesh3d_sf3d;
use crate::commands::voice_loop::manifest::RemoteFile;
use crate::commands::{bad_request, internal, not_found, CmdResult};
use crate::install_state::InstallSlot;
@@ -98,6 +99,10 @@ const PINNED: [&str; 34] = [
"transformers==4.57.6", "trimesh==5.1.1", "typing-extensions==4.15.0", "urllib3==2.6.3",
];
+/// TripoSR's pins, for the test of the other engine's shared versions.
+#[cfg(test)]
+pub(crate) const PINNED_FOR_TESTS: &[&str] = &PINNED;
+
/// What the install proves it can import before the self test.
const MODULE: &str = "torch, transformers, omegaconf, trimesh, skimage.measure, einops, PIL";
@@ -138,11 +143,11 @@ fn root() -> PathBuf {
crate::os_paths::data_dir().join("mesh3d")
}
-fn venv_dir(root: &Path) -> PathBuf {
+pub(crate) fn venv_dir(root: &Path) -> PathBuf {
root.join("venv")
}
-fn venv_python(venv: &Path) -> PathBuf {
+pub(crate) fn venv_python(venv: &Path) -> PathBuf {
venv.join("bin").join("python")
}
@@ -152,16 +157,16 @@ fn source_dir(root: &Path) -> PathBuf {
}
/// `model.ckpt`, `config.yaml` and the encoder's `dino-vitb16/config.json`.
-fn weights_dir(root: &Path) -> PathBuf {
+pub(crate) fn weights_dir(root: &Path) -> PathBuf {
root.join("weights")
}
/// Where the downloads that are not the weights wait to be unpacked.
-fn downloads_dir(root: &Path) -> PathBuf {
+pub(crate) fn downloads_dir(root: &Path) -> PathBuf {
root.join("downloads")
}
-fn work_dir(root: &Path) -> PathBuf {
+pub(crate) fn work_dir(root: &Path) -> PathBuf {
root.join("work")
}
@@ -188,6 +193,7 @@ fn ensure_apple_silicon() -> Result<(), String> {
// ── The engine ────────────────────────────────────────────────────────
+#[cfg(test)]
fn pip_args() -> Vec<String> {
["-m", "pip", "install", "--upgrade", "--only-binary", ":all:", "--disable-pip-version-check"]
.iter()
@@ -208,7 +214,7 @@ fn engine_ready_at(venv: &Path) -> bool {
venv_python(venv).exists() && std::fs::read_to_string(stamp_file(venv)).is_ok_and(|s| s == stamp())
}
-fn python_has_module(python: &str, module: &str) -> bool {
+pub(crate) fn python_has_module(python: &str, module: &str) -> bool {
crate::python::python_command(python)
.args(["-I", "-c", &format!("import {module}")])
.stdin(Stdio::null())
@@ -219,7 +225,7 @@ fn python_has_module(python: &str, module: &str) -> bool {
.unwrap_or(false)
}
-fn create_venv(slot: &InstallSlot, base: &str, venv: &Path) -> Result<(), String> {
+pub(crate) fn create_venv(slot: &InstallSlot, base: &str, venv: &Path) -> Result<(), String> {
if let Some(parent) = venv.parent() {
std::fs::create_dir_all(parent).map_err(|e| os_error::english(&e))?;
}
@@ -238,8 +244,40 @@ fn create_venv(slot: &InstallSlot, base: &str, venv: &Path) -> Result<(), String
/// not. Built from LU's own Python (`private_python`), never one found on the
/// Mac. `base` is for the tests.
fn ensure_engine_at(slot: &InstallSlot, base: Option<String>, venv: &Path) -> Result<String, String> {
+ let engine = Engine { pinned: &PINNED, wheels: &[], module: MODULE, stamp: stamp(), stamp_file: stamp_file(venv) };
+ ensure_engine_with(slot, base, venv, &engine)
+}
+
+/// What a 3D engine's venv holds: the packages from PyPI, wheels LU ships
+/// itself (paths on disk, written and checked by the caller), the import
+/// that proves it, and the stamp that says it is this pin.
+pub(crate) struct Engine<'a> {
+ pub pinned: &'a [&'a str],
+ pub wheels: &'a [PathBuf],
+ pub module: &'a str,
+ pub stamp: String,
+ pub stamp_file: PathBuf,
+}
+
+impl Engine<'_> {
+ pub(crate) fn ready(&self, venv: &Path) -> bool {
+ venv_python(venv).exists() && std::fs::read_to_string(&self.stamp_file).is_ok_and(|s| s == self.stamp)
+ }
+
+ pub(crate) fn pip_args(&self) -> Vec<String> {
+ ["-m", "pip", "install", "--upgrade", "--only-binary", ":all:", "--disable-pip-version-check"]
+ .iter()
+ .map(|a| a.to_string())
+ .chain(self.pinned.iter().map(|p| p.to_string()))
+ .chain(self.wheels.iter().map(|w| w.to_string_lossy().to_string()))
+ .collect()
+ }
+}
+
+/// The venv of `engine`, built when it is not there or not this pin.
+pub(crate) fn ensure_engine_with(slot: &InstallSlot, base: Option<String>, venv: &Path, engine: &Engine<'_>) -> Result<String, String> {
let python = venv_python(venv).to_string_lossy().to_string();
- if engine_ready_at(venv) {
+ if engine.ready(venv) {
return Ok(python);
}
if !(venv_python(venv).exists() && python_has_module(&python, "pip")) {
@@ -250,15 +288,15 @@ fn ensure_engine_at(slot: &InstallSlot, base: Option<String>, venv: &Path) -> Re
slot.log(format!("Python: {base}"));
create_venv(slot, &base, venv)?;
}
- let _ = std::fs::remove_file(stamp_file(venv));
- slot.log(format!("installing the 3D engine packages, {} pinned (one-time)", PINNED.len()));
+ let _ = std::fs::remove_file(&engine.stamp_file);
+ slot.log(format!("installing the 3D engine packages, {} pinned (one-time)", engine.pinned.len() + engine.wheels.len()));
let mut pip = crate::python::python_command(&python);
- pip.args(pip_args());
+ pip.args(engine.pip_args());
crate::commands::video::run_streamed(slot, &mut pip).map_err(|e| format!("Could not install the 3D engine. {e}"))?;
- if !python_has_module(&python, MODULE) {
- return Err(format!("pip install finished but `import {MODULE}` still fails"));
+ if !python_has_module(&python, engine.module) {
+ return Err(format!("pip install finished but `import {}` still fails", engine.module));
}
- std::fs::write(stamp_file(venv), stamp()).map_err(|e| os_error::english(&e))?;
+ std::fs::write(&engine.stamp_file, &engine.stamp).map_err(|e| os_error::english(&e))?;
Ok(python)
}
@@ -403,6 +441,12 @@ fn bytes_to_fetch(root: &Path) -> u64 {
/// Fetch every `(remote, destination)` that is not there yet, one after the
/// other, with one bar over all of them.
fn fetch_files(slot: &InstallSlot, files: &[(RemoteFile, PathBuf)], what: &str) -> Result<(), String> {
+ fetch_files_as(slot, files, what, None)
+}
+
+/// `fetch_files` with a Hugging Face token for a gated repository. A refusal
+/// of the hub is said in the words the image lane uses for it.
+pub(crate) fn fetch_files_as(slot: &InstallSlot, files: &[(RemoteFile, PathBuf)], what: &str, hub_token: Option<&str>) -> Result<(), String> {
use crate::commands::voice_loop::fetch;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
@@ -424,9 +468,14 @@ fn fetch_files(slot: &InstallSlot, files: &[(RemoteFile, PathBuf)], what: &str)
let seconds = started.elapsed().as_secs_f64().max(0.001);
meter.set_download(all, total, (all.saturating_sub(first) as f64 / seconds) as u64);
};
- let fetched = runtime.block_on(fetch::fetch_verified(&client, remote, dest, &cancel, &mut on_progress));
+ let fetched = runtime.block_on(fetch::fetch_verified_as(&client, remote, dest, hub_token, &cancel, &mut on_progress));
if let Err(e) = fetched {
slot.set_download(0, 0, 0);
+ if let fetch::FetchError::Http(status) = e {
+ if let Some(why) = crate::commands::mlx::hub_denied_message(status, hub_token.is_some()) {
+ return Err(why.to_string());
+ }
+ }
return Err(e.user_message(what));
}
before += remote.size;
@@ -466,15 +515,19 @@ fn install_weights(slot: &InstallSlot, root: &Path) -> Result<(), String> {
/// The runner on the disk, as compiled into this build.
fn write_runner(root: &Path) -> Result<PathBuf, String> {
- let file = runner_file(root);
- if std::fs::read_to_string(&file).is_ok_and(|s| s == RUNNER) {
- return Ok(file);
+ write_runner_at(&runner_file(root), RUNNER)
+}
+
+/// A runner `text` at `file`, written only when it differs.
+pub(crate) fn write_runner_at(file: &Path, text: &str) -> Result<PathBuf, String> {
+ if std::fs::read_to_string(file).is_ok_and(|s| s == text) {
+ return Ok(file.to_path_buf());
}
if let Some(dir) = file.parent() {
std::fs::create_dir_all(dir).map_err(|e| os_error::english(&e))?;
}
- std::fs::write(&file, RUNNER).map_err(|e| os_error::english(&e))?;
- Ok(file)
+ std::fs::write(file, text).map_err(|e| os_error::english(&e))?;
+ Ok(file.to_path_buf())
}
/// The runner's own test: a sphere through the surface, colour and GLB code,
@@ -513,7 +566,10 @@ pub fn mesh3d_status(_state: &AppState, _args: &Value) -> CmdResult {
let root = root();
let engine = engine_ready_at(&venv_dir(&root));
let installed = installed_at(&root);
+ let sf3d = mesh3d_sf3d::model_json(mesh3d_sf3d::installed_at(&mesh3d_sf3d::root()), crate::commands::mlx::hf_token().is_some());
Ok(json!({
+ "models": [model_json(installed), sf3d],
+ "installing": installing_model(),
"available": apple_silicon,
"appleSilicon": apple_silicon,
"engineInstalled": engine,
@@ -525,13 +581,51 @@ pub fn mesh3d_status(_state: &AppState, _args: &Value) -> CmdResult {
}))
}
-pub fn mesh3d_install(state: &AppState, _args: &Value) -> CmdResult {
+/// Which model of the 3D lane an install or a run is for. TripoSR when
+/// the caller names none, as every caller before the second model did.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) enum Which {
+ TripoSr,
+ Sf3d,
+}
+
+#[derive(Deserialize, Default)]
+struct ModelArg {
+ #[serde(default)]
+ model: Option<String>,
+ /// What the Model Manager and the real run send.
+ #[serde(default)]
+ id: Option<String>,
+}
+
+fn which(args: &Value) -> Result<Which, String> {
+ let a: ModelArg = serde_json::from_value(args.clone()).unwrap_or_default();
+ match a.model.as_deref().or(a.id.as_deref()) {
+ None | Some(MODEL_ID) => Ok(Which::TripoSr),
+ Some(mesh3d_sf3d::MODEL_ID) => Ok(Which::Sf3d),
+ Some(other) => Err(bad_request(format!("There is no 3D model called {other} on this Mac."))),
+ }
+}
+
+/// The model the install slot works or worked on, for the poll.
+static INSTALLING: Mutex<Option<&'static str>> = Mutex::new(None);
+
+fn installing_model() -> Option<&'static str> {
+ *INSTALLING.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+pub fn mesh3d_install(state: &AppState, args: &Value) -> CmdResult {
ensure_apple_silicon()?;
- let root = root();
+ let model = which(args)?;
let slot = state.install_mesh3d();
if slot.is_running() {
- return Ok(json!({ "ok": true, "status": "installing" }));
+ return Ok(json!({ "ok": true, "status": "installing", "id": installing_model() }));
+ }
+ if model == Which::Sf3d {
+ return install_sf3d(slot);
}
+ *INSTALLING.lock().unwrap_or_else(|e| e.into_inner()) = Some(MODEL_ID);
+ let root = root();
if installed_at(&root) {
if slot.try_start() {
slot.complete(format!("{MODEL_ID} already installed"));
@@ -559,8 +653,37 @@ pub fn mesh3d_install(state: &AppState, _args: &Value) -> CmdResult {
Ok(json!({ "ok": true, "status": "installing", "id": MODEL_ID }))
}
+/// Stable Fast 3D on the same slot: its weights are gated, so nothing is
+/// fetched before the user's Hugging Face token is there.
+fn install_sf3d(slot: crate::install_state::InstallSlot) -> CmdResult {
+ let root = mesh3d_sf3d::root();
+ *INSTALLING.lock().unwrap_or_else(|e| e.into_inner()) = Some(mesh3d_sf3d::MODEL_ID);
+ if mesh3d_sf3d::installed_at(&root) {
+ if slot.try_start() {
+ slot.complete(format!("{} already installed", mesh3d_sf3d::MODEL_ID));
+ }
+ return Ok(json!({ "ok": true, "status": "complete", "id": mesh3d_sf3d::MODEL_ID }));
+ }
+ let Some(token) = crate::commands::mlx::hf_token() else {
+ return Err(bad_request(crate::commands::mlx::hub_denied_message(401, false).unwrap_or_default()));
+ };
+ let (need, note) = mesh3d_sf3d::install_need(&root);
+ crate::commands::system::ensure_free_space(&crate::os_paths::data_dir(), mesh3d_sf3d::MODEL_NAME, need, note).map_err(bad_request)?;
+ std::fs::create_dir_all(&root).map_err(|e| internal(os_error::english(&e)))?;
+ crate::media_store::keep_out_of_backups(&root);
+ if !slot.try_start() {
+ return Ok(json!({ "ok": true, "status": "installing", "id": installing_model() }));
+ }
+ crate::install_state::spawn_install(slot, move |slot| mesh3d_sf3d::install(slot, &root, &token));
+ Ok(json!({ "ok": true, "status": "installing", "id": mesh3d_sf3d::MODEL_ID }))
+}
+
pub fn mesh3d_install_status(state: &AppState, _args: &Value) -> CmdResult {
- Ok(serde_json::to_value(state.install_mesh3d().snapshot()).unwrap_or(Value::Null))
+ let mut answer = serde_json::to_value(state.install_mesh3d().snapshot()).unwrap_or(Value::Null);
+ if answer.is_object() {
+ answer["model"] = json!(installing_model());
+ }
+ Ok(answer)
}
pub fn mesh3d_cancel_install(state: &AppState, _args: &Value) -> CmdResult {
@@ -568,13 +691,18 @@ pub fn mesh3d_cancel_install(state: &AppState, _args: &Value) -> CmdResult {
}
/// Remove the weights. The engine and the source stay, as with music.
-pub fn mesh3d_delete(state: &AppState, _args: &Value) -> CmdResult {
+pub fn mesh3d_delete(state: &AppState, args: &Value) -> CmdResult {
+ let model = which(args)?;
if busy() {
return Err(bad_request("A 3D model is being made. Wait for it to finish before removing the model."));
}
if state.install_mesh3d().is_running() {
return Err(bad_request("The 3D model is still installing. Wait for it to finish, or stop it first."));
}
+ if model == Which::Sf3d {
+ mesh3d_sf3d::delete_at(&mesh3d_sf3d::root())?;
+ return Ok(json!({ "ok": true, "id": mesh3d_sf3d::MODEL_ID }));
+ }
delete_at(&root())?;
Ok(json!({ "ok": true, "id": MODEL_ID }))
}
@@ -605,6 +733,12 @@ struct GenerateArgs {
/// picture that is transparent already is never cut again.
#[serde(default)]
cutout: Option<bool>,
+ /// `triposr` (the default) or `sf3d`.
+ #[serde(default)]
+ model: Option<String>,
+ /// The texture side of Stable Fast 3D: 512, 1024 or 2048.
+ #[serde(default)]
+ texture: Option<u32>,
}
/// The grid side a run uses, within what this lane offers, on steps of 32.
@@ -680,13 +814,18 @@ fn run_command(root: &Path, runner: &Path, job_file: &Path) -> Command {
cmd
}
+#[cfg(test)]
fn memory_refusal(total_bytes: u64) -> Option<String> {
+ memory_refusal_for(total_bytes, MODEL_NAME, MIN_RAM_GB)
+}
+
+fn memory_refusal_for(total_bytes: u64, name: &str, min_gb: u32) -> Option<String> {
if total_bytes == 0 {
return None;
}
let have = (total_bytes as f64 / 1_073_741_824.0).round() as u32;
- (have < MIN_RAM_GB).then(|| {
- format!("{MODEL_NAME} needs a Mac with {MIN_RAM_GB} GB of memory, and this one has {have} GB. It was not started, because loading it would freeze this Mac.")
+ (have < min_gb).then(|| {
+ format!("{name} needs a Mac with {min_gb} GB of memory, and this one has {have} GB. It was not started, because loading it would freeze this Mac.")
})
}
@@ -1040,11 +1179,23 @@ pub async fn mesh3d_generate(state: &AppState, args: &Value) -> CmdResult {
let run = run_file_stem(req.run.trim()).ok_or_else(|| bad_request("The run needs a name of letters, digits and dashes."))?.to_string();
let input = crate::commands::mlx_cutout::staged_input(&req.image_path, &crate::commands::mlx_cutout::staged_images_dir())
.map_err(|e| bad_request(if e == crate::commands::mlx_cutout::NO_IMAGE { "Add a picture of one object first.".to_string() } else { e }))?;
- let root = root();
- if !installed_at(&root) {
- return Err(bad_request(format!("{MODEL_NAME} is not installed. Install it in the Model Manager first.")));
+ let model = match req.model.as_deref() {
+ None | Some(MODEL_ID) => Which::TripoSr,
+ Some(mesh3d_sf3d::MODEL_ID) => Which::Sf3d,
+ Some(other) => return Err(bad_request(format!("There is no 3D model called {other} on this Mac."))),
+ };
+ let (root, name, min_gb) = match model {
+ Which::TripoSr => (root(), MODEL_NAME, MIN_RAM_GB),
+ Which::Sf3d => (mesh3d_sf3d::root(), mesh3d_sf3d::MODEL_NAME, mesh3d_sf3d::MIN_RAM_GB),
+ };
+ let installed = match model {
+ Which::TripoSr => installed_at(&root),
+ Which::Sf3d => mesh3d_sf3d::installed_at(&root),
+ };
+ if !installed {
+ return Err(bad_request(format!("{name} is not installed. Set it up in the 3D tab first.")));
}
- if let Some(refusal) = memory_refusal(crate::commands::system::total_memory_bytes()) {
+ if let Some(refusal) = memory_refusal_for(crate::commands::system::total_memory_bytes(), name, min_gb) {
return Err(bad_request(refusal));
}
// One model in the memory at a time.
@@ -1075,7 +1226,11 @@ pub async fn mesh3d_generate(state: &AppState, args: &Value) -> CmdResult {
return Err(internal(why));
}
}
- let runner = match write_runner(&root) {
+ let written = match model {
+ Which::TripoSr => write_runner(&root),
+ Which::Sf3d => write_runner_at(&mesh3d_sf3d::runner_file(&root), mesh3d_sf3d::RUNNER),
+ };
+ let runner = match written {
Ok(path) => path,
Err(why) => {
RUNS.conclude(&Err(why.clone()));
@@ -1084,10 +1239,16 @@ pub async fn mesh3d_generate(state: &AppState, args: &Value) -> CmdResult {
};
let output = output_for(&out_dir, &run, &job);
let resolution = resolution_for(req.resolution);
+ let texture = mesh3d_sf3d::texture_for(req.texture);
let cutout = req.cutout.unwrap_or(true);
RUNS.view().output = Some(output.to_string_lossy().to_string());
- tracing::info!("[mesh3d] TripoSR at {}: grid {resolution}, cutout {cutout}", &SOURCE_COMMIT[..7]);
- let pid_file = run_pid_file(&root);
+ match model {
+ Which::TripoSr => tracing::info!("[mesh3d] TripoSR at {}: grid {resolution}, cutout {cutout}", &SOURCE_COMMIT[..7]),
+ Which::Sf3d => tracing::info!("[mesh3d] Stable Fast 3D at {}: texture {texture}, cutout {cutout}", &mesh3d_sf3d::SOURCE_COMMIT[..7]),
+ }
+ // One pid file for the lane, in TripoSR's folder, whatever the model:
+ // there is one run at a time, and the reaper reads this one.
+ let pid_file = run_pid_file(&self::root());
let out = output.clone();
std::thread::spawn(move || {
let verdict = (|| {
@@ -1099,7 +1260,11 @@ pub async fn mesh3d_generate(state: &AppState, args: &Value) -> CmdResult {
};
RUNS.set_phase("load", 5);
let job_file = job_dir.join("job.json");
- std::fs::write(&job_file, job_json(&root, &picture, resolution, &job_dir, &out).to_string())
+ let job = match model {
+ Which::TripoSr => job_json(&root, &picture, resolution, &job_dir, &out),
+ Which::Sf3d => mesh3d_sf3d::job_json(&root, &picture, texture, &job_dir, &out),
+ };
+ std::fs::write(&job_file, job.to_string())
.map_err(|e| format!("write {}: {}", job_file.display(), os_error::english(&e)))?;
let child = start(&RUNS, run_command(&root, &runner, &job_file), Some(&pid_file))?;
finish(&RUNS, child, &out, Some(&pid_file), GENERATE_TIMEOUT, STALL_AFTER)
@@ -1122,7 +1287,9 @@ pub async fn mesh3d_generate(state: &AppState, args: &Value) -> CmdResult {
"jobId": job,
"run": run,
"output": output,
+ "model": match model { Which::TripoSr => MODEL_ID, Which::Sf3d => mesh3d_sf3d::MODEL_ID },
"resolution": resolution,
+ "texture": texture,
"cutout": cutout,
}))
}
@@ -1175,7 +1342,8 @@ pub(crate) fn reap_orphaned_run() -> Option<u32> {
return None;
};
let row = Leftover { parent: process.parent().map(|p| p.as_u32()), cmd: crate::process_util::cmdline_of(process) };
- if !is_orphaned_run(&row, &work_dir(&root)) {
+ let ours = is_orphaned_run(&row, &work_dir(&root)) || is_orphaned_run(&row, &work_dir(&mesh3d_sf3d::root()));
+ if !ours {
if row.parent == Some(1) {
let _ = std::fs::remove_file(&pid_file);
}
@@ -1455,6 +1623,30 @@ mod tests {
assert_eq!(env_of(&cmd, "TRANSFORMERS_OFFLINE").as_deref(), Some("1"));
}
+ #[test]
+ fn a_command_names_its_model_or_means_triposr() {
+ assert_eq!(which(&json!({})), Ok(Which::TripoSr));
+ assert_eq!(which(&Value::Null), Ok(Which::TripoSr));
+ assert_eq!(which(&json!({ "model": "triposr" })), Ok(Which::TripoSr));
+ assert_eq!(which(&json!({ "model": "sf3d" })), Ok(Which::Sf3d));
+ assert_eq!(which(&json!({ "id": "sf3d" })), Ok(Which::Sf3d));
+ assert!(which(&json!({ "model": "spar3d" })).unwrap_err().contains("no 3D model called spar3d"));
+ // One pid file for the lane, and a leftover run of either model is found.
+ let src = production_source();
+ assert!(src.contains("let pid_file = run_pid_file(&self::root());"));
+ assert!(src.contains("is_orphaned_run(&row, &work_dir(&mesh3d_sf3d::root()))"));
+ }
+
+ #[test]
+ fn stable_fast_3d_is_not_set_up_without_a_token() {
+ let src = production_source();
+ let body = &src[src.find("fn install_sf3d(").unwrap()..src.find("pub fn mesh3d_install_status(").unwrap()];
+ let token = body.find("hf_token()").unwrap();
+ let space = body.find("ensure_free_space(").unwrap();
+ let spawn = body.find("spawn_install(").unwrap();
+ assert!(token < space && space < spawn, "nothing is fetched before the token is there");
+ }
+
#[test]
fn a_mac_with_too_little_memory_is_told_before_anything_loads() {
const GIB: u64 = 1_073_741_824;
@@ -1611,8 +1803,8 @@ mod tests {
let src = production_source();
let generate = &src[src.find("pub async fn mesh3d_generate(").unwrap()..src.find("pub fn mesh3d_progress(").unwrap()];
let staged = generate.find("mlx_cutout::staged_input(").expect("a picture from anywhere on the disk");
- let installed = generate.find("if !installed_at(&root)").unwrap();
- let memory = generate.find("memory_refusal(").unwrap();
+ let installed = generate.find("if !installed {").unwrap();
+ let memory = generate.find("memory_refusal_for(").unwrap();
let train = generate.find("train::refusal()").unwrap();
let image = generate.find("image_engine_busy()").unwrap();
let video = generate.find("state.video_process()").unwrap();
diff --git a/src-tauri/src/commands/mesh3d_sf3d.rs b/src-tauri/src/commands/mesh3d_sf3d.rs
new file mode 100644
index 00000000..ed817779
--- /dev/null
+++ b/src-tauri/src/commands/mesh3d_sf3d.rs
@@ -0,0 +1,762 @@
+//! The second local 3D model of the Mac: Stable Fast 3D (SF3D), one picture
+//! in, one GLB with a baked texture out.
+//!
+//! It runs on the machinery of `mesh3d.rs` (one run at a time, one Python
+//! process per model, Cancel ends it, offline during the run). What is its
+//! own lives here: a venv of its own, the source at one commit, the gated
+//! weights at one revision, and the two C++ extensions of SF3D as wheels LU
+//! built itself.
+//!
+//! The two extensions (`texture_baker`, `uv_unwrapper`, both in the SF3D
+//! repository) are compiled by `pip install ./texture_baker/` upstream, which
+//! a customer's Mac cannot do: it has no compiler. LU builds them once
+//! (`scripts/build-sf3d-wheels.sh`, against torch 2.10.0 and Python 3.12 of
+//! the pins below), keeps the two wheels in `resources/mesh3d/wheels/` and
+//! compiles them into this binary. The install writes them next to the venv,
+//! checks their sha256 and hands them to pip as files. Nothing is compiled
+//! and nothing of them comes from the net. They link only torch's own
+//! libraries (`@rpath`, found through `@loader_path/../torch/lib`) and the
+//! system's, not Homebrew's OpenMP; `uv_unwrapper` runs single-threaded as
+//! the upstream Mac build does.
+//!
+//! What the runner (`resources/mesh3d/run_sf3d.py`) puts in place of what
+//! does not run on a customer's Mac, read at the pinned commit (13.11.2026):
+//! - `rembg` (downloads a model of its own): LU cuts the object out with
+//! Vision before the run, as for TripoSR.
+//! - `gpytoolbox` and `pynanoinstantmeshes`: only for the remesh option,
+//! which LU does not offer.
+//! - the DINOv2 and CLIP encoders would download their weights when the
+//! model is built. `model.safetensors` is loaded strictly
+//! (`safetensors.torch.load_model`), so it holds every weight of both;
+//! they are built empty, DINOv2 from its `config.json` fetched here at a
+//! fixed revision.
+//!
+//! Content filter: none. `grep -riE "safety|nsfw|censor|filter|explicit|porn|
+//! nude|watermark|blocklist|moderat"` over every `.py` file of `sf3d/` at
+//! `SOURCE_COMMIT` finds nothing. The only network calls are the hub
+//! downloads above, none of which a run makes. The licence's Acceptable Use
+//! Policy forbids sexual content: that is a rule of the licence, not a filter
+//! in the code, and the model is not marked unfiltered.
+//!
+//! The licence: Stability AI Community License (the `LICENSE.md` of the
+//! source archive, the same text on the weights). Free for research,
+//! non-commercial use and for people or companies under a yearly revenue of
+//! one million (US currency), with registration at Stability AI for
+//! commercial use. Whoever passes the code on keeps the licence and a notice
+//! file with it, which the install writes beside the venv (`NOTICE`). The
+//! weights are gated: the user accepts the licence on the model's page and
+//! downloads with their own Hugging Face token (Settings). LU never holds the
+//! weights.
+//!
+//! The digests of the gated files: the hub shows the sha256 of a gated file
+//! only to a signed-in account. What it shows to everyone is the git object
+//! id of each file at the revision. For `config.yaml` that is the sha1 of the
+//! file itself as a git blob; for `model.safetensors` it is the sha1 of its
+//! LFS pointer, and the pointer names the file's sha256. Both ids are pinned
+//! here. The install reads the sha256 with the user's token, rebuilds the
+//! pointer, and goes on only when its id is the pinned one; the download is
+//! then held against that sha256 like every other file of the app.
+//!
+//! Where it was read:
+//! - the code: <https://github.com/Stability-AI/stable-fast-3d> at
+//! `SOURCE_COMMIT` (head of `main` since 22.01.2025)
+//! - the weights, gated: <https://huggingface.co/stabilityai/stable-fast-3d>
+//! at `REVISION` (tree listing: sizes and object ids)
+//! - the DINOv2 config, Apache 2.0, not gated:
+//! <https://huggingface.co/facebook/dinov2-large> at `DINO_REVISION`
+
+use crate::commands::mesh3d::{self, Engine};
+use crate::commands::voice_loop::manifest::RemoteFile;
+use crate::commands::{internal, not_found};
+use crate::install_state::InstallSlot;
+use crate::os_error;
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use std::path::{Path, PathBuf};
+
+// ── The pins ──────────────────────────────────────────────────────────
+
+pub(crate) const MODEL_ID: &str = "sf3d";
+pub(crate) const MODEL_NAME: &str = "Stable Fast 3D";
+
+/// The head of `main` on 13.11.2026, last changed 22.01.2025.
+pub(crate) const SOURCE_COMMIT: &str = "ff21fc491b4dc5314bf6734c7c0dabd86b5f5bb2";
+const SOURCE: &str = "https://github.com/Stability-AI/stable-fast-3d/archive";
+const SOURCE_BYTES: u64 = 25_450_752;
+const SOURCE_SHA256: &str = "3674ecf09167764be5471a803cf716b390feccbedc389d8c37aa710b754e2808";
+
+pub(crate) const REPO: &str = "stabilityai/stable-fast-3d";
+pub(crate) const REVISION: &str = "f0c9a8ffd62cb1bbc8a7a53c9f87a0be1b6be778";
+const CONFIG_BYTES: u64 = 2405;
+/// The git blob id of `config.yaml` at `REVISION`.
+const CONFIG_BLOB: &str = "4a44aec5e6af76975afcaedae7e888b96412c832";
+const WEIGHTS_FILE_BYTES: u64 = 4_024_289_892;
+/// The git blob id of the LFS pointer of `model.safetensors` at `REVISION`.
+const WEIGHTS_POINTER_BLOB: &str = "d4d83a9c711ace2e5adccf27c7c5e386725acfe2";
+
+const DINO_REPO: &str = "facebook/dinov2-large";
+const DINO_REVISION: &str = "47b73eefe95e8d44ec3623f8890bd894b6ea2d6c";
+const DINO_CONFIG_BYTES: u64 = 549;
+const DINO_CONFIG_SHA256: &str = "12df51c069a2dc1305e34ba71ef58bc2407ea553b75f4722a1715c1bce3bbed0";
+
+pub(crate) const WEIGHTS_BYTES: u64 = WEIGHTS_FILE_BYTES + CONFIG_BYTES + DINO_CONFIG_BYTES;
+
+/// Every package the runner pulls in, resolved by pip for Python 3.12 on
+/// Apple Silicon as wheels only (13.11.2026), 39 from PyPI. What TripoSR's
+/// venv has stands at its versions, so pip's cache serves both. New against
+/// it: torchvision (the build of torch 2.10.0), open-clip-torch 2.24.0 (the
+/// version SF3D names) with ftfy, protobuf, sentencepiece, timm and wcwidth,
+/// and jaxtyping with wadler-lindig. Releases younger than a month stand one
+/// or two back (sentencepiece, timm, wcwidth, wadler-lindig, protobuf).
+/// scipy is there for trimesh's normals in the GLB export.
+pub(crate) const PINNED: [&str; 39] = [
+ "certifi==2026.1.4", "charset-normalizer==3.4.4", "einops==0.8.2", "filelock==3.20.3", "fsspec==2026.1.0",
+ "ftfy==6.3.1", "hf-xet==1.2.0", "huggingface-hub==0.36.0", "idna==3.11", "jaxtyping==0.3.11",
+ "jinja2==3.1.6", "markupsafe==3.0.3", "mpmath==1.3.0", "networkx==3.6.1", "numpy==2.3.5",
+ "omegaconf==2.4.0", "open-clip-torch==2.24.0", "packaging==26.0", "pillow==12.1.0", "protobuf==7.36.1",
+ "pyyaml==6.0.3", "regex==2026.1.15", "requests==2.32.5", "safetensors==0.7.0", "scipy==1.17.0",
+ "sentencepiece==0.2.2", "setuptools==71.1.0", "sympy==1.14.0", "timm==1.0.29", "tokenizers==0.22.2",
+ "torch==2.10.0", "torchvision==0.25.0", "tqdm==4.67.1", "transformers==4.57.6", "trimesh==5.1.1",
+ "typing-extensions==4.15.0", "urllib3==2.6.3", "wadler-lindig==0.1.7", "wcwidth==0.8.5",
+];
+
+const MODULE: &str = "torch, torchvision, transformers, open_clip, jaxtyping, omegaconf, trimesh, texture_baker, uv_unwrapper";
+
+/// One wheel LU built: its file name, its bytes and their sha256.
+pub(crate) struct Wheel {
+ pub name: &'static str,
+ pub bytes: &'static [u8],
+ pub sha256: &'static str,
+}
+
+/// The two extensions, built by `scripts/build-sf3d-wheels.sh` on 13.11.2026.
+#[cfg(target_os = "macos")]
+pub(crate) const WHEELS: [Wheel; 2] = [
+ Wheel {
+ name: "texture_baker-0.0.1-cp312-cp312-macosx_14_0_arm64.whl",
+ bytes: include_bytes!("../../resources/mesh3d/wheels/texture_baker-0.0.1-cp312-cp312-macosx_14_0_arm64.whl"),
+ sha256: "b415a0b88f478755179d4a3e1637415af10e078fb5baf8457ec6abe0cdfc0529",
+ },
+ Wheel {
+ name: "uv_unwrapper-0.0.1-cp312-cp312-macosx_14_0_arm64.whl",
+ bytes: include_bytes!("../../resources/mesh3d/wheels/uv_unwrapper-0.0.1-cp312-cp312-macosx_14_0_arm64.whl"),
+ sha256: "8fd84a82fa22d8d72cd87196d123ec60afe25d8e83b6f349ec5befe796fdbf75",
+ },
+];
+
+/// Only a Mac carries the wheels; elsewhere the install is refused before.
+#[cfg(not(target_os = "macos"))]
+pub(crate) const WHEELS: [Wheel; 0] = [];
+
+/// The venv and the wheels on disk, with room for what pip unpacks.
+const ENGINE_INSTALL_BYTES: u64 = 2_000_000_000;
+
+/// Below this a run is refused. The README names about 6 GB of graphics
+/// memory and says MPS takes more than that; not measured yet on a Mac.
+pub(crate) const MIN_RAM_GB: u32 = 16;
+
+/// The texture side per step of Detail (`TEXTURES` of the runner).
+const DEFAULT_TEXTURE: u32 = 1024;
+const TEXTURES: [u32; 3] = [512, 1024, 2048];
+
+/// What the licence asks to be kept with the code that is passed on.
+pub(crate) const NOTICE: &str = "This Stability AI Model is licensed under the Stability AI Community License, Copyright © Stability AI Ltd. All Rights Reserved.\n";
+
+pub(crate) const RUNNER: &str = include_str!("../../resources/mesh3d/run_sf3d.py");
+
+// ── Where it lives ────────────────────────────────────────────────────
+
+/// A folder of its own beside TripoSR's, with the same layout inside
+/// (`venv`, `weights`, `work`, `downloads`), so `mesh3d.rs` runs it the same way.
+pub(crate) fn root() -> PathBuf {
+ crate::os_paths::data_dir().join("mesh3d-sf3d")
+}
+
+fn source_dir(root: &Path) -> PathBuf {
+ root.join("source").join(SOURCE_COMMIT)
+}
+
+fn wheels_dir(root: &Path) -> PathBuf {
+ root.join("wheels")
+}
+
+pub(crate) fn runner_file(root: &Path) -> PathBuf {
+ root.join("runner").join("run_sf3d.py")
+}
+
+// ── The engine ────────────────────────────────────────────────────────
+
+fn stamp() -> String {
+ let wheels: Vec<&str> = WHEELS.iter().map(|w| w.sha256).collect();
+ format!("{}\n{}", PINNED.join("\n"), wheels.join("\n"))
+}
+
+fn engine(root: &Path, wheels: &[PathBuf]) -> EngineSpec {
+ EngineSpec { stamp: stamp(), stamp_file: mesh3d::venv_dir(root).join(".lu-mesh3d-sf3d-engine"), wheels: wheels.to_vec() }
+}
+
+/// The parts of `Engine` that are owned, so it can be built on the fly.
+struct EngineSpec {
+ stamp: String,
+ stamp_file: PathBuf,
+ wheels: Vec<PathBuf>,
+}
+
+impl EngineSpec {
+ fn as_engine(&self) -> Engine<'_> {
+ Engine { pinned: &PINNED, wheels: &self.wheels, module: MODULE, stamp: self.stamp.clone(), stamp_file: self.stamp_file.clone() }
+ }
+}
+
+fn engine_ready_at(root: &Path) -> bool {
+ engine(root, &[]).as_engine().ready(&mesh3d::venv_dir(root))
+}
+
+/// Write the wheels of this build next to the venv and check them.
+fn write_wheels(root: &Path) -> Result<Vec<PathBuf>, String> {
+ let dir = wheels_dir(root);
+ std::fs::create_dir_all(&dir).map_err(|e| os_error::english(&e))?;
+ let mut paths = Vec::new();
+ for wheel in &WHEELS {
+ let path = dir.join(wheel.name);
+ std::fs::write(&path, wheel.bytes).map_err(|e| os_error::english(&e))?;
+ let actual = crate::commands::install::sha256_file(&path)?;
+ if !crate::commands::install::digest_matches(wheel.sha256, &actual) {
+ let _ = std::fs::remove_file(&path);
+ return Err(format!("The 3D engine part {} is damaged in this copy of LU. Install LU again.", wheel.name));
+ }
+ paths.push(path);
+ }
+ Ok(paths)
+}
+
+fn ensure_engine(slot: &InstallSlot, root: &Path) -> Result<String, String> {
+ let venv = mesh3d::venv_dir(root);
+ if engine_ready_at(root) {
+ return Ok(mesh3d::venv_python(&venv).to_string_lossy().to_string());
+ }
+ let wheels = write_wheels(root)?;
+ let spec = engine(root, &wheels);
+ mesh3d::ensure_engine_with(slot, None, &venv, &spec.as_engine())
+}
+
+// ── The source ────────────────────────────────────────────────────────
+
+fn source_remote() -> RemoteFile {
+ RemoteFile { url: format!("{SOURCE}/{SOURCE_COMMIT}.zip"), size: SOURCE_BYTES, sha256: SOURCE_SHA256.to_string() }
+}
+
+const SOURCE_MARKER: &str = ".lu-sf3d-source";
+
+fn source_ready_at(root: &Path) -> bool {
+ let dir = source_dir(root);
+ dir.join("sf3d").join("system.py").is_file()
+ && dir.join("load").join("tets").join("160_tets.npz").is_file()
+ && std::fs::read_to_string(dir.join(SOURCE_MARKER)).is_ok_and(|s| s.trim() == SOURCE_SHA256)
+}
+
+/// What is kept of the archive: the Python files of `sf3d/`, the grids of
+/// `load/tets/`, and the licence. Not the extensions' sources (LU ships
+/// them built), not the demo, the Gradio app, the ComfyUI node or `run.py`.
+fn kept_entry(name: &str) -> Option<PathBuf> {
+ let top = format!("stable-fast-3d-{SOURCE_COMMIT}/");
+ let rest = name.strip_prefix(&top)?;
+ let path = Path::new(rest);
+ if path.components().any(|c| !matches!(c, std::path::Component::Normal(_))) {
+ return None;
+ }
+ let keep = rest == "LICENSE.md"
+ || (rest.starts_with("sf3d/") && rest.ends_with(".py"))
+ || (rest.starts_with("load/tets/") && rest.ends_with(".npz"));
+ keep.then(|| path.to_path_buf())
+}
+
+fn unpack_source(archive: &Path, root: &Path) -> Result<(), String> {
+ let target = source_dir(root);
+ let staging = target.with_extension("unpack");
+ let _ = std::fs::remove_dir_all(&staging);
+ std::fs::create_dir_all(&staging).map_err(|e| os_error::english(&e))?;
+ let file = std::fs::File::open(archive).map_err(|e| os_error::english(&e))?;
+ let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("The Stable Fast 3D archive could not be read ({e})."))?;
+ for i in 0..zip.len() {
+ let mut entry = zip.by_index(i).map_err(|e| format!("The Stable Fast 3D archive could not be read ({e})."))?;
+ if !entry.is_file() {
+ continue;
+ }
+ let name = entry.name().map(|n| n.to_string()).unwrap_or_default();
+ let Some(rel) = kept_entry(&name) else { continue };
+ let out = staging.join(&rel);
+ if let Some(parent) = out.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| os_error::english(&e))?;
+ }
+ let mut dest = std::fs::File::create(&out).map_err(|e| os_error::english(&e))?;
+ std::io::copy(&mut entry, &mut dest).map_err(|e| os_error::english(&e))?;
+ }
+ if !staging.join("sf3d").join("system.py").is_file() || !staging.join("LICENSE.md").is_file() {
+ let _ = std::fs::remove_dir_all(&staging);
+ return Err("The Stable Fast 3D archive is not complete. Start the download again.".to_string());
+ }
+ std::fs::write(staging.join("NOTICE"), NOTICE).map_err(|e| os_error::english(&e))?;
+ std::fs::write(staging.join(SOURCE_MARKER), SOURCE_SHA256).map_err(|e| os_error::english(&e))?;
+ let _ = std::fs::remove_dir_all(&target);
+ std::fs::rename(&staging, &target).map_err(|e| os_error::english(&e))?;
+ Ok(())
+}
+
+fn install_source(slot: &InstallSlot, root: &Path) -> Result<(), String> {
+ if source_ready_at(root) {
+ return Ok(());
+ }
+ slot.log(format!("downloading the Stable Fast 3D source at {}", &SOURCE_COMMIT[..7]));
+ let archive = mesh3d::downloads_dir(root).join(format!("stable-fast-3d-{SOURCE_COMMIT}.zip"));
+ mesh3d::fetch_files_as(slot, &[(source_remote(), archive.clone())], "the Stable Fast 3D source", None)?;
+ unpack_source(&archive, root)?;
+ let _ = std::fs::remove_file(&archive);
+ Ok(())
+}
+
+// ── The weights ───────────────────────────────────────────────────────
+
+/// The id git gives `content` as a blob: sha1 of `blob <len>\0<content>`.
+pub(crate) fn git_blob_id(content: &[u8]) -> String {
+ use sha1::{Digest, Sha1};
+ let mut hasher = Sha1::new();
+ hasher.update(format!("blob {}\0", content.len()).as_bytes());
+ hasher.update(content);
+ hasher.finalize().iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// The LFS pointer git keeps for a file of `size` bytes with `sha256`.
+fn lfs_pointer(sha256: &str, size: u64) -> String {
+ format!("version https://git-lfs.github.com/spec/v1\noid sha256:{sha256}\nsize {size}\n")
+}
+
+/// Whether `sha256` is the digest the pinned pointer names.
+pub(crate) fn weights_digest_is_pinned(sha256: &str) -> bool {
+ sha256.len() == 64
+ && sha256.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
+ && git_blob_id(lfs_pointer(sha256, WEIGHTS_FILE_BYTES).as_bytes()) == WEIGHTS_POINTER_BLOB
+}
+
+/// `config.yaml` is this revision's when its size and blob id match.
+pub(crate) fn config_is_pinned(content: &[u8]) -> bool {
+ content.len() as u64 == CONFIG_BYTES && git_blob_id(content) == CONFIG_BLOB
+}
+
+#[derive(Deserialize)]
+struct TreeEntry {
+ path: String,
+ size: u64,
+ #[serde(default)]
+ lfs: Option<TreeLfs>,
+}
+
+#[derive(Deserialize)]
+struct TreeLfs {
+ oid: String,
+}
+
+/// The sha256 of `model.safetensors` out of the hub's tree listing at the
+/// pinned revision, accepted only when it is the one the pointer names.
+pub(crate) fn weights_digest_from_tree(listing: &str) -> Result<String, String> {
+ let entries: Vec<TreeEntry> =
+ serde_json::from_str(listing).map_err(|_| "Hugging Face sent an answer this version of LU cannot read. Try again later.".to_string())?;
+ let entry = entries
+ .iter()
+ .find(|e| e.path == "model.safetensors" && e.size == WEIGHTS_FILE_BYTES)
+ .ok_or("The Stable Fast 3D files on Hugging Face are not the ones this version of LU knows.")?;
+ let oid = entry.lfs.as_ref().map(|l| l.oid.as_str()).unwrap_or("");
+ if weights_digest_is_pinned(oid) {
+ return Ok(oid.to_string());
+ }
+ // The hub hides the digest of a gated file from an account that has not
+ // accepted the licence.
+ if oid.contains('*') || oid.is_empty() {
+ return Err(crate::commands::mlx::hub_denied_message(403, true).unwrap_or_default().to_string());
+ }
+ Err("The Stable Fast 3D weights on Hugging Face do not match the ones this version of LU knows. Nothing was downloaded.".to_string())
+}
+
+/// GET a small hub file with the user's token, into memory.
+fn hub_get(url: &str, token: &str) -> Result<Vec<u8>, String> {
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .map_err(|e| format!("The download could not be started: {}.", os_error::io_english(&e)))?;
+ let client = crate::commands::voice_loop::fetch::http_client()?;
+ runtime.block_on(async {
+ let answer = client
+ .get(url)
+ .bearer_auth(token)
+ .send()
+ .await
+ .map_err(|_| "Hugging Face could not be reached. Check your internet connection and start the setup again.".to_string())?;
+ let status = answer.status().as_u16();
+ if let Some(why) = crate::commands::mlx::hub_denied_message(status, true) {
+ return Err(why.to_string());
+ }
+ if !answer.status().is_success() {
+ return Err(format!("Hugging Face refused the download of Stable Fast 3D (HTTP {status}). Try again later."));
+ }
+ answer.bytes().await.map(|b| b.to_vec()).map_err(|_| "The download from Hugging Face was interrupted. Start the setup again.".to_string())
+ })
+}
+
+fn hub(repo: &str, revision: &str, file: &str) -> String {
+ format!("https://huggingface.co/{repo}/resolve/{revision}/{file}")
+}
+
+const MANIFEST: &str = ".lu-mesh3d-sf3d-weights.json";
+
+#[derive(Serialize, Deserialize, Debug, PartialEq)]
+struct Manifest {
+ revision: String,
+ dino_revision: String,
+}
+
+fn this_manifest() -> Manifest {
+ Manifest { revision: REVISION.to_string(), dino_revision: DINO_REVISION.to_string() }
+}
+
+const WEIGHT_PATHS: [(&str, u64); 3] =
+ [("model.safetensors", WEIGHTS_FILE_BYTES), ("config.yaml", CONFIG_BYTES), ("dinov2-large/config.json", DINO_CONFIG_BYTES)];
+
+fn weights_complete(dir: &Path) -> bool {
+ let manifest = std::fs::read_to_string(dir.join(MANIFEST)).ok().and_then(|s| serde_json::from_str::<Manifest>(&s).ok());
+ manifest.is_some_and(|m| m == this_manifest())
+ && WEIGHT_PATHS.iter().all(|(path, size)| std::fs::metadata(dir.join(path)).map(|m| m.is_file() && m.len() == *size).unwrap_or(false))
+}
+
+pub(crate) fn installed_at(root: &Path) -> bool {
+ engine_ready_at(root) && source_ready_at(root) && weights_complete(&mesh3d::weights_dir(root))
+}
+
+fn bytes_to_fetch(root: &Path) -> u64 {
+ let dir = mesh3d::weights_dir(root);
+ let weights = if weights_complete(&dir) { 0 } else { WEIGHTS_BYTES.saturating_sub(crate::install_state::dir_size(&dir)) };
+ let source = if source_ready_at(root) { 0 } else { SOURCE_BYTES };
+ weights + source + if engine_ready_at(root) { 0 } else { ENGINE_INSTALL_BYTES }
+}
+
+fn install_weights(slot: &InstallSlot, root: &Path, token: &str) -> Result<(), String> {
+ let dir = mesh3d::weights_dir(root);
+ if weights_complete(&dir) {
+ slot.log("the weights of Stable Fast 3D are on disk already");
+ return Ok(());
+ }
+ std::fs::create_dir_all(&dir).map_err(|e| os_error::english(&e))?;
+ let _ = std::fs::remove_file(dir.join(MANIFEST));
+
+ slot.log(format!("checking {REPO} at {}", &REVISION[..7]));
+ let listing = hub_get(&format!("https://huggingface.co/api/models/{REPO}/tree/{REVISION}"), token)?;
+ let sha256 = weights_digest_from_tree(&String::from_utf8_lossy(&listing))?;
+ let config = hub_get(&hub(REPO, REVISION, "config.yaml"), token)?;
+ if !config_is_pinned(&config) {
+ return Err("The Stable Fast 3D settings on Hugging Face do not match the ones this version of LU knows. Nothing was downloaded.".to_string());
+ }
+ std::fs::write(dir.join("config.yaml"), &config).map_err(|e| os_error::english(&e))?;
+
+ slot.log(format!("downloading {REPO} ({})", crate::commands::mlx_snapshot::human_bytes(WEIGHTS_BYTES)));
+ let files = [
+ (RemoteFile { url: hub(REPO, REVISION, "model.safetensors"), size: WEIGHTS_FILE_BYTES, sha256 }, dir.join("model.safetensors")),
+ (
+ RemoteFile { url: hub(DINO_REPO, DINO_REVISION, "config.json"), size: DINO_CONFIG_BYTES, sha256: DINO_CONFIG_SHA256.to_string() },
+ dir.join("dinov2-large").join("config.json"),
+ ),
+ ];
+ mesh3d::fetch_files_as(slot, &files, "the Stable Fast 3D model", Some(token))?;
+ let record = serde_json::to_string(&this_manifest()).unwrap_or_default();
+ std::fs::write(dir.join(MANIFEST), record).map_err(|e| os_error::english(&e))?;
+ Ok(())
+}
+
+fn self_test(slot: &InstallSlot, python: &str, root: &Path) -> Result<(), String> {
+ let runner = mesh3d::write_runner_at(&runner_file(root), RUNNER)?;
+ let work = mesh3d::work_dir(root);
+ std::fs::create_dir_all(&work).map_err(|e| os_error::english(&e))?;
+ let out = work.join("selftest.glb");
+ let mut cmd = crate::python::python_command(python);
+ cmd.arg("-I").arg(&runner).arg("--lu-mesh3d-selftest").arg(&out).arg("--source").arg(source_dir(root));
+ cmd.current_dir(&work).env("HF_HUB_OFFLINE", "1").env("PYTORCH_ENABLE_MPS_FALLBACK", "1");
+ crate::commands::video::run_streamed(slot, &mut cmd).map_err(|e| format!("The 3D engine did not pass its self test. {e}"))?;
+ let _ = std::fs::remove_file(&out);
+ Ok(())
+}
+
+/// The whole install on the slot: the token first (nothing is fetched
+/// without it), then engine, source, self test and weights.
+pub(crate) fn install(slot: &InstallSlot, root: &Path, token: &str) -> Result<String, String> {
+ let python = ensure_engine(slot, root)?;
+ install_source(slot, root)?;
+ self_test(slot, &python, root)?;
+ install_weights(slot, root, token)?;
+ if !installed_at(root) {
+ return Err("The download finished, but the model is not complete on disk. Start it again.".to_string());
+ }
+ Ok(format!("{MODEL_ID} installed"))
+}
+
+/// What the install still has to write, and the note for the free-space check.
+pub(crate) fn install_need(root: &Path) -> (u64, &'static str) {
+ (bytes_to_fetch(root), if engine_ready_at(root) { "" } else { "incl. its own 3D engine" })
+}
+
+pub(crate) fn delete_at(root: &Path) -> Result<(), String> {
+ let dir = mesh3d::weights_dir(root);
+ if !dir.is_dir() {
+ return Err(not_found(format!("{MODEL_ID} is not installed")));
+ }
+ std::fs::remove_dir_all(&dir).map_err(|e| internal(format!("delete {MODEL_ID}: {}", os_error::english(&e))))?;
+ let _ = std::fs::remove_dir_all(mesh3d::downloads_dir(root));
+ Ok(())
+}
+
+// ── The card and the run ──────────────────────────────────────────────
+
+const DESCRIPTION: &str = "Turns one picture of an object into a 3D model with a painted texture, on this Mac. The download is the official Stable Fast 3D release.";
+
+/// The short, human words of the licence, shown before the setup.
+pub(crate) const LICENSE_TEXT: &str = "Stable Fast 3D comes under the Stability AI Community License. It is free for personal use, research, and for people and companies that earn less than one million dollars a year; businesses register with Stability AI first. Sexual content is not allowed under its use policy. To download it, accept the licence on the model's Hugging Face page and add your Hugging Face token in Settings. Powered by Stability AI.";
+
+pub(crate) const LICENSE_URL: &str = "https://huggingface.co/stabilityai/stable-fast-3d";
+
+pub(crate) fn model_json(installed: bool, has_token: bool) -> Value {
+ json!({
+ "id": MODEL_ID,
+ "name": MODEL_NAME,
+ "repo": REPO,
+ "sizeGB": ((WEIGHTS_BYTES as f64) / 1e8).round() / 10.0,
+ "minRamGB": MIN_RAM_GB,
+ "unfiltered": false,
+ "description": DESCRIPTION,
+ "installed": installed,
+ "gated": true,
+ "hasToken": has_token,
+ "license": "Stability AI Community License",
+ "licenseText": LICENSE_TEXT,
+ "licenseUrl": LICENSE_URL,
+ "engineCommit": SOURCE_COMMIT,
+ })
+}
+
+/// The texture side a run uses: one of the three the runner knows.
+pub(crate) fn texture_for(asked: Option<u32>) -> u32 {
+ asked.filter(|t| TEXTURES.contains(t)).unwrap_or(DEFAULT_TEXTURE)
+}
+
+/// What the runner reads, one file per run.
+pub(crate) fn job_json(root: &Path, image: &Path, texture: u32, job_dir: &Path, output: &Path) -> Value {
+ let weights = mesh3d::weights_dir(root);
+ json!({
+ "image": image,
+ "source": source_dir(root),
+ "weights_dir": weights,
+ "dino_config": weights.join("dinov2-large").join("config.json"),
+ "texture": texture,
+ "foreground_ratio": 0.85,
+ "device": "auto",
+ "work": job_dir,
+ "output": output,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_source_and_the_weights_are_pinned() {
+ let hex = |s: &str, n: usize| s.len() == n && s.chars().all(|c| c.is_ascii_hexdigit());
+ assert!(hex(SOURCE_COMMIT, 40) && hex(REVISION, 40) && hex(DINO_REVISION, 40) && hex(CONFIG_BLOB, 40) && hex(WEIGHTS_POINTER_BLOB, 40));
+ assert!(hex(SOURCE_SHA256, 64) && hex(DINO_CONFIG_SHA256, 64));
+ assert_eq!(source_remote().url, format!("https://github.com/Stability-AI/stable-fast-3d/archive/{SOURCE_COMMIT}.zip"));
+ assert_eq!(model_json(false, false)["sizeGB"], 4.0);
+ assert_eq!(model_json(false, false)["unfiltered"], false);
+ for url in [hub(REPO, REVISION, "model.safetensors"), hub(DINO_REPO, DINO_REVISION, "config.json")] {
+ assert!(url.starts_with("https://huggingface.co/") && !url.contains("/main/"), "{url}");
+ }
+ }
+
+ #[test]
+ fn every_package_is_pinned_and_shared_ones_match_triposr() {
+ let mut names: Vec<&str> = PINNED.iter().map(|s| s.split("==").next().unwrap()).collect();
+ for spec in &PINNED {
+ let (name, version) = spec.split_once("==").unwrap_or_else(|| panic!("{spec} is not pinned"));
+ assert!(!name.is_empty() && !version.contains(['<', '>', '*', ' ']), "{spec}");
+ }
+ let sorted = names.clone();
+ names.sort();
+ assert_eq!(names, sorted, "kept in order");
+ names.dedup();
+ assert_eq!(names.len(), PINNED.len());
+ for shared in mesh3d::PINNED_FOR_TESTS {
+ let name = shared.split("==").next().unwrap();
+ if let Some(ours) = PINNED.iter().find(|p| p.split("==").next() == Some(name)) {
+ assert_eq!(ours, shared, "the same wheel as TripoSR");
+ }
+ }
+ for never in ["rembg", "gpytoolbox", "pynanoinstantmeshes", "onnxruntime", "gradio", "texture-baker", "uv-unwrapper"] {
+ assert!(!PINNED.iter().any(|p| p.starts_with(&format!("{never}=="))), "{never}");
+ }
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn the_wheels_in_the_binary_are_the_ones_pinned() {
+ use sha2::{Digest, Sha256};
+ for wheel in &WHEELS {
+ let digest: String = Sha256::digest(wheel.bytes).iter().map(|b| format!("{b:02x}")).collect();
+ assert_eq!(digest, wheel.sha256, "{}", wheel.name);
+ assert!(wheel.name.ends_with("-cp312-cp312-macosx_14_0_arm64.whl"), "{}", wheel.name);
+ assert_eq!(&wheel.bytes[..2], b"PK", "a wheel is a zip");
+ }
+ let tmp = tempfile::tempdir().unwrap();
+ let written = write_wheels(tmp.path()).unwrap();
+ assert_eq!(written.len(), 2);
+ assert!(engine(tmp.path(), &written).as_engine().pip_args().iter().any(|a| a.ends_with("texture_baker-0.0.1-cp312-cp312-macosx_14_0_arm64.whl")));
+ }
+
+ #[test]
+ fn a_git_blob_id_is_the_one_git_computes() {
+ // `printf 'hello\n' | git hash-object --stdin`
+ assert_eq!(git_blob_id(b"hello\n"), "ce013625030ba8dba906f756967f9e9ca394464a");
+ assert_eq!(git_blob_id(b""), "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391");
+ // The pointer of TripoSR's `model.ckpt`, whose digest the hub shows to
+ // everyone: its rebuilt pointer has the object id of the tree listing.
+ let pointer = lfs_pointer("429e2c6b22a0923967459de24d67f05962b235f79cde6b032aa7ed2ffcd970ee", 1_677_246_742);
+ assert_eq!(git_blob_id(pointer.as_bytes()), "f78322668f0723c948059fe36edd9d1d815b7071");
+ }
+
+ #[test]
+ fn only_the_digest_the_pointer_names_is_taken() {
+ assert!(!weights_digest_is_pinned(&"0".repeat(64)));
+ assert!(!weights_digest_is_pinned("*".repeat(64).as_str()));
+ assert!(!weights_digest_is_pinned("abc"));
+ let masked = format!("[{{\"type\":\"file\",\"path\":\"model.safetensors\",\"size\":{WEIGHTS_FILE_BYTES},\"lfs\":{{\"oid\":\"{}\"}}}}]", "*".repeat(64));
+ assert!(weights_digest_from_tree(&masked).unwrap_err().contains("accept its terms"), "a gated answer reads as a licence not yet accepted");
+ let wrong = format!("[{{\"type\":\"file\",\"path\":\"model.safetensors\",\"size\":{WEIGHTS_FILE_BYTES},\"lfs\":{{\"oid\":\"{}\"}}}}]", "a".repeat(64));
+ assert!(weights_digest_from_tree(&wrong).unwrap_err().contains("do not match"));
+ let other_size = "[{\"type\":\"file\",\"path\":\"model.safetensors\",\"size\":5,\"lfs\":{\"oid\":\"x\"}}]";
+ assert!(weights_digest_from_tree(other_size).unwrap_err().contains("not the ones"));
+ assert!(weights_digest_from_tree("<html>").is_err());
+ assert!(!config_is_pinned(b"cond_image_size: 512\n"));
+ }
+
+ #[test]
+ fn only_the_package_the_tets_and_the_licence_are_taken_from_the_archive() {
+ let top = format!("stable-fast-3d-{SOURCE_COMMIT}/");
+ for (name, kept) in [
+ ("sf3d/system.py", true),
+ ("sf3d/models/tokenizers/dinov2.py", true),
+ ("load/tets/160_tets.npz", true),
+ ("LICENSE.md", true),
+ ("run.py", false),
+ ("gradio_app.py", false),
+ ("texture_baker/setup.py", false),
+ ("uv_unwrapper/uv_unwrapper/csrc/bvh.cpp", false),
+ ("comfyui/nodes.py", false),
+ ("sf3d/../../x.py", false),
+ ("demo_files/x.png", false),
+ ] {
+ assert_eq!(kept_entry(&format!("{top}{name}")).is_some(), kept, "{name}");
+ }
+ assert_eq!(kept_entry("stable-fast-3d-main/sf3d/system.py"), None);
+ }
+
+ #[test]
+ fn an_archive_is_unpacked_with_the_notice_or_not_at_all() {
+ use std::io::Write;
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path();
+ let zip_path = root.join("a.zip");
+ let write = |names: &[&str]| {
+ let mut zip = zip::ZipWriter::new(std::fs::File::create(&zip_path).unwrap());
+ for name in names {
+ zip.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
+ zip.write_all(b"x").unwrap();
+ }
+ zip.finish().unwrap();
+ };
+ let top = format!("stable-fast-3d-{SOURCE_COMMIT}");
+ write(&[&format!("{top}/sf3d/system.py")]);
+ assert!(unpack_source(&zip_path, root).is_err(), "no licence, no source");
+ write(&[&format!("{top}/sf3d/system.py"), &format!("{top}/LICENSE.md"), &format!("{top}/load/tets/160_tets.npz"), &format!("{top}/run.py")]);
+ unpack_source(&zip_path, root).unwrap();
+ assert!(source_ready_at(root));
+ assert_eq!(std::fs::read_to_string(source_dir(root).join("NOTICE")).unwrap(), NOTICE);
+ assert!(!source_dir(root).join("run.py").exists());
+ }
+
+ #[test]
+ fn installed_is_engine_source_and_weights_and_remove_takes_the_weights() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path();
+ assert!(!installed_at(root));
+ assert_eq!(bytes_to_fetch(root), WEIGHTS_BYTES + SOURCE_BYTES + ENGINE_INSTALL_BYTES);
+ let dir = mesh3d::weights_dir(root);
+ for (path, size) in WEIGHT_PATHS {
+ crate::test_support::sized_file(&dir.join(path), size);
+ }
+ assert!(!weights_complete(&dir), "no manifest, no model");
+ std::fs::write(dir.join(MANIFEST), serde_json::to_string(&this_manifest()).unwrap()).unwrap();
+ assert!(weights_complete(&dir));
+ let venv = mesh3d::venv_dir(root);
+ crate::test_support::sized_file(&mesh3d::venv_python(&venv), 1);
+ std::fs::write(venv.join(".lu-mesh3d-sf3d-engine"), stamp()).unwrap();
+ assert!(!installed_at(root), "no source");
+ for f in ["sf3d/system.py", "load/tets/160_tets.npz"] {
+ crate::test_support::sized_file(&source_dir(root).join(f), 3);
+ }
+ std::fs::write(source_dir(root).join(SOURCE_MARKER), SOURCE_SHA256).unwrap();
+ assert!(installed_at(root));
+ assert_eq!(bytes_to_fetch(root), 0);
+ delete_at(root).unwrap();
+ assert!(!installed_at(root) && engine_ready_at(root) && source_ready_at(root));
+ }
+
+ #[test]
+ fn the_job_carries_what_the_runner_reads() {
+ let job = job_json(Path::new("/d/mesh3d-sf3d"), Path::new("/s/a.png"), 1024, Path::new("/d/w/j"), Path::new("/c/3d/r.glb"));
+ for key in ["image", "source", "weights_dir", "dino_config", "texture", "foreground_ratio", "work", "output"] {
+ assert!(RUNNER.contains(&format!("job[\"{key}\"]")), "the runner does not read {key}");
+ assert!(!job[key].is_null(), "{key}");
+ }
+ assert_eq!(texture_for(None), 1024);
+ assert_eq!(texture_for(Some(2048)), 2048);
+ assert_eq!(texture_for(Some(4096)), 1024, "only what the runner offers");
+ }
+
+ #[test]
+ fn the_runner_replaces_what_a_mac_cannot_install_and_stays_offline() {
+ for needed in [
+ "sys.modules[name] = refusing_module",
+ "\"rembg\"",
+ "\"gpytoolbox\"",
+ "\"pynanoinstantmeshes\"",
+ "kwargs[\"pretrained\"] = None",
+ "Dinov2Config.from_json_file",
+ "unwrap_on_the_cpu()",
+ "remesh=\"none\"",
+ "PREFIX = \"LU-MESH3D \"",
+ "JOB_FLAG = \"--lu-mesh3d-job\"",
+ ] {
+ assert!(RUNNER.contains(needed), "{needed}");
+ }
+ for never in ["rembg.new_session()", "hf_hub_download(", "snapshot_download", "requests.get", "urllib", "torch.load("] {
+ assert!(!RUNNER.contains(never), "{never}");
+ }
+ assert!(RUNNER.contains(&format!("DINO_REPO = \"{DINO_REPO}\"")));
+ }
+
+ #[test]
+ fn the_licence_is_said_before_the_setup_in_plain_words() {
+ let card = model_json(false, false);
+ assert_eq!(card["gated"], true);
+ let text = card["licenseText"].as_str().unwrap();
+ for needed in ["Stability AI Community License", "one million dollars", "Hugging Face token", "Powered by Stability AI"] {
+ assert!(text.contains(needed), "{needed}");
+ }
+ assert!(!text.contains('$'), "no money signs in the tree");
+ assert!(NOTICE.starts_with("This Stability AI Model is licensed under the Stability AI Community License"));
+ }
+}
diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rs
index 386f98da..4be7abf7 100644
--- a/src-tauri/src/commands/mlx.rs
+++ b/src-tauri/src/commands/mlx.rs
@@ -692,7 +692,7 @@ const HF_TOKEN_NO_ACCESS: &str = "Your Hugging Face token has no access to this
/// its built-in file patterns, the download then failed on the same refusal,
/// and the user read "The installer stopped with exit code 1" with the word
/// "gated" only in the log (Fehlerkontrolle Mac, 08.10.2026, Fund 9).
-fn hub_denied_message(status: u16, has_token: bool) -> Option<&'static str> {
+pub(crate) fn hub_denied_message(status: u16, has_token: bool) -> Option<&'static str> {
match status {
401 | 403 if has_token => Some(HF_TOKEN_NO_ACCESS),
401 | 403 => Some(HF_TOKEN_NEEDED),
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index 518b48fe..b612f4d8 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -60,6 +60,8 @@ pub mod logging;
pub mod media_cmds;
// The local 3D engine of the Mac (TripoSR), see mesh3d.rs.
pub mod mesh3d;
+// Stable Fast 3D, the second model of the 3D lane, see mesh3d_sf3d.rs.
+pub mod mesh3d_sf3d;
pub mod mlx;
pub mod mlx_cutout;
pub mod mlx_loras;
diff --git a/src-tauri/src/commands/real_run_mac.rs b/src-tauri/src/commands/real_run_mac.rs
index c4485ce9..485db44d 100644
--- a/src-tauri/src/commands/real_run_mac.rs
+++ b/src-tauri/src/commands/real_run_mac.rs
@@ -43,7 +43,9 @@
//! `LU_REAL_CANCEL_AFTER` (seconds into an install or a video),
//! `LU_REAL_CANCEL_AT_STEP` (an image), `LU_REAL_NAME` (the name the result is
//! kept under), `LU_REAL_OUT` (the folder for results and the record),
-//! `LU_REAL_ANY_POWER` (`1`: do not wait for mains) and `LU_REAL_RUN_HOME`
+//! `LU_REAL_ANY_POWER` (`1`: do not wait for mains), `LU_REAL_3D_MODEL` (`triposr` or
+//! `sf3d`, the 3D model of `mesh_run` and `mesh_text`), `LU_REAL_TEXTURE` (the
+//! texture side of Stable Fast 3D) and `LU_REAL_RUN_HOME`
//! (an absolute folder the run takes as the app's data, config and cache
//! folders, so the real app's folders on this Mac stay untouched; the 3D
//! runs use it, see `mesh_install`).
@@ -397,17 +399,48 @@ fn music_lane() -> Lane {
}
}
-/// The 3D lane installs its engine, its source and its weights on one slot.
+/// The 3D lane installs its engine, its source and its weights on one slot,
+/// for the model `LU_REAL_MODEL` names (`triposr` or `sf3d`).
fn mesh_lane() -> Lane {
Lane {
name: "mesh3d",
install: mesh3d::mesh3d_install,
status: mesh3d::mesh3d_install_status,
cancel: mesh3d::mesh3d_cancel_install,
- weights: crate::os_paths::data_dir().join("mesh3d").join("weights"),
+ weights: mesh_root().join("weights"),
}
}
+/// The folder of the 3D model `LU_REAL_MODEL` names.
+fn mesh_root() -> PathBuf {
+ if mesh_model() == super::mesh3d_sf3d::MODEL_ID {
+ super::mesh3d_sf3d::root()
+ } else {
+ mesh3d::real_run_root()
+ }
+}
+
+/// `LU_REAL_3D_MODEL`, else `LU_REAL_MODEL` when it names a 3D model (the
+/// install), else TripoSR. `mesh_text` uses `LU_REAL_MODEL` for its image model.
+fn mesh_model() -> String {
+ let three_d = |m: &String| m == mesh3d::MODEL_ID || m == super::mesh3d_sf3d::MODEL_ID;
+ var("LU_REAL_3D_MODEL").or_else(|| var("LU_REAL_MODEL").filter(three_d)).unwrap_or_else(|| mesh3d::MODEL_ID.to_string())
+}
+
+/// A gated model downloads with a Hugging Face token. The real run takes the
+/// one `huggingface-cli login` keeps (`~/.cache/huggingface/token`) and no
+/// other: never the app's keychain entry.
+fn hub_token_for_the_run() -> bool {
+ let Some(home) = std::env::var_os("HOME") else { return false };
+ let file = PathBuf::from(home).join(".cache").join("huggingface").join("token");
+ let Ok(token) = std::fs::read_to_string(&file) else {
+ println!("no Hugging Face token in {}", file.display());
+ return false;
+ };
+ let _ = mlx::set_hf_token(state(), &json!({ "token": token.trim() }));
+ true
+}
+
fn video_lane() -> Lane {
Lane {
name: "video",
@@ -1278,8 +1311,11 @@ fn own_folder_only() -> bool {
#[ignore = "the real run: needs LU_REAL_RUN=1"]
fn mesh_install() {
if on() && own_folder_only() {
+ if mesh_model() == super::mesh3d_sf3d::MODEL_ID {
+ assert!(hub_token_for_the_run(), "Stable Fast 3D needs a Hugging Face token");
+ }
install_model(mesh_lane());
- let root = mesh3d::real_run_root();
+ let root = mesh_root();
record("mesh3d folders", json!({ "venvGB": dir_gb(&root.join("venv")), "weightsGB": dir_gb(&root.join("weights")), "sourceGB": dir_gb(&root.join("source")) }));
}
}
@@ -1308,13 +1344,19 @@ fn mesh_run() {
fn mesh_from_picture(state: &'static AppState, picture: &str, name: &str, before: Value) {
let none = json!({});
let status = mesh3d::mesh3d_status(state, &none).expect("mlx_mesh3d_status");
- assert_eq!(status["installed"], true, "the 3D model is not installed: {status}");
+ let model = mesh_model();
+ let card = status["models"].as_array().and_then(|all| all.iter().find(|m| m["id"] == model.as_str())).cloned().unwrap_or(Value::Null);
+ assert_eq!(card["installed"], true, "the 3D model {model} is not installed: {status}");
let staged = stage(picture);
let run = format!("real-run-{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0));
- let mut args = json!({ "run": run, "imagePath": staged });
+ let mut args = json!({ "run": run, "imagePath": staged, "model": model });
if let Some(resolution) = number::<u32>("LU_REAL_RESOLUTION") {
args["resolution"] = json!(resolution);
}
+ // Stable Fast 3D's texture side (512, 1024, 2048).
+ if let Some(texture) = number::<u32>("LU_REAL_TEXTURE") {
+ args["texture"] = json!(texture);
+ }
println!("mlx_mesh3d_generate {args}");
let available_before = available_memory_gb();
let started = Instant::now();
diff --git a/src-tauri/src/commands/voice_loop/fetch.rs b/src-tauri/src/commands/voice_loop/fetch.rs
index 4bd94f8b..d4b07a30 100644
--- a/src-tauri/src/commands/voice_loop/fetch.rs
+++ b/src-tauri/src/commands/voice_loop/fetch.rs
@@ -114,10 +114,25 @@ pub async fn fetch_verified(
cancel: &AtomicBool,
on_progress: &mut (dyn FnMut(u64) + Send),
) -> Result<(), FetchError> {
+ fetch_verified_as(client, remote, dest, None, cancel, on_progress).await
+}
+
+/// `fetch_verified` with a Hugging Face token, for a gated repository. The
+/// token goes out only to `huggingface.co` itself; reqwest drops the header
+/// when the hub redirects to its storage host.
+pub async fn fetch_verified_as(
+ client: &reqwest::Client,
+ remote: &RemoteFile,
+ dest: &Path,
+ hub_token: Option<&str>,
+ cancel: &AtomicBool,
+ on_progress: &mut (dyn FnMut(u64) + Send),
+) -> Result<(), FetchError> {
+ let bearer = hub_token.filter(|_| crate::commands::download::is_huggingface_host(&remote.url));
let mut wait = Duration::from_secs(2);
let mut attempt = 1;
loop {
- match fetch_once(client, remote, dest, cancel, on_progress).await {
+ match fetch_once(client, remote, dest, bearer, cancel, on_progress).await {
Err(e) if e.worth_a_retry() && attempt < ATTEMPTS => {
tracing::warn!(attempt, "voice loop download attempt failed, retrying: {e:?}");
let mut waited = Duration::ZERO;
@@ -140,6 +155,7 @@ async fn fetch_once(
client: &reqwest::Client,
remote: &RemoteFile,
dest: &Path,
+ bearer: Option<&str>,
cancel: &AtomicBool,
on_progress: &mut (dyn FnMut(u64) + Send),
) -> Result<(), FetchError> {
@@ -166,6 +182,9 @@ async fn fetch_once(
if have < remote.size {
let mut request = client.get(&remote.url);
+ if let Some(token) = bearer {
+ request = request.bearer_auth(token);
+ }
if have > 0 {
request = request.header(reqwest::header::RANGE, format!("bytes={have}-"));
}
@@ -396,7 +415,7 @@ mod tests {
async fn run(remote: &RemoteFile, dest: &Path) -> (Result<(), FetchError>, Vec<u64>) {
let cancel = AtomicBool::new(false);
let mut seen = Vec::new();
- let result = fetch_once(&http_client().unwrap(), remote, dest, &cancel, &mut |n| seen.push(n)).await;
+ let result = fetch_once(&http_client().unwrap(), remote, dest, None, &cancel, &mut |n| seen.push(n)).await;
(result, seen)
}
diff --git a/src/lib/__tests__/mac-engine-pins.test.ts b/src/lib/__tests__/mac-engine-pins.test.ts
index fac21a4b..dc00fc50 100644
--- a/src/lib/__tests__/mac-engine-pins.test.ts
+++ b/src/lib/__tests__/mac-engine-pins.test.ts
@@ -41,7 +41,7 @@ const byId = (id: string) => engines.find((e) => e.id === id)!
describe('the working tree', () => {
it('yields the five engines, in a fixed order', () => {
- expect(engines.map((e) => e.id)).toEqual(['image', 'mflux', 'mlx-video', 'ltx-2-mlx', 'mesh3d'])
+ expect(engines.map((e) => e.id)).toEqual(['image', 'mflux', 'mlx-video', 'ltx-2-mlx', 'mesh3d', 'mesh3d-sf3d'])
for (const engine of engines) expect(engine.source).toBe(SOURCES[engine.id])
})
@@ -106,6 +106,20 @@ describe('the working tree', () => {
expect(specs.some((s) => s.startsWith('torchmcubes') || s.startsWith('rembg'))).toBe(false)
})
+ it('reads the Stable Fast 3D engine as the PINNED array of mesh3d_sf3d.rs, without its own wheels', () => {
+ const source = read(SOURCES['mesh3d-sf3d'])
+ const declared = Number(source.match(/const PINNED: \[&str; (\d+)\]/)![1])
+ const specs = byId('mesh3d-sf3d').specs
+ expect(specs).toHaveLength(declared)
+ expect(specs.every((s) => !s.includes(' @ '))).toBe(true)
+ expect(specs).toContain('torch==2.10.0')
+ // The two extensions are LU's own wheels in the app, never asked of PyPI;
+ // what LU replaces is not installed at all.
+ for (const never of ['texture-baker', 'uv-unwrapper', 'rembg', 'gpytoolbox', 'pynanoinstantmeshes']) {
+ expect(specs.some((s) => s.startsWith(`${never}==`))).toBe(false)
+ }
+ })
+
it('takes the Python line from python.json', () => {
expect(pythonLine()).toMatch(/^3\.\d+$/)
expect(JSON.parse(read('src-tauri/resources/voice_loop/python.json')).version.startsWith(pythonLine() + '.')).toBe(true)