Delete progress_panel.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256"""Progress panel for the text-to-3D pipeline: three steps and the four views, as HTML.
The server re-renders the panel only when a state changes; running timers count up in thebrowser from the `data-elapsed` value stamped at render time (see `JS`)."""
import hashlibimport htmlimport tempfileimport timefrom pathlib import Path
from PIL import Image
VIEWS = (("front", "Front", 0), ("right", "Right", 90), ("back", "Back", 180), ("left", "Left", 270))_LATER_STEPS = ( ("angles", "Camera angles", "Qwen-Image-Edit-2511 adds the right, back and left views"), ("model", "3D model", "UniForge3D builds the textured 3D model"),)STEPS = (("image", "Image", "Krea 2 draws the object"),) + _LATER_STEPSIMAGE_STEPS = ( ("image", "Front view", "The background is removed automatically"), ("angles", "Other views", "The right, back and left views are generated from your image"), _LATER_STEPS[1],)# Shown in the empty view slots before the first run of the Image → 3D tab.IMAGE_VIEW_HINTS = {"front": "your image", "right": "auto-generated", "back": "auto-generated", "left": "auto-generated"}
class Item: """State of one step or one view: waiting, queued, running, done or failed."""
def __init__(self): self.state = "waiting" self.note = "" self.started = None self.finished = None self.thumb = None
def update(self, state, note=""): if self.started is None: self.started = time.monotonic() self.state, self.note = state, note
def done(self, note=""): self.update("done", note) self.finished = time.monotonic()
def fail(self, note): self.update("failed", note) self.finished = time.monotonic()
def elapsed(self): if self.started is None: return 0.0 return (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 to API 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): seconds = int(round(seconds)) return f"{seconds} s" if seconds < 60 else f"{seconds // 60} min {seconds % 60:02d} s"
def _timer(item): if item.state in ("queued", "running"): return f'<span class="u3d-time" data-elapsed="{item.elapsed():.1f}">{duration(item.elapsed())}</span>' if item.state in ("done", "failed") and item.started is not None and item.elapsed() >= 0.5: return f'<span class="u3d-time">{duration(item.elapsed())}</span>' return '<span class="u3d-time"></span>'
class Progress: def __init__(self, steps=STEPS, view_hints=None): self.step_info = steps self.view_hints = view_hints or {} self.steps = {key: Item() for key, *_ in steps} self.views = {key: Item() for key, *_ in VIEWS} self.error = None
def signature(self): """Everything shown except the timers, to skip re-renders that change nothing.""" items = list(self.steps.values()) + list(self.views.values()) return tuple((i.state, i.note, i.thumb is not None) for i in items) + (self.error,)
def status(self): """(state, text) of the line under the strip: the active or failed step's note, the final note when done, else what the pipeline does.""" items = [self.steps[key] for key, *_ in self.step_info] for item in items: if item.state == "failed": return "failed", item.note for item in items: if item.state in ("queued", "running"): return item.state, item.note if all(item.state == "done" for item in items): return "done", items[-1].note return "idle", " → ".join(idle for *_, idle in self.step_info)
def html(self): strip = [] for index, (key, title, _) in enumerate(self.step_info, 1): item = self.steps[key] if index > 1: previous = self.steps[self.step_info[index - 2][0]] strip.append(f'<li class="u3d-link is-{previous.state}" aria-hidden="true"></li>') strip.append( f'<li class="u3d-step is-{item.state}">' f'<span class="u3d-icon" aria-hidden="true">{index}</span>' f'<div class="u3d-body"><span class="u3d-title">{title}</span>{_timer(item)}</div></li>' ) state, text = self.status() tiles = [] active = any(item.started is not None for item in [*self.steps.values(), *self.views.values()]) for key, label, azimuth in VIEWS: item = self.views[key] if item.thumb: inner = f'<img src="{item.thumb}" alt="{label} view">' else: placeholder = item.note or ("waiting" if active else self.view_hints.get(key, "")) inner = f'<span class="u3d-placeholder">{html.escape(placeholder)}</span>' tiles.append( f'<figure class="u3d-view is-{item.state}"><div class="u3d-thumb">{inner}</div>' f'<figcaption><span>{label} <span class="u3d-deg">{azimuth}°</span></span>' f"{_timer(item) if item.state != 'waiting' else ''}</figcaption></figure>" ) error = f'<div class="u3d-error" role="alert">{html.escape(self.error)}</div>' if self.error else "" return ( '<div class="u3d-panel">' f'<ol class="u3d-steps">{"".join(strip)}</ol>' f'<div class="u3d-status is-{state}">{html.escape(text)}</div>' f'<div class="u3d-views">{"".join(tiles)}</div>' f"{error}</div>" )
def starting_html(steps=STEPS): progress = Progress(steps) progress.steps["image"].update("queued", "Starting…") return progress.html()
def finished_html(view_paths, notes, steps=STEPS): """Panel for a finished run, e.g. the cached examples; `notes` maps step keys to text.""" progress = Progress(steps) for key, *_ in steps: progress.steps[key].state = "done" progress.steps[key].note = notes.get(key, "") for (key, *_), path in zip(VIEWS, view_paths): progress.views[key].state = "done" progress.views[key].thumb = thumbnail(path) return progress.html()
JS = """const fmt = (s) => (s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${String(s % 60).padStart(2, "0")} s`);const tick = () => { const now = performance.now(); element.querySelectorAll("[data-elapsed]").forEach((el) => { if (!el.dataset.t0) el.dataset.t0 = String(now - parseFloat(el.dataset.elapsed) * 1000); el.textContent = fmt(Math.max(0, Math.floor((now - parseFloat(el.dataset.t0)) / 1000))); });};tick();setInterval(tick, 500);watch("value", tick);"""
CSS = """.u3d-panel { display: flex; flex-direction: column; gap: 10px; font-size: 14px; color: var(--body-text-color); }.u3d-steps { list-style: none; margin: 0; padding: 0; display: flex; align-items: center; gap: 8px; }.u3d-step { display: flex; align-items: center; gap: 8px; margin: 0; flex: none; }.u3d-link { flex: 1 1 auto; min-width: 12px; height: 2px; margin: 0; border-radius: 1px; background: var(--border-color-primary); }.u3d-link.is-done { background: var(--color-accent); }.u3d-icon { width: 24px; height: 24px; border-radius: 50%; box-sizing: border-box; flex: none; display: grid; place-items: center; font-size: 12px; font-weight: 600; border: 2px solid var(--border-color-primary); color: var(--body-text-color-subdued);}.u3d-body { display: flex; flex-direction: column; line-height: 1.2; }.u3d-title { font-weight: 600; white-space: nowrap; }.u3d-time { font-size: 12px; font-variant-numeric: tabular-nums; color: var(--body-text-color-subdued); white-space: nowrap; min-height: 14px; }.u3d-step.is-waiting .u3d-title { color: var(--body-text-color-subdued); }.u3d-status { font-size: 13px; line-height: 1.4; color: var(--body-text-color-subdued); overflow-wrap: anywhere; }.u3d-status.is-running, .u3d-status.is-queued { color: var(--body-text-color); }.u3d-status.is-failed { color: var(--error-text-color, #dc2626); }
.u3d-step.is-running .u3d-icon, .u3d-step.is-queued .u3d-icon { color: transparent; border-color: var(--border-color-primary); border-top-color: var(--color-accent); animation: u3d-spin 0.9s linear infinite;}.u3d-step.is-queued .u3d-icon { animation-duration: 2.4s; }.u3d-step.is-done .u3d-icon { background: var(--color-accent); border-color: var(--color-accent); color: #fff; font-size: 0; }.u3d-step.is-done .u3d-icon::after { content: "✓"; font-size: 13px; }.u3d-step.is-failed .u3d-icon { border-color: var(--error-icon-color, #dc2626); color: var(--error-icon-color, #dc2626); font-size: 0; }.u3d-step.is-failed .u3d-icon::after { content: "✕"; font-size: 12px; }
.u3d-views { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }.u3d-view { margin: 0; display: flex; flex-direction: column; gap: 4px; }.u3d-thumb { aspect-ratio: 1; border-radius: 8px; overflow: hidden; position: relative; border: 1px solid var(--border-color-primary); background: var(--background-fill-secondary); display: grid; place-items: center;}.u3d-thumb img { width: 100%; height: 100%; object-fit: contain; background: #fff; display: block; }.u3d-placeholder { font-size: 12px; color: var(--body-text-color-subdued); text-align: center; padding: 6px; position: relative; z-index: 1; }.u3d-view.is-waiting .u3d-thumb, .u3d-view.is-stopped .u3d-thumb { border-style: dashed; }.u3d-view.is-queued .u3d-thumb::before, .u3d-view.is-running .u3d-thumb::before { content: ""; position: absolute; inset: 0; background: linear-gradient(100deg, transparent 20%, color-mix(in srgb, var(--color-accent) 18%, transparent) 50%, transparent 80%); background-size: 200% 100%; animation: u3d-shimmer 1.4s linear infinite;}.u3d-view.is-running .u3d-thumb { border-color: var(--color-accent); }.u3d-view.is-running .u3d-placeholder, .u3d-view.is-queued .u3d-placeholder { color: var(--body-text-color); }.u3d-view.is-failed .u3d-thumb { border-color: var(--error-icon-color, #dc2626); }.u3d-view.is-failed .u3d-placeholder { color: var(--error-text-color, #dc2626); }.u3d-view figcaption { display: flex; justify-content: space-between; gap: 4px; font-size: 12px; }.u3d-deg { color: var(--body-text-color-subdued); }.u3d-error { border: 1px solid var(--error-border-color, #fca5a5); background: var(--error-background-fill, #fef2f2); color: var(--error-text-color, #b91c1c); border-radius: 8px; padding: 10px 12px; overflow-wrap: anywhere;}@media (prefers-reduced-motion: reduce) { .u3d-step .u3d-icon, .u3d-thumb::before { animation: none !important; }}@media (max-width: 480px) { .u3d-views { grid-template-columns: repeat(2, minmax(0, 1fr)); } .u3d-steps { gap: 6px; } .u3d-title { white-space: normal; }}"""
# Keyframes must go in the page-level CSS: Gradio nests a component's css_template inside its# id selector, and an @keyframes block nested in a style rule is dropped, which left the# spinners and shimmers standing still.GLOBAL_CSS = """@keyframes u3d-spin { to { transform: rotate(360deg); } }@keyframes u3d-shimmer { from { background-position: 150% 0; } to { background-position: -50% 0; } }"""progress_panel.pyDeleted-256