Download button saves an in-browser copy of the GLB (survives Space restarts)
Browse filesFiles changed (2)
- app.py+13-8
- download_button.pyAdded+104
26 unmodified lines272829303132258 unmodified lines291292293294295296297138 unmodified lines43643743843944044144215 unmodified lines4584594604614624634643 unmodified lines46846947047147247323 unmodified lines49749849950050150250350426 unmodified lines5315325335345355365375383 unmodified lines54254354454526 unmodified linesfrom uniforge3d import UniForge3DImageTo3DPipelinefrom uniforge3d.models.lora import LoRALinearimport progress_panel as ppMODEL_ID = "xibushu/UniForge3D"258 unmodified linesdef frame(model=None, finished=False):# The button is an output too: a `.then()` after this event does not run when it raises.button = gr.update(value="Generate 3D model", interactive=True) if finished else gr.update(value="Generating…", interactive=False)return progress.html(), model, model, seed, buttondef stop(item, view_items, error, what):progress.error = _explain(error, what)138 unmodified linesif "empty alpha mask" in str(e):raise gr.Error("Couldn't find the object in one of the images. Try a clearer shot.")raisereturn out_path, out_path, int(seed), f"Done in {time.perf_counter() - t0:.0f} s ({len(paths)} view(s))."# ---------------------------------------------------------------- UI15 unmodified lines"angles": "Re-shot on Woffee/qwen-image-multiple-angles-3d-camera","model": "Pre-computed example (20 sampling steps); type your own object above",}return pp.finished_html(views, notes), glb, glb, 42def _lock():3 unmodified linesCSS = """.gradio-container { max-width: 1280px !important; margin: 0 auto; }.hint { color: var(--body-text-color-subdued); font-size: 0.9em; }"""with gr.Blocks(title="UniForge3D Text-to-3D") as demo:23 unmodified linessteps = gr.Slider(8, 20, value=12, step=1, label="Sampling steps (shape & texture; 20 = paper setting, slower)")panel = gr.HTML(pp.Progress().html(), css_template=pp.CSS, js_on_load=pp.JS, padding=False)with gr.Column(scale=6):model3d = gr.Model3D(label="3D model", height=480, clear_color=[0.0, 0.0, 0.0, 0.0])download = gr.DownloadButton("Download .glb", variant="secondary")gr.Examples([[prompt] for prompt in EXAMPLE_SLUGS],[subject],26 unmodified linessteps2 = gr.Slider(8, 20, value=12, step=1, label="Sampling steps (shape & texture; 20 = paper setting, slower)")status2 = gr.Markdown(elem_classes="hint")with gr.Column(scale=6):model3d2 = gr.Model3D(label="3D model", height=480, clear_color=[0.0, 0.0, 0.0, 0.0])download2 = gr.DownloadButton("Download .glb", variant="secondary")btn2.click(images_to_3d,[images, seed2, randomize2, faces2, texture_size2, steps2],3 unmodified linesif __name__ == "__main__":demo.queue(default_concurrency_limit=4).launch(css=CSS)26 unmodified lines27282930313233258 unmodified lines292293294295296297298138 unmodified lines43743843944044144244315 unmodified lines4594604614624634644653 unmodified lines46947047147247347447547647723 unmodified lines50150250350450550650750826 unmodified lines5355365375385395405415423 unmodified lines54654754854955026 unmodified linesfrom uniforge3d import UniForge3DImageTo3DPipelinefrom uniforge3d.models.lora import LoRALinearimport download_button as dlimport progress_panel as ppMODEL_ID = "xibushu/UniForge3D"258 unmodified linesdef frame(model=None, finished=False):# The button is an output too: a `.then()` after this event does not run when it raises.button = gr.update(value="Generate 3D model", interactive=True) if finished else gr.update(value="Generating…", interactive=False)return progress.html(), model, dl.value(model, dl.filename(subject)), seed, buttondef stop(item, view_items, error, what):progress.error = _explain(error, what)138 unmodified linesif "empty alpha mask" in str(e):raise gr.Error("Couldn't find the object in one of the images. Try a clearer shot.")raisereturn out_path, dl.value(out_path), int(seed), f"Done in {time.perf_counter() - t0:.0f} s ({len(paths)} view(s))."# ---------------------------------------------------------------- UI15 unmodified lines"angles": "Re-shot on Woffee/qwen-image-multiple-angles-3d-camera","model": "Pre-computed example (20 sampling steps); type your own object above",}return pp.finished_html(views, notes), glb, dl.value(glb, f"uniforge3d-{EXAMPLE_SLUGS[subject]}.glb"), 42def _lock():3 unmodified linesCSS = """.gradio-container { max-width: 1280px !important; margin: 0 auto; }.hint { color: var(--body-text-color-subdued); font-size: 0.9em; }/* The viewer's own download icon links straight to the server file, which is gone after aSpace restart; the Download .glb button below saves an in-browser copy instead. */.u3d-viewer a[download] { display: none !important; }"""with gr.Blocks(title="UniForge3D Text-to-3D") as demo:23 unmodified linessteps = gr.Slider(8, 20, value=12, step=1, label="Sampling steps (shape & texture; 20 = paper setting, slower)")panel = gr.HTML(pp.Progress().html(), css_template=pp.CSS, js_on_load=pp.JS, padding=False)with gr.Column(scale=6):model3d = gr.Model3D(label="3D model", height=480, clear_color=[0.0, 0.0, 0.0, 0.0], elem_classes="u3d-viewer")download = dl.component()gr.Examples([[prompt] for prompt in EXAMPLE_SLUGS],[subject],26 unmodified linessteps2 = gr.Slider(8, 20, value=12, step=1, label="Sampling steps (shape & texture; 20 = paper setting, slower)")status2 = gr.Markdown(elem_classes="hint")with gr.Column(scale=6):model3d2 = gr.Model3D(label="3D model", height=480, clear_color=[0.0, 0.0, 0.0, 0.0], elem_classes="u3d-viewer")download2 = dl.component()btn2.click(images_to_3d,[images, seed2, randomize2, faces2, texture_size2, steps2],3 unmodified linesif __name__ == "__main__":# The download buttons fetch generated and example GLBs through Gradio's file route.demo.queue(default_concurrency_limit=4).launch(css=CSS, allowed_paths=[str(OUT_DIR), str(EX_DIR)])
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""GLB download button that saves an in-browser copy of the model.
A plain link to the file breaks as soon as the server loses the file: a Space restart wipes/tmp, and the stale link then fails with "File wasn't available on site" while the 3D viewerstill shows the model it already loaded. This button fetches the GLB as soon as a result isshown (while the file certainly exists) and saves that copy on click."""
import jsonimport osimport re
import gradio as gr
def value(path, name="uniforge3d.glb"): """Component value for a GLB on this server; "" clears the button.""" if not path: return "" return json.dumps({"url": f"gradio_api/file={path}", "name": name, "size": os.path.getsize(path)})
def filename(subject): slug = re.sub(r"[^a-z0-9]+", "-", (subject or "").lower()).strip("-")[:48].strip("-") return f"uniforge3d-{slug}.glb" if slug else "uniforge3d.glb"
TEMPLATE = """<div class="u3d-dl"> <button type="button" class="u3d-dl-btn" disabled>Download .glb</button> <div class="u3d-dl-note" role="status"></div></div>"""
CSS = """.u3d-dl { display: flex; flex-direction: column; gap: 6px; }.u3d-dl-btn { width: 100%; cursor: pointer; font-weight: 600; padding: var(--button-large-padding, 10px 16px); border-radius: var(--button-large-radius, 8px); font-size: var(--button-large-text-size, 16px); background: var(--button-secondary-background-fill); color: var(--button-secondary-text-color); border: var(--button-border-width, 1px) solid var(--button-secondary-border-color);}.u3d-dl-btn:hover:not(:disabled) { background: var(--button-secondary-background-fill-hover); }.u3d-dl-btn:disabled { cursor: default; opacity: 0.55; }.u3d-dl-note { font-size: 13px; color: var(--body-text-color-subdued); overflow-wrap: anywhere; }.u3d-dl-note:empty { display: none; }.u3d-dl-note.is-error { color: var(--error-text-color, #dc2626); }"""
JS = """const state = { key: undefined, blob: null, name: "uniforge3d.glb", view: ["Download .glb", false, "", false] };const mb = (n) => `${(n / 1e6).toFixed(1)} MB`;const show = (label, enabled, note = "", error = false) => { state.view = [label, enabled, note, error]; const btn = element.querySelector(".u3d-dl-btn"); const msg = element.querySelector(".u3d-dl-note"); if (!btn || !msg) return; btn.textContent = label; btn.disabled = !enabled; msg.textContent = note; msg.classList.toggle("is-error", error);};const prepare = async () => { let info = null; try { info = props.value ? JSON.parse(props.value) : null; } catch (e) { info = null; } const key = info ? info.url : null; if (key === state.key) { show(...state.view); return; } state.key = key; state.blob = null; if (!info) { show("Download .glb", false); return; } state.name = info.name || "uniforge3d.glb"; show(`Preparing download… (${mb(info.size)})`, false); try { const response = await fetch(info.url, { credentials: "same-origin" }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const blob = await response.blob(); if (state.key !== key) return; state.blob = blob; show(`Download .glb (${mb(blob.size)})`, true); } catch (e) { if (state.key !== key) return; show("Download .glb", false, `Couldn't fetch the model from the Space (${e.message}). If the Space restarted since it was made, generate it again.`, true); }};element.addEventListener("click", (event) => { if (!event.target.closest(".u3d-dl-btn") || !state.blob) return; const href = URL.createObjectURL(state.blob); const link = document.createElement("a"); link.href = href; link.download = state.name; document.body.appendChild(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(href), 60000);});watch("value", prepare);prepare();"""
def component(): return gr.HTML("", html_template=TEMPLATE, css_template=CSS, js_on_load=JS, padding=False)app.py+13-8
download_button.pyAdded+104