Delete app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812import os
HERE = os.path.dirname(os.path.abspath(__file__))os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")os.environ.setdefault("ATTN_BACKEND", "flash_attn")os.environ.setdefault("FLEX_GEMM_AUTOTUNE_CACHE_PATH", os.path.join(HERE, "autotune_cache.json"))
import spaces # before torch
import gcimport jsonimport randomimport tempfileimport threadingimport timeimport uuidfrom functools import partial, wrapsfrom pathlib import Path
import gradio as grimport numpy as npimport torchfrom gradio_client import Client, handle_filefrom gradio_client.utils import Statusfrom huggingface_hub import snapshot_downloadfrom PIL import Image, ImageOps
import cumeshimport cumesh.remeshingfrom uniforge3d import UniForge3DImageTo3DPipelinefrom uniforge3d.models.lora import LoRALinearfrom uniforge3d.representations.mesh import base as _mesh_base
import agent_apiimport agent_bannerimport model_view as mvimport cutoutimport progress_panel as pp
MODEL_ID = "xibushu/UniForge3D"# The official config points at two gated repos; use open equivalents.DINO_ID = "camenduru/dinov3-vitl16-pretrain-lvd1689m" # mirror of facebook/dinov3-vitl16-pretrain-lvd1689mREMBG_ID = "ZhengPeng7/BiRefNet" # same architecture as briaai/RMBG-2.0MAX_SEED = 2**31 - 1OUT_DIR = Path(tempfile.gettempdir()) / "uniforge3d-outputs"OUT_DIR.mkdir(parents=True, exist_ok=True)pp.THUMB_DIR = OUT_DIR / "thumbs"
# Text-to-image and camera re-angling run on existing ZeroGPU Spaces, called with the# visitor's own ZeroGPU token so their quota is used, not this Space's.T2I_SPACES = ["krea/Krea-2", "Qwen/Qwen-Image-2.1"]ANGLE_SPACES = ["Woffee/qwen-image-multiple-angles-3d-camera", "multimodalart/qwen-image-multiple-angles-3d-camera"]
PROMPT_TEMPLATE = ( "{subject}. A single complete object, front view, centered and fully in frame with margin, " "isolated on a plain pure white background, soft even studio lighting, highly detailed 3D asset, " "no text, no shadow on the ground.")
def _gb(module): return sum(p.numel() * p.element_size() for p in module.parameters()) / 1e9
def _bf16_torsos(pipe): """Store the transformer torsos in bf16 instead of fp32 (~34 GB -> ~21 GB resident).
Their matmuls already run under bf16 autocast, which casts fp32 weights to bf16 on every call, so the numbers barely change. The three structured-latent denoisers use their own TRELLIS-style `convert_to` (manual casts at the torso boundaries) after the LoRA is merged; the stage-1 model only ever runs inside autocast. The freed memory lets CuMesh remesh detailed shapes on a 48 GB `large` slice instead of the full card. """ before = sum(_gb(m) for m in (pipe.structure_model, pipe.shape512_model, pipe.shape1024_model, pipe.texture_model)) for model in (pipe.shape512_model, pipe.shape1024_model, pipe.texture_model): model.denoiser = model.denoiser.merge_and_unload() model.denoiser.convert_to(torch.bfloat16) pipe.structure_model.dit.convert_to(torch.bfloat16) for m in pipe.structure_model.vggt.modules(): if isinstance(m, (torch.nn.Linear, LoRALinear)): for p in m.parameters(recurse=False): p.data = p.data.to(torch.bfloat16) after = sum(_gb(m) for m in (pipe.structure_model, pipe.shape512_model, pipe.shape1024_model, pipe.texture_model)) print(f"[load] flow models {before:.1f} GB -> {after:.1f} GB", flush=True)
def _load_pipeline(): root = Path(snapshot_download(MODEL_ID, allow_patterns=["pipeline.json", "uniforge3d/**/*.pt"])) config = json.loads((root / "pipeline.json").read_text(encoding="utf-8")) config["external_models"]["dino"] = DINO_ID config["image_preprocess"]["rembg_model"] = REMBG_ID cfg_path = Path(tempfile.mkdtemp()) / "pipeline.json" cfg_path.write_text(json.dumps(config), encoding="utf-8") pipe = UniForge3DImageTo3DPipeline.from_config(cfg_path, weights_root=root, low_vram=False) _bf16_torsos(pipe) # All weights stay resident on the GPU (upstream low_vram offloading doubles the run time). for m in ( pipe.dino, pipe.conditioner, pipe.structure_model, pipe.structure_decoder, pipe.shape512_model, pipe.shape512_decoder, pipe.shape1024_model, pipe.shape1024_decoder, pipe.texture_model, pipe.texture_decoder, pipe.remove_background.model, ): m.to("cuda") return pipe
pipeline = _load_pipeline()
def _is_oom(error): return "out of memory" in str(error).lower()
def _free_cached_memory(stage): """CuMesh allocates GPU memory itself, so memory PyTorch keeps cached is not available to it.""" gc.collect() reserved = torch.cuda.memory_reserved() torch.cuda.empty_cache() free, total = torch.cuda.mem_get_info() print(f"[3d] {stage}: released {(reserved - torch.cuda.memory_reserved()) / 1e9:.1f} GB cached, " f"{free / 1e9:.1f} of {total / 1e9:.1f} GB free", flush=True)
def _timed(name, fn, cumesh=None): """Times a stage. CuMesh stages (cumesh="retry" or "free") start with PyTorch's cached memory released; "retry" stages build new meshes from their inputs, so they are retried once after running out of GPU memory.""" def wrapper(*args, **kwargs): t0 = time.perf_counter() try: if cumesh: _free_cached_memory(name) try: return fn(*args, **kwargs) except RuntimeError as e: if cumesh != "retry" or not _is_oom(e): raise print(f"[3d] {name}: out of GPU memory, retrying once", flush=True) # Retried outside the except block: until it ends, the traceback keeps the failed # attempt's meshes (and their GPU memory) alive. _free_cached_memory(name) return fn(*args, **kwargs) finally: torch.cuda.synchronize() print(f"[3d] {name}: {time.perf_counter() - t0:.1f}s", flush=True) return wrapper
# CuMesh allocates GPU memory itself, so memory PyTorch keeps cached is not available to it. The# out-of-memory failures came from fill_holes on the decoded 1024 mesh right after the shape and# texture decoders, whose activations were still cached: release the cache before every CuMesh# call (a no-op when little is cached).def _release_cache(): if torch.cuda.memory_reserved() - torch.cuda.memory_allocated() > 2**28: torch.cuda.empty_cache()
def _before_cumesh(fn): @wraps(fn) def wrapper(*args, **kwargs): _release_cache() return fn(*args, **kwargs) return wrapper
for _name, _member in list(vars(cumesh.CuMesh).items()): if callable(_member) and not _name.startswith(("_", "read")): setattr(cumesh.CuMesh, _name, _before_cumesh(_member))cumesh.cuBVH.__init__ = _before_cumesh(cumesh.cuBVH.__init__)cumesh.remeshing.remesh_narrow_band_dc = _before_cumesh(cumesh.remeshing.remesh_narrow_band_dc)
def _mesh_op(name, fn): """Mesh.fill_holes / simplify build a new CuMesh from the mesh's own tensors, so a failed attempt leaves nothing behind: log the mesh size and free memory, retry once on OOM.""" @wraps(fn) def wrapper(mesh, *args, **kwargs): faces = int(mesh.faces.shape[0]) _release_cache() print(f"[3d] {name}: {faces:,} faces, {torch.cuda.memory_allocated() / 1e9:.1f} GB in use, " f"{torch.cuda.mem_get_info()[0] / 1e9:.1f} GB free", flush=True) try: return fn(mesh, *args, **kwargs) except RuntimeError as e: if not _is_oom(e): raise print(f"[3d] {name}: out of GPU memory with {faces:,} faces, retrying once", flush=True) gc.collect() torch.cuda.empty_cache() return fn(mesh, *args, **kwargs) return wrapper
_mesh_base.Mesh.fill_holes = _mesh_op("fill_holes", _mesh_base.Mesh.fill_holes)_mesh_base.Mesh.simplify = _mesh_op("simplify", _mesh_base.Mesh.simplify)
for _stage in ("_preprocess_images", "_encode_dino", "_generate_structure", "_generate_shape512", "_generate_shape1024", "_generate_texture"): setattr(pipeline, _stage, _timed(_stage, getattr(pipeline, _stage)))
import uniforge3d.pipelines.uniforge3d_image_to_3d as _u3d
_CUMESH = {"official_shape_only_postprocess": "retry", "decode_shape_and_texture": "retry", "remesh_and_bake_texture": "free"}for _fn in ("official_shape_only_postprocess", "sample_shape_latent", "sample_texture", "decode_shape_and_texture", "remesh_and_bake_texture"): setattr(_u3d, _fn, _timed(_fn, getattr(_u3d, _fn), _CUMESH.get(_fn)))
def _duration(paths, seed, faces, texture_size, steps, *args, **kwargs): # Measured on `large` (2026-10-16), whole GPU step: a detailed espresso machine took 156 / 203 / # 298 s at 8 / 12 / 20 steps (~12 s per step), a bonsai 134-223 s, a rocking chair 48-82 s. # Sized for the espresso machine plus a margin, so the Quality preset is not cut short. return int(min(420, 60 + 8 * len(paths) + 13 * int(steps) + 5e-5 * int(faces)))
@spaces.GPU(duration=_duration)def _reconstruct(paths, seed, faces, texture_size, steps, out_path): t0 = time.perf_counter() torch.cuda.reset_peak_memory_stats() pipeline.config["texture"]["decimation_target"] = int(faces) pipeline.config["texture"]["texture_size"] = int(texture_size) for stage in ("structured_latent_512", "structured_latent_1024", "texture"): pipeline.config[stage]["sampler"]["params"]["steps"] = int(steps) print(f"[3d] start views={len(paths)} faces={faces} tex={texture_size} steps={steps} seed={seed}", flush=True) try: pipeline.run(paths, out_path, seed=int(seed), overwrite=True) except Exception as e: # ZeroGPU passes a gr.Error's message on to the app, but only the class name of other errors. if _is_oom(e): raise gr.Error("the GPU ran out of memory on this very detailed shape. Try another seed or a simpler object.") from e raise gr.Error(f"{type(e).__name__}: {str(e).strip()[:300]}") from e print(f"[3d] views={len(paths)} faces={faces} tex={texture_size} steps={steps} -> {time.perf_counter() - t0:.1f}s, " f"peak {torch.cuda.max_memory_allocated() / 1e9:.1f} GB", flush=True) return out_path
@spaces.GPU(duration=30)def _object_matte(image): """Foreground matte (L image) of an uploaded photo, from the BiRefNet model UniForge3D loads.""" t0 = time.perf_counter() matte = pipeline.remove_background(image.convert("RGB")).getchannel("A") print(f"[cutout] {image.size[0]}x{image.size[1]} -> {time.perf_counter() - t0:.1f}s", flush=True) return matte
# ---------------------------------------------------------------- remote Spaces
def _path(value): if isinstance(value, (list, tuple)): value = value[-1] if isinstance(value, dict): value = value.get("path") or value.get("image") or value.get("url") return _path(value) if isinstance(value, dict) else value return value
def _is_quota(error): return "quota" in str(error).lower()
def _explain(error, what): message = str(getattr(error, "message", None) or error).strip().strip("'\"") or type(error).__name__ if _is_quota(error): message = message.split(" Authenticate with")[0] return ( f"Out of ZeroGPU quota while {what}. {message} A full run uses about 3–5 minutes of GPU " "time: logged-out visitors get 2 minutes a day, free accounts 5 and PRO accounts 40, " "so log in to Hugging Face (API callers: send your token as Authorization: Bearer $HF_TOKEN) " "or come back later." ) return f"Failed while {what}: {message}"
class RemoteTask(threading.Thread): """One call to another ZeroGPU Space, tried on each fallback Space in turn.
`phase`, `rank` and `size` mirror the remote job so the panel can show queue positions. A quota error stops at once, since every fallback would bill the same quota. """
def __init__(self, label, space_ids, call, headers): super().__init__(daemon=True) self.label, self.space_ids, self.call, self.headers = label, space_ids, call, headers self.space = space_ids[0] self.phase, self.rank, self.size = "connecting", None, None self.result = self.error = None self.cancelled = False
@property def fallback(self): return self.space != self.space_ids[0]
def follow(self, job): self.phase, self.rank, self.size = "waiting", None, None # submitted, not started yet while not job.done(): if self.cancelled: job.cancel() raise RuntimeError("cancelled") status = job.status() if status.code == Status.IN_QUEUE and status.rank is not None: self.phase, self.rank, self.size = "queued", status.rank + 1, status.queue_size elif status.code in (Status.PROCESSING, Status.ITERATING, Status.PROGRESS): self.phase = "running" time.sleep(0.3) return job.result()
def run(self): for space in self.space_ids: self.space, self.phase, self.rank, self.size = space, "connecting", None, None t0 = time.perf_counter() try: client = Client(space, headers=self.headers, verbose=False, download_files=str(OUT_DIR)) self.result = self.call(space, client, self.follow) print(f"[{self.label}] {space} {time.perf_counter() - t0:.1f}s", flush=True) return except Exception as e: print(f"[{self.label}] {space} failed: {e!r}", flush=True) self.error = e if _is_quota(e) or self.cancelled: return
def queue_text(self, short=False): if self.rank is None: return "in queue" if short: return f"queue {self.rank}/{self.size}" if self.size else f"queue #{self.rank}" return f"position {self.rank} of {self.size}" if self.size else f"position {self.rank}"
def _t2i_call(space, client, follow, prompt, seed): if space == "krea/Krea-2": image, _ = follow(client.submit(prompt, "", "Turbo", 8, 0.0, 1024, 1024, seed, False, api_name="/generate")) else: # Qwen/Qwen-Image-2.1: rewrite stage (disabled) then generation, sharing session state follow(client.submit([], prompt, False, False, "speed", seed, False, api_name="/prepare_request")) image = follow(client.submit(prompt, False, False, "./generation_logs_paper_case", seed, 1024, 1024, " ", api_name="/generate_request")) return _path(image)
def _angle_call(space, client, follow, image_path, azimuth, seed, size): width, height = size image, _, _ = follow(client.submit( handle_file(image_path), azimuth, 0, 1.0, seed, False, 1.0, 4, height, width, api_name="/infer_camera_edit", )) return _path(image)
# ---------------------------------------------------------------- pipeline
def _job_dir(): d = OUT_DIR / uuid.uuid4().hex[:12] d.mkdir(parents=True, exist_ok=True) return d
def _save_png(src, dst): Image.open(src).convert("RGB").save(dst) return str(dst)
def _load_upload(path): """The upload upright, longest side at most 2048 px, and its own alpha if it is really transparent somewhere (then no background removal is needed).""" image = ImageOps.exif_transpose(Image.open(path)) image.thumbnail((2048, 2048), Image.LANCZOS) alpha = None if image.mode in ("RGBA", "LA", "PA") or "transparency" in image.info: channel = image.convert("RGBA").getchannel("A") if np.mean(np.asarray(channel) < 128) > 0.01: alpha = channel return image.convert("RGB"), alpha
def _headers(request): token = request.headers.get("x-ip-token") if request is not None else None return {"x-ip-token": token} if token else None
def _space_name(task): return f"{task.space} (fallback)" if task.fallback else task.space
class Run: """Progress panel state of one run and the outputs it yields; both tabs share the layout (panel, 3D view with download, hidden GLB file for the API, seed, generate button)."""
def __init__(self, steps, seed, filename): self.progress = pp.Progress(steps) self.seed, self.filename = seed, filename
def frame(self, model=None, finished=False): # The button is an output too: a `.then()` after this event does not run when it raises. if finished: button = gr.update(value="Generate 3D model", interactive=True) else: button = gr.update(value="Generating…", interactive=False) return self.progress.html(), mv.value(model, self.filename), model, self.seed, button
def fail(self, item, error, what, views=()): self.progress.error = _explain(error, what) item.fail("Failed, see the message below") for view in views: view.fail("failed") return self.frame(finished=True)
def _make_views(run, front_path, job, headers, size=(1024, 1024)): """Step 2: right, back and left views from the front view, in parallel. Returns all four paths.""" progress = run.progress angle_step = progress.steps["angles"] tasks = {} for key, _, azimuth in pp.VIEWS[1:]: tasks[key] = RemoteTask( f"angle {azimuth}", ANGLE_SPACES, partial(_angle_call, image_path=front_path, azimuth=azimuth, seed=run.seed, size=size), headers, ) tasks[key].start() paths = {"front": front_path} shown = None while True: alive = {key: task.is_alive() for key, task in tasks.items()} for key, task in tasks.items(): view = progress.views[key] if view.state in ("done", "failed"): continue if not alive[key]: if task.result: paths[key] = _save_png(task.result, job / f"view_{key}.png") view.thumb = pp.thumbnail(paths[key]) view.done() else: view.fail("failed") elif task.phase == "queued": view.update("queued", task.queue_text(short=True)) elif task.phase == "running": view.update("running", "generating…") elif task.phase == "waiting": view.update("queued", "in line…") else: view.update("queued", "connecting…") views = [progress.views[key] for key in tasks] n_done = sum(view.state == "done" for view in views) queued = [task for key, task in tasks.items() if task.phase == "queued" and progress.views[key].state == "queued"] if any(view.state == "running" for view in views): angle_step.update("running", f"Generating the right, back and left views · {n_done} of 3 done · usually 10–20 s") elif queued: first = min(queued, key=lambda t: t.rank or 0) angle_step.update("queued", f"Waiting in the {_space_name(first)} queue, {first.queue_text()} · {n_done} of 3 done") elif any(task.phase == "waiting" and alive[key] for key, task in tasks.items()): space = next(_space_name(t) for k, t in tasks.items() if t.phase == "waiting" and alive[k]) angle_step.update("queued", f"Sent to {space}, waiting for it to start · {n_done} of 3 done") elif any(alive.values()): angle_step.update("queued", f"Connecting to {_space_name(next(iter(tasks.values())))}…") if any(view.state == "failed" for view in views): # The run needs all four views: stop the other calls instead of spending more quota. for key, task in tasks.items(): if progress.views[key].state not in ("done", "failed"): task.cancelled = True progress.views[key].update("stopped", "stopped") break if not any(alive.values()): break if progress.signature() != shown: shown = progress.signature() yield run.frame() time.sleep(0.3) failed = [(key, tasks[key]) for key, *_ in pp.VIEWS[1:] if progress.views[key].state == "failed"] if failed: names = " and ".join(key for key, _ in failed) yield run.fail(angle_step, failed[0][1].error, f"generating the {names} view on {failed[0][1].space}") raise gr.Error(progress.error) angle_step.done(f"Generated on {_space_name(tasks['right'])}") return paths
def _make_model(run, paths, job, faces, texture_size, steps, retry_hint): """Step 3: UniForge3D on this Space's ZeroGPU, from all four views.""" progress = run.progress model_step = progress.steps["model"] model_step.update("running", "Waiting for a ZeroGPU slot, then building the textured mesh · usually 2–4 min, keep this tab open") yield run.frame() out_path = str(job / "uniforge3d.glb") try: _reconstruct([paths[key] for key, *_ in pp.VIEWS], run.seed, faces, texture_size, steps, out_path) except Exception as e: if "empty alpha mask" in str(e): e = RuntimeError(f"couldn't separate the object from the background in one view. {retry_hint}") yield run.fail(model_step, e, "building the 3D model") raise gr.Error(progress.error) total = sum(step.elapsed() for step in progress.steps.values()) model_step.done(f"Done in {pp.duration(total)} · {int(faces) // 1000}k faces, {int(texture_size)} px texture") yield run.frame(out_path, finished=True)
def text_to_3d(subject, seed, randomize, faces, texture_size, steps, request: gr.Request): """Text -> front image (Krea 2) -> right/back/left views (Qwen-Image-Edit-2511) -> GLB (UniForge3D).""" subject = (subject or "").strip() run = Run(pp.STEPS, random.randint(0, MAX_SEED) if randomize else int(seed), mv.filename(subject)) if not subject: yield run.frame(finished=True) raise gr.Error("Describe the object you want first.") headers = _headers(request) job = _job_dir() progress = run.progress image_step, front = progress.steps["image"], progress.views["front"]
# 1. Front image task = RemoteTask("t2i", T2I_SPACES, partial(_t2i_call, prompt=PROMPT_TEMPLATE.format(subject=subject), seed=run.seed), headers) task.start() shown = None while True: alive = task.is_alive() if task.phase == "queued": image_step.update("queued", f"Waiting in the {_space_name(task)} queue, {task.queue_text()}") front.update("queued", task.queue_text(short=True)) elif task.phase == "running": image_step.update("running", f"Drawing the object on {_space_name(task)} · usually 10–20 s") front.update("running", "drawing…") elif task.phase == "waiting": image_step.update("queued", f"Sent to {_space_name(task)}, waiting for it to start") front.update("queued", "in line…") else: image_step.update("queued", f"Connecting to {_space_name(task)}…") front.update("queued", "connecting…") if not alive: break if progress.signature() != shown: shown = progress.signature() yield run.frame() time.sleep(0.3) if not task.result: yield run.fail(image_step, task.error, f"drawing the image on {task.space}", views=[front]) raise gr.Error(progress.error) front_path = _save_png(task.result, job / "view_000.png") front.thumb = pp.thumbnail(front_path) front.done() image_step.done(f"Drawn on {_space_name(task)}")
# 2. and 3. paths = yield from _make_views(run, front_path, job, headers) yield from _make_model(run, paths, job, faces, texture_size, steps, "Try another seed or prompt.")
def image_to_3d(image, seed, randomize, faces, texture_size, steps, request: gr.Request): """One image (front view) -> right/back/left views (Qwen-Image-Edit-2511) -> GLB (UniForge3D).""" name = mv.filename(Path(image).stem) if image else "uniforge3d.glb" run = Run(pp.IMAGE_STEPS, random.randint(0, MAX_SEED) if randomize else int(seed), name) if not image: yield run.frame(finished=True) raise gr.Error("Upload an image of the object first.") job = _job_dir() image_step, front = run.progress.steps["image"], run.progress.views["front"] try: rgb, alpha = _load_upload(image) except Exception as e: yield run.fail(image_step, e, "reading the image", views=[front]) raise gr.Error(run.progress.error)
# 1. Background removal (skipped when the upload already has a transparent background) if alpha is None: image_step.update("running", "Removing the background · usually a few seconds") front.update("running", "cutting out…") yield run.frame() try: alpha = _object_matte(rgb) except Exception as e: yield run.fail(image_step, e, "removing the background", views=[front]) raise gr.Error(run.progress.error) note = "Background removed automatically" else: note = "Your image's transparent background was used" matte = cutout.main_object(alpha) if matte is None or np.mean(np.asarray(matte) > 127) < 0.002: front_image, note = cutout.padded(rgb), "No single object found, so the whole image is used" else: front_image = cutout.front_view(rgb, matte) front_path = str(job / "view_000.png") front_image.save(front_path) front.thumb = pp.thumbnail(front_path) front.done() image_step.done(note)
# 2. and 3. paths = yield from _make_views(run, front_path, job, _headers(request)) yield from _make_model(run, paths, job, faces, texture_size, steps, "Try another seed or another photo of the object.")
# ---------------------------------------------------------------- UI
EX_DIR = Path(HERE) / "examples"EXAMPLE_ORDER = ("fox", "mushroom", "watch", "cactus", "robot", "scooter", "teapot", "astronaut", "cupcake", "lamp")EXAMPLE_PROMPTS = {slug: (EX_DIR / slug / "prompt.txt").read_text(encoding="utf-8").strip() for slug in EXAMPLE_ORDER}# Square tiles: a small isometric render of each finished model (transparent background).EXAMPLE_TILES = [str(EX_DIR / slug / f"iso_{slug}.webp") for slug in EXAMPLE_ORDER]
def _tile_signature(path): image = Image.open(path).convert("RGBA") flat = Image.new("RGBA", image.size, "white") flat.alpha_composite(image) return np.asarray(flat.convert("L").resize((32, 32)), dtype=np.float32)
TILE_SIGNATURES = {slug: _tile_signature(tile) for slug, tile in zip(EXAMPLE_ORDER, EXAMPLE_TILES)}
def _example_slug(tile): """The example behind a tile. Gradio hands the function a cached copy of the tile image, so match it by name and, failing that, by its pixels (every tile is a different render).""" stem = Path(tile).stem.removeprefix("iso_") if stem in EXAMPLE_PROMPTS: return stem signature = _tile_signature(tile) return min(TILE_SIGNATURES, key=lambda s: float(np.abs(TILE_SIGNATURES[s] - signature).mean()))
def _example_outputs(slug, steps, notes): folder = EX_DIR / slug views = [folder / f"view_{key}.webp" for key in ("front", "90", "180", "270")] glb = str(folder / "model.glb") return pp.finished_html(views, notes, steps), mv.value(glb, f"uniforge3d-{slug}.glb"), 42
def show_example(tile): """Text tab: the example's prompt and its pre-computed result (20 sampling steps).""" slug = _example_slug(tile) return (EXAMPLE_PROMPTS[slug],) + _example_outputs(slug, pp.STEPS, { "image": "Drawn on krea/Krea-2", "angles": "Generated on Woffee/qwen-image-multiple-angles-3d-camera", "model": "Pre-computed example (20 sampling steps); type your own object above", })
def show_image_example(tile): """Image tab: the example's front view as the upload and the same pre-computed result (the pipeline from the front view on is identical).""" slug = _example_slug(tile) return (str(EX_DIR / slug / "view_front.webp"),) + _example_outputs(slug, pp.IMAGE_STEPS, { "image": "Example front view", "angles": "Generated on Woffee/qwen-image-multiple-angles-3d-camera", "model": "Pre-computed example (20 sampling steps); upload your own image above", })
def _examples(fn, outputs): """Square, image-only example tiles, cached at startup so a click needs no GPU or queue.""" tile = gr.Image(type="filepath", image_mode="RGBA", format="webp", visible=False) gr.Examples( [[path] for path in EXAMPLE_TILES], [tile], outputs, fn=fn, cache_examples=True, cache_mode="eager", # No example on page load: it arrives seconds later on the Space and would overwrite a # prompt typed in the meantime (and the run would then use the example's prompt). preload=False, label="Examples", )
def _lock(steps): return gr.update(value="Generating…", interactive=False), pp.starting_html(steps)
CSS = """.gradio-container { max-width: 1280px !important; margin: 0 auto; }.hint { color: var(--body-text-color-subdued); font-size: 0.9em; }/* Example tiles: 5 equal squares per row, the whole isometric render visible. */.u3d-examples div.gallery:not(.container) { display: grid !important; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 8px; }.u3d-examples .gallery-item { width: 100% !important; aspect-ratio: 1; padding: 0 !important; margin: 0 !important; }.u3d-examples .gallery-item .container { width: 100% !important; height: 100% !important; max-width: none !important; max-height: none !important; padding: 6px; box-sizing: border-box; border-radius: 8px; background: var(--background-fill-secondary);}.u3d-examples .gallery-item img { width: 100% !important; height: 100% !important; object-fit: contain !important; }""" + pp.GLOBAL_CSS + agent_banner.PAGE_CSS
QUOTA_HINT = "uses 3–5 minutes of your daily ZeroGPU quota. Log in to Hugging Face first: logged-out visitors only get 2 minutes."STEPS_LABEL = "Sampling steps (shape & texture; 20 = paper setting, slower)"
PRESET_INFO = " · ".join( f"{name}: {steps} steps, {faces // 1000}k faces, {texture} px, {time.replace('-', '–')}" for name, (steps, faces, texture, time) in agent_api.PRESETS.items())
def _apply_preset(name): steps, faces, texture_size, _ = agent_api.PRESETS[name] return faces, texture_size, steps
def _settings(randomize_default): with gr.Accordion("Settings", open=False): preset = gr.Radio(list(agent_api.PRESETS), value="Balanced", label="Preset", info=PRESET_INFO) seed = gr.Slider(0, MAX_SEED, value=42, step=1, label="Seed") randomize = gr.Checkbox(value=randomize_default, label="Random seed") faces = gr.Slider(100_000, 500_000, value=300_000, step=50_000, label="Detail (number of faces)") texture_size = agent_api.TextureSize(list(agent_api.TEXTURE_SIZES), value="2048", label="Texture size") steps = gr.Slider(8, 20, value=12, step=1, label=STEPS_LABEL) preset.input(_apply_preset, preset, [faces, texture_size, steps], queue=False, show_progress="hidden", api_visibility="private") return seed, randomize, faces, texture_size, steps
def _output_components(): """Created before the layout (render=False) so the examples above the panel can target them.""" panel_steps = {"text": (pp.STEPS, None), "image": (pp.IMAGE_STEPS, pp.IMAGE_VIEW_HINTS)} return { key: ( gr.HTML( pp.Progress(*panel_steps[key]).html(), css_template=pp.CSS, js_on_load=pp.JS, padding=False, label="Progress (HTML for the web page)", render=False, ), mv.component(label="3D viewer state (for the web page)", render=False), gr.File(label="3D model (GLB)", visible=False, render=False), # the API's model output ) for key in panel_steps }
with gr.Blocks(title="UniForge3D · Text & Image to 3D", head=mv.HEAD) as demo: gr.Markdown( "# UniForge3D · Text & Image to 3D\n" "Describe an object or upload one image of it. [Krea 2](https://huggingface.co/krea/Krea-2-Turbo) draws it " "from your text, [Qwen-Image-Edit-2511 + Multiple-Angles LoRA](https://huggingface.co/fal/Qwen-Image-Edit-2511-Multiple-Angles-LoRA) " "generates its right, back and left views, and [UniForge3D](https://huggingface.co/xibushu/UniForge3D) " "fuses the front, right, back and left views into a textured 3D model (GLB)." ) agent_banner.component() outputs = _output_components() with gr.Tabs(): with gr.Tab("Text → 3D"): panel, view, glb_file = outputs["text"] with gr.Row(): with gr.Column(scale=5): subject = gr.Textbox(label="Object", placeholder="e.g. a cute cartoon fox figurine wearing a red scarf", lines=2) btn = gr.Button("Generate 3D model", variant="primary") gr.Markdown(f"Takes about 1–5 minutes and {QUOTA_HINT}", elem_classes="hint") seed, randomize, faces, texture_size, steps = _settings(randomize_default=True) with gr.Column(elem_classes="u3d-examples"): _examples(show_example, [subject, panel, view, seed]) with gr.Column(scale=6): view.render() panel.render() glb_file.render() # The panel is the progress display, so Gradio's generic overlays are hidden. gr.on( [btn.click, subject.submit], partial(_lock, pp.STEPS), None, [btn, panel], queue=False, show_progress="hidden", api_visibility="private", ).then( text_to_3d, [subject, seed, randomize, faces, texture_size, steps], [panel, view, glb_file, seed, btn], api_name="text_to_3d", api_description=agent_api.TEXT_API, show_progress="hidden", ) with gr.Tab("Image → 3D"): panel2, view2, glb_file2 = outputs["image"] gr.Markdown( "**Upload one image.** The app removes its background, generates the right, back and left " "views from it, then UniForge3D builds the 3D model from all four." ) with gr.Row(): with gr.Column(scale=5): image = gr.Image( label="Your image: one object, seen from the front", type="filepath", image_mode=None, format="png", sources=["upload", "clipboard"], height=320, ) btn2 = gr.Button("Generate 3D model", variant="primary") gr.Markdown( f"Any photo of one object works: the background is removed automatically. Takes about 1–5 minutes and {QUOTA_HINT}", elem_classes="hint", ) seed2, randomize2, faces2, texture_size2, steps2 = _settings(randomize_default=False) with gr.Column(elem_classes="u3d-examples"): _examples(show_image_example, [image, panel2, view2, seed2]) with gr.Column(scale=6): view2.render() panel2.render() glb_file2.render() btn2.click( partial(_lock, pp.IMAGE_STEPS), None, [btn2, panel2], queue=False, show_progress="hidden", api_visibility="private", ).then( image_to_3d, [image, seed2, randomize2, faces2, texture_size2, steps2], [panel2, view2, glb_file2, seed2, btn2], api_name="image_to_3d", api_description=agent_api.IMAGE_API, show_progress="hidden", )
agent_api.document_only(demo, ("/text_to_3d", "/image_to_3d"))
if __name__ == "__main__": # The 3D views fetch generated and example GLBs through Gradio's file route. Server-side # rendering is off: on this Space its renderer cannot reach the app's API and serves # Gradio's login form ("Could not get API info") until the browser replaces it. demo.queue(default_concurrency_limit=4).launch( css=CSS, allowed_paths=[str(OUT_DIR), str(EX_DIR)], ssr_mode=False, )app.pyDeleted-812