Spaces:
Running on Zero
Running on Zero
Use compact SPLAT data for browser visualization
Browse filesFiles changed (3)
- README.md+2-1
- app.py+196-9
- src/model/splat_export.pyAdded+79
74 unmodified lines7576777879808174 unmodified linesThe repository includes a ZeroGPU-compatible Gradio demo in `app.py`. It accepts1-64 ordered, overlapping views and returns a scale-filtered Gaussian PLY with aninteractive Gradio `Model3D` viewer. New-view rendering is intentionally not run by thedemo. The interface includes a quick-start guide, uploaded-view previews, five examplescenes with five views each, and a direct PLY download. Clicking a scene's cover imageloads its five views and starts reconstruction automatically. Uploaded images follow the OF3GS data pipeline: they are rescaled to cover74 unmodified lines757677787980818274 unmodified linesThe repository includes a ZeroGPU-compatible Gradio demo in `app.py`. It accepts1-64 ordered, overlapping views and returns a scale-filtered Gaussian PLY with aninteractive `gsplat.js` WebGL viewer. The browser loads a compact `.splat` file whilethe full PLY remains available for download. New-view rendering is intentionally not run by thedemo. The interface includes a quick-start guide, uploaded-view previews, five examplescenes with five views each, and a direct PLY download. Clicking a scene's cover imageloads its five views and starts reconstruction automatically. Uploaded images follow the OF3GS data pipeline: they are rescaled to cover
21 unmodified lines222324252627229 unmodified lines25725825926026126210 unmodified lines2732742752762772782792802812822837 unmodified lines29129229329429529629713 unmodified lines31131231331431531664 unmodified lines38138238338438538638738838939039116 unmodified lines40840941041141241341414 unmodified lines42943043143243343443543643743843944044144244344444544644744821 unmodified lines)from src.model.model.of3gs import OF3GSfrom src.model.ply_export import export_plyMODEL_REPO = os.getenv("OF3GS_MODEL_REPO", "richardchencccc/OF3GS")229 unmodified linesprogress(0.8, desc="Filtering and writing Gaussians")ply_path = output_directory / "of3gs_gaussians.ply"scale = gaussians.scales[0]keep_mask = scale.max(dim=-1).values <= scale_thresholdkept_count = int(keep_mask.sum().item())10 unmodified linesscale_threshold=float(scale_threshold),save_sh_dc_only=True,)progress(0.95, desc="Preparing 3DGS viewer")progress(1.0, desc="Loading 3DGS viewer")status = f"{images.shape[1]} views | {kept_count:,} Gaussians kept"return str(ply_path), str(ply_path), statusfinally:del images, target_images, gaussians, scale, keep_mask, harmonicsgc.collect()7 unmodified linesrequest: gr.Request,progress: gr.Progress = gr.Progress(track_tqdm=False),) -> tuple[str, str, str]:"""Reconstruct an interactive Gaussian PLY from 1-64 ordered images."""images = _prepare_images(files)return _run_reconstruction(images,13 unmodified linesshutil.rmtree(directory, ignore_errors=True)CSS = """.gradio-container {width: 100% !important;64 unmodified lines"*P.S. Large Gaussian scenes may take a while to load. Please be patient.*",elem_id="viewer-note",)reconstruction = gr.Model3D(label="3DGS Viewer",height=680,elem_id="model-output",)gr.Markdown("### Output Files", elem_id="section-title")ply_download = gr.File(label="3DGS Model (.ply)")status = gr.Textbox(16 unmodified lineselem_id="example-gallery",)outputs = [reconstruction, ply_download, status]image_files.change(fn=_preview_images,inputs=image_files,14 unmodified linesoutputs=preview_gallery,show_progress="hidden",)example_event.then(fn=reconstruct_images,inputs=[image_files, scale_threshold],outputs=outputs,show_progress="full",show_progress_on=[reconstruction],)image_submit.click(fn=reconstruct_images,inputs=[image_files, scale_threshold],outputs=outputs,show_progress="full",show_progress_on=[reconstruction],)demo.unload(cleanup_session)demo.queue()21 unmodified lines22232425262728229 unmodified lines25825926026126226326410 unmodified lines2752762772782792802812822832842852862872882892902912922932942952962972982997 unmodified lines30730830931031131231313 unmodified lines32732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148264 unmodified lines54754854955055155255355455555655755855956056156256356416 unmodified lines58158258358458558658714 unmodified lines60260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463521 unmodified lines)from src.model.model.of3gs import OF3GSfrom src.model.ply_export import export_plyfrom src.model.splat_export import export_splatMODEL_REPO = os.getenv("OF3GS_MODEL_REPO", "richardchencccc/OF3GS")229 unmodified linesprogress(0.8, desc="Filtering and writing Gaussians")ply_path = output_directory / "of3gs_gaussians.ply"splat_path = output_directory / "of3gs_gaussians.splat"scale = gaussians.scales[0]keep_mask = scale.max(dim=-1).values <= scale_thresholdkept_count = int(keep_mask.sum().item())10 unmodified linesscale_threshold=float(scale_threshold),save_sh_dc_only=True,)export_splat(gaussians.means[0],gaussians.scales[0],gaussians.rotations[0],harmonics,gaussians.opacities[0],splat_path,scale_threshold=float(scale_threshold),)progress(0.95, desc="Preparing 3DGS viewer")progress(1.0, desc="Loading 3DGS viewer")viewer_mb = splat_path.stat().st_size / (1024 * 1024)ply_mb = ply_path.stat().st_size / (1024 * 1024)status = (f"{images.shape[1]} views | {kept_count:,} Gaussians kept | "f"Viewer {viewer_mb:.1f} MB | PLY {ply_mb:.1f} MB")return str(splat_path), str(ply_path), statusfinally:del images, target_images, gaussians, scale, keep_mask, harmonicsgc.collect()7 unmodified linesrequest: gr.Request,progress: gr.Progress = gr.Progress(track_tqdm=False),) -> tuple[str, str, str]:"""Reconstruct compact viewer data and a downloadable Gaussian PLY."""images = _prepare_images(files)return _run_reconstruction(images,13 unmodified linesshutil.rmtree(directory, ignore_errors=True)SPLAT_VIEWER_HTML = """<div class="of3gs-splat-viewer"><canvas aria-label="Interactive 3D Gaussian scene"></canvas><div class="of3gs-viewer-overlay"><div class="of3gs-viewer-message">Reconstruct a scene to view it here.</div><div class="of3gs-viewer-progress" hidden><div class="of3gs-viewer-progress-fill"></div></div></div></div>"""SPLAT_VIEWER_JS = r"""const canvas = element.querySelector("canvas");const overlay = element.querySelector(".of3gs-viewer-overlay");const message = element.querySelector(".of3gs-viewer-message");const progressBar = element.querySelector(".of3gs-viewer-progress");const progressFill = element.querySelector(".of3gs-viewer-progress-fill");const libraryPromise = import("https://cdn.jsdelivr.net/npm/gsplat@1.2.9/+esm");let renderer = null;let controls = null;let frameId = null;let resizeObserver = null;let loadGeneration = 0;function stopViewer() {if (frameId !== null) cancelAnimationFrame(frameId);if (resizeObserver) resizeObserver.disconnect();if (controls) controls.dispose();if (renderer) renderer.dispose();frameId = null;resizeObserver = null;controls = null;renderer = null;}function showState(text, progress = null) {overlay.hidden = false;message.textContent = text;if (progress === null) {progressBar.hidden = true;} else {progressBar.hidden = false;progressFill.style.width = `${Math.max(0, Math.min(1, progress)) * 100}%`;}}async function loadScene() {const url = props.value;const generation = ++loadGeneration;stopViewer();if (!url) {showState("Reconstruct a scene to view it here.");return;}showState("Loading compact 3DGS data...", 0);try {const SPLAT = await libraryPromise;if (generation !== loadGeneration) return;const scene = new SPLAT.Scene();const splat = await SPLAT.Loader.LoadAsync(url,scene,(progress) => showState(`Loading 3DGS... ${Math.round(progress * 100)}%`, progress),false,);if (generation !== loadGeneration) return;const bounds = splat.bounds;const center = bounds.center();const size = bounds.size();const radius = Math.max(0.5, Math.min(30, Math.max(size.x, size.y, size.z) * 1.35));const camera = new SPLAT.Camera();controls = new SPLAT.OrbitControls(camera, canvas, 0.5, 0.25, radius, true, center);controls.minZoom = Math.max(0.01, radius * 0.02);controls.maxZoom = Math.max(30, radius * 10);renderer = new SPLAT.WebGLRenderer(canvas);renderer.resize();resizeObserver = new ResizeObserver(() => renderer?.resize());resizeObserver.observe(canvas);overlay.hidden = true;const frame = () => {if (generation !== loadGeneration || !renderer || !controls) return;controls.update();renderer.resize();renderer.render(scene, camera);frameId = requestAnimationFrame(frame);};frameId = requestAnimationFrame(frame);} catch (error) {console.error("Failed to load 3DGS viewer", error);showState("The 3DGS viewer could not load this scene.");}}watch("value", () => void loadScene());void loadScene();"""SPLAT_VIEWER_CSS = """.of3gs-splat-viewer {position: relative;width: 100%;height: 680px;overflow: hidden;background: #000;}.of3gs-splat-viewer canvas {display: block;width: 100%;height: 100%;touch-action: none;}.of3gs-viewer-overlay {position: absolute;inset: 0;display: flex;flex-direction: column;align-items: center;justify-content: center;gap: 0.75rem;padding: 1rem;color: #e5e7eb;background: #111;text-align: center;}.of3gs-viewer-overlay[hidden] { display: none; }.of3gs-viewer-progress {width: min(22rem, 70%);height: 0.45rem;overflow: hidden;background: #3f3f46;}.of3gs-viewer-progress-fill {width: 0;height: 100%;background: #f97316;transition: width 120ms linear;}"""SPLAT_FILE_TO_VIEWER_JS = """(file) => file ? (file.url || file.path || "") : """""CSS = """.gradio-container {width: 100% !important;64 unmodified lines"*P.S. Large Gaussian scenes may take a while to load. Please be patient.*",elem_id="viewer-note",)reconstruction = gr.HTML(value="",html_template=SPLAT_VIEWER_HTML,css_template=SPLAT_VIEWER_CSS,js_on_load=SPLAT_VIEWER_JS,elem_id="model-output",)viewer_file = gr.File(visible="hidden",show_label=False,container=False,)gr.Markdown("### Output Files", elem_id="section-title")ply_download = gr.File(label="3DGS Model (.ply)")status = gr.Textbox(16 unmodified lineselem_id="example-gallery",)outputs = [viewer_file, ply_download, status]image_files.change(fn=_preview_images,inputs=image_files,14 unmodified linesoutputs=preview_gallery,show_progress="hidden",)example_reconstruction = example_event.then(fn=reconstruct_images,inputs=[image_files, scale_threshold],outputs=outputs,show_progress="full",show_progress_on=[reconstruction],)example_reconstruction.then(fn=None,inputs=viewer_file,outputs=reconstruction,js=SPLAT_FILE_TO_VIEWER_JS,show_progress="hidden",)reconstruction_event = image_submit.click(fn=reconstruct_images,inputs=[image_files, scale_threshold],outputs=outputs,show_progress="full",show_progress_on=[reconstruction],)reconstruction_event.then(fn=None,inputs=viewer_file,outputs=reconstruction,js=SPLAT_FILE_TO_VIEWER_JS,show_progress="hidden",)demo.unload(cleanup_session)demo.queue()
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879from pathlib import Path
import numpy as npimport torchfrom jaxtyping import Floatfrom torch import Tensor
SH_C0 = 0.28209479177387814
def export_splat( means: Float[Tensor, "gaussian 3"], scales: Float[Tensor, "gaussian 3"], rotations: Float[Tensor, "gaussian 4"], harmonics: Float[Tensor, "gaussian 3 d_sh"], opacities: Float[Tensor, " gaussian"], path: Path, scale_threshold: float | None = None,) -> None: """Write the compact 32-byte-per-Gaussian format used by gsplat.js.""" if harmonics.ndim == 3 and harmonics.shape[-1] == 3 and harmonics.shape[-2] != 3: harmonics = harmonics.transpose(-1, -2)
if scale_threshold is not None: if scale_threshold <= 0: raise ValueError("scale_threshold must be positive") keep = scales.max(dim=-1).values <= scale_threshold if not keep.any(): raise ValueError( f"No Gaussians remain below scale threshold {scale_threshold:.4f}" ) means = means[keep] scales = scales[keep] rotations = rotations[keep] harmonics = harmonics[keep] opacities = opacities[keep]
positions_np = means.detach().float().cpu().contiguous().numpy().astype("<f4") scales_np = scales.detach().float().cpu().contiguous().numpy().astype("<f4")
colors = (0.5 + SH_C0 * harmonics[..., 0]).clamp(0.0, 1.0) rgb_np = ( colors.detach().float().cpu().mul(255).round().to(torch.uint8).numpy() ) alpha_np = ( opacities.detach() .float() .cpu() .clamp(0.0, 1.0) .mul(255) .round() .to(torch.uint8) .numpy() )
# OF3GS trains directly with gsplat, whose quaternion convention is wxyz. rotations = torch.nn.functional.normalize(rotations.float(), dim=-1) rotations_np = ( rotations.detach() .cpu() .mul(128) .add(128) .clamp(0, 255) .round() .to(torch.uint8) .numpy() )
count = positions_np.shape[0] rows = np.empty((count, 32), dtype=np.uint8) rows[:, 0:12] = positions_np.view(np.uint8).reshape(count, 12) rows[:, 12:24] = scales_np.view(np.uint8).reshape(count, 12) rows[:, 24:27] = rgb_np rows[:, 27] = alpha_np rows[:, 28:32] = rotations_np
path.parent.mkdir(exist_ok=True, parents=True) path.write_bytes(rows.tobytes())README.md+2-1
app.py+196-9
src/model/splat_export.pyAdded+79