InfiniSplat / app.py
akhaliq's picture
akhaliq HF Staff
Fix Invalid URL crash in runPipeline and surface file sizes
769d659
Raw
History Blame Contribute Delete
58.6 kB
from __future__ import annotations
import os
import shutil
import time
import uuid
from pathlib import Path
os.environ.setdefault("GRADIO_SSR_MODE", "false")
import spaces # noqa: F401 - must patch torch before model modules are imported
from fastapi.responses import HTMLResponse
from gradio import Server
from gradio.data_classes import FileData
from urllib.parse import quote, urlparse
from src.demo.hf_runtime import (
InfiniSplatRuntime,
ViewerTemplate,
export_browser_viewer,
export_filtered_gaussian_ply,
export_standalone_viewer,
prepare_viewer_template,
)
OUTPUT_ROOT = Path(os.environ.get("GRADIO_TEMP_DIR", "/tmp/gradio")) / "infinisplat"
OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)
GPU_DURATION_SECONDS = 6
runtime = InfiniSplatRuntime.load()
viewer_template = prepare_viewer_template(OUTPUT_ROOT)
app = Server(
title="InfiniSplat",
description="Implicit Gaussian decoding for large-baseline monocular view synthesis.",
)
def _log(stage: str, **metrics) -> None:
import json
print(f"INFINISPLAT_TIMING {json.dumps({'stage': stage, **metrics}, sort_keys=True)}", flush=True)
def _file_url(path: Path) -> str:
"""Return the public Gradio file URL for a server-side path."""
return f"/gradio_api/file={quote(str(path.resolve()))}"
def _resolve_file_path(value: FileData | str) -> Path:
"""Resolve a FileData input (or URL/path string) back to a local file path."""
if isinstance(value, str):
path_str = value
elif isinstance(value, dict):
path_str = value.get("path") or value.get("url") or ""
else:
path_str = str(value)
if not path_str:
raise ValueError(f"Cannot resolve file path from input: {value!r}")
# Strip Gradio's /gradio_api/file= URL prefix to get the real path
if path_str.startswith("/gradio_api/file="):
decoded = urlparse(path_str).path[len("/gradio_api/file="):]
return Path(decoded)
# Already a server-local path
if path_str.startswith("/"):
return Path(path_str)
return Path(path_str)
@app.api(name="reconstruct", queue=True, concurrency_limit=1, concurrency_id="gpu")
@spaces.GPU(duration=GPU_DURATION_SECONDS)
def reconstruct(image_path: FileData) -> dict:
"""Run GPU reconstruction and return a public URL for the artifact."""
started = time.perf_counter()
request_dir = OUTPUT_ROOT / uuid.uuid4().hex
request_dir.mkdir(parents=True, exist_ok=True)
artifact = runtime.infer_to_artifact(
image_path=_resolve_file_path(image_path),
artifact_path=request_dir / "gaussians.pt",
)
_log(
"gpu_reconstruct",
request=request_dir.name,
seconds=round(time.perf_counter() - started, 3),
bytes=artifact.stat().st_size,
)
return {"url": _file_url(artifact), "size": artifact.stat().st_size}
@app.api(name="export_ply", queue=True, concurrency_limit=2)
def export_ply(artifact_url: str) -> dict:
"""Filter one PLY artifact and return its public URL."""
started = time.perf_counter()
internal = _resolve_file_path(artifact_url)
scene_ply = export_filtered_gaussian_ply(
artifact_path=internal,
output_dir=internal.parent,
)
internal.unlink(missing_ok=True)
_log(
"ply_export",
request=scene_ply.parent.name,
seconds=round(time.perf_counter() - started, 3),
bytes=scene_ply.stat().st_size,
)
return {"url": _file_url(scene_ply), "size": scene_ply.stat().st_size}
@app.api(name="export_viewer", queue=True, concurrency_limit=2)
def export_viewer(scene_ply_url: str) -> dict:
"""Build the browser viewer and return its iframe-ready HTML URL."""
started = time.perf_counter()
scene_ply_path = _resolve_file_path(scene_ply_url)
exported = export_browser_viewer(
scene_ply=scene_ply_path,
viewer_template=viewer_template,
)
_log(
"browser_viewer",
request=exported.viewer_html.parent.name,
seconds=round(time.perf_counter() - started, 3),
sog_bytes=exported.scene_sog.stat().st_size,
viewer_html_bytes=exported.viewer_html.stat().st_size,
)
return {"url": _file_url(exported.viewer_html), "size": exported.viewer_html.stat().st_size}
@app.api(name="export_html", queue=True, concurrency_limit=2)
def export_html(viewer_html_url: str) -> dict:
"""Bundle a standalone HTML viewer and return its public URL."""
started = time.perf_counter()
viewer_html_path = _resolve_file_path(viewer_html_url)
standalone = export_standalone_viewer(
viewer_html=viewer_html_path,
viewer_template=viewer_template,
)
_log(
"standalone_html",
request=standalone.parent.name,
seconds=round(time.perf_counter() - started, 3),
bytes=standalone.stat().st_size,
)
return {"url": _file_url(standalone), "size": standalone.stat().st_size}
@app.api(name="viewer_html", queue=False)
def viewer_html() -> dict:
"""Serve the preloaded viewer template HTML for fast first paint."""
return {"url": _file_url(viewer_template.viewer_html)}
INDEX_HTML = r"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>InfiniSplat — Studio</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" />
<style>
/* ─────────────── Design tokens ─────────────── */
:root {
color-scheme: dark;
--bg: #0c1014;
--bg-grid: #0e1217;
--surface: #151a21;
--surface-2: #1a2028;
--surface-3: #222932;
--panel: #161b22;
--panel-hi: #1d242e;
--border: #232b35;
--border-strong: #34404e;
--text: #e7eaed;
--text-2: #b6bec8;
--muted: #8a95a3;
--muted-2: #5c6675;
--accent: #ffb547;
--accent-hi: #ffc870;
--accent-soft: rgba(255, 181, 71, 0.14);
--accent-glow: rgba(255, 181, 71, 0.28);
--success: #34d399;
--success-soft: rgba(52, 211, 153, 0.14);
--danger: #f87171;
--warn: #fbbf24;
--info: #60a5fa;
--viewer: #0a0d10;
--radius: 6px;
--radius-sm: 4px;
--shadow: 0 1px 0 rgba(255,255,255,0.02), 0 8px 24px rgba(0,0,0,0.35);
--grid-line: rgba(255,255,255,0.02);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; }
body {
background: var(--bg);
color: var(--text);
font-family: 'Inter', system-ui, sans-serif;
font-size: 13px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
overflow: hidden;
}
.mono { font-family: 'JetBrains Mono', ui-monospace, monospace; font-feature-settings: "tnum"; }
/* ─────────────── App shell ─────────────── */
.app {
display: grid;
grid-template-rows: 44px 1fr 24px;
height: 100vh;
background: var(--bg);
}
/* ─────────────── Toolbar ─────────────── */
.toolbar {
display: grid;
grid-template-columns: auto 1fr auto auto;
align-items: center;
gap: 16px;
padding: 0 12px;
background: var(--surface);
border-bottom: 1px solid var(--border);
user-select: none;
}
.tb-brand {
display: flex; align-items: center; gap: 10px;
padding-right: 14px; height: 100%;
border-right: 1px solid var(--border);
}
.tb-logo {
width: 22px; height: 22px;
display: grid; place-items: center;
background: var(--accent);
color: #0c1014;
border-radius: var(--radius-sm);
box-shadow: 0 0 12px var(--accent-glow);
}
.tb-logo svg { width: 14px; height: 14px; }
.tb-name {
font-weight: 800; font-size: 13px; letter-spacing: -0.01em;
}
.tb-name .accent { color: var(--accent); }
.tb-build {
font-family: 'JetBrains Mono', monospace;
font-size: 10px; color: var(--muted-2);
padding: 2px 6px; border: 1px solid var(--border);
border-radius: 3px; margin-left: 4px;
}
.tb-scene {
display: flex; align-items: center; gap: 8px;
min-width: 0;
}
.tb-scene-label { font-size: 11px; color: var(--muted); }
.tb-scene-name {
font-weight: 600; font-size: 12px;
padding: 4px 8px;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.tb-actions { display: flex; align-items: center; gap: 6px; }
.tb-shortcut {
font-family: 'JetBrains Mono', monospace;
font-size: 10px; color: var(--muted-2);
padding: 1px 4px; border: 1px solid var(--border-strong);
border-radius: 3px; margin-left: 6px;
}
.icon-btn {
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
min-height: 28px; padding: 0 10px;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
color: var(--text-2);
font: 500 12px 'Inter', sans-serif;
text-decoration: none;
cursor: pointer;
transition: border-color 120ms ease, background 120ms ease, color 120ms ease;
}
.icon-btn:hover { border-color: var(--accent); color: var(--text); }
.icon-btn svg { width: 13px; height: 13px; }
.icon-btn.ghost { background: transparent; border-color: transparent; }
.icon-btn.ghost:hover { background: var(--surface-2); border-color: var(--border); }
/* Primary reconstruct button */
.reconstruct-btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
min-height: 32px; padding: 0 16px;
background: var(--accent); color: #0c1014;
border: 0; border-radius: var(--radius-sm);
font: 700 12px 'Inter', sans-serif;
text-transform: uppercase; letter-spacing: 0.04em;
cursor: pointer;
box-shadow: 0 0 0 1px var(--accent), 0 0 16px var(--accent-glow);
transition: background 120ms ease, box-shadow 120ms ease;
}
.reconstruct-btn:hover { background: var(--accent-hi); }
.reconstruct-btn:active { transform: translateY(1px); }
.reconstruct-btn:disabled {
background: var(--surface-3); color: var(--muted-2);
box-shadow: 0 0 0 1px var(--border);
cursor: not-allowed;
}
.reconstruct-btn .spinner {
width: 12px; height: 12px;
border: 2px solid rgba(12,16,20,0.3);
border-top-color: #0c1014;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* ─────────────── Workspace ─────────────── */
.workspace {
display: grid;
grid-template-columns: 240px 1fr 280px;
gap: 1px;
background: var(--border);
min-height: 0;
overflow: hidden;
}
@media (max-width: 1100px) { .workspace { grid-template-columns: 220px 1fr 240px; } }
@media (max-width: 900px) {
.workspace { grid-template-columns: 1fr; grid-template-rows: auto 1fr auto; }
}
.col {
display: flex; flex-direction: column;
background: var(--bg);
min-height: 0; min-width: 0;
overflow: hidden;
}
/* ─────────────── Panel chrome ─────────────── */
.panel {
display: flex; flex-direction: column;
background: var(--panel);
min-height: 0; flex: 1 1 auto;
overflow: hidden;
}
.panel + .panel { border-top: 1px solid var(--border); }
.panel-head {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 10px;
padding: 0 12px;
min-height: 30px;
background: var(--surface);
border-bottom: 1px solid var(--border);
user-select: none;
}
.panel-head .bar {
width: 3px; height: 14px;
background: var(--accent);
border-radius: 1px;
}
.panel-head h3 {
font-size: 11px; font-weight: 700;
text-transform: uppercase; letter-spacing: 0.08em;
color: var(--text-2);
}
.panel-head .meta {
font-family: 'JetBrains Mono', monospace;
font-size: 10px; color: var(--muted);
}
.panel-body {
padding: 12px;
overflow: auto;
flex: 1 1 auto;
min-height: 0;
}
.panel-body.tight { padding: 8px; }
/* ─────────────── Drop zone ─────────────── */
.drop {
position: relative;
aspect-ratio: 4 / 3;
border: 1.5px dashed var(--border-strong);
border-radius: var(--radius);
background: var(--surface-2);
display: grid; place-items: center;
overflow: hidden;
cursor: pointer;
transition: border-color 150ms ease, background 150ms ease;
}
.drop.dragover { border-color: var(--accent); background: var(--accent-soft); }
.drop.has-image { border-style: solid; border-color: var(--border); cursor: default; }
.drop input[type="file"] {
position: absolute; inset: 0; opacity: 0; cursor: pointer;
}
.drop.has-image input[type="file"] { pointer-events: none; }
.drop-empty {
display: flex; flex-direction: column; align-items: center; gap: 8px;
color: var(--muted); text-align: center; padding: 16px;
}
.drop-empty .icon {
width: 36px; height: 36px;
display: grid; place-items: center;
background: var(--surface-3);
border: 1px solid var(--border-strong);
border-radius: var(--radius);
}
.drop-empty .icon svg { width: 18px; height: 18px; color: var(--accent); }
.drop-empty strong { color: var(--text); font-weight: 600; font-size: 12px; }
.drop-empty span { font-size: 11px; color: var(--muted); }
.drop-preview {
width: 100%; height: 100%; object-fit: contain;
background: #0a0d10; display: block;
}
.drop-meta {
margin-top: 10px;
display: grid; grid-template-columns: auto 1fr; gap: 4px 10px;
font-family: 'JetBrains Mono', monospace; font-size: 11px;
}
.drop-meta dt { color: var(--muted); }
.drop-meta dd { color: var(--text-2); }
/* ─────────────── Viewport ─────────────── */
.viewport {
position: relative;
flex: 1 1 auto;
min-height: 0;
background: var(--viewer);
overflow: hidden;
}
.viewport-frame {
width: 100%; height: 100%; border: 0; display: block;
background: var(--viewer);
opacity: 0; transition: opacity 240ms ease;
}
.viewport-frame.ready { opacity: 1; }
/* Viewport overlay (corner badges, status) */
.vp-overlay {
position: absolute; pointer-events: none;
transition: opacity 200ms ease;
}
.vp-overlay.hidden { opacity: 0; visibility: hidden; }
.vp-top-left {
top: 12px; left: 12px;
display: flex; flex-direction: column; gap: 6px;
}
.vp-bottom-left {
bottom: 12px; left: 12px;
display: flex; flex-direction: column; gap: 6px;
}
.vp-bottom-right {
bottom: 12px; right: 12px;
display: flex; gap: 6px;
pointer-events: auto;
}
.vp-top-right {
top: 12px; right: 12px;
pointer-events: auto;
}
.vp-badge {
display: inline-flex; align-items: center; gap: 6px;
padding: 4px 8px;
background: rgba(10, 13, 16, 0.7);
backdrop-filter: blur(8px);
border: 1px solid rgba(255,255,255,0.06);
border-radius: var(--radius-sm);
font-family: 'JetBrains Mono', monospace;
font-size: 10px;
color: var(--text-2);
letter-spacing: 0.04em;
text-transform: uppercase;
}
.vp-badge .dot {
width: 6px; height: 6px; border-radius: 50%;
background: var(--muted);
}
.vp-badge.ok .dot { background: var(--success); box-shadow: 0 0 6px var(--success); }
.vp-badge.warn .dot { background: var(--accent); box-shadow: 0 0 6px var(--accent); }
.vp-badge.err .dot { background: var(--danger); box-shadow: 0 0 6px var(--danger); }
.vp-badge.run .dot {
background: var(--accent);
animation: pulse 1.2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.5; transform: scale(0.85); }
}
.vp-crosshair {
position: absolute; top: 50%; left: 50%;
width: 20px; height: 20px;
transform: translate(-50%, -50%);
pointer-events: none;
}
.vp-crosshair::before, .vp-crosshair::after {
content: ""; position: absolute;
background: rgba(255,255,255,0.06);
}
.vp-crosshair::before { top: 50%; left: 0; right: 0; height: 1px; }
.vp-crosshair::after { left: 50%; top: 0; bottom: 0; width: 1px; }
/* Viewport controls (view cube + zoom) */
.vp-controls {
display: flex; gap: 4px;
background: rgba(10, 13, 16, 0.7);
backdrop-filter: blur(8px);
border: 1px solid rgba(255,255,255,0.06);
border-radius: var(--radius-sm);
padding: 4px;
}
.vp-ctrl {
width: 26px; height: 26px;
display: grid; place-items: center;
background: transparent;
border: 0; border-radius: 3px;
color: var(--text-2);
cursor: pointer;
transition: background 120ms ease, color 120ms ease;
}
.vp-ctrl:hover { background: rgba(255,255,255,0.08); color: var(--text); }
.vp-ctrl svg { width: 14px; height: 14px; }
/* Loading + idle + error states inside viewport */
.vp-state {
position: absolute; inset: 0;
display: flex; flex-direction: column; align-items: center; justify-content: center;
gap: 12px;
color: var(--text-2); text-align: center;
padding: 24px;
background: var(--viewer);
transition: opacity 200ms ease, visibility 200ms ease;
}
.vp-state.hidden { opacity: 0; visibility: hidden; pointer-events: none; }
.vp-state .ring {
width: 32px; height: 32px;
border: 2px solid var(--surface-3);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.9s linear infinite;
}
.vp-state .idle-ring {
width: 48px; height: 48px;
border: 1px dashed var(--border-strong);
border-radius: 50%;
display: grid; place-items: center;
color: var(--muted);
}
.vp-state .idle-ring svg { width: 22px; height: 22px; }
.vp-state strong { font-size: 13px; font-weight: 600; color: var(--text); }
.vp-state span { font-size: 11px; color: var(--muted); }
.vp-state .vp-progress {
width: 200px; height: 3px;
background: var(--surface-3);
border-radius: 999px; overflow: hidden;
margin-top: 4px;
}
.vp-state .vp-progress > div {
height: 100%; background: var(--accent);
width: 0%; transition: width 250ms ease;
}
.vp-state .err-bar { width: 32px; height: 3px; background: var(--danger); border-radius: 2px; }
/* Export bar inside viewport panel */
.export-bar {
display: grid; grid-template-columns: 1fr 1fr; gap: 1px;
background: var(--border);
border-top: 1px solid var(--border);
}
.export-btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
min-height: 36px; padding: 0 12px;
background: var(--surface);
border: 0;
color: var(--text-2);
font: 600 11px 'Inter', sans-serif;
text-transform: uppercase; letter-spacing: 0.06em;
cursor: pointer;
transition: background 120ms ease, color 120ms ease;
}
.export-btn:hover { background: var(--surface-2); color: var(--text); }
.export-btn[aria-disabled="true"], .export-btn:disabled {
opacity: 0.4; cursor: not-allowed; pointer-events: none;
}
.export-btn.ready { color: var(--accent); }
.export-btn.ready:hover { color: var(--accent-hi); }
.export-btn svg { width: 14px; height: 14px; }
/* ─────────────── Inspector (right column) ─────────────── */
.inspector { display: flex; flex-direction: column; min-height: 0; }
/* Section group inside inspector */
.section {
border-bottom: 1px solid var(--border);
}
.section:last-child { border-bottom: 0; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
.section-head {
display: flex; align-items: center; justify-content: space-between;
padding: 8px 12px;
background: var(--surface);
border-bottom: 1px solid var(--border);
user-select: none;
cursor: pointer;
}
.section-head h4 {
font-size: 10px; font-weight: 700;
text-transform: uppercase; letter-spacing: 0.08em;
color: var(--text-2);
}
.section-head .chev {
color: var(--muted); font-size: 10px;
transition: transform 150ms ease;
}
.section.collapsed .chev { transform: rotate(-90deg); }
.section.collapsed .section-body { display: none; }
.section-body { padding: 10px 12px; }
/* Scene tree */
.tree { display: flex; flex-direction: column; gap: 4px; font-size: 12px; }
.tree-row {
display: grid; grid-template-columns: 14px 1fr auto;
align-items: center; gap: 8px;
padding: 4px 6px;
border-radius: 3px;
color: var(--text-2);
}
.tree-row:hover { background: var(--surface-2); }
.tree-row .ico {
width: 14px; height: 14px;
display: grid; place-items: center;
color: var(--accent);
}
.tree-row .ico svg { width: 12px; height: 12px; }
.tree-row .val {
font-family: 'JetBrains Mono', monospace;
font-size: 11px; color: var(--text-2);
}
.tree-row.pending .ico { color: var(--muted); }
.tree-row.pending .val { color: var(--muted-2); }
.tree-row.active .ico svg { animation: pulse 1.2s ease-in-out infinite; }
.tree-row.done .ico { color: var(--success); }
.tree-row.error .ico { color: var(--danger); }
/* Telemetry */
.telemetry { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 12px; font-size: 11px; }
.telemetry .label { color: var(--muted); }
.telemetry .val {
font-family: 'JetBrains Mono', monospace;
color: var(--text-2); text-align: right;
}
.telemetry .val.accent { color: var(--accent); }
/* Pipeline log */
.log {
flex: 1 1 auto; min-height: 80px;
overflow: auto;
font-family: 'JetBrains Mono', monospace;
font-size: 11px;
line-height: 1.6;
color: var(--text-2);
background: var(--bg);
padding: 8px 12px;
}
.log-line { display: grid; grid-template-columns: 56px 60px 1fr; gap: 8px; }
.log-time { color: var(--muted-2); }
.log-stage { color: var(--accent); }
.log-stage.info { color: var(--info); }
.log-stage.ok { color: var(--success); }
.log-stage.err { color: var(--danger); }
.log-msg { color: var(--text-2); }
.log-empty { color: var(--muted); padding: 12px 0; text-align: center; }
/* Examples */
.examples-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.ex-thumb {
position: relative;
aspect-ratio: 4 / 3;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
overflow: hidden;
cursor: pointer;
background: var(--surface-2);
transition: border-color 120ms ease, transform 120ms ease;
}
.ex-thumb:hover { border-color: var(--accent); transform: translateY(-1px); }
.ex-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
.ex-thumb .ex-label {
position: absolute; inset: auto 0 0 0;
padding: 14px 6px 4px;
background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
color: #fff; font-size: 10px; font-weight: 500;
}
/* ─────────────── Status bar ─────────────── */
.statusbar {
display: grid;
grid-template-columns: auto auto auto auto 1fr auto;
align-items: center;
gap: 16px;
padding: 0 12px;
background: var(--surface);
border-top: 1px solid var(--border);
font-family: 'JetBrains Mono', monospace;
font-size: 10px;
color: var(--muted);
user-select: none;
}
.status-item { display: flex; align-items: center; gap: 6px; }
.status-item .label { color: var(--muted-2); }
.status-item .val { color: var(--text-2); }
.status-item .val.accent { color: var(--accent); }
.status-item .val.success { color: var(--success); }
.status-item .val.danger { color: var(--danger); }
.status-dot {
width: 6px; height: 6px; border-radius: 50%;
background: var(--muted-2);
}
.status-dot.idle { background: var(--success); box-shadow: 0 0 4px var(--success); }
.status-dot.run { background: var(--accent); animation: pulse 1.2s ease-in-out infinite; }
.status-dot.err { background: var(--danger); box-shadow: 0 0 4px var(--danger); }
/* Toast */
.toast {
position: fixed; bottom: 36px; left: 50%;
transform: translateX(-50%) translateY(8px);
background: var(--surface-3); color: var(--text);
padding: 8px 14px; border-radius: var(--radius-sm);
border: 1px solid var(--border-strong);
font-size: 12px;
box-shadow: var(--shadow);
opacity: 0; transition: opacity 200ms ease, transform 200ms ease;
pointer-events: none; z-index: 100;
}
.toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
.toast.error { border-color: var(--danger); color: var(--danger); }
/* Utility */
.hidden { display: none !important; }
.sr-only {
position: absolute; width: 1px; height: 1px;
padding: 0; margin: -1px; overflow: hidden;
clip: rect(0,0,0,0); white-space: nowrap; border: 0;
}
</style>
</head>
<body>
<div class="app">
<!-- ───── Toolbar ───── -->
<header class="toolbar">
<div class="tb-brand">
<div class="tb-logo" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 2 L22 7 L22 17 L12 22 L2 17 L2 7 Z"/>
<path d="M12 2 L12 12 M22 7 L12 12 M2 7 L12 12"/>
</svg>
</div>
<div class="tb-name">Infini<span class="accent">Splat</span><span class="tb-build">v1.0</span></div>
</div>
<div class="tb-scene">
<span class="tb-scene-label">SCENE</span>
<span class="tb-scene-name mono" id="sceneName">untitled.gsplat</span>
</div>
<div class="tb-actions">
<button class="reconstruct-btn" id="runBtn" disabled>
<span class="btn-label">Reconstruct</span>
<span class="tb-shortcut">R</span>
</button>
</div>
<div class="tb-actions">
<a class="icon-btn ghost" href="https://github.com/zju3dv/InfiniSplat" target="_blank" rel="noopener">
<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 .3a12 12 0 0 0-3.8 23.4c.6.1.8-.3.8-.6v-2.2c-3.3.7-4-1.6-4-1.6-.6-1.4-1.4-1.8-1.4-1.8-1.1-.7.1-.7.1-.7 1.2.1 1.9 1.3 1.9 1.3 1.1 1.9 2.9 1.4 3.6 1 .1-.8.4-1.4.8-1.7-2.7-.3-5.5-1.3-5.5-6 0-1.3.5-2.4 1.3-3.2-.1-.3-.6-1.6.1-3.3 0 0 1-.3 3.3 1.2a11.4 11.4 0 0 1 6 0c2.3-1.5 3.3-1.2 3.3-1.2.7 1.7.2 3 .1 3.3.8.8 1.3 1.9 1.3 3.2 0 4.7-2.8 5.7-5.5 6 .4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6A12 12 0 0 0 12 .3"/></svg>
GitHub
</a>
<a class="icon-btn ghost" href="https://zju3dv.github.io/InfiniSplat" target="_blank" rel="noopener">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M3 12h18M12 3v18"/></svg>
Project
</a>
</div>
</header>
<!-- ───── Workspace ───── -->
<main class="workspace">
<!-- LEFT: Input -->
<section class="col">
<div class="panel">
<div class="panel-head">
<div class="bar"></div>
<h3>Input</h3>
<span class="meta mono" id="inputMeta">no source</span>
</div>
<div class="panel-body">
<label class="drop" id="drop">
<input type="file" id="file" accept="image/*" />
<div class="drop-empty" id="dropEmpty">
<div class="icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
<polyline points="17 8 12 3 7 8"/>
<line x1="12" y1="3" x2="12" y2="15"/>
</svg>
</div>
<strong>Drop image</strong>
<span>JPG · PNG · WebP</span>
</div>
<img class="drop-preview hidden" id="preview" alt="" />
</label>
<dl class="drop-meta">
<dt>FILE</dt><dd class="mono" id="inputFileName">—</dd>
<dt>SIZE</dt><dd class="mono" id="inputFileSize">—</dd>
<dt>FORMAT</dt><dd class="mono" id="inputFormat">—</dd>
</dl>
</div>
</div>
</section>
<!-- CENTER: Viewport -->
<section class="col">
<div class="panel" style="flex: 1 1 auto;">
<div class="panel-head">
<div class="bar"></div>
<h3>Viewport</h3>
<span class="meta mono" id="viewportMeta">idle</span>
</div>
<div class="viewport" id="viewport">
<!-- Corner overlays -->
<div class="vp-overlay vp-top-left" id="vpTopLeft">
<div class="vp-badge" id="vpBadge">
<span class="dot"></span>
<span id="vpBadgeText">STAGE 0 / 4</span>
</div>
</div>
<div class="vp-overlay vp-bottom-left" id="vpBottomLeft">
<div class="vp-badge mono">
<span id="vpSceneLabel">—</span>
</div>
</div>
<div class="vp-overlay vp-bottom-right" id="vpBottomRight">
<div class="vp-controls">
<button class="vp-ctrl" id="vpReset" title="Reset view (V)">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/></svg>
</button>
<button class="vp-ctrl" id="vpZoomIn" title="Zoom in (+)">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/><line x1="16" y1="16" x2="21" y2="21"/></svg>
</button>
<button class="vp-ctrl" id="vpZoomOut" title="Zoom out (−)">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><line x1="8" y1="11" x2="14" y2="11"/><line x1="16" y1="16" x2="21" y2="21"/></svg>
</button>
</div>
</div>
<!-- State overlays -->
<div class="vp-state" id="vpIdle">
<div class="idle-ring">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 2 L22 7 L22 17 L12 22 L2 17 L2 7 Z"/>
<path d="M2 7 L12 12 L22 7 M12 12 L12 22"/>
</svg>
</div>
<strong>No scene loaded</strong>
<span>Upload an image to begin reconstruction</span>
</div>
<div class="vp-state hidden" id="vpLoading">
<div class="ring"></div>
<strong id="vpLoadingTitle">Reconstructing scene</strong>
<span id="vpLoadingDetail">Running model inference</span>
<div class="vp-progress"><div id="vpProgressBar"></div></div>
</div>
<div class="vp-state hidden" id="vpError">
<div class="err-bar"></div>
<strong>Reconstruction stopped</strong>
<span id="vpErrorDetail">See console for details</span>
</div>
<!-- The actual iframe (always present, faded in when ready) -->
<iframe class="viewport-frame" id="viewerFrame" title="Gaussian scene"></iframe>
</div>
<div class="export-bar">
<button class="export-btn" id="dlPly" aria-disabled="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
<span class="dl-label">Download PLY</span>
</button>
<button class="export-btn" id="dlHtml" aria-disabled="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
<span class="dl-label">Download HTML</span>
</button>
</div>
</div>
</section>
<!-- RIGHT: Inspector -->
<aside class="col inspector">
<div class="section">
<div class="section-head" data-toggle>
<h4>Scene tree</h4>
<span class="chev">▾</span>
</div>
<div class="section-body" id="sceneTree">
<div class="tree">
<div class="tree-row pending" data-stage="input">
<div class="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></div>
<span>Input image</span>
<span class="val">—</span>
</div>
<div class="tree-row pending" data-stage="reconstruct">
<div class="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/><line x1="9" y1="2" x2="9" y2="4"/><line x1="15" y1="2" x2="15" y2="4"/><line x1="9" y1="20" x2="9" y2="22"/><line x1="15" y1="20" x2="15" y2="22"/></svg></div>
<span>Reconstruct</span>
<span class="val">—</span>
</div>
<div class="tree-row pending" data-stage="ply">
<div class="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2 L22 7 L22 17 L12 22 L2 17 L2 7 Z"/></svg></div>
<span>Filter PLY</span>
<span class="val">—</span>
</div>
<div class="tree-row pending" data-stage="viewer">
<div class="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><line x1="12" y1="3" x2="12" y2="21"/><line x1="3" y1="12" x2="21" y2="12"/></svg></div>
<span>WebGL viewer</span>
<span class="val">—</span>
</div>
<div class="tree-row pending" data-stage="html">
<div class="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg></div>
<span>Standalone HTML</span>
<span class="val">—</span>
</div>
</div>
</div>
</div>
<div class="section">
<div class="section-head" data-toggle>
<h4>Telemetry</h4>
<span class="chev">▾</span>
</div>
<div class="section-body">
<div class="telemetry">
<span class="label">Gaussians</span><span class="val accent" id="telGaussians">—</span>
<span class="label">Artifact</span><span class="val" id="telArtifact">—</span>
<span class="label">PLY</span><span class="val" id="telPly">—</span>
<span class="label">Viewer</span><span class="val" id="telViewer">—</span>
<span class="label">GPU time</span><span class="val" id="telGpu">—</span>
<span class="label">Total</span><span class="val" id="telTotal">—</span>
</div>
</div>
</div>
<div class="section">
<div class="section-head" data-toggle>
<h4>Pipeline log</h4>
<span class="chev">▾</span>
</div>
<div class="log mono" id="log">
<div class="log-empty">ready · awaiting input</div>
</div>
</div>
<div class="section">
<div class="section-head" data-toggle>
<h4>Examples</h4>
<span class="meta mono" id="examplesCount">—</span>
<span class="chev">▾</span>
</div>
<div class="section-body">
<div class="examples-grid" id="gallery"></div>
</div>
</div>
</aside>
</main>
<!-- ───── Status bar ───── -->
<footer class="statusbar">
<div class="status-item">
<span class="status-dot idle" id="statusDot"></span>
<span class="label">STATE</span>
<span class="val" id="statusState">idle</span>
</div>
<div class="status-item">
<span class="label">GPU</span>
<span class="val" id="statusGpu">idle</span>
</div>
<div class="status-item">
<span class="label">QUEUE</span>
<span class="val" id="statusQueue">0</span>
</div>
<div class="status-item">
<span class="label">STAGE</span>
<span class="val" id="statusStage">0 / 4</span>
</div>
<div></div>
<div class="status-item">
<span class="label">zju3dv / InfiniSplat</span>
</div>
</footer>
</div>
<div class="toast" id="toast"></div>
<script type="module">
import { Client, handle_file } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
const $ = (id) => document.getElementById(id);
const fileInput = $("file"), drop = $("drop"), preview = $("preview"),
dropEmpty = $("dropEmpty"), runBtn = $("runBtn"),
btnLabel = runBtn.querySelector(".btn-label"),
viewerFrame = $("viewerFrame"),
vpIdle = $("vpIdle"), vpLoading = $("vpLoading"), vpError = $("vpError"),
vpLoadingTitle = $("vpLoadingTitle"), vpLoadingDetail = $("vpLoadingDetail"),
vpProgressBar = $("vpProgressBar"), vpErrorDetail = $("vpErrorDetail"),
vpBadge = $("vpBadge"), vpBadgeText = $("vpBadgeText"),
vpSceneLabel = $("vpSceneLabel"),
dlPly = $("dlPly"), dlHtml = $("dlHtml"),
sceneName = $("sceneName"),
inputMeta = $("inputMeta"),
inputFileName = $("inputFileName"), inputFileSize = $("inputFileSize"), inputFormat = $("inputFormat"),
viewportMeta = $("viewportMeta"),
gallery = $("gallery"), examplesCount = $("examplesCount"),
log = $("log"),
statusDot = $("statusDot"), statusState = $("statusState"),
statusGpu = $("statusGpu"), statusQueue = $("statusQueue"), statusStage = $("statusStage"),
toast = $("toast");
let pendingFile = null;
let pipelineStart = 0;
const stageTimings = {};
const STAGES = ["input", "reconstruct", "ply", "viewer", "html"];
function logLine(stage, kind, msg) {
const time = new Date().toLocaleTimeString("en-US", { hour12: false });
const line = document.createElement("div");
line.className = "log-line";
line.innerHTML = `
<span class="log-time">${time}</span>
<span class="log-stage ${kind}">${stage}</span>
<span class="log-msg">${msg}</span>
`;
// Remove empty placeholder
const empty = log.querySelector(".log-empty");
if (empty) empty.remove();
log.appendChild(line);
log.scrollTop = log.scrollHeight;
}
function clearLog() {
log.innerHTML = '<div class="log-empty">ready · awaiting input</div>';
}
function setStage(stageId, state, val) {
const row = document.querySelector(`.tree-row[data-stage="${stageId}"]`);
if (!row) return;
row.classList.remove("pending", "active", "done", "error");
row.classList.add(state);
if (val !== undefined) row.querySelector(".val").textContent = val;
}
function resetStages() {
STAGES.forEach((s) => {
const row = document.querySelector(`.tree-row[data-stage="${s}"]`);
if (row) {
row.classList.remove("active", "done", "error");
row.classList.add("pending");
row.querySelector(".val").textContent = "—";
}
});
document.getElementById("telGaussians").textContent = "—";
document.getElementById("telArtifact").textContent = "—";
document.getElementById("telPly").textContent = "—";
document.getElementById("telViewer").textContent = "—";
document.getElementById("telGpu").textContent = "—";
document.getElementById("telTotal").textContent = "—";
}
function setStatus(state, opts) {
opts = opts || {};
statusDot.classList.remove("idle", "run", "err");
statusDot.classList.add(state);
const stateMap = { idle: "idle", run: "running", err: "error" };
statusState.textContent = stateMap[state] || state;
statusState.classList.remove("accent", "success", "danger");
if (state === "idle") statusState.classList.add("success");
if (state === "err") statusState.classList.add("danger");
if (state === "run") statusState.classList.add("accent");
if (opts.gpu) statusGpu.textContent = opts.gpu;
if (opts.queue !== undefined) statusQueue.textContent = String(opts.queue);
if (opts.stage !== undefined) statusStage.textContent = opts.stage;
}
function setViewerState(state, opts) {
opts = opts || {};
const isReady = state === "ready";
const isLoading = state === "loading";
const isError = state === "error";
vpIdle.classList.toggle("hidden", !(!isReady && !isLoading && !isError));
vpLoading.classList.toggle("hidden", !isLoading);
vpError.classList.toggle("hidden", !isError);
if (isLoading) {
vpLoadingTitle.textContent = opts.title || "Reconstructing scene";
vpLoadingDetail.textContent = opts.detail || "Running model inference";
vpProgressBar.style.width = (opts.progress || 0) + "%";
}
if (isError) vpErrorDetail.textContent = opts.detail || "Unknown error";
if (isReady) {
vpIdle.classList.add("hidden");
vpLoading.classList.add("hidden");
vpError.classList.add("hidden");
viewerFrame.classList.add("ready");
} else {
viewerFrame.classList.remove("ready");
}
// Top-left badge
vpBadge.classList.remove("ok", "warn", "err", "run");
const badgeText = $("vpBadgeText");
if (isLoading) {
vpBadge.classList.add("run");
badgeText.textContent = opts.stageLabel || "STAGE";
} else if (isReady) {
vpBadge.classList.add("ok");
badgeText.textContent = "RENDERING";
} else if (isError) {
vpBadge.classList.add("err");
badgeText.textContent = "ERROR";
} else {
badgeText.textContent = "IDLE";
}
}
function setReady(ready) {
runBtn.disabled = !ready;
btnLabel.textContent = ready ? "Reconstruct" : "Reconstructing";
if (ready) {
const sp = runBtn.querySelector(".spinner");
if (sp) sp.remove();
} else {
if (!runBtn.querySelector(".spinner")) {
const sp = document.createElement("span");
sp.className = "spinner";
runBtn.insertBefore(sp, btnLabel);
}
}
}
function setDownload(btn, url, label) {
btn.disabled = !url;
btn.setAttribute("aria-disabled", String(!url));
const lbl = btn.querySelector(".dl-label");
lbl.textContent = label;
btn.classList.toggle("ready", !!url);
if (url) {
btn.onclick = () => {
const a = document.createElement("a");
a.href = url; a.download = ""; a.click();
};
} else {
btn.onclick = null;
}
}
function showPreview(file) {
const url = URL.createObjectURL(file);
preview.src = url;
preview.classList.remove("hidden");
dropEmpty.classList.add("hidden");
drop.classList.add("has-image");
setTimeout(() => URL.revokeObjectURL(url), 60_000);
// Update source metadata
const fname = file.name || "image";
inputFileName.textContent = fname.length > 22 ? fname.slice(0, 20) + "…" : fname;
const sizeKb = (file.size / 1024);
inputFileSize.textContent = sizeKb > 1024 ? (sizeKb / 1024).toFixed(2) + " MB" : sizeKb.toFixed(1) + " KB";
inputFormat.textContent = (file.type || "image").split("/").pop().toUpperCase();
inputMeta.textContent = (file.size / 1024 / 1024).toFixed(2) + " MB";
// Update scene name
const stem = fname.replace(/\.[^.]+$/, "");
sceneName.textContent = `${stem}.gsplat`;
vpSceneLabel.textContent = `${stem}.gsplat`;
setStage("input", "done", inputFormat.textContent);
}
function clearPreview() {
pendingFile = null;
preview.src = "";
preview.classList.add("hidden");
dropEmpty.classList.remove("hidden");
drop.classList.remove("has-image");
setReady(false);
resetStages();
sceneName.textContent = "untitled.gsplat";
inputFileName.textContent = "—";
inputFileSize.textContent = "—";
inputFormat.textContent = "—";
inputMeta.textContent = "no source";
viewportMeta.textContent = "idle";
}
function toastMsg(msg, isError) {
toast.textContent = msg;
toast.classList.toggle("error", !!isError);
toast.classList.add("show");
clearTimeout(toast._t);
toast._t = setTimeout(() => toast.classList.remove("show"), 2400);
}
function fmtBytes(n) {
if (!n) return "—";
if (n > 1024 * 1024) return (n / 1024 / 1024).toFixed(2) + " MB";
if (n > 1024) return (n / 1024).toFixed(1) + " KB";
return n + " B";
}
function fmtSec(s) {
if (s == null) return "—";
if (s > 60) return Math.floor(s / 60) + "m " + (s % 60).toFixed(1) + "s";
return s.toFixed(2) + "s";
}
fileInput.addEventListener("change", (e) => {
const f = e.target.files && e.target.files[0];
if (f) {
pendingFile = f;
showPreview(f);
setReady(true);
}
});
["dragenter", "dragover"].forEach(ev =>
drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add("dragover"); })
);
["dragleave", "drop"].forEach(ev =>
drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.remove("dragover"); })
);
drop.addEventListener("drop", (e) => {
const f = e.dataTransfer.files && e.dataTransfer.files[0];
if (f && f.type.startsWith("image/")) {
pendingFile = f;
showPreview(f);
setReady(true);
}
});
// Collapsible sections
document.querySelectorAll(".section-head[data-toggle]").forEach((head) => {
head.addEventListener("click", () => {
head.parentElement.classList.toggle("collapsed");
});
});
// Connect to backend
let client;
try {
client = await Client.connect(window.location.origin);
logLine("client", "ok", "backend connected");
} catch (err) {
toastMsg("Failed to connect to backend", true);
logLine("client", "err", err.message || String(err));
console.error(err);
}
// Preload viewer template so the iframe swaps in instantly
try {
const pre = await client.predict("/viewer_html", {});
if (pre && pre.data && pre.data[0]) {
const url = pre.data[0].url;
viewerFrame.src = url + "#preload";
logLine("viewer", "info", "template preloaded");
}
} catch (err) {
console.warn("Viewer preload skipped:", err);
}
async function timeStage(fn) {
const t0 = performance.now();
const result = await fn();
return { result, ms: performance.now() - t0 };
}
async function runPipeline() {
if (!pendingFile || !client) return;
setReady(false);
setDownload(dlPly, null, "Preparing PLY…");
setDownload(dlHtml, null, "Preparing HTML…");
viewerFrame.classList.remove("ready");
pipelineStart = performance.now();
setStatus("run", { gpu: "queued", queue: 1, stage: "0 / 4" });
try {
// Stage 1: Reconstruct (GPU)
setViewerState("loading", { title: "Reconstructing scene", detail: "Running model inference", progress: 15, stageLabel: "STAGE 1 / 4 · GPU" });
setStage("reconstruct", "active");
setStatus("run", { gpu: "running", queue: 1, stage: "1 / 4" });
const reconWrap = await timeStage(() =>
client.predict("/reconstruct", { image_path: handle_file(pendingFile) })
);
const artifactUrl = reconWrap.result.data[0].url;
const artifactSize = reconWrap.result.data[0].size;
stageTimings.gpu = reconWrap.ms;
setStage("reconstruct", "done", fmtSec(reconWrap.ms / 1000));
document.getElementById("telGpu").textContent = fmtSec(reconWrap.ms / 1000);
document.getElementById("telArtifact").textContent = fmtBytes(artifactSize);
logLine("reconstruct", "ok", `${fmtSec(reconWrap.ms / 1000)} · ${fmtBytes(artifactSize)}`);
// Stage 2: PLY export
setViewerState("loading", { title: "Preparing PLY", detail: "Filtering Gaussians", progress: 45, stageLabel: "STAGE 2 / 4 · CPU" });
setStage("ply", "active");
setStatus("run", { gpu: "—", queue: 1, stage: "2 / 4" });
const plyWrap = await timeStage(() =>
client.predict("/export_ply", { artifact_url: artifactUrl })
);
const plyUrl = plyWrap.result.data[0].url;
const plySize = plyWrap.result.data[0].size;
setStage("ply", "done", fmtBytes(plySize));
setDownload(dlPly, plyUrl, "Download PLY");
document.getElementById("telPly").textContent = fmtBytes(plySize);
logLine("ply", "ok", `${fmtSec(plyWrap.ms / 1000)} · ${fmtBytes(plySize)}`);
// Stage 3: Viewer
setViewerState("loading", { title: "Encoding viewer", detail: "Building WebGL scene", progress: 70, stageLabel: "STAGE 3 / 4 · ENCODE" });
setStage("viewer", "active");
setStatus("run", { gpu: "—", queue: 1, stage: "3 / 4" });
const viewWrap = await timeStage(() =>
client.predict("/export_viewer", { scene_ply_url: plyUrl })
);
const viewerUrl = viewWrap.result.data[0].url + "?v=" + Date.now();
const viewerSize = viewWrap.result.data[0].size;
setStage("viewer", "done", fmtBytes(viewerSize));
document.getElementById("telViewer").textContent = fmtBytes(viewerSize);
viewerFrame.src = viewerUrl;
viewerFrame.onload = () => {
viewerFrame.classList.add("ready");
setViewerState("ready");
viewportMeta.textContent = "ready";
};
logLine("viewer", "ok", `${fmtSec(viewWrap.ms / 1000)} · ${fmtBytes(viewerSize)}`);
// Stage 4: HTML
setViewerState("loading", { title: "Bundling HTML", detail: "Embedding assets for download", progress: 92, stageLabel: "STAGE 4 / 4 · BUNDLE" });
setStage("html", "active");
setStatus("run", { gpu: "—", queue: 1, stage: "4 / 4" });
const htmlWrap = await timeStage(() =>
client.predict("/export_html", { viewer_html_url: viewerUrl.replace(/[?#].*/, "") })
);
const htmlUrl = htmlWrap.result.data[0].url;
const htmlSize = htmlWrap.result.data[0].size;
setStage("html", "done", fmtBytes(htmlSize));
setDownload(dlHtml, htmlUrl, "Download HTML");
const totalSec = (performance.now() - pipelineStart) / 1000;
document.getElementById("telTotal").textContent = fmtSec(totalSec);
logLine("html", "ok", `${fmtSec(htmlWrap.ms / 1000)} · ${fmtBytes(htmlSize)}`);
setViewerState("ready");
setStatus("idle", { gpu: "idle", queue: 0, stage: "4 / 4" });
viewportMeta.textContent = "ready";
toastMsg("Reconstruction complete");
} catch (err) {
console.error(err);
setViewerState("error", { detail: err.message || "Pipeline failed" });
setStage("reconstruct", "error");
setStatus("err", { gpu: "—", queue: 0, stage: "—" });
logLine("error", "err", err.message || String(err));
toastMsg(err.message || "Reconstruction failed", true);
} finally {
setReady(true);
}
}
runBtn.addEventListener("click", runPipeline);
// Keyboard shortcuts
document.addEventListener("keydown", (e) => {
if (e.target.tagName === "INPUT" && e.target.type !== "button") return;
if (e.key === "r" || e.key === "R") {
if (!runBtn.disabled) runBtn.click();
}
});
// Viewport controls — postMessage to the embedded viewer when supported
function postToViewer(msg) {
try { viewerFrame.contentWindow?.postMessage(msg, "*"); } catch (_) {}
}
$("vpReset").addEventListener("click", () => postToViewer({ type: "infinisplat:reset" }));
$("vpZoomIn").addEventListener("click", () => postToViewer({ type: "infinisplat:zoom", delta: 1 }));
$("vpZoomOut").addEventListener("click", () => postToViewer({ type: "infinisplat:zoom", delta: -1 }));
// Examples — fall back to a curated list served via /__examples/{name}
const EXAMPLES = [
{ label: "Bedroom", path: "/__examples/bedroom.jpg" },
{ label: "Living room", path: "/__examples/living_room.jpg" },
{ label: "Loft", path: "/__examples/loft_room.jpg" },
{ label: "Gym", path: "/__examples/gym.png" },
{ label: "Meerkat", path: "/__examples/meerkat.jpg" },
{ label: "Painting", path: "/__examples/painting_room.jpg" },
{ label: "Ghibli room", path: "/__examples/ghibli_room.jpg" },
{ label: "Sofa", path: "/__examples/sofa_ai.jpg" },
{ label: "Summer", path: "/__examples/summer_room.jpg" },
{ label: "Animate", path: "/__examples/animate_room.jpg" },
{ label: "My bedroom", path: "/__examples/my_bedroom.JPG" },
{ label: "Cave", path: "/__examples/cave_ai.jpg" },
];
gallery.innerHTML = EXAMPLES.map((ex) => `
<div class="ex-thumb" data-path="${ex.path}" title="${ex.label}">
<img loading="lazy" src="${ex.path}" alt="${ex.label}" />
<div class="ex-label">${ex.label}</div>
</div>
`).join("");
examplesCount.textContent = `${EXAMPLES.length}`;
gallery.addEventListener("click", async (e) => {
const t = e.target.closest(".ex-thumb");
if (!t) return;
const path = t.dataset.path;
try {
const resp = await fetch(path);
const blob = await resp.blob();
const f = new File([blob], path.split("/").pop(), { type: blob.type });
pendingFile = f;
showPreview(f);
setReady(true);
logLine("input", "info", `loaded example: ${path.split("/").pop()}`);
toastMsg("Example loaded");
} catch (err) {
toastMsg("Failed to load example", true);
logLine("input", "err", err.message || String(err));
}
});
// Initial status
setStatus("idle", { gpu: "idle", queue: 0, stage: "0 / 4" });
</script>
</body>
</html>
"""
@app.get("/", response_class=HTMLResponse)
async def homepage() -> str:
return INDEX_HTML
@app.get("/__examples/{name}")
async def serve_example(name: str):
"""Serve curated example images from the bundled examples directory."""
from fastapi.responses import FileResponse
examples_dir = Path(__file__).resolve().parent / "examples" / "data" / "rgb_demo"
candidate = examples_dir / name
if not candidate.is_file() or not str(candidate.resolve()).startswith(str(examples_dir.resolve())):
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="Example not found")
return FileResponse(candidate)
def _cleanup() -> None:
"""Remove expired per-request directories on shutdown."""
if not OUTPUT_ROOT.is_dir():
return
cutoff = time.time() - 3600
for request_dir in OUTPUT_ROOT.iterdir():
if request_dir.is_symlink() or not request_dir.is_dir():
continue
try:
if uuid.UUID(hex=request_dir.name).hex != request_dir.name:
continue
except ValueError:
continue
if request_dir.lstat().st_mtime > cutoff:
continue
shutil.rmtree(request_dir, ignore_errors=True)
import atexit as _atexit
_atexit.register(_cleanup)
if __name__ == "__main__":
app.launch(
server_name="0.0.0.0",
server_port=int(os.environ.get("PORT", "7860")),
allowed_paths=[str(OUTPUT_ROOT)],
max_file_size="20mb",
show_error=True,
ssr_mode=False,
footer_links=[],
)