github-actions[bot] commited on
Commit ·
b76c75b
1
Parent(s): c989fa6
Automated Deploy: 4a48a08c1c59fade83ab592f13334fff83760820
Browse files- app.py +373 -135
- visualizer.gpu.toml +3 -0
- visualizer.local.toml +3 -0
app.py
CHANGED
|
@@ -2,13 +2,14 @@ import asyncio
|
|
| 2 |
import base64
|
| 3 |
import hashlib
|
| 4 |
import io
|
| 5 |
-
import json
|
| 6 |
-
import os
|
| 7 |
-
import shutil
|
| 8 |
-
import time
|
| 9 |
-
import urllib.error
|
| 10 |
-
import urllib.parse
|
| 11 |
-
import urllib.request
|
|
|
|
| 12 |
try:
|
| 13 |
import tomllib
|
| 14 |
except ImportError:
|
|
@@ -27,9 +28,10 @@ from pathlib import Path
|
|
| 27 |
import cv2
|
| 28 |
import numpy as np
|
| 29 |
import torch
|
| 30 |
-
from fastapi import FastAPI, File, Form, HTTPException, Response, UploadFile, BackgroundTasks
|
| 31 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 32 |
-
from fastapi.
|
|
|
|
| 33 |
from PIL import Image
|
| 34 |
from transformers import (
|
| 35 |
AutoImageProcessor,
|
|
@@ -198,17 +200,35 @@ ENABLE_INTRINSIC_SHADING = str(config_value(
|
|
| 198 |
"enable_intrinsic_shading",
|
| 199 |
"0",
|
| 200 |
)).lower() in {"1", "true", "yes", "on"}
|
| 201 |
-
ENABLE_SHADING_TRANSFER = str(config_value(
|
| 202 |
-
"ENABLE_SHADING_TRANSFER",
|
| 203 |
-
"runtime",
|
| 204 |
-
"enable_shading_transfer",
|
| 205 |
-
"1",
|
| 206 |
-
)).lower() in {"1", "true", "yes", "on"}
|
| 207 |
-
|
| 208 |
-
"
|
| 209 |
-
"runtime",
|
| 210 |
-
"
|
| 211 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
))
|
| 213 |
GEMINI_API_KEY = str(config_value(
|
| 214 |
"GEMINI_API_KEY",
|
|
@@ -375,14 +395,17 @@ def hf_offline() -> bool:
|
|
| 375 |
return os.getenv("HF_HUB_OFFLINE") == "1" or os.getenv("TRANSFORMERS_OFFLINE") == "1"
|
| 376 |
|
| 377 |
|
| 378 |
-
def _load_segmentation_model():
|
| 379 |
-
global seg_processor, seg_model, segmentation_backend
|
| 380 |
-
|
| 381 |
-
if
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
|
|
|
|
|
|
|
|
|
| 386 |
local_files_only=hf_offline(),
|
| 387 |
)
|
| 388 |
seg_model = OneFormerForUniversalSegmentation.from_pretrained(
|
|
@@ -463,22 +486,100 @@ def _load_intrinsic_model():
|
|
| 463 |
from intrinsic.pipeline import load_models
|
| 464 |
intrinsic_models = load_models(INTRINSIC_MODEL_VERSION, device=str(device))
|
| 465 |
print("Intrinsic model loaded.", flush=True)
|
| 466 |
-
except Exception as exc:
|
| 467 |
-
print(f"Intrinsic model failed to load ({exc}). Falling back to luminance shading.", flush=True)
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
| 483 |
JOB_DIR.mkdir(parents=True, exist_ok=True)
|
| 484 |
MATERIAL_DIR.mkdir(parents=True, exist_ok=True)
|
|
@@ -513,41 +614,29 @@ def class_ids(names: set[str]) -> list[int]:
|
|
| 513 |
return [idx for idx, name in enumerate(ADE20K_CLASSES) if name in names]
|
| 514 |
|
| 515 |
|
| 516 |
-
def estimate_depth(img: Image.Image, width: int, height: int):
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
local_files_only=hf_offline(),
|
| 528 |
-
)
|
| 529 |
-
depth_model = AutoModelForDepthEstimation.from_pretrained(
|
| 530 |
-
model_name,
|
| 531 |
-
local_files_only=hf_offline(),
|
| 532 |
-
).to(device)
|
| 533 |
-
depth_model.eval()
|
| 534 |
-
print("Depth model loaded.", flush=True)
|
| 535 |
-
|
| 536 |
-
inputs = depth_processor(images=img, return_tensors="pt").to(device)
|
| 537 |
-
with torch.no_grad():
|
| 538 |
-
outputs = depth_model(**inputs)
|
| 539 |
depth = torch.nn.functional.interpolate(
|
| 540 |
outputs.predicted_depth.unsqueeze(1),
|
| 541 |
size=(height, width),
|
| 542 |
mode="bicubic",
|
| 543 |
align_corners=False,
|
| 544 |
-
).squeeze().cpu().numpy()
|
| 545 |
-
depth = cv2.GaussianBlur(depth.astype(np.float32), (0, 0), sigmaX=3)
|
| 546 |
-
if "metric" in
|
| 547 |
-
return depth
|
| 548 |
-
depth_min, depth_max = float(np.min(depth)), float(np.max(depth))
|
| 549 |
-
if depth_max - depth_min < 1e-6:
|
| 550 |
-
return None
|
| 551 |
return (depth - depth_min) / (depth_max - depth_min)
|
| 552 |
except Exception as exc:
|
| 553 |
print(f"Depth estimation skipped ({exc}).", flush=True)
|
|
@@ -560,24 +649,19 @@ def _to_numpy(value):
|
|
| 560 |
if isinstance(value, torch.Tensor):
|
| 561 |
return value.detach().float().cpu().numpy()
|
| 562 |
return np.asarray(value)
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
def estimate_moge_geometry(img_np: np.ndarray):
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
moge_model.
|
| 576 |
-
print("MoGe geometry model loaded.", flush=True)
|
| 577 |
-
|
| 578 |
-
image_tensor = torch.from_numpy(img_np.astype(np.float32) / 255.0).permute(2, 0, 1).to(device)
|
| 579 |
-
with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.float16):
|
| 580 |
-
output = moge_model.infer(image_tensor)
|
| 581 |
|
| 582 |
points = _to_numpy(output.get("points"))
|
| 583 |
depth = _to_numpy(output.get("depth"))
|
|
@@ -2821,19 +2905,152 @@ def build_tile_material_package(contents: bytes, base_roughness: float = 0.42) -
|
|
| 2821 |
}
|
| 2822 |
|
| 2823 |
|
| 2824 |
-
def material_map_urls(cache_key: str) -> dict[str, str]:
|
| 2825 |
-
return {
|
| 2826 |
-
"albedoMap": f"/materials/{cache_key}/albedo.png",
|
| 2827 |
-
"normalMap": f"/materials/{cache_key}/normal.png",
|
| 2828 |
-
"heightMap": f"/materials/{cache_key}/height.png",
|
| 2829 |
-
"roughnessMap": f"/materials/{cache_key}/roughness.png",
|
| 2830 |
-
"aoMap": f"/materials/{cache_key}/ao.png",
|
| 2831 |
-
"specularMap": f"/materials/{cache_key}/specular.png",
|
| 2832 |
-
}
|
| 2833 |
-
|
| 2834 |
-
|
| 2835 |
-
def
|
| 2836 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2837 |
|
| 2838 |
t0 = time.perf_counter()
|
| 2839 |
img = Image.open(io.BytesIO(contents)).convert("RGB")
|
|
@@ -2847,9 +3064,8 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 2847 |
print(f"[TIMING] Floor segmentation took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 2848 |
|
| 2849 |
t0 = time.perf_counter()
|
| 2850 |
-
|
| 2851 |
-
|
| 2852 |
-
print(f"[TIMING] Image RGBA encoding took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 2853 |
|
| 2854 |
t0 = time.perf_counter()
|
| 2855 |
primary_floor_ids = class_ids(PRIMARY_FLOOR_CLASSES)
|
|
@@ -3095,20 +3311,27 @@ def write_job(job: dict):
|
|
| 3095 |
job_path(job["id"]).write_text(json.dumps(job))
|
| 3096 |
|
| 3097 |
|
| 3098 |
-
def run_conversion_task(job_id: str, upload_path: Path):
|
| 3099 |
-
try:
|
| 3100 |
-
t_start = time.perf_counter()
|
| 3101 |
-
image_bytes = upload_path.read_bytes()
|
| 3102 |
-
bundle = build_segmentation_bundle(image_bytes)
|
| 3103 |
-
|
| 3104 |
-
|
| 3105 |
-
|
| 3106 |
-
|
| 3107 |
-
|
| 3108 |
-
|
| 3109 |
-
|
| 3110 |
-
|
| 3111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3112 |
try:
|
| 3113 |
job = read_job(job_id)
|
| 3114 |
job["status"] = "FAILED"
|
|
@@ -3307,18 +3530,33 @@ async def viz2d_job_status(job_id: str):
|
|
| 3307 |
|
| 3308 |
|
| 3309 |
@app.get("/viz2d/jobs/{job_id}/file")
|
| 3310 |
-
async def viz2d_job_file(job_id: str):
|
| 3311 |
-
job = read_job(job_id)
|
| 3312 |
-
if job.get("status") != "COMPLETED":
|
| 3313 |
-
raise HTTPException(status_code=409, detail="Job is not completed yet.")
|
| 3314 |
-
|
| 3315 |
-
if not
|
| 3316 |
-
raise HTTPException(status_code=404, detail="Job output not found.")
|
| 3317 |
-
return Response(
|
| 3318 |
-
content=
|
| 3319 |
-
media_type="application/
|
| 3320 |
-
headers={"Content-Disposition": 'attachment; filename="visualizer.vizbundle
|
| 3321 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3322 |
|
| 3323 |
|
| 3324 |
def build_oneformer_polygon_response(
|
|
|
|
| 2 |
import base64
|
| 3 |
import hashlib
|
| 4 |
import io
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import shutil
|
| 8 |
+
import time
|
| 9 |
+
import urllib.error
|
| 10 |
+
import urllib.parse
|
| 11 |
+
import urllib.request
|
| 12 |
+
import zipfile
|
| 13 |
try:
|
| 14 |
import tomllib
|
| 15 |
except ImportError:
|
|
|
|
| 28 |
import cv2
|
| 29 |
import numpy as np
|
| 30 |
import torch
|
| 31 |
+
from fastapi import FastAPI, File, Form, HTTPException, Response, UploadFile, BackgroundTasks
|
| 32 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 33 |
+
from fastapi.middleware.gzip import GZipMiddleware
|
| 34 |
+
from fastapi.staticfiles import StaticFiles
|
| 35 |
from PIL import Image
|
| 36 |
from transformers import (
|
| 37 |
AutoImageProcessor,
|
|
|
|
| 200 |
"enable_intrinsic_shading",
|
| 201 |
"0",
|
| 202 |
)).lower() in {"1", "true", "yes", "on"}
|
| 203 |
+
ENABLE_SHADING_TRANSFER = str(config_value(
|
| 204 |
+
"ENABLE_SHADING_TRANSFER",
|
| 205 |
+
"runtime",
|
| 206 |
+
"enable_shading_transfer",
|
| 207 |
+
"1",
|
| 208 |
+
)).lower() in {"1", "true", "yes", "on"}
|
| 209 |
+
WARM_START_MODELS = str(config_value(
|
| 210 |
+
"WARM_START_MODELS",
|
| 211 |
+
"runtime",
|
| 212 |
+
"warm_start_models",
|
| 213 |
+
"1",
|
| 214 |
+
)).lower() in {"1", "true", "yes", "on"}
|
| 215 |
+
BUNDLE_IMAGE_FORMAT = str(config_value(
|
| 216 |
+
"BUNDLE_IMAGE_FORMAT",
|
| 217 |
+
"runtime",
|
| 218 |
+
"bundle_image_format",
|
| 219 |
+
"jpeg",
|
| 220 |
+
)).lower()
|
| 221 |
+
BUNDLE_IMAGE_QUALITY = int(config_value(
|
| 222 |
+
"BUNDLE_IMAGE_QUALITY",
|
| 223 |
+
"runtime",
|
| 224 |
+
"bundle_image_quality",
|
| 225 |
+
"92",
|
| 226 |
+
))
|
| 227 |
+
VISUALIZER_DATA_DIR = str(config_value(
|
| 228 |
+
"VISUALIZER_DATA_DIR",
|
| 229 |
+
"runtime",
|
| 230 |
+
"data_dir",
|
| 231 |
+
"data",
|
| 232 |
))
|
| 233 |
GEMINI_API_KEY = str(config_value(
|
| 234 |
"GEMINI_API_KEY",
|
|
|
|
| 395 |
return os.getenv("HF_HUB_OFFLINE") == "1" or os.getenv("TRANSFORMERS_OFFLINE") == "1"
|
| 396 |
|
| 397 |
|
| 398 |
+
def _load_segmentation_model():
|
| 399 |
+
global seg_processor, seg_model, segmentation_backend
|
| 400 |
+
|
| 401 |
+
if seg_processor is not None and seg_model is not None:
|
| 402 |
+
return
|
| 403 |
+
|
| 404 |
+
if SEGMENTATION_MODEL == "oneformer":
|
| 405 |
+
try:
|
| 406 |
+
print(f"Loading OneFormer: {ONEFORMER_MODEL_NAME} ...", flush=True)
|
| 407 |
+
seg_processor = OneFormerProcessor.from_pretrained(
|
| 408 |
+
ONEFORMER_MODEL_NAME,
|
| 409 |
local_files_only=hf_offline(),
|
| 410 |
)
|
| 411 |
seg_model = OneFormerForUniversalSegmentation.from_pretrained(
|
|
|
|
| 486 |
from intrinsic.pipeline import load_models
|
| 487 |
intrinsic_models = load_models(INTRINSIC_MODEL_VERSION, device=str(device))
|
| 488 |
print("Intrinsic model loaded.", flush=True)
|
| 489 |
+
except Exception as exc:
|
| 490 |
+
print(f"Intrinsic model failed to load ({exc}). Falling back to luminance shading.", flush=True)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def _load_depth_model() -> bool:
|
| 494 |
+
global depth_processor, depth_model
|
| 495 |
+
if not ENABLE_DEPTH_ESTIMATION:
|
| 496 |
+
return False
|
| 497 |
+
if depth_processor is not None and depth_model is not None:
|
| 498 |
+
return True
|
| 499 |
+
|
| 500 |
+
print(f"Loading depth model: {DEPTH_MODEL_NAME} ...", flush=True)
|
| 501 |
+
depth_processor = AutoImageProcessor.from_pretrained(
|
| 502 |
+
DEPTH_MODEL_NAME,
|
| 503 |
+
local_files_only=hf_offline(),
|
| 504 |
+
)
|
| 505 |
+
depth_model = AutoModelForDepthEstimation.from_pretrained(
|
| 506 |
+
DEPTH_MODEL_NAME,
|
| 507 |
+
local_files_only=hf_offline(),
|
| 508 |
+
).to(device)
|
| 509 |
+
depth_model.eval()
|
| 510 |
+
print("Depth model loaded.", flush=True)
|
| 511 |
+
return True
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def _load_moge_model() -> bool:
|
| 515 |
+
global moge_model
|
| 516 |
+
if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or device.type != "cuda":
|
| 517 |
+
return False
|
| 518 |
+
if moge_model is not None:
|
| 519 |
+
return True
|
| 520 |
+
|
| 521 |
+
print(f"Loading MoGe geometry model: {MOGE_MODEL_NAME} ...", flush=True)
|
| 522 |
+
from moge.model.v2 import MoGeModel
|
| 523 |
+
moge_model = MoGeModel.from_pretrained(MOGE_MODEL_NAME).to(device)
|
| 524 |
+
moge_model.eval()
|
| 525 |
+
print("MoGe geometry model loaded.", flush=True)
|
| 526 |
+
return True
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def warm_start_models():
|
| 530 |
+
if not WARM_START_MODELS:
|
| 531 |
+
print("Model warm start disabled; models will load on first use.", flush=True)
|
| 532 |
+
return
|
| 533 |
+
|
| 534 |
+
t_start = time.perf_counter()
|
| 535 |
+
print(f"Warm-starting visualizer models on {device} ...", flush=True)
|
| 536 |
+
|
| 537 |
+
_load_segmentation_model()
|
| 538 |
+
|
| 539 |
+
moge_loaded = False
|
| 540 |
+
if ENABLE_MOGE_GEOMETRY and GEOMETRY_MODEL == "moge":
|
| 541 |
+
try:
|
| 542 |
+
moge_loaded = _load_moge_model()
|
| 543 |
+
except Exception as exc:
|
| 544 |
+
print(f"MoGe warm start skipped ({exc}); depth fallback may be used.", flush=True)
|
| 545 |
+
if device.type == "cuda":
|
| 546 |
+
torch.cuda.empty_cache()
|
| 547 |
+
|
| 548 |
+
if ENABLE_DEPTH_ESTIMATION and not moge_loaded:
|
| 549 |
+
try:
|
| 550 |
+
_load_depth_model()
|
| 551 |
+
except Exception as exc:
|
| 552 |
+
print(f"Depth model warm start skipped ({exc}); depth will be retried on first use.", flush=True)
|
| 553 |
+
if device.type == "cuda":
|
| 554 |
+
torch.cuda.empty_cache()
|
| 555 |
+
|
| 556 |
+
if ENABLE_SAM_REFINEMENT:
|
| 557 |
+
_load_sam2_predictor()
|
| 558 |
+
|
| 559 |
+
if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING:
|
| 560 |
+
_load_intrinsic_model()
|
| 561 |
+
|
| 562 |
+
print(f"[TIMING] Model warm start took {time.perf_counter() - t_start:.3f} seconds", flush=True)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
app = FastAPI()
|
| 566 |
+
app.add_middleware(
|
| 567 |
+
CORSMiddleware,
|
| 568 |
+
allow_origins=["*"],
|
| 569 |
+
allow_methods=["*"],
|
| 570 |
+
allow_headers=["*"],
|
| 571 |
+
)
|
| 572 |
+
app.add_middleware(GZipMiddleware, minimum_size=1024)
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
@app.on_event("startup")
|
| 576 |
+
def startup_warm_start_models():
|
| 577 |
+
warm_start_models()
|
| 578 |
+
|
| 579 |
+
DATA_DIR = Path(VISUALIZER_DATA_DIR).resolve()
|
| 580 |
+
UPLOAD_DIR = DATA_DIR / "uploads"
|
| 581 |
+
JOB_DIR = DATA_DIR / "jobs"
|
| 582 |
+
MATERIAL_DIR = DATA_DIR / "materials"
|
| 583 |
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
| 584 |
JOB_DIR.mkdir(parents=True, exist_ok=True)
|
| 585 |
MATERIAL_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 614 |
return [idx for idx, name in enumerate(ADE20K_CLASSES) if name in names]
|
| 615 |
|
| 616 |
|
| 617 |
+
def estimate_depth(img: Image.Image, width: int, height: int):
|
| 618 |
+
if not ENABLE_DEPTH_ESTIMATION:
|
| 619 |
+
return None
|
| 620 |
+
|
| 621 |
+
try:
|
| 622 |
+
if not _load_depth_model():
|
| 623 |
+
return None
|
| 624 |
+
|
| 625 |
+
inputs = depth_processor(images=img, return_tensors="pt").to(device)
|
| 626 |
+
with torch.no_grad():
|
| 627 |
+
outputs = depth_model(**inputs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 628 |
depth = torch.nn.functional.interpolate(
|
| 629 |
outputs.predicted_depth.unsqueeze(1),
|
| 630 |
size=(height, width),
|
| 631 |
mode="bicubic",
|
| 632 |
align_corners=False,
|
| 633 |
+
).squeeze().cpu().numpy()
|
| 634 |
+
depth = cv2.GaussianBlur(depth.astype(np.float32), (0, 0), sigmaX=3)
|
| 635 |
+
if "metric" in DEPTH_MODEL_NAME.lower():
|
| 636 |
+
return depth
|
| 637 |
+
depth_min, depth_max = float(np.min(depth)), float(np.max(depth))
|
| 638 |
+
if depth_max - depth_min < 1e-6:
|
| 639 |
+
return None
|
| 640 |
return (depth - depth_min) / (depth_max - depth_min)
|
| 641 |
except Exception as exc:
|
| 642 |
print(f"Depth estimation skipped ({exc}).", flush=True)
|
|
|
|
| 649 |
if isinstance(value, torch.Tensor):
|
| 650 |
return value.detach().float().cpu().numpy()
|
| 651 |
return np.asarray(value)
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def estimate_moge_geometry(img_np: np.ndarray):
|
| 655 |
+
if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or device.type != "cuda":
|
| 656 |
+
return None
|
| 657 |
+
|
| 658 |
+
try:
|
| 659 |
+
if not _load_moge_model():
|
| 660 |
+
return None
|
| 661 |
+
|
| 662 |
+
image_tensor = torch.from_numpy(img_np.astype(np.float32) / 255.0).permute(2, 0, 1).to(device)
|
| 663 |
+
with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.float16):
|
| 664 |
+
output = moge_model.infer(image_tensor)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 665 |
|
| 666 |
points = _to_numpy(output.get("points"))
|
| 667 |
depth = _to_numpy(output.get("depth"))
|
|
|
|
| 2905 |
}
|
| 2906 |
|
| 2907 |
|
| 2908 |
+
def material_map_urls(cache_key: str) -> dict[str, str]:
|
| 2909 |
+
return {
|
| 2910 |
+
"albedoMap": f"/materials/{cache_key}/albedo.png",
|
| 2911 |
+
"normalMap": f"/materials/{cache_key}/normal.png",
|
| 2912 |
+
"heightMap": f"/materials/{cache_key}/height.png",
|
| 2913 |
+
"roughnessMap": f"/materials/{cache_key}/roughness.png",
|
| 2914 |
+
"aoMap": f"/materials/{cache_key}/ao.png",
|
| 2915 |
+
"specularMap": f"/materials/{cache_key}/specular.png",
|
| 2916 |
+
}
|
| 2917 |
+
|
| 2918 |
+
|
| 2919 |
+
def encode_bundle_image_data_url(img_np: np.ndarray) -> str:
|
| 2920 |
+
image_format = BUNDLE_IMAGE_FORMAT
|
| 2921 |
+
if image_format in {"jpg", "jpeg"}:
|
| 2922 |
+
pil_format = "JPEG"
|
| 2923 |
+
mime_type = "image/jpeg"
|
| 2924 |
+
extension = "jpg"
|
| 2925 |
+
elif image_format == "webp":
|
| 2926 |
+
pil_format = "WEBP"
|
| 2927 |
+
mime_type = "image/webp"
|
| 2928 |
+
extension = "webp"
|
| 2929 |
+
else:
|
| 2930 |
+
pil_format = "JPEG"
|
| 2931 |
+
mime_type = "image/jpeg"
|
| 2932 |
+
extension = "jpg"
|
| 2933 |
+
|
| 2934 |
+
image = Image.fromarray(img_np.astype(np.uint8))
|
| 2935 |
+
buffer = io.BytesIO()
|
| 2936 |
+
try:
|
| 2937 |
+
save_kwargs = {
|
| 2938 |
+
"quality": int(np.clip(BUNDLE_IMAGE_QUALITY, 1, 100)),
|
| 2939 |
+
"optimize": True,
|
| 2940 |
+
}
|
| 2941 |
+
if pil_format == "WEBP":
|
| 2942 |
+
save_kwargs["method"] = 4
|
| 2943 |
+
image.save(buffer, format=pil_format, **save_kwargs)
|
| 2944 |
+
except Exception as exc:
|
| 2945 |
+
print(f"Bundle {extension} encoding failed ({exc}); falling back to JPEG.", flush=True)
|
| 2946 |
+
buffer = io.BytesIO()
|
| 2947 |
+
image.save(buffer, format="JPEG", quality=92, optimize=True)
|
| 2948 |
+
mime_type = "image/jpeg"
|
| 2949 |
+
|
| 2950 |
+
encoded = base64.b64encode(buffer.getvalue()).decode()
|
| 2951 |
+
return f"data:{mime_type};base64,{encoded}"
|
| 2952 |
+
|
| 2953 |
+
|
| 2954 |
+
def data_url_to_bytes(value: str) -> tuple[str, bytes]:
|
| 2955 |
+
if value.startswith("data:"):
|
| 2956 |
+
header, encoded = value.split(",", 1)
|
| 2957 |
+
mime_type = header[5:].split(";", 1)[0] or "application/octet-stream"
|
| 2958 |
+
return mime_type, base64.b64decode(encoded)
|
| 2959 |
+
return "application/octet-stream", base64.b64decode(value)
|
| 2960 |
+
|
| 2961 |
+
|
| 2962 |
+
def bundle_image_extension(mime_type: str) -> str:
|
| 2963 |
+
if mime_type == "image/webp":
|
| 2964 |
+
return "webp"
|
| 2965 |
+
if mime_type == "image/png":
|
| 2966 |
+
return "png"
|
| 2967 |
+
return "jpg"
|
| 2968 |
+
|
| 2969 |
+
|
| 2970 |
+
def make_binary_ref(path: str, data: bytes, dtype: str) -> dict:
|
| 2971 |
+
return {
|
| 2972 |
+
"path": path,
|
| 2973 |
+
"dtype": dtype,
|
| 2974 |
+
"byteLength": len(data),
|
| 2975 |
+
}
|
| 2976 |
+
|
| 2977 |
+
|
| 2978 |
+
def build_manifest_segmentation_bundle(
|
| 2979 |
+
bundle: dict,
|
| 2980 |
+
job_id: str,
|
| 2981 |
+
*,
|
| 2982 |
+
image_url: str | None = None,
|
| 2983 |
+
include_image: bool = False,
|
| 2984 |
+
) -> bytes:
|
| 2985 |
+
metadata = dict(bundle)
|
| 2986 |
+
metadata["format"] = "baetes-vizbundle"
|
| 2987 |
+
metadata["bundleVersion"] = 2
|
| 2988 |
+
metadata["encoding"] = "zip-store"
|
| 2989 |
+
metadata["assetBaseUrl"] = f"/viz2d/jobs/{job_id}/assets/"
|
| 2990 |
+
metadata["pixels"] = None
|
| 2991 |
+
if image_url:
|
| 2992 |
+
metadata["imageUrl"] = image_url
|
| 2993 |
+
metadata["segments"] = []
|
| 2994 |
+
asset_dir = JOB_DIR / f"{job_id}.assets"
|
| 2995 |
+
asset_dir.mkdir(parents=True, exist_ok=True)
|
| 2996 |
+
|
| 2997 |
+
buffer = io.BytesIO()
|
| 2998 |
+
with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_STORED) as archive:
|
| 2999 |
+
if include_image:
|
| 3000 |
+
pixels_mime, pixels = data_url_to_bytes(bundle["pixels"])
|
| 3001 |
+
image_path = f"image.{bundle_image_extension(pixels_mime)}"
|
| 3002 |
+
archive.writestr(image_path, pixels)
|
| 3003 |
+
metadata["pixels"] = {
|
| 3004 |
+
"path": image_path,
|
| 3005 |
+
"mimeType": pixels_mime,
|
| 3006 |
+
"byteLength": len(pixels),
|
| 3007 |
+
}
|
| 3008 |
+
|
| 3009 |
+
manifest_fields = {
|
| 3010 |
+
"mask": ("mask.u32", "uint32"),
|
| 3011 |
+
}
|
| 3012 |
+
lazy_asset_fields = {
|
| 3013 |
+
"surfaceUv": ("surface-uv.f32", "float32"),
|
| 3014 |
+
"surfacePlaneIds": ("surface-plane-ids.u8", "uint8"),
|
| 3015 |
+
"shadeMap": ("shade.u8", "uint8"),
|
| 3016 |
+
"showroomShadeMap": ("showroom-shade.u8", "uint8"),
|
| 3017 |
+
"reflectionMap": ("reflection.u8", "uint8"),
|
| 3018 |
+
}
|
| 3019 |
+
|
| 3020 |
+
for segment_index, segment in enumerate(bundle.get("segments", [])):
|
| 3021 |
+
segment_metadata = dict(segment)
|
| 3022 |
+
for field, (filename, dtype) in manifest_fields.items():
|
| 3023 |
+
value = segment.get(field)
|
| 3024 |
+
if not value:
|
| 3025 |
+
continue
|
| 3026 |
+
data = base64.b64decode(value)
|
| 3027 |
+
path = f"segments/{segment_index}/{filename}"
|
| 3028 |
+
archive.writestr(path, data)
|
| 3029 |
+
segment_metadata[field] = make_binary_ref(path, data, dtype)
|
| 3030 |
+
for field, (filename, dtype) in lazy_asset_fields.items():
|
| 3031 |
+
value = segment.get(field)
|
| 3032 |
+
if not value:
|
| 3033 |
+
continue
|
| 3034 |
+
data = base64.b64decode(value)
|
| 3035 |
+
asset_name = f"s{segment_index}-{filename}"
|
| 3036 |
+
(asset_dir / asset_name).write_bytes(data)
|
| 3037 |
+
segment_metadata[field] = {
|
| 3038 |
+
**make_binary_ref(asset_name, data, dtype),
|
| 3039 |
+
"url": f"/viz2d/jobs/{job_id}/assets/{asset_name}",
|
| 3040 |
+
"lazy": True,
|
| 3041 |
+
}
|
| 3042 |
+
metadata["segments"].append(segment_metadata)
|
| 3043 |
+
|
| 3044 |
+
archive.writestr(
|
| 3045 |
+
"metadata.json",
|
| 3046 |
+
json.dumps(metadata, separators=(",", ":")).encode("utf-8"),
|
| 3047 |
+
)
|
| 3048 |
+
|
| 3049 |
+
return buffer.getvalue()
|
| 3050 |
+
|
| 3051 |
+
|
| 3052 |
+
def build_segmentation_bundle(contents: bytes):
|
| 3053 |
+
t_start = time.perf_counter()
|
| 3054 |
|
| 3055 |
t0 = time.perf_counter()
|
| 3056 |
img = Image.open(io.BytesIO(contents)).convert("RGB")
|
|
|
|
| 3064 |
print(f"[TIMING] Floor segmentation took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 3065 |
|
| 3066 |
t0 = time.perf_counter()
|
| 3067 |
+
pixels_b64 = encode_bundle_image_data_url(img_np)
|
| 3068 |
+
print(f"[TIMING] Image bundle encoding took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
|
|
|
| 3069 |
|
| 3070 |
t0 = time.perf_counter()
|
| 3071 |
primary_floor_ids = class_ids(PRIMARY_FLOOR_CLASSES)
|
|
|
|
| 3311 |
job_path(job["id"]).write_text(json.dumps(job))
|
| 3312 |
|
| 3313 |
|
| 3314 |
+
def run_conversion_task(job_id: str, upload_path: Path):
|
| 3315 |
+
try:
|
| 3316 |
+
t_start = time.perf_counter()
|
| 3317 |
+
image_bytes = upload_path.read_bytes()
|
| 3318 |
+
bundle = build_segmentation_bundle(image_bytes)
|
| 3319 |
+
binary_bundle = build_manifest_segmentation_bundle(
|
| 3320 |
+
bundle,
|
| 3321 |
+
job_id,
|
| 3322 |
+
image_url=f"/uploads/{upload_path.name}",
|
| 3323 |
+
include_image=False,
|
| 3324 |
+
)
|
| 3325 |
+
(JOB_DIR / f"{job_id}.vizbundle").write_bytes(binary_bundle)
|
| 3326 |
+
job = read_job(job_id)
|
| 3327 |
+
job["status"] = "COMPLETED"
|
| 3328 |
+
job["modelName"] = bundle.get("modelName")
|
| 3329 |
+
job["models"] = bundle.get("models")
|
| 3330 |
+
job["outputFormat"] = "split-vizbundle"
|
| 3331 |
+
write_job(job)
|
| 3332 |
+
print(f"[TIMING] Background conversion task for job {job_id} took {time.perf_counter() - t_start:.3f} seconds", flush=True)
|
| 3333 |
+
except Exception as exc:
|
| 3334 |
+
print(f"Background conversion failed: {exc}", flush=True)
|
| 3335 |
try:
|
| 3336 |
job = read_job(job_id)
|
| 3337 |
job["status"] = "FAILED"
|
|
|
|
| 3530 |
|
| 3531 |
|
| 3532 |
@app.get("/viz2d/jobs/{job_id}/file")
|
| 3533 |
+
async def viz2d_job_file(job_id: str):
|
| 3534 |
+
job = read_job(job_id)
|
| 3535 |
+
if job.get("status") != "COMPLETED":
|
| 3536 |
+
raise HTTPException(status_code=409, detail="Job is not completed yet.")
|
| 3537 |
+
binary_bundle_path = JOB_DIR / f"{job_id}.vizbundle"
|
| 3538 |
+
if not binary_bundle_path.exists():
|
| 3539 |
+
raise HTTPException(status_code=404, detail="Job output not found.")
|
| 3540 |
+
return Response(
|
| 3541 |
+
content=binary_bundle_path.read_bytes(),
|
| 3542 |
+
media_type="application/zip",
|
| 3543 |
+
headers={"Content-Disposition": 'attachment; filename="visualizer.vizbundle"'},
|
| 3544 |
+
)
|
| 3545 |
+
|
| 3546 |
+
|
| 3547 |
+
@app.get("/viz2d/jobs/{job_id}/assets/{asset_name}")
|
| 3548 |
+
async def viz2d_job_asset(job_id: str, asset_name: str):
|
| 3549 |
+
read_job(job_id)
|
| 3550 |
+
if Path(asset_name).name != asset_name:
|
| 3551 |
+
raise HTTPException(status_code=400, detail="Invalid asset name.")
|
| 3552 |
+
asset_path = JOB_DIR / f"{job_id}.assets" / asset_name
|
| 3553 |
+
if not asset_path.exists() or not asset_path.is_file():
|
| 3554 |
+
raise HTTPException(status_code=404, detail="Job asset not found.")
|
| 3555 |
+
return Response(
|
| 3556 |
+
content=asset_path.read_bytes(),
|
| 3557 |
+
media_type="application/octet-stream",
|
| 3558 |
+
headers={"Cache-Control": "private, max-age=3600"},
|
| 3559 |
+
)
|
| 3560 |
|
| 3561 |
|
| 3562 |
def build_oneformer_polygon_response(
|
visualizer.gpu.toml
CHANGED
|
@@ -24,6 +24,9 @@ enable_intrinsic_shading = true
|
|
| 24 |
enable_shading_transfer = true
|
| 25 |
enable_sam_refinement = false
|
| 26 |
enable_floor_mask_cleanup = false
|
|
|
|
|
|
|
|
|
|
| 27 |
data_dir = "data"
|
| 28 |
|
| 29 |
[surface_mapping]
|
|
|
|
| 24 |
enable_shading_transfer = true
|
| 25 |
enable_sam_refinement = false
|
| 26 |
enable_floor_mask_cleanup = false
|
| 27 |
+
warm_start_models = true
|
| 28 |
+
bundle_image_format = "jpeg"
|
| 29 |
+
bundle_image_quality = 92
|
| 30 |
data_dir = "data"
|
| 31 |
|
| 32 |
[surface_mapping]
|
visualizer.local.toml
CHANGED
|
@@ -17,6 +17,9 @@ enable_multi_plane_surfaces = true
|
|
| 17 |
enable_intrinsic_shading = false
|
| 18 |
enable_shading_transfer = true
|
| 19 |
enable_sam_refinement = false
|
|
|
|
|
|
|
|
|
|
| 20 |
data_dir = "data"
|
| 21 |
|
| 22 |
[surface_mapping]
|
|
|
|
| 17 |
enable_intrinsic_shading = false
|
| 18 |
enable_shading_transfer = true
|
| 19 |
enable_sam_refinement = false
|
| 20 |
+
warm_start_models = true
|
| 21 |
+
bundle_image_format = "jpeg"
|
| 22 |
+
bundle_image_quality = 92
|
| 23 |
data_dir = "data"
|
| 24 |
|
| 25 |
[surface_mapping]
|