Space app: SLaT session cache, tone-mapper safety, CUDA/inference fixes
Browse files- HDRI preview uses standalone ToneMapper(view=); dropdown calls setup_tone_mapper
- Image workflow stores SLaT in _SESSION_SLAT; file path still for uploaded npz
- Move NeAR and Hunyuan to CUDA when available on __main__
- export_glb and export_glb_from_slat run under inference_mode for slat_decoder_mesh
- setup_tone_mapper uses ToneMapper(view=) to avoid missing .cpu after OCIO errors
- spconv SparseTensor.replace: align feat buffer with spconv tensor storage
Made-with: Cursor
- app.py +95 -411
- trellis/modules/sparse/basic.py +1 -5
- trellis/pipelines/near_image_to_relightable_3d.py +14 -18
app.py
CHANGED
|
@@ -1,28 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
-
|
| 4 |
-
if not os.environ.get("HF_TOKEN") and not os.environ.get("HUGGING_FACE_HUB_TOKEN"):
|
| 5 |
-
_hub_tok = (os.environ.get("near") or os.environ.get("NEAR") or "").strip()
|
| 6 |
-
if _hub_tok:
|
| 7 |
-
os.environ["HF_TOKEN"] = _hub_tok
|
| 8 |
-
print("[NeAR] HF_TOKEN from Space secret 'near'.", flush=True)
|
| 9 |
-
|
| 10 |
-
try:
|
| 11 |
-
_raw_zerogpu_cap = int(os.environ.get("NEAR_ZEROGPU_HF_CEILING_S", "90"))
|
| 12 |
-
except ValueError:
|
| 13 |
-
_raw_zerogpu_cap = 90
|
| 14 |
-
_ZEROGPU_ENV_CAP_S = min(max(15, _raw_zerogpu_cap), 120)
|
| 15 |
-
for _ek in ("NEAR_ZEROGPU_MAX_SECONDS", "NEAR_ZEROGPU_DURATION_CAP"):
|
| 16 |
-
if _ek in os.environ:
|
| 17 |
-
try:
|
| 18 |
-
if int(os.environ[_ek]) > _ZEROGPU_ENV_CAP_S:
|
| 19 |
-
os.environ[_ek] = str(_ZEROGPU_ENV_CAP_S)
|
| 20 |
-
except ValueError:
|
| 21 |
-
pass
|
| 22 |
-
print(f"[NeAR] ZeroGPU cap {_ZEROGPU_ENV_CAP_S}s (NEAR_ZEROGPU_HF_CEILING_S).", flush=True)
|
| 23 |
-
|
| 24 |
import shutil
|
| 25 |
-
import subprocess
|
| 26 |
import threading
|
| 27 |
import time
|
| 28 |
from pathlib import Path
|
|
@@ -31,7 +9,7 @@ from typing import Any, Dict, Optional
|
|
| 31 |
import gradio as gr
|
| 32 |
|
| 33 |
try:
|
| 34 |
-
import spaces
|
| 35 |
except ImportError:
|
| 36 |
spaces = None
|
| 37 |
import imageio
|
|
@@ -41,20 +19,6 @@ import trimesh
|
|
| 41 |
from PIL import Image
|
| 42 |
from simple_ocio import ToneMapper # pyright: ignore[reportMissingImports]
|
| 43 |
|
| 44 |
-
try:
|
| 45 |
-
import gradio_client.utils as client_utils
|
| 46 |
-
|
| 47 |
-
_get_type_orig = client_utils.get_type
|
| 48 |
-
|
| 49 |
-
def _get_type_patched(schema):
|
| 50 |
-
if isinstance(schema, bool):
|
| 51 |
-
return "boolean"
|
| 52 |
-
return _get_type_orig(schema)
|
| 53 |
-
|
| 54 |
-
client_utils.get_type = _get_type_patched
|
| 55 |
-
except Exception:
|
| 56 |
-
pass
|
| 57 |
-
|
| 58 |
sys.path.insert(0, "./hy3dshape")
|
| 59 |
os.environ.setdefault("ATTN_BACKEND", "xformers")
|
| 60 |
os.environ.setdefault("SPCONV_ALGO", "native")
|
|
@@ -103,126 +67,19 @@ def _warn_example_assets() -> None:
|
|
| 103 |
_warn_example_assets()
|
| 104 |
|
| 105 |
DEFAULT_IMAGE = APP_DIR / "assets/example_image/T.png"
|
| 106 |
-
DEFAULT_SLAT = APP_DIR / "assets/example_slats/2a0d671ce308adb93323eae7141953fc1a5ba68f38cc69f476d5e904c634864d.npz"
|
| 107 |
DEFAULT_HDRI = APP_DIR / "assets/hdris/studio_small_03_1k.exr"
|
| 108 |
-
DEFAULT_PORT = 7860
|
| 109 |
MAX_SEED = np.iinfo(np.int32).max
|
| 110 |
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
with _SESSION_TOUCH_LOCK:
|
| 118 |
-
_SESSION_LAST_TOUCH[session_id] = time.time()
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
def _session_forget(session_id: str) -> None:
|
| 122 |
-
with _SESSION_TOUCH_LOCK:
|
| 123 |
-
_SESSION_LAST_TOUCH.pop(session_id, None)
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
def ensure_session_dir(req: Optional[gr.Request]) -> Path:
|
| 127 |
-
session_id = getattr(req, "session_hash", None) or "shared"
|
| 128 |
-
d = CACHE_DIR / str(session_id)
|
| 129 |
-
d.mkdir(parents=True, exist_ok=True)
|
| 130 |
-
_session_touch(session_id)
|
| 131 |
-
return d
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
def clear_session_dir(req: Optional[gr.Request]) -> str:
|
| 135 |
-
d = ensure_session_dir(req)
|
| 136 |
-
shutil.rmtree(d, ignore_errors=True)
|
| 137 |
-
d.mkdir(parents=True, exist_ok=True)
|
| 138 |
-
# Do not touch torch.cuda here: on HF Stateless / ZeroGPU Spaces, CUDA must
|
| 139 |
-
# not be initialized in the main Gradio process (only inside @spaces.GPU).
|
| 140 |
-
return "Session cache cleared."
|
| 141 |
-
|
| 142 |
-
|
| 143 |
def end_session(req: gr.Request):
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
_session_forget(session_id)
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
def _session_dir_latest_mtime(path: Path) -> float:
|
| 151 |
-
try:
|
| 152 |
-
latest = path.stat().st_mtime
|
| 153 |
-
except OSError:
|
| 154 |
-
return 0.0
|
| 155 |
-
try:
|
| 156 |
-
for child in path.rglob("*"):
|
| 157 |
-
if child.is_file():
|
| 158 |
-
try:
|
| 159 |
-
latest = max(latest, child.stat().st_mtime)
|
| 160 |
-
except OSError:
|
| 161 |
-
pass
|
| 162 |
-
except OSError:
|
| 163 |
-
pass
|
| 164 |
-
return latest
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
def prune_tmp_gradio_sessions(max_age_s: int) -> int:
|
| 168 |
-
"""Delete CACHE_DIR/<session> when both API idle and on-disk files are older than max_age_s."""
|
| 169 |
-
|
| 170 |
-
if max_age_s <= 0 or not CACHE_DIR.is_dir():
|
| 171 |
-
return 0
|
| 172 |
-
now = time.time()
|
| 173 |
-
removed = 0
|
| 174 |
-
with _SESSION_TOUCH_LOCK:
|
| 175 |
-
touch_snap = dict(_SESSION_LAST_TOUCH)
|
| 176 |
-
try:
|
| 177 |
-
entries = list(CACHE_DIR.iterdir())
|
| 178 |
-
except OSError:
|
| 179 |
-
return 0
|
| 180 |
-
for p in entries:
|
| 181 |
-
if not p.is_dir():
|
| 182 |
-
continue
|
| 183 |
-
sid = p.name
|
| 184 |
-
try:
|
| 185 |
-
last_api = touch_snap.get(sid)
|
| 186 |
-
latest_file = _session_dir_latest_mtime(p)
|
| 187 |
-
last_seen = max(last_api or 0.0, latest_file)
|
| 188 |
-
if now - last_seen < max_age_s:
|
| 189 |
-
continue
|
| 190 |
-
shutil.rmtree(p, ignore_errors=True)
|
| 191 |
-
_session_forget(sid)
|
| 192 |
-
removed += 1
|
| 193 |
-
except OSError:
|
| 194 |
-
continue
|
| 195 |
-
return removed
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
_tmp_pruner_started = False
|
| 199 |
-
_tmp_pruner_lock = threading.Lock()
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
def start_tmp_gradio_pruner() -> None:
|
| 203 |
-
"""Background prune of tmp_gradio session dirs (disk, not RAM). Configurable via env."""
|
| 204 |
-
|
| 205 |
-
global _tmp_pruner_started
|
| 206 |
-
interval = int(os.environ.get("NEAR_TMP_PRUNE_INTERVAL_S", "900"))
|
| 207 |
-
if interval <= 0:
|
| 208 |
-
return
|
| 209 |
-
with _tmp_pruner_lock:
|
| 210 |
-
if _tmp_pruner_started:
|
| 211 |
-
return
|
| 212 |
-
_tmp_pruner_started = True
|
| 213 |
-
max_age = int(os.environ.get("NEAR_TMP_GRADIO_MAX_AGE_S", str(48 * 3600)))
|
| 214 |
-
|
| 215 |
-
def _loop() -> None:
|
| 216 |
-
while True:
|
| 217 |
-
try:
|
| 218 |
-
n = prune_tmp_gradio_sessions(max_age)
|
| 219 |
-
if n:
|
| 220 |
-
print(f"[NeAR] tmp_gradio prune: removed {n} stale session dir(s)", flush=True)
|
| 221 |
-
except Exception as exc:
|
| 222 |
-
print(f"[NeAR] tmp_gradio prune error: {exc}", flush=True)
|
| 223 |
-
time.sleep(interval)
|
| 224 |
-
|
| 225 |
-
threading.Thread(target=_loop, daemon=True, name="near-tmp-prune").start()
|
| 226 |
|
| 227 |
|
| 228 |
def get_file_path(file_obj: Any) -> Optional[str]:
|
|
@@ -237,62 +94,20 @@ def get_file_path(file_obj: Any) -> Optional[str]:
|
|
| 237 |
return None
|
| 238 |
|
| 239 |
|
| 240 |
-
_model_lock = threading.Lock()
|
| 241 |
PIPELINE: Optional[NeARImageToRelightable3DPipeline] = None
|
| 242 |
GEOMETRY_PIPELINE: Optional[Hunyuan3DDiTFlowMatchingPipeline] = None
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
_geometry_on_cuda = False
|
| 246 |
-
_near_on_cuda = False
|
| 247 |
-
|
| 248 |
-
_FALLBACK_TONE_MAPPER_CHOICES = ["AgX", "False", "Khronos neutrals", "Filmic", "Khronos glTF PBR"]
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
def _truthy_env(name: str, default: str) -> bool:
|
| 252 |
-
v = (os.environ.get(name) if name in os.environ else default).strip().lower()
|
| 253 |
-
return v in ("1", "true", "yes", "on")
|
| 254 |
|
|
|
|
|
|
|
| 255 |
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
# to bind immediately and load on first @spaces.GPU click instead (faster "page up", riskier UX).
|
| 260 |
-
_CPU_PRELOAD_DEFAULT = "1"
|
| 261 |
-
_CPU_PRELOAD_AT_START = _truthy_env(
|
| 262 |
-
"NEAR_MODEL_CPU_PRELOAD_AT_START",
|
| 263 |
-
_CPU_PRELOAD_DEFAULT,
|
| 264 |
-
)
|
| 265 |
-
print(
|
| 266 |
-
f"[NeAR] NEAR_MODEL_CPU_PRELOAD_AT_START={'1' if _CPU_PRELOAD_AT_START else '0'} "
|
| 267 |
-
"(1 = block server start until CPU weights ready; 0 = lazy load on first GPU action).",
|
| 268 |
-
flush=True,
|
| 269 |
-
)
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
def _default_tone_mapper_choices() -> list[str]:
|
| 273 |
-
try:
|
| 274 |
-
views = getattr(ToneMapper(), "available_views", None)
|
| 275 |
-
if isinstance(views, (list, tuple)) and views:
|
| 276 |
-
return [str(v) for v in views]
|
| 277 |
-
except Exception as exc:
|
| 278 |
-
print(f"[NeAR] ToneMapper view discovery failed, using fallback choices: {exc}", flush=True)
|
| 279 |
-
return list(_FALLBACK_TONE_MAPPER_CHOICES)
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
TONE_MAPPER_CHOICES = _default_tone_mapper_choices()
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
def _get_light_image_preprocessor():
|
| 286 |
-
global _light_preprocessor
|
| 287 |
-
if _light_preprocessor is not None:
|
| 288 |
-
return _light_preprocessor
|
| 289 |
-
with _light_preprocess_lock:
|
| 290 |
-
if _light_preprocessor is None:
|
| 291 |
-
from hy3dshape.rembg import BackgroundRemover # pyright: ignore[reportMissingImports]
|
| 292 |
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
return _light_preprocessor
|
| 296 |
|
| 297 |
|
| 298 |
def _preprocess_image_rgba_light(input_image: Image.Image) -> Image.Image:
|
|
@@ -313,7 +128,7 @@ def _preprocess_image_rgba_light(input_image: Image.Image) -> Image.Image:
|
|
| 313 |
(int(rgb.width * scale), int(rgb.height * scale)),
|
| 314 |
Image.Resampling.LANCZOS,
|
| 315 |
)
|
| 316 |
-
output =
|
| 317 |
|
| 318 |
if output.mode != "RGBA":
|
| 319 |
output = output.convert("RGBA")
|
|
@@ -344,96 +159,15 @@ def _flatten_rgba_on_matte(image: Image.Image, matte_rgb: tuple[float, float, fl
|
|
| 344 |
return NeARImageToRelightable3DPipeline.flatten_rgba_on_matte(image, matte_rgb)
|
| 345 |
|
| 346 |
|
| 347 |
-
def
|
| 348 |
-
global TONE_MAPPER_CHOICES
|
| 349 |
-
views = getattr(tone_mapper, "available_views", None)
|
| 350 |
-
if isinstance(views, (list, tuple)) and views:
|
| 351 |
-
TONE_MAPPER_CHOICES = [str(v) for v in views]
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
def _ensure_geometry_cpu_locked() -> None:
|
| 355 |
-
global GEOMETRY_PIPELINE
|
| 356 |
-
if GEOMETRY_PIPELINE is not None:
|
| 357 |
-
return
|
| 358 |
-
hy_id = os.environ.get("NEAR_HUNYUAN_PRETRAINED", "tencent/Hunyuan3D-2.1")
|
| 359 |
-
t0 = time.time()
|
| 360 |
-
print(f"[NeAR] Hunyuan geometry on CPU from {hy_id!r}...", flush=True)
|
| 361 |
-
GEOMETRY_PIPELINE = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(hy_id, device="cpu")
|
| 362 |
-
print(f"[NeAR] Hunyuan CPU load {time.time() - t0:.1f}s", flush=True)
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
def _ensure_near_cpu_locked() -> None:
|
| 366 |
-
global PIPELINE
|
| 367 |
-
if PIPELINE is not None:
|
| 368 |
-
return
|
| 369 |
-
near_id = os.environ.get("NEAR_PRETRAINED", "luh0502/NeAR")
|
| 370 |
-
t0 = time.time()
|
| 371 |
-
print(f"[NeAR] NeAR on CPU from {near_id!r}...", flush=True)
|
| 372 |
-
p = NeARImageToRelightable3DPipeline.from_pretrained(near_id)
|
| 373 |
-
p.to("cpu")
|
| 374 |
-
_update_tone_mapper_choices(p.tone_mapper)
|
| 375 |
-
PIPELINE = p
|
| 376 |
-
print(f"[NeAR] NeAR CPU load {time.time() - t0:.1f}s", flush=True)
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
def ensure_geometry_on_cuda() -> Hunyuan3DDiTFlowMatchingPipeline:
|
| 380 |
-
global _geometry_on_cuda
|
| 381 |
-
with _model_lock:
|
| 382 |
-
_ensure_geometry_cpu_locked()
|
| 383 |
-
assert GEOMETRY_PIPELINE is not None
|
| 384 |
-
if torch.cuda.is_available() and not _geometry_on_cuda:
|
| 385 |
-
t0 = time.time()
|
| 386 |
-
GEOMETRY_PIPELINE.to("cuda")
|
| 387 |
-
_geometry_on_cuda = True
|
| 388 |
-
print(f"[NeAR] Hunyuan -> cuda {time.time() - t0:.1f}s", flush=True)
|
| 389 |
-
return GEOMETRY_PIPELINE
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
def ensure_near_on_cuda() -> NeARImageToRelightable3DPipeline:
|
| 393 |
-
global _near_on_cuda
|
| 394 |
-
with _model_lock:
|
| 395 |
-
_ensure_near_cpu_locked()
|
| 396 |
-
assert PIPELINE is not None
|
| 397 |
-
if torch.cuda.is_available() and not _near_on_cuda:
|
| 398 |
-
t0 = time.time()
|
| 399 |
-
PIPELINE.to("cuda")
|
| 400 |
-
_near_on_cuda = True
|
| 401 |
-
print(f"[NeAR] NeAR -> cuda {time.time() - t0:.1f}s", flush=True)
|
| 402 |
-
return PIPELINE
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
def run_model_cpu_preload_blocking() -> None:
|
| 406 |
-
"""Load Hunyuan + NeAR on CPU before Gradio binds (main UI appears only after this)."""
|
| 407 |
-
|
| 408 |
-
t0 = time.time()
|
| 409 |
-
print("[NeAR] blocking CPU preload before server bind ...", flush=True)
|
| 410 |
-
with _model_lock:
|
| 411 |
-
_ensure_geometry_cpu_locked()
|
| 412 |
-
_ensure_near_cpu_locked()
|
| 413 |
-
print(
|
| 414 |
-
f"[NeAR] CPU preload done {time.time() - t0:.1f}s — Gradio will accept traffic now.",
|
| 415 |
-
flush=True,
|
| 416 |
-
)
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
def set_tone_mapper(view_name: str):
|
| 420 |
-
pipeline = ensure_near_on_cuda()
|
| 421 |
-
if view_name:
|
| 422 |
-
pipeline.setup_tone_mapper(view_name)
|
| 423 |
-
return pipeline
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
def preview_hdri(hdri_file_obj: Any, tone_mapper_name: str):
|
| 427 |
hdri_path = get_file_path(hdri_file_obj)
|
| 428 |
if not hdri_path:
|
| 429 |
return None, "Upload an HDRI `.exr` (left column)."
|
| 430 |
import pyexr # pyright: ignore[reportMissingImports]
|
| 431 |
|
| 432 |
-
tone_mapper = ToneMapper()
|
| 433 |
-
if tone_mapper_name:
|
| 434 |
-
tone_mapper.view = tone_mapper_name
|
| 435 |
hdri_np = pyexr.read(hdri_path)[..., :3]
|
| 436 |
-
|
|
|
|
| 437 |
preview = (np.clip(preview, 0, 1) * 255).astype(np.uint8)
|
| 438 |
name = Path(hdri_path).name
|
| 439 |
return preview, f"HDRI **{name}** — preview updated."
|
|
@@ -446,10 +180,6 @@ def switch_asset_source(mode: str):
|
|
| 446 |
def _ensure_rgba(img: Image.Image) -> Image.Image:
|
| 447 |
if img.mode == "RGBA":
|
| 448 |
return img
|
| 449 |
-
if img.mode == "RGB":
|
| 450 |
-
r, g, b = img.split()
|
| 451 |
-
a = Image.new("L", img.size, 255)
|
| 452 |
-
return Image.merge("RGBA", (r, g, b, a))
|
| 453 |
return img.convert("RGBA")
|
| 454 |
|
| 455 |
|
|
@@ -460,14 +190,6 @@ def preprocess_image_only(image_input: Optional[Image.Image]):
|
|
| 460 |
return _preprocess_image_rgba_light(image_input)
|
| 461 |
|
| 462 |
|
| 463 |
-
def save_slat_npz(slat, save_path: Path):
|
| 464 |
-
np.savez(
|
| 465 |
-
save_path,
|
| 466 |
-
feats=slat.feats.detach().cpu().numpy(),
|
| 467 |
-
coords=slat.coords.detach().cpu().numpy(),
|
| 468 |
-
)
|
| 469 |
-
|
| 470 |
-
|
| 471 |
@GPU
|
| 472 |
@torch.inference_mode()
|
| 473 |
def generate_mesh(
|
|
@@ -475,8 +197,7 @@ def generate_mesh(
|
|
| 475 |
req: gr.Request,
|
| 476 |
progress=gr.Progress(track_tqdm=True),
|
| 477 |
):
|
| 478 |
-
|
| 479 |
-
session_dir = ensure_session_dir(req)
|
| 480 |
|
| 481 |
if image_input is None:
|
| 482 |
raise gr.Error("Please upload an input image.")
|
|
@@ -490,15 +211,17 @@ def generate_mesh(
|
|
| 490 |
mesh_rgb.save(session_dir / "input_processed.png")
|
| 491 |
|
| 492 |
progress(0.6, desc="Generating geometry")
|
| 493 |
-
mesh =
|
| 494 |
mesh_path = session_dir / "initial_3d_shape.glb"
|
| 495 |
mesh.export(mesh_path)
|
| 496 |
|
|
|
|
| 497 |
state = {
|
| 498 |
"mode": "image",
|
| 499 |
"mesh_path": str(mesh_path),
|
| 500 |
"processed_image_path": str(session_dir / "input_processed.png"),
|
| 501 |
"slat_path": None,
|
|
|
|
| 502 |
}
|
| 503 |
return (
|
| 504 |
state,
|
|
@@ -509,16 +232,14 @@ def generate_mesh(
|
|
| 509 |
|
| 510 |
@GPU
|
| 511 |
@torch.inference_mode()
|
| 512 |
-
def
|
| 513 |
asset_state: Dict[str, Any],
|
| 514 |
image_input: Optional[Image.Image],
|
| 515 |
seed: int,
|
| 516 |
req: gr.Request,
|
| 517 |
progress=gr.Progress(track_tqdm=True),
|
| 518 |
):
|
| 519 |
-
|
| 520 |
-
session_dir = ensure_session_dir(req)
|
| 521 |
-
|
| 522 |
if not asset_state or not asset_state.get("mesh_path"):
|
| 523 |
raise gr.Error("Please run ① Generate Mesh first.")
|
| 524 |
mesh_path = asset_state["mesh_path"]
|
|
@@ -536,28 +257,35 @@ def generate_slat(
|
|
| 536 |
slat_rgb = _flatten_rgba_on_matte(rgba, (0.0, 0.0, 0.0))
|
| 537 |
|
| 538 |
progress(0.3, desc="Computing SLaT coordinates")
|
| 539 |
-
coords =
|
| 540 |
|
| 541 |
progress(0.6, desc="Generating SLaT")
|
| 542 |
-
slat =
|
| 543 |
-
|
| 544 |
-
slat_path = session_dir / "generated_slat.npz"
|
| 545 |
-
save_slat_npz(slat, slat_path)
|
| 546 |
|
| 547 |
-
|
|
|
|
| 548 |
return new_state, f"**Asset ready** — SLaT generated (seed `{seed}`)."
|
| 549 |
|
| 550 |
|
| 551 |
-
def
|
| 552 |
resolved = get_file_path(slat_upload) or (slat_path_text.strip() if slat_path_text else "")
|
| 553 |
if not resolved:
|
| 554 |
raise gr.Error("Please provide a SLaT `.npz` path or upload one.")
|
| 555 |
if not os.path.exists(resolved):
|
| 556 |
raise gr.Error(f"SLaT file not found: `{resolved}`")
|
| 557 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
return state, f"SLaT **{Path(resolved).name}** loaded."
|
| 559 |
|
| 560 |
|
|
|
|
|
|
|
| 561 |
def prepare_slat(
|
| 562 |
source_mode: str,
|
| 563 |
asset_state: Dict[str, Any],
|
|
@@ -569,25 +297,34 @@ def prepare_slat(
|
|
| 569 |
progress=gr.Progress(track_tqdm=True),
|
| 570 |
):
|
| 571 |
if source_mode == "From Image":
|
| 572 |
-
return
|
| 573 |
-
return
|
| 574 |
|
| 575 |
|
| 576 |
def require_asset_state(asset_state: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
| 577 |
-
if not asset_state
|
| 578 |
raise gr.Error("Please generate or load a SLaT first.")
|
| 579 |
-
|
|
|
|
|
|
|
| 580 |
|
| 581 |
|
| 582 |
-
def load_asset_and_hdri(asset_state: Dict[str, Any], hdri_file_obj: Any,
|
| 583 |
asset_state = require_asset_state(asset_state)
|
| 584 |
hdri_path = get_file_path(hdri_file_obj)
|
| 585 |
if not hdri_path:
|
| 586 |
raise gr.Error("Please upload an HDRI `.exr` file.")
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 591 |
|
| 592 |
|
| 593 |
@GPU
|
|
@@ -595,7 +332,6 @@ def load_asset_and_hdri(asset_state: Dict[str, Any], hdri_file_obj: Any, tone_ma
|
|
| 595 |
def render_preview(
|
| 596 |
asset_state: Dict[str, Any],
|
| 597 |
hdri_file_obj: Any,
|
| 598 |
-
tone_mapper_name: str,
|
| 599 |
hdri_rot: float,
|
| 600 |
yaw: float,
|
| 601 |
pitch: float,
|
|
@@ -606,12 +342,12 @@ def render_preview(
|
|
| 606 |
progress=gr.Progress(track_tqdm=True),
|
| 607 |
):
|
| 608 |
t0 = time.time()
|
| 609 |
-
session_dir =
|
| 610 |
progress(0.1, desc="Loading SLaT and HDRI")
|
| 611 |
-
|
| 612 |
|
| 613 |
progress(0.5, desc="Rendering")
|
| 614 |
-
views =
|
| 615 |
slat, hdri_np,
|
| 616 |
yaw_deg=yaw, pitch_deg=pitch, fov=fov, radius=radius,
|
| 617 |
hdri_rot_deg=hdri_rot, resolution=int(resolution),
|
|
@@ -640,7 +376,6 @@ def render_preview(
|
|
| 640 |
def render_camera_video(
|
| 641 |
asset_state: Dict[str, Any],
|
| 642 |
hdri_file_obj: Any,
|
| 643 |
-
tone_mapper_name: str,
|
| 644 |
hdri_rot: float,
|
| 645 |
fps: int,
|
| 646 |
num_views: int,
|
|
@@ -652,12 +387,12 @@ def render_camera_video(
|
|
| 652 |
progress=gr.Progress(track_tqdm=True),
|
| 653 |
):
|
| 654 |
t0 = time.time()
|
| 655 |
-
session_dir =
|
| 656 |
progress(0.1, desc="Loading SLaT and HDRI")
|
| 657 |
-
|
| 658 |
|
| 659 |
progress(0.4, desc="Rendering camera path")
|
| 660 |
-
frames =
|
| 661 |
slat, hdri_np,
|
| 662 |
num_views=int(num_views), fov=fov, radius=radius,
|
| 663 |
hdri_rot_deg=hdri_rot, full_video=full_video, shadow_video=shadow_video,
|
|
@@ -674,7 +409,6 @@ def render_camera_video(
|
|
| 674 |
def render_hdri_video(
|
| 675 |
asset_state: Dict[str, Any],
|
| 676 |
hdri_file_obj: Any,
|
| 677 |
-
tone_mapper_name: str,
|
| 678 |
fps: int,
|
| 679 |
num_frames: int,
|
| 680 |
yaw: float,
|
|
@@ -687,12 +421,12 @@ def render_hdri_video(
|
|
| 687 |
progress=gr.Progress(track_tqdm=True),
|
| 688 |
):
|
| 689 |
t0 = time.time()
|
| 690 |
-
session_dir =
|
| 691 |
progress(0.1, desc="Loading SLaT and HDRI")
|
| 692 |
-
|
| 693 |
|
| 694 |
progress(0.4, desc="Rendering HDRI rotation")
|
| 695 |
-
hdri_roll_frames, render_frames =
|
| 696 |
slat, hdri_np,
|
| 697 |
num_frames=int(num_frames), yaw_deg=yaw, pitch_deg=pitch,
|
| 698 |
fov=fov, radius=radius, full_video=full_video, shadow_video=shadow_video,
|
|
@@ -710,7 +444,6 @@ def render_hdri_video(
|
|
| 710 |
def export_glb(
|
| 711 |
asset_state: Dict[str, Any],
|
| 712 |
hdri_file_obj: Any,
|
| 713 |
-
tone_mapper_name: str,
|
| 714 |
hdri_rot: float,
|
| 715 |
simplify: float,
|
| 716 |
texture_size: int,
|
|
@@ -718,12 +451,12 @@ def export_glb(
|
|
| 718 |
progress=gr.Progress(track_tqdm=True),
|
| 719 |
):
|
| 720 |
t0 = time.time()
|
| 721 |
-
session_dir =
|
| 722 |
progress(0.1, desc="Loading SLaT and HDRI")
|
| 723 |
-
|
| 724 |
|
| 725 |
progress(0.6, desc="Baking PBR textures")
|
| 726 |
-
glb =
|
| 727 |
slat, hdri_np,
|
| 728 |
hdri_rot_deg=hdri_rot, base_mesh=None,
|
| 729 |
simplify=simplify, texture_size=int(texture_size), fill_holes=True,
|
|
@@ -1018,7 +751,7 @@ def build_app() -> gr.Blocks:
|
|
| 1018 |
value=str(DEFAULT_IMAGE) if DEFAULT_IMAGE.exists() else None,
|
| 1019 |
height=400,
|
| 1020 |
)
|
| 1021 |
-
seed = gr.Slider(0, MAX_SEED, value=
|
| 1022 |
mesh_button = gr.Button("① Generate Mesh", variant="primary", min_width=100)
|
| 1023 |
|
| 1024 |
with gr.Tab("SLaT", id=1):
|
|
@@ -1074,11 +807,10 @@ def build_app() -> gr.Blocks:
|
|
| 1074 |
gr.HTML("<div class='ctrl-strip-title'>Camera & HDRI</div>")
|
| 1075 |
with gr.Row():
|
| 1076 |
tone_mapper_name = gr.Dropdown(
|
| 1077 |
-
choices=
|
| 1078 |
-
value=
|
| 1079 |
label="Tone Mapper",
|
| 1080 |
min_width=120,
|
| 1081 |
-
allow_custom_value=True,
|
| 1082 |
)
|
| 1083 |
hdri_rot = gr.Slider(0, 360, value=0, step=1, label="HDRI Rotation °")
|
| 1084 |
resolution = gr.Slider(256, 1024, value=512, step=256, label="Preview Res")
|
|
@@ -1088,6 +820,12 @@ def build_app() -> gr.Blocks:
|
|
| 1088 |
fov = gr.Slider(10, 70, value=40, step=1, label="FoV")
|
| 1089 |
radius = gr.Slider(1.0, 4.0, value=2.0, step=0.05, label="Radius")
|
| 1090 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1091 |
with gr.Tabs(elem_classes=["main-output-tabs"]):
|
| 1092 |
|
| 1093 |
with gr.Tab("Geometry", id=0):
|
|
@@ -1103,10 +841,6 @@ def build_app() -> gr.Blocks:
|
|
| 1103 |
export_glb_button = gr.Button("Export PBR GLB", variant="primary", min_width=140)
|
| 1104 |
|
| 1105 |
with gr.Tab("Preview", id=1):
|
| 1106 |
-
gr.HTML(
|
| 1107 |
-
"<p style='font-size:0.78rem;color:#9ca3af;margin:0 0 0.35rem 0;'>"
|
| 1108 |
-
"Use <b>Camera & HDRI</b> under the tabs, then render.</p>"
|
| 1109 |
-
)
|
| 1110 |
preview_button = gr.Button("Render Preview", variant="primary", min_width=100)
|
| 1111 |
gr.HTML("<hr class='divider'>")
|
| 1112 |
with gr.Row():
|
|
@@ -1181,6 +915,7 @@ def build_app() -> gr.Blocks:
|
|
| 1181 |
else:
|
| 1182 |
gr.Markdown("*No `.exr` examples in `assets/hdris`*")
|
| 1183 |
|
|
|
|
| 1184 |
demo.unload(end_session)
|
| 1185 |
|
| 1186 |
source_mode.change(switch_asset_source, inputs=[source_mode], outputs=[source_tabs])
|
|
@@ -1193,10 +928,10 @@ def build_app() -> gr.Blocks:
|
|
| 1193 |
outputs=[col_img_examples, col_slat_examples],
|
| 1194 |
)
|
| 1195 |
|
| 1196 |
-
for _trigger in (hdri_file.upload, hdri_file.change
|
| 1197 |
_trigger(
|
| 1198 |
preview_hdri,
|
| 1199 |
-
inputs=[hdri_file
|
| 1200 |
outputs=[hdri_preview, status_md],
|
| 1201 |
)
|
| 1202 |
|
|
@@ -1220,7 +955,7 @@ def build_app() -> gr.Blocks:
|
|
| 1220 |
|
| 1221 |
preview_button.click(
|
| 1222 |
render_preview,
|
| 1223 |
-
inputs=[asset_state, hdri_file,
|
| 1224 |
yaw, pitch, fov, radius, resolution],
|
| 1225 |
outputs=[
|
| 1226 |
color_output,
|
|
@@ -1234,87 +969,36 @@ def build_app() -> gr.Blocks:
|
|
| 1234 |
|
| 1235 |
camera_video_button.click(
|
| 1236 |
render_camera_video,
|
| 1237 |
-
inputs=[asset_state, hdri_file,
|
| 1238 |
fps, num_views, fov, radius, full_video, shadow_video],
|
| 1239 |
outputs=[camera_video_output, status_md],
|
| 1240 |
)
|
| 1241 |
|
| 1242 |
hdri_video_button.click(
|
| 1243 |
render_hdri_video,
|
| 1244 |
-
inputs=[asset_state, hdri_file,
|
| 1245 |
fps, num_frames, yaw, pitch, fov, radius, full_video, shadow_video],
|
| 1246 |
outputs=[hdri_roll_video_output, hdri_render_video_output, status_md],
|
| 1247 |
)
|
| 1248 |
|
| 1249 |
export_glb_button.click(
|
| 1250 |
export_glb,
|
| 1251 |
-
inputs=[asset_state, hdri_file,
|
| 1252 |
outputs=[pbr_viewer, status_md],
|
| 1253 |
)
|
| 1254 |
-
|
| 1255 |
-
clear_button.click(
|
| 1256 |
-
clear_session_dir,
|
| 1257 |
-
outputs=[status_md],
|
| 1258 |
-
).then(
|
| 1259 |
-
lambda: ({}, None, None, None, None, None, None, None, None, None, None),
|
| 1260 |
-
outputs=[
|
| 1261 |
-
asset_state,
|
| 1262 |
-
mesh_viewer,
|
| 1263 |
-
pbr_viewer,
|
| 1264 |
-
color_output,
|
| 1265 |
-
base_color_output,
|
| 1266 |
-
metallic_output,
|
| 1267 |
-
roughness_output,
|
| 1268 |
-
shadow_output,
|
| 1269 |
-
camera_video_output,
|
| 1270 |
-
hdri_roll_video_output,
|
| 1271 |
-
hdri_render_video_output,
|
| 1272 |
-
],
|
| 1273 |
-
)
|
| 1274 |
-
|
| 1275 |
return demo
|
| 1276 |
|
| 1277 |
|
| 1278 |
demo = build_app()
|
| 1279 |
-
demo.queue(max_size=8)
|
| 1280 |
-
|
| 1281 |
-
# Gradio 6: theme/css must be passed to launch(); HF Spaces calls demo.launch() without our __main__ block.
|
| 1282 |
-
_orig_blocks_launch = demo.launch
|
| 1283 |
-
|
| 1284 |
-
|
| 1285 |
-
def _near_launch(*args: Any, **kwargs: Any):
|
| 1286 |
-
kwargs.setdefault("theme", NEAR_GRADIO_THEME)
|
| 1287 |
-
kwargs.setdefault("css", CUSTOM_CSS)
|
| 1288 |
-
if _CPU_PRELOAD_AT_START:
|
| 1289 |
-
run_model_cpu_preload_blocking()
|
| 1290 |
-
return _orig_blocks_launch(*args, **kwargs)
|
| 1291 |
-
|
| 1292 |
-
|
| 1293 |
-
demo.launch = _near_launch # type: ignore[method-assign]
|
| 1294 |
-
|
| 1295 |
-
start_tmp_gradio_pruner()
|
| 1296 |
|
| 1297 |
if __name__ == "__main__":
|
| 1298 |
-
import argparse
|
| 1299 |
|
| 1300 |
-
|
| 1301 |
-
|
| 1302 |
-
|
| 1303 |
-
|
| 1304 |
-
|
| 1305 |
-
)
|
| 1306 |
-
parser.add_argument(
|
| 1307 |
-
"--port",
|
| 1308 |
-
type=int,
|
| 1309 |
-
default=int(
|
| 1310 |
-
os.environ.get("PORT", os.environ.get("GRADIO_SERVER_PORT", str(DEFAULT_PORT)))
|
| 1311 |
-
),
|
| 1312 |
-
)
|
| 1313 |
-
parser.add_argument("--share", action="store_true")
|
| 1314 |
-
args = parser.parse_args()
|
| 1315 |
|
| 1316 |
demo.launch(
|
| 1317 |
-
|
| 1318 |
-
server_port=args.port,
|
| 1319 |
-
share=args.share,
|
| 1320 |
)
|
|
|
|
| 1 |
import os
|
| 2 |
import sys
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import shutil
|
|
|
|
| 4 |
import threading
|
| 5 |
import time
|
| 6 |
from pathlib import Path
|
|
|
|
| 9 |
import gradio as gr
|
| 10 |
|
| 11 |
try:
|
| 12 |
+
import spaces # pyright: ignore[reportMissingImports]
|
| 13 |
except ImportError:
|
| 14 |
spaces = None
|
| 15 |
import imageio
|
|
|
|
| 19 |
from PIL import Image
|
| 20 |
from simple_ocio import ToneMapper # pyright: ignore[reportMissingImports]
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
sys.path.insert(0, "./hy3dshape")
|
| 23 |
os.environ.setdefault("ATTN_BACKEND", "xformers")
|
| 24 |
os.environ.setdefault("SPCONV_ALGO", "native")
|
|
|
|
| 67 |
_warn_example_assets()
|
| 68 |
|
| 69 |
DEFAULT_IMAGE = APP_DIR / "assets/example_image/T.png"
|
|
|
|
| 70 |
DEFAULT_HDRI = APP_DIR / "assets/hdris/studio_small_03_1k.exr"
|
|
|
|
| 71 |
MAX_SEED = np.iinfo(np.int32).max
|
| 72 |
|
| 73 |
|
| 74 |
+
def start_session(req: gr.Request):
|
| 75 |
+
user_dir = CACHE_DIR / str(req.session_hash)
|
| 76 |
+
os.makedirs(user_dir, exist_ok=True)
|
| 77 |
+
|
| 78 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
def end_session(req: gr.Request):
|
| 80 |
+
user_dir = CACHE_DIR / str(req.session_hash)
|
| 81 |
+
shutil.rmtree(user_dir)
|
| 82 |
+
_SESSION_SLAT.pop(str(req.session_hash), None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
|
| 85 |
def get_file_path(file_obj: Any) -> Optional[str]:
|
|
|
|
| 94 |
return None
|
| 95 |
|
| 96 |
|
|
|
|
| 97 |
PIPELINE: Optional[NeARImageToRelightable3DPipeline] = None
|
| 98 |
GEOMETRY_PIPELINE: Optional[Hunyuan3DDiTFlowMatchingPipeline] = None
|
| 99 |
+
tone_mapper = ToneMapper()
|
| 100 |
+
AVAILABLE_TONE_MAPPERS = getattr(tone_mapper, "available_views", ["AgX"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
# In-process SLaT for the image workflow (not serialized through Gradio State).
|
| 103 |
+
_SESSION_SLAT: Dict[str, Any] = {}
|
| 104 |
|
| 105 |
+
def set_tone_mapper(view_name: str):
|
| 106 |
+
if view_name and PIPELINE is not None:
|
| 107 |
+
PIPELINE.setup_tone_mapper(view_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
+
from hy3dshape.rembg import BackgroundRemover # pyright: ignore[reportMissingImports]
|
| 110 |
+
LIGHT_PREPROCESSOR = BackgroundRemover()
|
|
|
|
| 111 |
|
| 112 |
|
| 113 |
def _preprocess_image_rgba_light(input_image: Image.Image) -> Image.Image:
|
|
|
|
| 128 |
(int(rgb.width * scale), int(rgb.height * scale)),
|
| 129 |
Image.Resampling.LANCZOS,
|
| 130 |
)
|
| 131 |
+
output = LIGHT_PREPROCESSOR(rgb)
|
| 132 |
|
| 133 |
if output.mode != "RGBA":
|
| 134 |
output = output.convert("RGBA")
|
|
|
|
| 159 |
return NeARImageToRelightable3DPipeline.flatten_rgba_on_matte(image, matte_rgb)
|
| 160 |
|
| 161 |
|
| 162 |
+
def preview_hdri(hdri_file_obj: Any):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
hdri_path = get_file_path(hdri_file_obj)
|
| 164 |
if not hdri_path:
|
| 165 |
return None, "Upload an HDRI `.exr` (left column)."
|
| 166 |
import pyexr # pyright: ignore[reportMissingImports]
|
| 167 |
|
|
|
|
|
|
|
|
|
|
| 168 |
hdri_np = pyexr.read(hdri_path)[..., :3]
|
| 169 |
+
tm = ToneMapper(view="Khronos PBR Neutral")
|
| 170 |
+
preview = tm.hdr_to_ldr(hdri_np)
|
| 171 |
preview = (np.clip(preview, 0, 1) * 255).astype(np.uint8)
|
| 172 |
name = Path(hdri_path).name
|
| 173 |
return preview, f"HDRI **{name}** — preview updated."
|
|
|
|
| 180 |
def _ensure_rgba(img: Image.Image) -> Image.Image:
|
| 181 |
if img.mode == "RGBA":
|
| 182 |
return img
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
return img.convert("RGBA")
|
| 184 |
|
| 185 |
|
|
|
|
| 190 |
return _preprocess_image_rgba_light(image_input)
|
| 191 |
|
| 192 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
@GPU
|
| 194 |
@torch.inference_mode()
|
| 195 |
def generate_mesh(
|
|
|
|
| 197 |
req: gr.Request,
|
| 198 |
progress=gr.Progress(track_tqdm=True),
|
| 199 |
):
|
| 200 |
+
session_dir = CACHE_DIR / str(req.session_hash)
|
|
|
|
| 201 |
|
| 202 |
if image_input is None:
|
| 203 |
raise gr.Error("Please upload an input image.")
|
|
|
|
| 211 |
mesh_rgb.save(session_dir / "input_processed.png")
|
| 212 |
|
| 213 |
progress(0.6, desc="Generating geometry")
|
| 214 |
+
mesh = GEOMETRY_PIPELINE(image=mesh_rgb)[0]
|
| 215 |
mesh_path = session_dir / "initial_3d_shape.glb"
|
| 216 |
mesh.export(mesh_path)
|
| 217 |
|
| 218 |
+
_SESSION_SLAT.pop(str(req.session_hash), None)
|
| 219 |
state = {
|
| 220 |
"mode": "image",
|
| 221 |
"mesh_path": str(mesh_path),
|
| 222 |
"processed_image_path": str(session_dir / "input_processed.png"),
|
| 223 |
"slat_path": None,
|
| 224 |
+
"slat_in_memory": False,
|
| 225 |
}
|
| 226 |
return (
|
| 227 |
state,
|
|
|
|
| 232 |
|
| 233 |
@GPU
|
| 234 |
@torch.inference_mode()
|
| 235 |
+
def _generate_slat_inner(
|
| 236 |
asset_state: Dict[str, Any],
|
| 237 |
image_input: Optional[Image.Image],
|
| 238 |
seed: int,
|
| 239 |
req: gr.Request,
|
| 240 |
progress=gr.Progress(track_tqdm=True),
|
| 241 |
):
|
| 242 |
+
"""GPU body for SLaT generation — must be called from within a @GPU context."""
|
|
|
|
|
|
|
| 243 |
if not asset_state or not asset_state.get("mesh_path"):
|
| 244 |
raise gr.Error("Please run ① Generate Mesh first.")
|
| 245 |
mesh_path = asset_state["mesh_path"]
|
|
|
|
| 257 |
slat_rgb = _flatten_rgba_on_matte(rgba, (0.0, 0.0, 0.0))
|
| 258 |
|
| 259 |
progress(0.3, desc="Computing SLaT coordinates")
|
| 260 |
+
coords = PIPELINE.shape_to_coords(mesh)
|
| 261 |
|
| 262 |
progress(0.6, desc="Generating SLaT")
|
| 263 |
+
slat = PIPELINE.run_with_coords([slat_rgb], coords, seed=int(seed), preprocess_image=False)
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
+
_SESSION_SLAT[str(req.session_hash)] = slat
|
| 266 |
+
new_state = {**asset_state, "slat_path": None, "slat_in_memory": True}
|
| 267 |
return new_state, f"**Asset ready** — SLaT generated (seed `{seed}`)."
|
| 268 |
|
| 269 |
|
| 270 |
+
def _load_slat_file_inner(slat_upload: Any, slat_path_text: str, req: gr.Request):
|
| 271 |
resolved = get_file_path(slat_upload) or (slat_path_text.strip() if slat_path_text else "")
|
| 272 |
if not resolved:
|
| 273 |
raise gr.Error("Please provide a SLaT `.npz` path or upload one.")
|
| 274 |
if not os.path.exists(resolved):
|
| 275 |
raise gr.Error(f"SLaT file not found: `{resolved}`")
|
| 276 |
+
_SESSION_SLAT.pop(str(req.session_hash), None)
|
| 277 |
+
state = {
|
| 278 |
+
"mode": "slat",
|
| 279 |
+
"slat_path": resolved,
|
| 280 |
+
"mesh_path": None,
|
| 281 |
+
"processed_image_path": None,
|
| 282 |
+
"slat_in_memory": False,
|
| 283 |
+
}
|
| 284 |
return state, f"SLaT **{Path(resolved).name}** loaded."
|
| 285 |
|
| 286 |
|
| 287 |
+
@GPU
|
| 288 |
+
@torch.inference_mode()
|
| 289 |
def prepare_slat(
|
| 290 |
source_mode: str,
|
| 291 |
asset_state: Dict[str, Any],
|
|
|
|
| 297 |
progress=gr.Progress(track_tqdm=True),
|
| 298 |
):
|
| 299 |
if source_mode == "From Image":
|
| 300 |
+
return _generate_slat_inner(asset_state, image_input, seed, req, progress)
|
| 301 |
+
return _load_slat_file_inner(slat_upload, slat_path_text, req)
|
| 302 |
|
| 303 |
|
| 304 |
def require_asset_state(asset_state: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
| 305 |
+
if not asset_state:
|
| 306 |
raise gr.Error("Please generate or load a SLaT first.")
|
| 307 |
+
if asset_state.get("slat_in_memory") or asset_state.get("slat_path"):
|
| 308 |
+
return asset_state
|
| 309 |
+
raise gr.Error("Please generate or load a SLaT first.")
|
| 310 |
|
| 311 |
|
| 312 |
+
def load_asset_and_hdri(asset_state: Dict[str, Any], hdri_file_obj: Any, req: gr.Request):
|
| 313 |
asset_state = require_asset_state(asset_state)
|
| 314 |
hdri_path = get_file_path(hdri_file_obj)
|
| 315 |
if not hdri_path:
|
| 316 |
raise gr.Error("Please upload an HDRI `.exr` file.")
|
| 317 |
+
if asset_state.get("slat_in_memory"):
|
| 318 |
+
slat = _SESSION_SLAT.get(str(req.session_hash))
|
| 319 |
+
if slat is None:
|
| 320 |
+
raise gr.Error("SLaT session expired — run **② Generate / Load SLaT** again.")
|
| 321 |
+
else:
|
| 322 |
+
slat_path = asset_state.get("slat_path")
|
| 323 |
+
if not slat_path:
|
| 324 |
+
raise gr.Error("Please generate or load a SLaT first.")
|
| 325 |
+
slat = PIPELINE.load_slat(slat_path)
|
| 326 |
+
hdri_np = PIPELINE.load_hdri(hdri_path)
|
| 327 |
+
return slat, hdri_np
|
| 328 |
|
| 329 |
|
| 330 |
@GPU
|
|
|
|
| 332 |
def render_preview(
|
| 333 |
asset_state: Dict[str, Any],
|
| 334 |
hdri_file_obj: Any,
|
|
|
|
| 335 |
hdri_rot: float,
|
| 336 |
yaw: float,
|
| 337 |
pitch: float,
|
|
|
|
| 342 |
progress=gr.Progress(track_tqdm=True),
|
| 343 |
):
|
| 344 |
t0 = time.time()
|
| 345 |
+
session_dir = CACHE_DIR / str(req.session_hash)
|
| 346 |
progress(0.1, desc="Loading SLaT and HDRI")
|
| 347 |
+
slat, hdri_np = load_asset_and_hdri(asset_state, hdri_file_obj, req)
|
| 348 |
|
| 349 |
progress(0.5, desc="Rendering")
|
| 350 |
+
views = PIPELINE.render_view(
|
| 351 |
slat, hdri_np,
|
| 352 |
yaw_deg=yaw, pitch_deg=pitch, fov=fov, radius=radius,
|
| 353 |
hdri_rot_deg=hdri_rot, resolution=int(resolution),
|
|
|
|
| 376 |
def render_camera_video(
|
| 377 |
asset_state: Dict[str, Any],
|
| 378 |
hdri_file_obj: Any,
|
|
|
|
| 379 |
hdri_rot: float,
|
| 380 |
fps: int,
|
| 381 |
num_views: int,
|
|
|
|
| 387 |
progress=gr.Progress(track_tqdm=True),
|
| 388 |
):
|
| 389 |
t0 = time.time()
|
| 390 |
+
session_dir = CACHE_DIR / str(req.session_hash)
|
| 391 |
progress(0.1, desc="Loading SLaT and HDRI")
|
| 392 |
+
slat, hdri_np = load_asset_and_hdri(asset_state, hdri_file_obj, req)
|
| 393 |
|
| 394 |
progress(0.4, desc="Rendering camera path")
|
| 395 |
+
frames = PIPELINE.render_camera_path_video(
|
| 396 |
slat, hdri_np,
|
| 397 |
num_views=int(num_views), fov=fov, radius=radius,
|
| 398 |
hdri_rot_deg=hdri_rot, full_video=full_video, shadow_video=shadow_video,
|
|
|
|
| 409 |
def render_hdri_video(
|
| 410 |
asset_state: Dict[str, Any],
|
| 411 |
hdri_file_obj: Any,
|
|
|
|
| 412 |
fps: int,
|
| 413 |
num_frames: int,
|
| 414 |
yaw: float,
|
|
|
|
| 421 |
progress=gr.Progress(track_tqdm=True),
|
| 422 |
):
|
| 423 |
t0 = time.time()
|
| 424 |
+
session_dir = CACHE_DIR / str(req.session_hash)
|
| 425 |
progress(0.1, desc="Loading SLaT and HDRI")
|
| 426 |
+
slat, hdri_np = load_asset_and_hdri(asset_state, hdri_file_obj, req)
|
| 427 |
|
| 428 |
progress(0.4, desc="Rendering HDRI rotation")
|
| 429 |
+
hdri_roll_frames, render_frames = PIPELINE.render_hdri_rotation_video(
|
| 430 |
slat, hdri_np,
|
| 431 |
num_frames=int(num_frames), yaw_deg=yaw, pitch_deg=pitch,
|
| 432 |
fov=fov, radius=radius, full_video=full_video, shadow_video=shadow_video,
|
|
|
|
| 444 |
def export_glb(
|
| 445 |
asset_state: Dict[str, Any],
|
| 446 |
hdri_file_obj: Any,
|
|
|
|
| 447 |
hdri_rot: float,
|
| 448 |
simplify: float,
|
| 449 |
texture_size: int,
|
|
|
|
| 451 |
progress=gr.Progress(track_tqdm=True),
|
| 452 |
):
|
| 453 |
t0 = time.time()
|
| 454 |
+
session_dir = CACHE_DIR / str(req.session_hash)
|
| 455 |
progress(0.1, desc="Loading SLaT and HDRI")
|
| 456 |
+
slat, hdri_np = load_asset_and_hdri(asset_state, hdri_file_obj, req)
|
| 457 |
|
| 458 |
progress(0.6, desc="Baking PBR textures")
|
| 459 |
+
glb = PIPELINE.export_glb_from_slat(
|
| 460 |
slat, hdri_np,
|
| 461 |
hdri_rot_deg=hdri_rot, base_mesh=None,
|
| 462 |
simplify=simplify, texture_size=int(texture_size), fill_holes=True,
|
|
|
|
| 751 |
value=str(DEFAULT_IMAGE) if DEFAULT_IMAGE.exists() else None,
|
| 752 |
height=400,
|
| 753 |
)
|
| 754 |
+
seed = gr.Slider(0, MAX_SEED, value=43, step=1, label="Seed (SLaT)")
|
| 755 |
mesh_button = gr.Button("① Generate Mesh", variant="primary", min_width=100)
|
| 756 |
|
| 757 |
with gr.Tab("SLaT", id=1):
|
|
|
|
| 807 |
gr.HTML("<div class='ctrl-strip-title'>Camera & HDRI</div>")
|
| 808 |
with gr.Row():
|
| 809 |
tone_mapper_name = gr.Dropdown(
|
| 810 |
+
choices=AVAILABLE_TONE_MAPPERS,
|
| 811 |
+
value="AgX",
|
| 812 |
label="Tone Mapper",
|
| 813 |
min_width=120,
|
|
|
|
| 814 |
)
|
| 815 |
hdri_rot = gr.Slider(0, 360, value=0, step=1, label="HDRI Rotation °")
|
| 816 |
resolution = gr.Slider(256, 1024, value=512, step=256, label="Preview Res")
|
|
|
|
| 820 |
fov = gr.Slider(10, 70, value=40, step=1, label="FoV")
|
| 821 |
radius = gr.Slider(1.0, 4.0, value=2.0, step=0.05, label="Radius")
|
| 822 |
|
| 823 |
+
tone_mapper_name.change(
|
| 824 |
+
set_tone_mapper,
|
| 825 |
+
inputs=[tone_mapper_name],
|
| 826 |
+
outputs=[],
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
with gr.Tabs(elem_classes=["main-output-tabs"]):
|
| 830 |
|
| 831 |
with gr.Tab("Geometry", id=0):
|
|
|
|
| 841 |
export_glb_button = gr.Button("Export PBR GLB", variant="primary", min_width=140)
|
| 842 |
|
| 843 |
with gr.Tab("Preview", id=1):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 844 |
preview_button = gr.Button("Render Preview", variant="primary", min_width=100)
|
| 845 |
gr.HTML("<hr class='divider'>")
|
| 846 |
with gr.Row():
|
|
|
|
| 915 |
else:
|
| 916 |
gr.Markdown("*No `.exr` examples in `assets/hdris`*")
|
| 917 |
|
| 918 |
+
demo.load(start_session)
|
| 919 |
demo.unload(end_session)
|
| 920 |
|
| 921 |
source_mode.change(switch_asset_source, inputs=[source_mode], outputs=[source_tabs])
|
|
|
|
| 928 |
outputs=[col_img_examples, col_slat_examples],
|
| 929 |
)
|
| 930 |
|
| 931 |
+
for _trigger in (hdri_file.upload, hdri_file.change):
|
| 932 |
_trigger(
|
| 933 |
preview_hdri,
|
| 934 |
+
inputs=[hdri_file],
|
| 935 |
outputs=[hdri_preview, status_md],
|
| 936 |
)
|
| 937 |
|
|
|
|
| 955 |
|
| 956 |
preview_button.click(
|
| 957 |
render_preview,
|
| 958 |
+
inputs=[asset_state, hdri_file, hdri_rot,
|
| 959 |
yaw, pitch, fov, radius, resolution],
|
| 960 |
outputs=[
|
| 961 |
color_output,
|
|
|
|
| 969 |
|
| 970 |
camera_video_button.click(
|
| 971 |
render_camera_video,
|
| 972 |
+
inputs=[asset_state, hdri_file, hdri_rot,
|
| 973 |
fps, num_views, fov, radius, full_video, shadow_video],
|
| 974 |
outputs=[camera_video_output, status_md],
|
| 975 |
)
|
| 976 |
|
| 977 |
hdri_video_button.click(
|
| 978 |
render_hdri_video,
|
| 979 |
+
inputs=[asset_state, hdri_file,
|
| 980 |
fps, num_frames, yaw, pitch, fov, radius, full_video, shadow_video],
|
| 981 |
outputs=[hdri_roll_video_output, hdri_render_video_output, status_md],
|
| 982 |
)
|
| 983 |
|
| 984 |
export_glb_button.click(
|
| 985 |
export_glb,
|
| 986 |
+
inputs=[asset_state, hdri_file, hdri_rot, simplify, texture_size],
|
| 987 |
outputs=[pbr_viewer, status_md],
|
| 988 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 989 |
return demo
|
| 990 |
|
| 991 |
|
| 992 |
demo = build_app()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 993 |
|
| 994 |
if __name__ == "__main__":
|
|
|
|
| 995 |
|
| 996 |
+
PIPELINE = NeARImageToRelightable3DPipeline.from_pretrained("luh0502/NeAR")
|
| 997 |
+
GEOMETRY_PIPELINE = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained("tencent/Hunyuan3D-2.1")
|
| 998 |
+
|
| 999 |
+
PIPELINE.to("cuda")
|
| 1000 |
+
GEOMETRY_PIPELINE.to("cuda")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1001 |
|
| 1002 |
demo.launch(
|
| 1003 |
+
mcp_server=True
|
|
|
|
|
|
|
| 1004 |
)
|
trellis/modules/sparse/basic.py
CHANGED
|
@@ -258,12 +258,8 @@ class SparseTensor:
|
|
| 258 |
)
|
| 259 |
new_data._caches = self.data._caches
|
| 260 |
elif BACKEND == 'spconv':
|
| 261 |
-
# Must store `feats` in the tensor that backs `.features`; only setting
|
| 262 |
-
# `_features` leaves `self.data.features` stale (breaks replace() callers
|
| 263 |
-
# that refresh feats, e.g. detach().clone() for inference tensors).
|
| 264 |
-
feats_storage = feats.reshape(feats.shape[0], -1).contiguous()
|
| 265 |
new_data = SparseTensorData(
|
| 266 |
-
|
| 267 |
self.data.indices,
|
| 268 |
self.data.spatial_shape,
|
| 269 |
self.data.batch_size,
|
|
|
|
| 258 |
)
|
| 259 |
new_data._caches = self.data._caches
|
| 260 |
elif BACKEND == 'spconv':
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
new_data = SparseTensorData(
|
| 262 |
+
self.data.features.reshape(self.data.features.shape[0], -1),
|
| 263 |
self.data.indices,
|
| 264 |
self.data.spatial_shape,
|
| 265 |
self.data.batch_size,
|
trellis/pipelines/near_image_to_relightable_3d.py
CHANGED
|
@@ -75,8 +75,9 @@ class NeARImageToRelightable3DPipeline(Pipeline):
|
|
| 75 |
|
| 76 |
def setup_tone_mapper(self, view: str = "AgX") -> None:
|
| 77 |
"""Initialize the tone mapper used for HDR-to-LDR conversion."""
|
| 78 |
-
self.
|
| 79 |
-
|
|
|
|
| 80 |
|
| 81 |
@staticmethod
|
| 82 |
def from_pretrained(path: str) -> "NeARImageToRelightable3DPipeline":
|
|
@@ -319,7 +320,7 @@ class NeARImageToRelightable3DPipeline(Pipeline):
|
|
| 319 |
@torch.no_grad()
|
| 320 |
def run_with_coords(
|
| 321 |
self,
|
| 322 |
-
image:
|
| 323 |
coords: torch.Tensor,
|
| 324 |
seed: int = 42,
|
| 325 |
preprocess_image: bool = True,
|
|
@@ -539,8 +540,6 @@ class NeARImageToRelightable3DPipeline(Pipeline):
|
|
| 539 |
hdri_roll_frames.append(ldr)
|
| 540 |
|
| 541 |
extr, intr = self.generate_camera(yaw_deg, pitch_deg, radius, fov)
|
| 542 |
-
extr = extr.to(self.device)
|
| 543 |
-
intr = intr.to(self.device)
|
| 544 |
hs, rfs = self.decoder_pbr_feats(slat)
|
| 545 |
render_frames: List[np.ndarray] = []
|
| 546 |
|
|
@@ -590,20 +589,17 @@ class NeARImageToRelightable3DPipeline(Pipeline):
|
|
| 590 |
fill_holes: bool = True,
|
| 591 |
) -> trimesh.Trimesh:
|
| 592 |
"""Export a textured PBR GLB, preferring an externally provided base mesh."""
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
raise ValueError(
|
| 602 |
-
"export_glb_from_slat requires `base_mesh` or pipeline model `slat_decoder_mesh`"
|
| 603 |
-
)
|
| 604 |
|
| 605 |
-
|
| 606 |
-
|
| 607 |
return render_utils_rl.to_glb(
|
| 608 |
self.models["renderer"],
|
| 609 |
hs,
|
|
|
|
| 75 |
|
| 76 |
def setup_tone_mapper(self, view: str = "AgX") -> None:
|
| 77 |
"""Initialize the tone mapper used for HDR-to-LDR conversion."""
|
| 78 |
+
# Construct with target view in one step so we never `del self.cpu` via the
|
| 79 |
+
# property setter without a successful rebuild (avoids missing `.cpu`).
|
| 80 |
+
self.tone_mapper = ToneMapper(view=view)
|
| 81 |
|
| 82 |
@staticmethod
|
| 83 |
def from_pretrained(path: str) -> "NeARImageToRelightable3DPipeline":
|
|
|
|
| 320 |
@torch.no_grad()
|
| 321 |
def run_with_coords(
|
| 322 |
self,
|
| 323 |
+
image: ImageInput,
|
| 324 |
coords: torch.Tensor,
|
| 325 |
seed: int = 42,
|
| 326 |
preprocess_image: bool = True,
|
|
|
|
| 540 |
hdri_roll_frames.append(ldr)
|
| 541 |
|
| 542 |
extr, intr = self.generate_camera(yaw_deg, pitch_deg, radius, fov)
|
|
|
|
|
|
|
| 543 |
hs, rfs = self.decoder_pbr_feats(slat)
|
| 544 |
render_frames: List[np.ndarray] = []
|
| 545 |
|
|
|
|
| 589 |
fill_holes: bool = True,
|
| 590 |
) -> trimesh.Trimesh:
|
| 591 |
"""Export a textured PBR GLB, preferring an externally provided base mesh."""
|
| 592 |
+
with torch.inference_mode():
|
| 593 |
+
if base_mesh is None and "slat_decoder_mesh" in self.models:
|
| 594 |
+
mesh_out = self.models["slat_decoder_mesh"](slat)
|
| 595 |
+
base_mesh = mesh_out[0] if isinstance(mesh_out, (list, tuple)) else mesh_out
|
| 596 |
+
if base_mesh is None:
|
| 597 |
+
raise ValueError(
|
| 598 |
+
"export_glb_from_slat requires `base_mesh` or pipeline model `slat_decoder_mesh`"
|
| 599 |
+
)
|
|
|
|
|
|
|
|
|
|
| 600 |
|
| 601 |
+
hdri_cond = self.encode_hdri(hdri_np, hdri_rot_deg)
|
| 602 |
+
hs, rfs = self.decoder_pbr_feats(slat)
|
| 603 |
return render_utils_rl.to_glb(
|
| 604 |
self.models["renderer"],
|
| 605 |
hs,
|