Agent API: consistent texture_size schema, endpoint docs, fixed snippets; JPEG uploads; small streamed panel; readable GPU errors and CuMesh OOM mitigation
Browse filesFiles changed (3)
- agent_api.pyAdded+126
- app.py+56-12
- progress_panel.py+18-7
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126"""What the API documents for agents: /gradio_api/info, which the Space's agents.md points to.
- texture_size: Gradio's clients render every enum as strings (python_type Literal['1024', '2048'], "2048" in the code snippets), so the documented choices are the strings "1024" and "2048". The numbers 1024 and 2048 are accepted too.- Endpoint descriptions: parameters, timing, auth, and where the GLB is in the result.- Code snippets: the bash one is generated with the public host (Gradio uses the host of the first /info request, which on Spaces is often http://localhost:7860), sends the HF token, and keeps EVENT_ID in bash (Gradio's `| read EVENT_ID` runs in a subshell there, so it is empty)."""
import osimport re
import gradio as grimport gradio.routes
TEXTURE_SIZES = ("1024", "2048")
class TextureSize(gr.Radio): """The texture size radio (create it with choices TEXTURE_SIZES); passes the size to the function as an int. No __init__ of its own: Gradio builds a component's config from its constructor's parameters."""
is_template = True # rendered by the frontend as a gr.Radio
def preprocess(self, payload): if payload is None: payload = self.value if isinstance(payload, (int, float)) and not isinstance(payload, bool) and float(payload).is_integer(): payload = str(int(payload)) elif isinstance(payload, str): payload = payload.strip() if payload not in TEXTURE_SIZES: raise gr.Error(f'texture_size must be "1024" or "2048" (got {payload!r}).') return int(super().preprocess(payload))
def api_info(self): return { **super().api_info(), "description": 'texture resolution in pixels: "1024" or "2048" (the numbers 1024 and 2048 work too)', }
_COMMON = ( "faces: 100000-500000, default 300000. " 'texture_size: "1024" or "2048", default "2048". ' "steps: 8-20, default 12 (20 is the paper setting, slower). " "A run takes about 2-4 minutes and uses 3-5 minutes of the caller's ZeroGPU quota, so send your " "Hugging Face token (Authorization: Bearer $HF_TOKEN). " "Poll GET /gradio_api/call/{endpoint}/{event_id}: it streams `generating` updates for the web page, then " "`event: complete` with data = [progress HTML, 3D viewer state, GLB file, seed used]. " "Download the model from data[2].url. A failure ends the stream with `event: error` and a message.")
TEXT_API = ( "Text to a textured 3D model (GLB): Krea 2 draws the object, Qwen-Image-Edit-2511 generates its " "right, back and left views, and UniForge3D builds the model from all four. " 'subject (required): the object, e.g. "a red vintage rotary telephone". ' "seed: integer, used only when randomize is false. randomize: default true. " + _COMMON)
IMAGE_API = ( "One image of a single object to a textured 3D model (GLB): the background is removed " "automatically, Qwen-Image-Edit-2511 generates the right, back and left views, and UniForge3D " "builds the model from all four. " "image (required): a photo or render of the object seen from the front (PNG, JPEG or WebP). " "Upload it with POST /gradio_api/upload -F files=@object.jpg and pass " '{"path": "<returned path>", "meta": {"_type": "gradio.FileData"}}, or pass a public image URL ' 'as {"path": "https://...", "meta": {"_type": "gradio.FileData"}}. ' "seed: integer, default 42, used only when randomize is false. randomize: default false. " + _COMMON)
AUTH = '-H "Authorization: Bearer $HF_TOKEN"'_BASH_CALL = re.compile( r'curl -X POST (?P<post>\S+) -s -H "Content-Type: application/json" \\\n' r"(?P<data> -d '.*') \\\n" r" \| awk -F'\"' '\{ print \$4\}' \\\n" r" \| read EVENT_ID; curl -N (?P<get>\S+)$")
def _fix_bash(snippet): match = _BASH_CALL.search(snippet) if not match: # a Gradio version with another template: keep it return snippet call = ( f'EVENT_ID=$(curl -s -X POST {match["post"]} -H "Content-Type: application/json" {AUTH} \\\n' f'{match["data"]} \\\n' " | awk -F'\"' '{ print $4}')\n" f'curl -sS -N {AUTH} {match["get"]}' ) snippet = snippet[: match.start()] + call return snippet.replace("FILE_PATH=$(curl -s -X POST ", f"FILE_PATH=$(curl -s {AUTH} -X POST ", 1)
def document_only(blocks, endpoints): """Keep the API docs to `endpoints`. While gr.Examples caches, Gradio registers a public endpoint named after the example function, and /info is computed once, on the first request, so whether such endpoints were documented depended on timing.""" get_api_info = blocks.get_api_info
def api_info(all_endpoints=False): info = get_api_info(all_endpoints) if not all_endpoints: info["named_endpoints"] = {k: v for k, v in info["named_endpoints"].items() if k in endpoints} info["unnamed_endpoints"] = {} return info
blocks.get_api_info = api_info
_generate_code_snippets = gradio.routes.generate_code_snippets
def _code_snippets(api_name, endpoint_info, root, space_id=None, api_prefix="/"): host = os.environ.get("SPACE_HOST") if host: root = f"https://{host}" snippets = _generate_code_snippets(api_name, endpoint_info, root, space_id=space_id, api_prefix=api_prefix) snippets["bash"] = _fix_bash(snippets["bash"]) return snippets
gradio.routes.generate_code_snippets = _code_snippets6 unmodified lines78910111214 unmodified lines2728293031326 unmodified lines39404142434464 unmodified lines1091101111121131141151161171181196 unmodified lines12612712812913013113213313412 unmodified lines14714814915015115215331 unmodified lines185186187188189190191413 unmodified lines6056066076086096106113 unmodified lines61561661761861962062162262332 unmodified lines6566576586596606616625 unmodified lines66866967067167267367414 unmodified lines6896906916926936946956966976986 unmodified linesimport spaces # before torchimport jsonimport randomimport tempfile14 unmodified linesfrom uniforge3d import UniForge3DImageTo3DPipelinefrom uniforge3d.models.lora import LoRALinearimport agent_bannerimport model_view as mvimport cutout6 unmodified linesMAX_SEED = 2**31 - 1OUT_DIR = Path(tempfile.gettempdir()) / "uniforge3d-outputs"OUT_DIR.mkdir(parents=True, exist_ok=True)# 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.64 unmodified linespipeline = _load_pipeline()def _timed(name, fn):def wrapper(*args, **kwargs):t0 = time.perf_counter()try:return fn(*args, **kwargs)finally:torch.cuda.synchronize()print(f"[3d] {name}: {time.perf_counter() - t0:.1f}s", flush=True)6 unmodified linesimport uniforge3d.pipelines.uniforge3d_image_to_3d as _u3dfor _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)))def _duration(paths, seed, faces, texture_size, steps, *args, **kwargs):12 unmodified linespipeline.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)pipeline.run(paths, out_path, seed=int(seed), overwrite=True)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_path31 unmodified linesreturn (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 or come back later.")return f"Failed while {what}: {message}"413 unmodified linesseed = 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 = gr.Radio([1024, 2048], value=2048, label="Texture size")steps = gr.Slider(8, 20, value=12, step=1, label=STEPS_LABEL)return seed, randomize, faces, texture_size, steps3 unmodified linespanel_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, render=False),mv.component(render=False),gr.File(label="GLB", visible=False, render=False), # the API's model output)for key in panel_steps}32 unmodified linestext_to_3d,[subject, seed, randomize, faces, texture_size, steps],[panel, view, glb_file, seed, btn],api_name="text_to_3d", show_progress="hidden",)with gr.Tab("Image → 3D"):panel2, view2, glb_file2 = outputs["image"]5 unmodified lineswith gr.Column(scale=5):image = gr.Image(label="Your image: one object, seen from the front", type="filepath",image_mode="RGBA", format="png", sources=["upload", "clipboard"], height=320,)btn2 = gr.Button("Generate 3D model", variant="primary")gr.Markdown(14 unmodified linesimage_to_3d,[image, seed2, randomize2, faces2, texture_size2, steps2],[panel2, view2, glb_file2, seed2, btn2],api_name="image_to_3d", show_progress="hidden",)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 serves6 unmodified lines7891011121314 unmodified lines282930313233346 unmodified lines4142434445464764 unmodified lines1121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471486 unmodified lines15515615715815916016116216316412 unmodified lines17717817918018118218318418518618718818919031 unmodified lines222223224225226227228229413 unmodified lines6436446456466476486493 unmodified lines65365465565665765865966066166266366432 unmodified lines6976986997007017027035 unmodified lines70971071171271371471514 unmodified lines7307317327337347357367377387397407417426 unmodified linesimport spaces # before torchimport gcimport jsonimport randomimport tempfile14 unmodified linesfrom uniforge3d import UniForge3DImageTo3DPipelinefrom uniforge3d.models.lora import LoRALinearimport agent_apiimport agent_bannerimport model_view as mvimport cutout6 unmodified linesMAX_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.64 unmodified linespipeline = _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 memoryreleased; "retry" stages build new meshes from their inputs, so they are retried once afterrunning 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):raiseprint(f"[3d] {name}: out of GPU memory, retrying once", flush=True)_free_cached_memory(name)return fn(*args, **kwargs)finally:torch.cuda.synchronize()print(f"[3d] {name}: {time.perf_counter() - t0:.1f}s", flush=True)6 unmodified linesimport 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):12 unmodified linespipeline.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 eraise gr.Error(f"{type(e).__name__}: {str(e).strip()[:300]}") from eprint(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_path31 unmodified linesreturn (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}"413 unmodified linesseed = 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)return seed, randomize, faces, texture_size, steps3 unmodified linespanel_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}32 unmodified linestext_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"]5 unmodified lineswith 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(14 unmodified linesimage_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
3 unmodified lines4567891011121341 unmodified lines5556575859606162636465663 unmodified linesbrowser from the `data-elapsed` value stamped at render time (see `JS`)."""import base64import htmlimport ioimport timefrom PIL import Image41 unmodified linesreturn (self.finished or time.monotonic()) - self.starteddef thumbnail(path, size=320):image = Image.open(path).convert("RGB")image.thumbnail((size, size))buf = io.BytesIO()image.save(buf, format="JPEG", quality=82)return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()def duration(seconds):3 unmodified lines456789101112131441 unmodified lines565758596061626364656667686970717273747576773 unmodified linesbrowser from the `data-elapsed` value stamped at render time (see `JS`)."""import hashlibimport htmlimport tempfileimport timefrom pathlib import Pathfrom PIL import Image41 unmodified linesreturn (self.finished or time.monotonic()) - self.started# Served through Gradio's file route, so it must be inside the app's allowed_paths.THUMB_DIR = Path(tempfile.gettempdir()) / "uniforge3d-outputs" / "thumbs"def thumbnail(path, size=320):"""URL of a small JPEG copy of a view for its tile. Not inline data: the panel is streamed toAPI clients on every update, and inline images made each update ~70 kB."""source = Path(path).resolve()key = f"{source}:{source.stat().st_mtime_ns}:{size}".encode()target = Path(THUMB_DIR) / f"{hashlib.sha1(key).hexdigest()[:24]}.jpg"if not target.exists():image = Image.open(source).convert("RGB")image.thumbnail((size, size))target.parent.mkdir(parents=True, exist_ok=True)image.save(target, format="JPEG", quality=82)return f"gradio_api/file={target}"def duration(seconds):
agent_api.pyAdded+126
app.py+56-12
progress_panel.py+18-7