Spaces:
Sleeping
Sleeping
Deploy BASILISC Texture Worker
Browse files- NOTICE.md +10 -0
- README.md +44 -5
- app.py +398 -0
- requirements.txt +32 -0
NOTICE.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Third-party notices
|
| 2 |
+
|
| 3 |
+
BASILISC Texture Worker is an integration layer created for Death Kitty Gaming Studios.
|
| 4 |
+
|
| 5 |
+
It uses the open-source MV-Adapter project:
|
| 6 |
+
https://github.com/huanngzh/MV-Adapter
|
| 7 |
+
|
| 8 |
+
MV-Adapter is distributed under the Apache License 2.0. This bundle does not include MV-Adapter model weights; Hugging Face downloads them at runtime from their respective repositories.
|
| 9 |
+
|
| 10 |
+
Other runtime dependencies retain their own licenses. Review those licenses before commercial redistribution of a pre-bundled environment.
|
README.md
CHANGED
|
@@ -1,13 +1,52 @@
|
|
| 1 |
---
|
| 2 |
title: BASILISC Texture Worker
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version:
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: BASILISC Texture Worker
|
| 3 |
+
emoji: 🐉
|
| 4 |
+
colorFrom: gray
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.49.1
|
| 8 |
+
python_version: 3.10.13
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
+
license: apache-2.0
|
| 12 |
+
short_description: Reference-image 3D texturing for BASILISC
|
| 13 |
+
models:
|
| 14 |
+
- huanngzh/mv-adapter
|
| 15 |
+
- stabilityai/stable-diffusion-xl-base-1.0
|
| 16 |
+
- madebyollin/sdxl-vae-fp16-fix
|
| 17 |
+
- ZhengPeng7/BiRefNet
|
| 18 |
---
|
| 19 |
|
| 20 |
+
# BASILISC Texture Worker
|
| 21 |
+
|
| 22 |
+
ZeroGPU backend for **BASILISC Auto Materialer**.
|
| 23 |
+
|
| 24 |
+
It accepts an existing GLB mesh plus one reference image and returns a textured GLB using the open-source MV-Adapter image+geometry pipeline.
|
| 25 |
+
|
| 26 |
+
## Required Space setting
|
| 27 |
+
|
| 28 |
+
After creating/uploading this Space, open **Settings → Hardware** and select **ZeroGPU**.
|
| 29 |
+
|
| 30 |
+
The Blender add-on talks to the named Gradio API endpoint:
|
| 31 |
+
|
| 32 |
+
`/basilisc_texture`
|
| 33 |
+
|
| 34 |
+
## Attribution
|
| 35 |
+
|
| 36 |
+
This worker builds on MV-Adapter by Zehuan Huang et al. The upstream project is Apache-2.0 licensed. See `NOTICE.md`.
|
| 37 |
+
|
| 38 |
+
## One-command deployment from Linux
|
| 39 |
+
|
| 40 |
+
1. Create a Hugging Face **write** token.
|
| 41 |
+
2. Unzip this bundle.
|
| 42 |
+
3. In a terminal inside the folder, run:
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
bash deploy.sh YOUR_HF_USERNAME/BASILISC-Texture-Worker
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
The script securely prompts for your Hugging Face write token, creates a private deployment virtual environment inside this folder, installs the deployment client there, creates/updates the Gradio Space, uploads the worker files, and requests the `zero-a10g` (ZeroGPU) hardware flavor. It does not modify Linux Mint's system Python. If `python3-venv` is missing, the script will tell you exactly which `apt` command to run. If your account requires the hardware choice to be confirmed in the UI, open the Space's Settings page and select **ZeroGPU** there.
|
| 49 |
+
|
| 50 |
+
## Deployment troubleshooting
|
| 51 |
+
|
| 52 |
+
The deployment script validates the token before creating or uploading anything. It prints the authenticated Hugging Face username so you can verify that the repository namespace matches the account associated with the token. A Hugging Face User Access Token with **Write** permission is required to create or update the Space.
|
app.py
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import ctypes
|
| 4 |
+
import importlib
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import shutil
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import tempfile
|
| 11 |
+
import uuid
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import gradio as gr
|
| 15 |
+
import numpy as np
|
| 16 |
+
import spaces
|
| 17 |
+
import torch
|
| 18 |
+
from diffusers import AutoencoderKL, DDPMScheduler, LCMScheduler, UNet2DConditionModel
|
| 19 |
+
from huggingface_hub import hf_hub_download
|
| 20 |
+
from PIL import Image
|
| 21 |
+
from torchvision import transforms
|
| 22 |
+
from transformers import AutoModelForImageSegmentation
|
| 23 |
+
|
| 24 |
+
from mvadapter.models.attention_processor import DecoupledMVRowColSelfAttnProcessor2_0
|
| 25 |
+
from mvadapter.pipelines.pipeline_mvadapter_i2mv_sdxl import MVAdapterI2MVSDXLPipeline
|
| 26 |
+
from mvadapter.schedulers.scheduling_shift_snr import ShiftSNRScheduler
|
| 27 |
+
|
| 28 |
+
DEVICE = "cuda"
|
| 29 |
+
DTYPE = torch.float16
|
| 30 |
+
NUM_VIEWS = 6
|
| 31 |
+
HEIGHT = 768
|
| 32 |
+
WIDTH = 768
|
| 33 |
+
NEGATIVE = "watermark, ugly, deformed, noisy, blurry, low contrast"
|
| 34 |
+
ROOT = Path(__file__).resolve().parent
|
| 35 |
+
CHECKPOINTS = ROOT / "checkpoints"
|
| 36 |
+
OUTPUTS = ROOT / "outputs"
|
| 37 |
+
CHECKPOINTS.mkdir(exist_ok=True)
|
| 38 |
+
OUTPUTS.mkdir(exist_ok=True)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _prepare_pipeline():
|
| 42 |
+
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix")
|
| 43 |
+
pipe = MVAdapterI2MVSDXLPipeline.from_pretrained(
|
| 44 |
+
"stabilityai/stable-diffusion-xl-base-1.0", vae=vae
|
| 45 |
+
)
|
| 46 |
+
pipe.scheduler = ShiftSNRScheduler.from_scheduler(
|
| 47 |
+
pipe.scheduler, shift_mode="interpolated", shift_scale=8.0, scheduler_class=None
|
| 48 |
+
)
|
| 49 |
+
pipe.init_custom_adapter(
|
| 50 |
+
num_views=NUM_VIEWS,
|
| 51 |
+
self_attn_processor=DecoupledMVRowColSelfAttnProcessor2_0,
|
| 52 |
+
)
|
| 53 |
+
pipe.load_custom_adapter(
|
| 54 |
+
"huanngzh/mv-adapter", weight_name="mvadapter_ig2mv_sdxl.safetensors"
|
| 55 |
+
)
|
| 56 |
+
pipe.to(device=DEVICE, dtype=DTYPE)
|
| 57 |
+
pipe.cond_encoder.to(device=DEVICE, dtype=DTYPE)
|
| 58 |
+
pipe.enable_vae_slicing()
|
| 59 |
+
return pipe
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# ZeroGPU emulation allows model placement on CUDA during startup. This is the
|
| 63 |
+
# recommended pattern because the real GPU is attached only while @spaces.GPU
|
| 64 |
+
# functions execute.
|
| 65 |
+
PIPE = _prepare_pipeline()
|
| 66 |
+
BIREFNET = AutoModelForImageSegmentation.from_pretrained(
|
| 67 |
+
"ZhengPeng7/BiRefNet", trust_remote_code=True
|
| 68 |
+
).to(DEVICE)
|
| 69 |
+
BG_TRANSFORM = transforms.Compose(
|
| 70 |
+
[
|
| 71 |
+
transforms.Resize((1024, 1024)),
|
| 72 |
+
transforms.ToTensor(),
|
| 73 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
| 74 |
+
]
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _ensure_checkpoints():
|
| 79 |
+
real_esrgan = CHECKPOINTS / "RealESRGAN_x2plus.pth"
|
| 80 |
+
if not real_esrgan.exists():
|
| 81 |
+
hf_hub_download(
|
| 82 |
+
"dtarnow/UPscaler",
|
| 83 |
+
filename="RealESRGAN_x2plus.pth",
|
| 84 |
+
local_dir=str(CHECKPOINTS),
|
| 85 |
+
)
|
| 86 |
+
lama = CHECKPOINTS / "big-lama.pt"
|
| 87 |
+
if not lama.exists():
|
| 88 |
+
subprocess.check_call(
|
| 89 |
+
[
|
| 90 |
+
"wget", "-q", "-O", str(lama),
|
| 91 |
+
"https://github.com/Sanster/models/releases/download/add_big_lama/big-lama.pt",
|
| 92 |
+
]
|
| 93 |
+
)
|
| 94 |
+
return real_esrgan, lama
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
REAL_ESRGAN, BIG_LAMA = _ensure_checkpoints()
|
| 98 |
+
_NVD_READY = False
|
| 99 |
+
_TEXTURE_PIPE = None
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _cuda_home() -> str:
|
| 103 |
+
candidates = [
|
| 104 |
+
os.environ.get("CUDA_HOME"),
|
| 105 |
+
"/cuda-image/usr/local/cuda-13.0",
|
| 106 |
+
"/usr/local/cuda-13.0",
|
| 107 |
+
"/usr/local/cuda",
|
| 108 |
+
]
|
| 109 |
+
for item in candidates:
|
| 110 |
+
if item and os.path.isdir(item):
|
| 111 |
+
return item
|
| 112 |
+
return "/cuda-image/usr/local/cuda-13.0"
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _ensure_nvdiffrast():
|
| 116 |
+
"""Compile/load nvdiffrast for current ZeroGPU Blackwell/PyTorch ABI."""
|
| 117 |
+
global _NVD_READY
|
| 118 |
+
if _NVD_READY:
|
| 119 |
+
return
|
| 120 |
+
try:
|
| 121 |
+
import nvdiffrast.torch # noqa: F401
|
| 122 |
+
_NVD_READY = True
|
| 123 |
+
return
|
| 124 |
+
except Exception:
|
| 125 |
+
pass
|
| 126 |
+
|
| 127 |
+
cuda_home = _cuda_home()
|
| 128 |
+
patch_dir = tempfile.mkdtemp(prefix="basilisc_torch_cuda_patch_")
|
| 129 |
+
Path(patch_dir, "sitecustomize.py").write_text(
|
| 130 |
+
"try:\n"
|
| 131 |
+
" import torch.utils.cpp_extension as _c\n"
|
| 132 |
+
" _c._check_cuda_version = lambda *a, **k: None\n"
|
| 133 |
+
"except Exception:\n"
|
| 134 |
+
" pass\n",
|
| 135 |
+
encoding="utf-8",
|
| 136 |
+
)
|
| 137 |
+
env = os.environ.copy()
|
| 138 |
+
env["CUDA_HOME"] = cuda_home
|
| 139 |
+
env["CUDA_PATH"] = cuda_home
|
| 140 |
+
env["PATH"] = os.path.join(cuda_home, "bin") + os.pathsep + env.get("PATH", "")
|
| 141 |
+
env["PYTHONPATH"] = patch_dir + os.pathsep + env.get("PYTHONPATH", "")
|
| 142 |
+
env["TORCH_CUDA_ARCH_LIST"] = "12.0"
|
| 143 |
+
env["MAX_JOBS"] = "2"
|
| 144 |
+
subprocess.check_call(
|
| 145 |
+
[
|
| 146 |
+
sys.executable,
|
| 147 |
+
"-m",
|
| 148 |
+
"pip",
|
| 149 |
+
"install",
|
| 150 |
+
"--no-build-isolation",
|
| 151 |
+
"--no-deps",
|
| 152 |
+
"git+https://github.com/NVlabs/nvdiffrast/",
|
| 153 |
+
],
|
| 154 |
+
env=env,
|
| 155 |
+
)
|
| 156 |
+
importlib.invalidate_caches()
|
| 157 |
+
|
| 158 |
+
libdir = os.path.join(cuda_home, "lib64")
|
| 159 |
+
for libname in ("libcudart.so.13", "libcudart.so"):
|
| 160 |
+
lib = os.path.join(libdir, libname)
|
| 161 |
+
if os.path.exists(lib):
|
| 162 |
+
try:
|
| 163 |
+
ctypes.CDLL(lib, mode=ctypes.RTLD_GLOBAL)
|
| 164 |
+
break
|
| 165 |
+
except OSError:
|
| 166 |
+
pass
|
| 167 |
+
os.environ["LD_LIBRARY_PATH"] = libdir + os.pathsep + os.environ.get("LD_LIBRARY_PATH", "")
|
| 168 |
+
import nvdiffrast.torch # noqa: F401
|
| 169 |
+
_NVD_READY = True
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _remove_bg(image: Image.Image) -> Image.Image:
|
| 173 |
+
image = image.convert("RGB")
|
| 174 |
+
original_size = image.size
|
| 175 |
+
input_images = BG_TRANSFORM(image).unsqueeze(0).to(DEVICE)
|
| 176 |
+
with torch.no_grad():
|
| 177 |
+
preds = BIREFNET(input_images)[-1].sigmoid().cpu()
|
| 178 |
+
mask = transforms.ToPILImage()(preds[0].squeeze()).resize(original_size)
|
| 179 |
+
rgba = image.convert("RGBA")
|
| 180 |
+
rgba.putalpha(mask)
|
| 181 |
+
return rgba
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _preprocess_image(image: Image.Image, height: int, width: int) -> Image.Image:
|
| 185 |
+
arr = np.array(image.convert("RGBA"))
|
| 186 |
+
alpha = arr[..., 3] > 0
|
| 187 |
+
ys, xs = np.where(alpha)
|
| 188 |
+
if len(xs) == 0 or len(ys) == 0:
|
| 189 |
+
return Image.new("RGB", (width, height), (127, 127, 127))
|
| 190 |
+
y0, y1 = max(int(ys.min()) - 1, 0), min(int(ys.max()) + 2, arr.shape[0])
|
| 191 |
+
x0, x1 = max(int(xs.min()) - 1, 0), min(int(xs.max()) + 2, arr.shape[1])
|
| 192 |
+
crop = arr[y0:y1, x0:x1]
|
| 193 |
+
ch, cw = crop.shape[:2]
|
| 194 |
+
scale = min((height * 0.9) / max(ch, 1), (width * 0.9) / max(cw, 1))
|
| 195 |
+
nh, nw = max(1, int(ch * scale)), max(1, int(cw * scale))
|
| 196 |
+
crop = np.array(Image.fromarray(crop).resize((nw, nh), Image.Resampling.LANCZOS))
|
| 197 |
+
canvas = np.zeros((height, width, 4), dtype=np.uint8)
|
| 198 |
+
sy, sx = (height - nh) // 2, (width - nw) // 2
|
| 199 |
+
canvas[sy:sy + nh, sx:sx + nw] = crop
|
| 200 |
+
f = canvas.astype(np.float32) / 255.0
|
| 201 |
+
rgb = f[..., :3] * f[..., 3:4] + (1.0 - f[..., 3:4]) * 0.5
|
| 202 |
+
return Image.fromarray((rgb * 255).clip(0, 255).astype(np.uint8))
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _path(value) -> str:
|
| 206 |
+
if isinstance(value, str):
|
| 207 |
+
return value
|
| 208 |
+
if isinstance(value, dict):
|
| 209 |
+
return value.get("path") or value.get("name") or ""
|
| 210 |
+
return getattr(value, "name", "") or ""
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _run_multiview(mesh_path: str, image_path: str, prompt: str, seed: int, steps: int, ref_strength: float):
|
| 214 |
+
from mvadapter.utils import tensor_to_image
|
| 215 |
+
from mvadapter.utils.mesh_utils import (
|
| 216 |
+
NVDiffRastContextWrapper,
|
| 217 |
+
get_orthogonal_camera,
|
| 218 |
+
load_mesh,
|
| 219 |
+
render,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
cameras = get_orthogonal_camera(
|
| 223 |
+
elevation_deg=[0, 0, 0, 0, 89.99, -89.99],
|
| 224 |
+
distance=[1.8] * NUM_VIEWS,
|
| 225 |
+
left=-0.55,
|
| 226 |
+
right=0.55,
|
| 227 |
+
bottom=-0.55,
|
| 228 |
+
top=0.55,
|
| 229 |
+
azimuth_deg=[x - 90 for x in [0, 90, 180, 270, 180, 180]],
|
| 230 |
+
device=DEVICE,
|
| 231 |
+
)
|
| 232 |
+
ctx = NVDiffRastContextWrapper(device=DEVICE, context_type="cuda")
|
| 233 |
+
mesh = load_mesh(mesh_path, rescale=True, device=DEVICE)
|
| 234 |
+
render_out = render(
|
| 235 |
+
ctx,
|
| 236 |
+
mesh,
|
| 237 |
+
cameras,
|
| 238 |
+
height=HEIGHT,
|
| 239 |
+
width=WIDTH,
|
| 240 |
+
render_attr=False,
|
| 241 |
+
normal_background=0.0,
|
| 242 |
+
)
|
| 243 |
+
control_images = (
|
| 244 |
+
torch.cat(
|
| 245 |
+
[
|
| 246 |
+
(render_out.pos + 0.5).clamp(0, 1),
|
| 247 |
+
(render_out.normal / 2 + 0.5).clamp(0, 1),
|
| 248 |
+
],
|
| 249 |
+
dim=-1,
|
| 250 |
+
)
|
| 251 |
+
.permute(0, 3, 1, 2)
|
| 252 |
+
.to(DEVICE)
|
| 253 |
+
)
|
| 254 |
+
reference = _preprocess_image(_remove_bg(Image.open(image_path)), HEIGHT, WIDTH)
|
| 255 |
+
generator = torch.Generator(device=DEVICE).manual_seed(int(seed))
|
| 256 |
+
images = PIPE(
|
| 257 |
+
prompt or "high quality",
|
| 258 |
+
height=HEIGHT,
|
| 259 |
+
width=WIDTH,
|
| 260 |
+
num_inference_steps=int(steps),
|
| 261 |
+
guidance_scale=3.0,
|
| 262 |
+
num_images_per_prompt=NUM_VIEWS,
|
| 263 |
+
control_image=control_images,
|
| 264 |
+
control_conditioning_scale=1.0,
|
| 265 |
+
reference_image=reference,
|
| 266 |
+
reference_conditioning_scale=float(ref_strength),
|
| 267 |
+
negative_prompt=NEGATIVE,
|
| 268 |
+
cross_attention_kwargs={"scale": 1.0},
|
| 269 |
+
generator=generator,
|
| 270 |
+
).images
|
| 271 |
+
del control_images, render_out, mesh, cameras, ctx
|
| 272 |
+
torch.cuda.empty_cache()
|
| 273 |
+
return images
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _texture_pipeline():
|
| 277 |
+
global _TEXTURE_PIPE
|
| 278 |
+
if _TEXTURE_PIPE is not None:
|
| 279 |
+
return _TEXTURE_PIPE
|
| 280 |
+
|
| 281 |
+
# MV-Adapter defaults to an OpenGL raster context in the texture pipeline.
|
| 282 |
+
# ZeroGPU is headless, so patch those constructors to use CUDA rasterization.
|
| 283 |
+
import mvadapter.pipelines.pipeline_texture as pt
|
| 284 |
+
import mvadapter.utils.mesh_utils.projection as projection_mod
|
| 285 |
+
import mvadapter.utils.mesh_utils.render as render_mod
|
| 286 |
+
import mvadapter.utils.mesh_utils.smart_paint as smart_mod
|
| 287 |
+
|
| 288 |
+
OrigCtx = render_mod.NVDiffRastContextWrapper
|
| 289 |
+
OrigProjection = projection_mod.CameraProjection
|
| 290 |
+
|
| 291 |
+
class CudaCtx(OrigCtx):
|
| 292 |
+
def __init__(self, device: str, context_type: str = "cuda"):
|
| 293 |
+
super().__init__(device=device, context_type="cuda")
|
| 294 |
+
|
| 295 |
+
class CudaProjection(OrigProjection):
|
| 296 |
+
def __init__(self, pb_backend: str, bg_remover, device: str, context_type: str = "cuda"):
|
| 297 |
+
super().__init__(pb_backend=pb_backend, bg_remover=bg_remover, device=device, context_type="cuda")
|
| 298 |
+
|
| 299 |
+
render_mod.NVDiffRastContextWrapper = CudaCtx
|
| 300 |
+
projection_mod.NVDiffRastContextWrapper = CudaCtx
|
| 301 |
+
projection_mod.CameraProjection = CudaProjection
|
| 302 |
+
smart_mod.NVDiffRastContextWrapper = CudaCtx
|
| 303 |
+
smart_mod.CameraProjection = CudaProjection
|
| 304 |
+
pt.NVDiffRastContextWrapper = CudaCtx
|
| 305 |
+
pt.CameraProjection = CudaProjection
|
| 306 |
+
|
| 307 |
+
_TEXTURE_PIPE = pt.TexturePipeline(
|
| 308 |
+
upscaler_ckpt_path=str(REAL_ESRGAN),
|
| 309 |
+
inpaint_ckpt_path=str(BIG_LAMA),
|
| 310 |
+
device=DEVICE,
|
| 311 |
+
)
|
| 312 |
+
return _TEXTURE_PIPE
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
@spaces.GPU(duration=300)
|
| 316 |
+
@torch.no_grad()
|
| 317 |
+
def basilisc_texture(
|
| 318 |
+
mesh_file,
|
| 319 |
+
reference_file,
|
| 320 |
+
prompt="high quality",
|
| 321 |
+
seed=42,
|
| 322 |
+
steps=25,
|
| 323 |
+
reference_strength=1.0,
|
| 324 |
+
uv_unwrap=False,
|
| 325 |
+
uv_size=2048,
|
| 326 |
+
):
|
| 327 |
+
"""One-shot mesh + reference image -> textured GLB endpoint for Blender."""
|
| 328 |
+
_ensure_nvdiffrast()
|
| 329 |
+
mesh_path = _path(mesh_file)
|
| 330 |
+
image_path = _path(reference_file)
|
| 331 |
+
if not mesh_path or not os.path.isfile(mesh_path):
|
| 332 |
+
raise gr.Error("Input mesh file was not received")
|
| 333 |
+
if not image_path or not os.path.isfile(image_path):
|
| 334 |
+
raise gr.Error("Reference image file was not received")
|
| 335 |
+
|
| 336 |
+
steps = max(8, min(int(steps), 50))
|
| 337 |
+
uv_size = max(1024, min(int(uv_size), 4096))
|
| 338 |
+
# Texture projection operates best on 512-aligned sizes.
|
| 339 |
+
uv_size = int(round(uv_size / 512.0) * 512)
|
| 340 |
+
seed = int(seed) if int(seed) >= 0 else random.randint(0, 2_147_483_647)
|
| 341 |
+
|
| 342 |
+
job_dir = OUTPUTS / uuid.uuid4().hex
|
| 343 |
+
job_dir.mkdir(parents=True, exist_ok=True)
|
| 344 |
+
images = _run_multiview(mesh_path, image_path, prompt, seed, steps, reference_strength)
|
| 345 |
+
|
| 346 |
+
from mvadapter.utils import make_image_grid
|
| 347 |
+
from mvadapter.pipelines.pipeline_texture import ModProcessConfig
|
| 348 |
+
|
| 349 |
+
grid_path = job_dir / "multiview.png"
|
| 350 |
+
make_image_grid(images, rows=1).save(grid_path)
|
| 351 |
+
del images
|
| 352 |
+
torch.cuda.empty_cache()
|
| 353 |
+
|
| 354 |
+
tex = _texture_pipeline()
|
| 355 |
+
result = tex(
|
| 356 |
+
mesh_path=mesh_path,
|
| 357 |
+
save_dir=str(job_dir),
|
| 358 |
+
save_name="basilisc_texture",
|
| 359 |
+
uv_unwarp=bool(uv_unwrap),
|
| 360 |
+
preprocess_mesh=False,
|
| 361 |
+
uv_size=uv_size,
|
| 362 |
+
rgb_path=str(grid_path),
|
| 363 |
+
rgb_process_config=ModProcessConfig(view_upscale=True, inpaint_mode="view"),
|
| 364 |
+
camera_azimuth_deg=[x - 90 for x in [0, 90, 180, 270, 180, 180]],
|
| 365 |
+
)
|
| 366 |
+
torch.cuda.empty_cache()
|
| 367 |
+
output = result.shaded_model_save_path
|
| 368 |
+
if not output or not os.path.isfile(output):
|
| 369 |
+
raise gr.Error("Texture pipeline completed without a GLB output")
|
| 370 |
+
return output
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
with gr.Blocks(title="BASILISC Texture Worker") as demo:
|
| 374 |
+
gr.Markdown(
|
| 375 |
+
"# BASILISC Texture Worker\n"
|
| 376 |
+
"Reference image + existing mesh → MV-Adapter multi-view generation → baked GLB texture."
|
| 377 |
+
)
|
| 378 |
+
with gr.Row():
|
| 379 |
+
mesh = gr.File(label="Mesh (GLB)", file_types=[".glb"], type="filepath")
|
| 380 |
+
reference = gr.Image(label="Reference Image", type="filepath")
|
| 381 |
+
with gr.Accordion("Settings", open=False):
|
| 382 |
+
prompt = gr.Textbox(label="Prompt", value="high quality")
|
| 383 |
+
seed = gr.Number(label="Seed", value=42, precision=0)
|
| 384 |
+
steps = gr.Slider(8, 50, value=25, step=1, label="Diffusion Steps")
|
| 385 |
+
strength = gr.Slider(0.1, 2.0, value=1.0, step=0.05, label="Reference Strength")
|
| 386 |
+
uv_unwrap = gr.Checkbox(label="Generate New UVs", value=False)
|
| 387 |
+
uv_size = gr.Dropdown([1024, 2048, 4096], value=2048, label="Texture Size")
|
| 388 |
+
run = gr.Button("Texture Model", variant="primary")
|
| 389 |
+
output = gr.File(label="Textured GLB")
|
| 390 |
+
run.click(
|
| 391 |
+
fn=basilisc_texture,
|
| 392 |
+
inputs=[mesh, reference, prompt, seed, steps, strength, uv_unwrap, uv_size],
|
| 393 |
+
outputs=[output],
|
| 394 |
+
api_name="basilisc_texture",
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
if __name__ == "__main__":
|
| 398 |
+
demo.queue(default_concurrency_limit=1).launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.10.0
|
| 2 |
+
torchvision==0.25.0
|
| 3 |
+
diffusers==0.31.0
|
| 4 |
+
transformers==4.46.3
|
| 5 |
+
accelerate
|
| 6 |
+
safetensors
|
| 7 |
+
peft
|
| 8 |
+
numpy==1.26.2
|
| 9 |
+
scipy==1.11.4
|
| 10 |
+
einops
|
| 11 |
+
huggingface_hub
|
| 12 |
+
opencv-python
|
| 13 |
+
trimesh==4.5.3
|
| 14 |
+
omegaconf
|
| 15 |
+
scikit-image
|
| 16 |
+
jaxtyping
|
| 17 |
+
typeguard
|
| 18 |
+
pymeshlab==2022.2.post4
|
| 19 |
+
open3d
|
| 20 |
+
timm
|
| 21 |
+
kornia
|
| 22 |
+
ninja
|
| 23 |
+
cvcuda_cu12
|
| 24 |
+
gltflib
|
| 25 |
+
spandrel==0.4.1
|
| 26 |
+
controlnet_aux
|
| 27 |
+
sentencepiece
|
| 28 |
+
# Install the official MV-Adapter package at a pinned upstream commit.
|
| 29 |
+
git+https://github.com/huanngzh/MV-Adapter.git@4277e0018232bac82bb2c103caf0893cedb711be
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
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
|