Commit ·
b7ed242
1
Parent(s): c0876f7
UI bettement
Browse filesFiles changed (7)
- UIPLAN.md+211-59
- app.py+163-33
- viewer/app.js+151-8
- viewer/index.html+93-41
- viewer/sample/gt_ndsm_m.npyDeleted-3
- viewer/sample/meta.jsonDeleted-34
- viewer/sample/ndsm_m.npyDeleted-3
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788# UI plan — Gradio demoGoal: make the Space easy for a first-time visitor. Keep it simple. Do notredesign the app, do not add dependencies, do not touch inference.**Only edit the `with gr.Blocks(...)` section and `_ABOUT` in `app.py`** (aroundlines 394–440). Leave `predict`, `_run_model`, and everything above them alone.---## 1. Cut the text`_ABOUT` is a 6-line paragraph. Replace with a title plus one line:```python_ABOUT = """# Single View Height EstimatorUpload an aerial or satellite image — get a per-pixel height map and a 3D view."""```Move the viewer feature list (orbit / drone cameras, drape, sun, probe) into acollapsed `gr.Accordion("How to read the result", open=False)` at the bottom ofthe page, or delete it. It does not belong above the fold.## 2. Shorten every labelCurrent labels explain internals. Use plain words; put detail in `info=` onlywhere a user could get it wrong.| now | change to || --- | --- || `Ground sampling distance (metres/pixel)` | label `Resolution (m/pixel)`, info `How many metres one pixel covers. Wrong value = wrong heights.` || `Test-time augmentation` + "Flip-averaged: steadier, roughly 4x slower." | label `Higher quality (slower)`, drop the info || `Estimate height` | `Estimate height` (keep) || `Artefacts` | `Downloads` || `Height16 (height = min + (R*256+G)/65535 * (max-min))` | label `Height (16-bit)`, move the formula to `info=` || `DSM viewer & 3D flythrough` | `3D view` || `Height colormap and hillshade` | `Height & hillshade` |## 3. Give the viewer roomThe 3D view is the payoff and it currently shares the page with everything else.- Change column scales from `1 / 2` to `1 / 3`.- Give the `gr.HTML` viewer a minimum height so it is not a thin strip before arun: wrap it in `gr.Column(min_width=...)` or set a height via the `elem_id`and a small `gr.Blocks(css=...)` rule. One short CSS rule is fine, no more.## 4. Order the left column by what the user doesInput → controls → button → status → downloads. That is already close; justmake sure `status` sits directly under the button and `downloads` is last.Set `downloads` to `visible=False` initially if that is easy, otherwise leave it.## 5. Put the two secondary outputs behind one accordion`gallery` and `height_output` are already in an accordion — keep it, but renameit `More outputs` and make sure it stays closed by default.## 6. Add examples (only if sample images exist)If there are usable aerial images in the repo or `/data`, add:```pythongr.Examples(examples=[[path, 0.5, False]], inputs=[image, gsd, tta])```There are none in `viewer/sample/` (it holds `.npy`, not images). If you cannotfind a real image, **skip this step** — do not generate a fake one.## 7. Show that something is happening`run.click(...)` gives no feedback during a 20–40 s inference.- Set `show_progress="full"` on the click.- Before the heavy work, have the button's handler clear `status`, or add atiny `.click()` chain that writes `Running…` first. Keep it to one extrahandler at most.---## Rules- No new pip packages. No custom theme files. No JS.- At most a few lines of CSS, inline in `gr.Blocks(css=...)`.- Do not change the `predict` signature or the outputs list order.- Do not run or test the app locally — the user has asked for this explicitly.Verify by reading the diff.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240# UI review — issues and bettermentsScope: the Gradio shell (`app.py`) and the embedded dual-pane viewer(`viewer/index.html` + `viewer/app.js`) as it renders inside the Space.Ordered by impact. Each item names the file and the concrete change.---## P0 — broken or misleading behaviour### 1. `Running…` is never cleared when the run fails`app.py` (`run.click(...).then(...)`) — the chain writes `"Running…"` into`status`, and `predict` raises `gr.Error` on every failure path. Gradio showsthe error toast, but `status` is an *output of the raising function*, so it isnever overwritten: the page keeps claiming the job is in flight, permanently.Fix: return errors as values instead of raising for the recoverable cases(quota exhausted, no image, non-finite output), or add a trailing cleanup stepthat resets `status` regardless of outcome.### 2. Stale results stay on screen during and after a new runUploading a second image leaves the previous run's viewer iframe, gallery,16-bit image and download bundle visible. A user who changes the GSD andre-runs sees the *old* 3D scene for the whole run and has no way to tell whichresult the downloads belong to.Fix: in the first `.then` step, clear every output (`gr.update(value=None)`for gallery/height/downloads, `""` for the viewer) alongside `"Running…"`.### 3. The run button is not disabled while a run is in flightTwo clicks = two ZeroGPU reservations = double the quota burn, which is thesingle most common failure mode for this Space (see the quota error text in`app.py`). Nothing in the UI prevents it.Fix: `run.click(lambda: (gr.update(interactive=False), "Running…"), ...)` andre-enable in a trailing `.then`. Setting `concurrency_limit=1` on the event isworth doing too.### 4. No empty state — the viewer is a 560 px void on first load`_CSS` reserves the height so the layout does not collapse, but nothing isdrawn there. A first-time visitor sees a large blank panel and no signal thatit will become a 3D scene.Fix: render a placeholder into `gr.HTML` at startup (a dashed frame with"Your 3D terrain will appear here" plus the one-line workflow), replaced onthe first result.### 5. No examplesThere is no `gr.Examples`. A visitor with no aerial imagery to hand — themajority — cannot try the demo at all. `viewer/sample/` already exists.Fix: `gr.Examples([[sample_png, 0.5, False]], inputs=[image, gsd, tta])` withtwo or three scenes at different GSDs.### 6. Silent downsampling is never surfaced`read_scene(..., max_side=1600)` resamples any large scene, and the viewerpayload is capped again at `_VIEWER_MAX_SIDE = 1024`. `meta.json` carries thenote; the UI says nothing. A user who uploads an 8000 px tile gets aquarter-resolution product and no warning.Fix: when the input was resampled, add a line to `status` — "Scene resampled8000 → 1600 px (GSD adjusted 0.15 → 0.75 m/px)."---## P1 — comprehension: the result cannot be read### 7. No colour legend anywhereThe turbo height colormap is the primary output — in the gallery, the 2D mappane and the 3D drape — and there is no colorbar in any of the three. Colourcannot be converted back to metres by eye. `viewer/app.js` has `turbo()`;nothing draws a scale from it.Fix: draw a vertical colorbar with min/mid/max metre ticks into the 2D paneand the 3D pane corner, and bake one into `height_colormap.png` in`_write_artifacts`.### 8. No scale bar or north arrow on the 2D mapThe pane reports nothing about ground extent. `S.gsd` is known, so a100 m / 500 m bar is a few lines of canvas.### 9. The elevation profile is unlabelled`drawProfile` in `viewer/app.js` prints only the max height. No y-axisminimum, no x-axis ground distance, no units on the axis. The numbers exist in`reportProbe` but are not tied to the plot.Fix: label both ends of the y range and the x extent in metres.### 10. The low-ground warning is buriedThe `frac_below_1m < 0.15` warning is appended to the bottom of a four-linemarkdown blob in the sidebar. It is the most important correctness signal theapp produces — it usually means the declared GSD is wrong.Fix: give it its own `gr.Markdown` with a visible warning style, above thestats, hidden when not triggered.### 11. Two product names in one pageThe Gradio header says "Single View Height Estimator"; the iframe sidebar says"DepthWizard · single-view DSM · SIH 2026 PS 26175". Inside one viewport thatreads as an embedded third-party tool.Fix: pick one name; hide or rewrite the viewer's `<h1>`/`.tag` under`body.embedded`.### 12. Dead UI in embedded modeThe viewer hides `#loadSection` when embedded, but leaves:- the **Validation** section telling the user to "load `gt_ndsm_m.npy`alongside" — impossible, the file picker is gone;- permanently-disabled `Reference height` / `Error vs reference` options inboth layer dropdowns.Fix: `body.embedded` hides the Validation section and both reference options;keep them for the standalone `viewer/index.html`.### 13. "Mesh detail" options are misleading in the SpaceThe embedded payload is capped at 1024 px (~1.05 M pixels), so "Full (1.5M)"and "Balanced (500k)" differ little and "Full" can never be reached.`_VIEWER_MAX_SIDE` and the `#quality` options are set independently anddisagree.Fix: derive the option list from the actual grid size, or relabel to Fast /Balanced / Full without vertex counts.### 14. Downloads are an unlabelled pile of temp paths`gr.File(file_count="multiple")` shows `dw_a1b2c3_result.zip`, `ndsm_m.npy`,`terrain.glb`… with no explanation of what to do with each. The zip name is atemp directory id.Fix: rename the archive after the uploaded file, and put a one-line legendunder the component — "`.npy` = raw metres · `.glb` = textured mesh ·`meta.json` = encoding + scene metadata".---## P2 — input ergonomics### 15. The GSD field is the app's main footgun and is under-supported`minimum=0.01`, no maximum, and `0` silently means "guess from thecheckpoint's canonical GSD" (`float(gsd or 0)` → `read_scene` falls back to`spec.canonical_gsd_m`). Nothing tells the user that, before or after.Fix: add a preset radio (0.3 / 0.5 / 1.0 m/px + Custom + "I don't know"), makethe "don't know" path explicit, and echo the *effective* GSD and its source inthe status line (`scene_meta.gsd_source` is already computed).### 16. TTA does not disclose its cost"Higher quality (slower)" hides the fact that it asks for a 120 s ZeroGPUwindow instead of 45 s — and that this is the usual cause of the quota error.The user only learns it from the failure message.Fix: `info="~4× the compute; reserves 120 s of GPU quota instead of 45 s"`.### 17. No expected runtime anywhereNothing tells the user whether to wait 10 s or 3 minutes before the first run.### 18. No reset / clearOnce a result is on screen there is no way back to the empty state.---## P3 — layout, theme, accessibility### 19. The Gradio shell is light, the viewer is hard-coded dark`viewer/index.html` sets `color-scheme: dark` and `--bg:#0d1013`. In default(light) Gradio that is a 760 px black slab in a white page.Fix: set a dark `gr.themes` on the Blocks, or make the viewer's palette follow`prefers-color-scheme` and pass the host theme in through the payload.### 20. Fixed 760 px iframe heightHard-coded in `_viewer()`. On a 768 px-tall laptop the viewer needs pagescrolling, while the viewer itself is `overflow:hidden` — so its sidebarscrolls independently inside a frame that is already clipped. Two nestedscroll contexts.Fix: size the iframe in viewport units (`height:min(760px, 78vh)`) with afloor, and add a fullscreen toggle (the frame already has `allowfullscreen`).### 21. The viewer's mobile breakpoint fires on desktop`@media (max-width:900px)` is evaluated against the *iframe* width. In the 3:1column split the frame is often under 900 px on a normal laptop, so the 2Dpane disappears and the sidebar stacks — the mobile layout on a desktop, whichreads as a bug.Fix: switch to a container-driven breakpoint (or lower it and set a`min_width` on the Gradio column so the frame stays wide).### 22. The 322 px fixed sidebar squeezes the 2D paneInside an already-narrow frame, `322px | 38% | 1fr` leaves the map pane asliver. Consider a collapsible sidebar.### 23. No `<label for=...>` anywhere in the viewerEvery control in `viewer/index.html` uses a bare `<label>` followed by asibling input — exaggeration, sun azimuth/elevation, drape, mesh detail.Labels are not clickable and screen readers announce nothing. The checkboxrows wrap their text in a `<span>`, not a label.Fix: add `for=`/`id=` pairs, or wrap the inputs.### 24. Mode buttons carry no pressed state for assistive tech`button.on` is visual only — add `aria-pressed`. `#hud`, `#probe` and `#info`update silently — add `aria-live="polite"` to `#probe` and `#warn`.### 25. `gr.HTML(label="3D view")` renders no label`gr.HTML` ignores `label`. The main output panel is unheaded.### 26. Keyboard shortcuts need a click first`F` and `R` are bound on the iframe's `window`; until the user clicks insidethe frame the host page owns the keyboard. The hint advertises themunconditionally.Fix: mention "click the scene first", or focus the canvas on load.### 27. Desktop-only interaction hints`drag = orbit · scroll = zoom` with no touch equivalents, and the 2D paneprobe is pointer-only with no zoom/pan.### 28. `warn()` appends without bound or dedupeIt concatenates into `#warn.innerHTML` forever. A repeating error grows thesidebar indefinitely and there is no dismiss.### 29. No progress feedback while the mesh builds`buildMesh()` on a ~1 M-vertex grid blocks the frame for seconds *after* theGradio progress bar has already finished. The user sees a frozen black paneand no spinner.### 30. Small type throughout the viewer11–12 px for controls, 11 px for `.tag`, `#hud` and `#hint`. Fine for a densedesktop tool, tight inside an embedded frame.---## Suggested order of work1. **P0 1–3** — state bugs; small diffs in the `run.click` chain.2. **P0 4–5** — empty state + examples; the biggest first-impression win.3. **P1 7–9** — colorbar, scale bar, profile axes; makes the output readable.4. **P1 10–14** + **P2 15–16** — messaging and input clarity.5. **P3** — theme unification (19) and the layout/breakpoint pair (20–22)together, then accessibility (23–25).
145 unmodified lines1461471481491501511521531541551561573 unmodified lines16116216316416516616716816917017117217345 unmodified lines2192202212222232249 unmodified lines23423523623723823924011 unmodified lines25225325425525625725825926026126226326426526626726841 unmodified lines31031131231331431531631731831932032132232328 unmodified lines3523533543553563579 unmodified lines3673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094 unmodified lines4144154164174184194204214224234244254264274284294304314324334344354364374384398 unmodified lines448449450451452453454455456457458459460145 unmodified linesreturn ('<iframe title="DSM viewer and 3D flythrough" ''allow="fullscreen; pointer-lock" allowfullscreen ''style="width:100%;height:760px;border:0;border-radius:10px;''background:#0d1013" 'f'srcdoc="{escaped}"></iframe>')# ---------------------------------------------------------------------# encodings and artefacts# ---------------------------------------------------------------------3 unmodified linesNothing downstream tolerates a NaN: it casts to garbage in the uint16encoding, puts a hole in the mesh, and makes `json.dumps` refuse themetadata. A fully non-finite prediction is a real failure, so it is raisedrather than patched."""finite = np.isfinite(height)if finite.all():return heightif not finite.any():raise gr.Error("The model returned no finite heights for this image.")out = height.copy()out[~finite] = float(height[finite].min())return out45 unmodified linesreturn resize(array, out_hw, order), out_hw[0] / array.shape[0]def _write_artifacts(out_dir: Path, rgb: np.ndarray, height: np.ndarray, meta: dict, gsd_m: float) -> list[str]:9 unmodified lines# the two pure-numpy figure primitives; neither needs matplotlibvmax = float(max(np.nanmax(height), 1.0))Image.fromarray(viz_figures.colorize(height, 0.0, vmax)).save(out_dir / "height_colormap.png")Image.fromarray(viz_figures.hillshade(height, gsd_m), mode="L").save(11 unmodified linesreturn filesdef _bundle(out_dir: Path, files: list[str]) -> list[str]:"""One zip plus the headline files — a mesh without its texture is junk, sothe OBJ set is only offered inside the archive."""archive = shutil.make_archive(str(out_dir.parent / f"{out_dir.name}_result"), "zip", out_dir)keep = ["ndsm_m.npy", "meta.json", "terrain.glb", "height_colormap.png","hillshade.png"]return [archive] + [str(out_dir / f) for f in keep if (out_dir / f).is_file()]# ---------------------------------------------------------------------# ZeroGPU bookkeeping# ---------------------------------------------------------------------41 unmodified lines_run_model_gpu_tta = spaces.GPU(duration=_GPU_DURATION_TTA)(_run_model)def predict(image_path: str | None, gsd: float, tta: bool = False):if not image_path:raise gr.Error("Upload an image first.")try:from dwdata.preprocess import read_scene# CPU work, deliberately outside the reservation_, spec, _ = _load_model_once()rgb, scene_meta = read_scene(image_path,user_gsd_m=float(gsd or 0),28 unmodified lines"preproc": spec.to_dict(),}out_dir = Path(tempfile.mkdtemp(prefix="dw_"))files = _write_artifacts(out_dir, rgb, height, meta, scene_meta.gsd_m)9 unmodified lines"meta": view_meta,})info = "\n\n".join([f"**Height** {low:.2f} – {high:.2f} m · mean "f"{meta['height_mean_m']:.2f} m · median {meta['height_median_m']:.2f} m",f"**GSD** {scene_meta.gsd_m:.3f} m/px ({scene_meta.gsd_source}) · "f"**scene** {height.shape[1]} × {height.shape[0]} px",f"**{meta['frac_below_1m'] * 100:.1f} %** of pixels below 1 m ""(a nadir urban scene is usually 40–70 %)",f"Product `{meta['product']}` · {len(files)} artefacts written",])if meta["frac_below_1m"] < 0.15:info += ("\n\n⚠️ Very little flat ground — the model may be reading texture ""as terrain. Check the declared GSD.")gallery = [(str(out_dir / "height_colormap.png"), "Height (turbo, 0 – max)"),(str(out_dir / "hillshade.png"), "Hillshade (315° / 45°)"),]return gallery, height16, viewer_html, _bundle(out_dir, files), infoexcept gr.Error:raiseexcept Exception as exc:text = str(exc).lower()if "quota" in text or "gpu task aborted" in text or "gpu time" in text:# not a model failure: the caller's ZeroGPU allowance ran outraise gr.Error("Your ZeroGPU quota for today is used up. Sign in to Hugging ""Face for a larger allowance, turn TTA off (it asks for a "f"{_GPU_DURATION_TTA} s window instead of {_GPU_DURATION} s), ""or retry after the quota resets.") from excraise gr.Error(f"Inference failed: {exc}") from exc_ABOUT = """# Single View Height EstimatorUpload an aerial or satellite image — get a per-pixel height map and a 3D view."""# the viewer's controls, kept out of the way until someone has a result to read4 unmodified linessurface to probe a height or slope; drag across it for an elevation profile."""# The HTML viewer has no intrinsic height, so it collapses to a strip before the# first run. One rule, so the empty state still looks like a stage._CSS = "#viewer, #viewer > div { min-height: 560px; }"with gr.Blocks(title="Single View Height Estimator", css=_CSS) as demo:gr.Markdown(_ABOUT)with gr.Row():with gr.Column(scale=1):image = gr.Image(type="filepath", label="Image", sources=["upload"])gsd = gr.Number(value=0.5, minimum=0.01,label="Resolution (m/pixel)",info="How many metres one pixel covers. Wrong value = wrong heights.",)tta = gr.Checkbox(value=False, label="Higher quality (slower)")run = gr.Button("Estimate height", variant="primary")status = gr.Markdown()downloads = gr.File(label="Downloads", file_count="multiple")with gr.Column(scale=3):viewer = gr.HTML(label="3D view", elem_id="viewer")with gr.Accordion("More outputs", open=False):gallery = gr.Gallery(label="Height & hillshade", columns=2, height=320,8 unmodified lineswith gr.Accordion("How to read the result", open=False):gr.Markdown(_VIEWER_HELP)run.click(lambda: "Running…", outputs=status,).then(predict,inputs=[image, gsd, tta],outputs=[gallery, height_output, viewer, downloads, status],show_progress="full",)145 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721733 unmodified lines17717817918018118218318418518618718818919045 unmodified lines2362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662679 unmodified lines27727827928028128228311 unmodified lines29529629729829930030130230330430530630730830931031131231331431531631731831932032141 unmodified lines36336436536636736836937037137237337437537637737837938038138238338438528 unmodified lines4144154164174184194209 unmodified lines4304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834 unmodified lines4884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405418 unmodified lines550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590145 unmodified linesreturn ('<iframe title="DSM viewer and 3D flythrough" ''allow="fullscreen; pointer-lock" allowfullscreen ''style="width:100%;height:min(760px,78vh);min-height:420px;border:0;''border-radius:10px;background:#0d1013" 'f'srcdoc="{escaped}"></iframe>')# A placeholder shown before the first run and whenever a run fails, so the# 560px slot the CSS reserves never reads as a broken/blank panel._EMPTY_VIEWER_HTML = ('<div style="height:min(760px,78vh);min-height:420px;border:1px dashed #3a4048;''border-radius:10px;background:#0d1013;color:#8a949e;display:flex;''flex-direction:column;align-items:center;justify-content:center;gap:10px;''text-align:center;padding:24px;font-family:system-ui,-apple-system,''\'Segoe UI\',sans-serif">''<div style="font-size:16px;color:#c7ced6">Your 3D terrain will appear here</div>''<div style="font-size:13px;max-width:420px;line-height:1.5">''Upload an aerial or satellite image, set its resolution (m/pixel), and ''click <b>Estimate height</b>.</div>''</div>')# ---------------------------------------------------------------------# encodings and artefacts# ---------------------------------------------------------------------3 unmodified linesNothing downstream tolerates a NaN: it casts to garbage in the uint16encoding, puts a hole in the mesh, and makes `json.dumps` refuse themetadata. A fully non-finite prediction is a real failure, so it is raisedrather than patched — the caller turns this into a status message insteadof a raw traceback."""finite = np.isfinite(height)if finite.all():return heightif not finite.any():raise ValueError("The model returned no finite heights for this image.")out = height.copy()out[~finite] = float(height[finite].min())return out45 unmodified linesreturn resize(array, out_hw, order), out_hw[0] / array.shape[0]def _with_colorbar(colormap: np.ndarray, low: float, high: float) -> Image.Image:"""Height colormap + a vertical turbo scale down its right edge.Colour cannot be converted back to metres by eye without this — the turboramp is the app's primary output and shipped with no legend otherwise."""from PIL import ImageDrawh, w = colormap.shape[:2]bar_w = max(28, w // 22)pad = 8canvas = Image.new("RGB", (w + bar_w + pad + 54, h), (13, 16, 19))canvas.paste(Image.fromarray(colormap), (0, 0))ramp = np.array(viz_figures.colorize(np.linspace(high, low, h).reshape(-1, 1), low, high),dtype=np.uint8,)canvas.paste(Image.fromarray(np.repeat(ramp, bar_w, axis=1)), (w + pad, 0))draw = ImageDraw.Draw(canvas)for frac, value in ((0.0, high), (0.5, (low + high) / 2), (1.0, low)):y = int(frac * (h - 1))y = min(max(y, 6), h - 8)draw.text((w + pad + bar_w + 4, y - 6), f"{value:.1f} m", fill=(232, 236, 241))return canvasdef _write_artifacts(out_dir: Path, rgb: np.ndarray, height: np.ndarray, meta: dict, gsd_m: float) -> list[str]:9 unmodified lines# the two pure-numpy figure primitives; neither needs matplotlibvmax = float(max(np.nanmax(height), 1.0))_with_colorbar(viz_figures.colorize(height, 0.0, vmax), 0.0, vmax).save(out_dir / "height_colormap.png")Image.fromarray(viz_figures.hillshade(height, gsd_m), mode="L").save(11 unmodified linesreturn filesdef _bundle(out_dir: Path, files: list[str], name_stem: str) -> list[str]:"""One zip plus the headline files — a mesh without its texture is junk, sothe OBJ set is only offered inside the archive.`name_stem` comes from the uploaded file, not the temp directory, so thedownload reads as e.g. `rooftop_result.zip` instead of `dw_a1b2c3_result.zip`."""archive = shutil.make_archive(str(out_dir.parent / f"{name_stem}_result"), "zip", out_dir)keep = ["ndsm_m.npy", "meta.json", "terrain.glb", "height_colormap.png","hillshade.png"]return [archive] + [str(out_dir / f) for f in keep if (out_dir / f).is_file()]def _safe_stem(image_path: str) -> str:stem = Path(image_path).stem or "scene"stem = re.sub(r"[^A-Za-z0-9_-]+", "_", stem).strip("_")return stem[:40] or "scene"# ---------------------------------------------------------------------# ZeroGPU bookkeeping# ---------------------------------------------------------------------41 unmodified lines_run_model_gpu_tta = spaces.GPU(duration=_GPU_DURATION_TTA)(_run_model)# Outputs of `predict`, in order — kept as a tuple factory so every return# path (success, validation failure, GPU failure) fills exactly these six# slots and a failed run never leaves a stale result on screen.def _result(gallery=None, height16=None, viewer_html=None, downloads=None,status="", warning=""):return gallery, height16, viewer_html or _EMPTY_VIEWER_HTML, downloads, status, warningdef predict(image_path: str | None, gsd: float, tta: bool = False):if not image_path:return _result(status="Upload an image first.")try:from dwdata.preprocess import read_scene# CPU work, deliberately outside the reservation_, spec, _ = _load_model_once()orig_w, orig_h = Image.open(image_path).sizergb, scene_meta = read_scene(image_path,user_gsd_m=float(gsd or 0),28 unmodified lines"preproc": spec.to_dict(),}stem = _safe_stem(image_path)out_dir = Path(tempfile.mkdtemp(prefix="dw_"))files = _write_artifacts(out_dir, rgb, height, meta, scene_meta.gsd_m)9 unmodified lines"meta": view_meta,})info = [f"**Height** {low:.2f} – {high:.2f} m · mean "f"{meta['height_mean_m']:.2f} m · median {meta['height_median_m']:.2f} m",f"**GSD** {scene_meta.gsd_m:.3f} m/px (effective, {scene_meta.gsd_source}) · "f"**scene** {height.shape[1]} × {height.shape[0]} px",f"**{meta['frac_below_1m'] * 100:.1f} %** of pixels below 1 m ""(a nadir urban scene is usually 40–70 %)",f"Product `{meta['product']}` · {len(files)} artefacts written",]if max(orig_w, orig_h) != max(scene_meta.width, scene_meta.height):info.append(f"Scene resampled {max(orig_w, orig_h)} → "f"{max(scene_meta.width, scene_meta.height)} px "f"(GSD adjusted to {scene_meta.gsd_m:.3f} m/px to match).")warning = ""if meta["frac_below_1m"] < 0.15:warning = ("⚠️ Very little flat ground in this result — the model may be ""reading texture as terrain. Double-check the declared GSD.")gallery = [(str(out_dir / "height_colormap.png"), "Height (turbo, 0 – max, with scale)"),(str(out_dir / "hillshade.png"), "Hillshade (315° / 45°)"),]return _result(gallery, height16, viewer_html, _bundle(out_dir, files, stem),"\n\n".join(info), warning,)except Exception as exc:text = str(exc).lower()if "quota" in text or "gpu task aborted" in text or "gpu time" in text:# not a model failure: the caller's ZeroGPU allowance ran outreturn _result(status=("Your ZeroGPU quota for today is used up. Sign in to Hugging ""Face for a larger allowance, turn TTA off (it asks for a "f"{_GPU_DURATION_TTA} s window instead of {_GPU_DURATION} s), ""or retry after the quota resets."))return _result(status=f"Inference failed: {exc}")_ABOUT = """# Single View Height EstimatorUpload an aerial or satellite image — get a per-pixel height map and a 3D view.A first run typically takes ~15-45 s (~1-2 min with **Higher quality**); nothingtouches a GPU until you click **Estimate height**."""# the viewer's controls, kept out of the way until someone has a result to read4 unmodified linessurface to probe a height or slope; drag across it for an elevation profile."""_DOWNLOADS_LEGEND = ("`.npy` = raw heights in metres (float32) · `.png` = colourised previews · ""`.glb` = textured 3D mesh · `meta.json` = encoding + scene metadata · ""the `.zip` bundles everything, named after your upload.")# The HTML viewer has no intrinsic height, so it collapses to a strip before the# first run. One rule, so the empty state still looks like a stage. The value# tracks the iframe's own `min-height` (`_viewer`/`_EMPTY_VIEWER_HTML` above)._CSS = "#viewer, #viewer > div { min-height: 420px; }"# The viewer's palette is hard-coded dark; keep the host shell in step so a# result does not read as a black slab dropped into a white page._FORCE_DARK_JS = "() => { document.body.classList.add('dark'); }"with gr.Blocks(title="Single View Height Estimator", css=_CSS, js=_FORCE_DARK_JS) as demo:gr.Markdown(_ABOUT)with gr.Row():with gr.Column(scale=1):image = gr.Image(type="filepath", label="Image", sources=["upload"])gsd = gr.Number(value=0.5, minimum=0,label="Resolution (m/pixel)",info="How many metres one pixel covers. Wrong value = wrong ""heights. Leave at 0 to let the model guess from its training ""resolution — the effective value used is always echoed below.",)tta = gr.Checkbox(value=False, label="Higher quality (slower)",info=f"~4× the compute; reserves {_GPU_DURATION_TTA} s of GPU "f"quota instead of {_GPU_DURATION} s. The usual cause of a ""quota error — leave off unless you need it.",)with gr.Row():run = gr.Button("Estimate height", variant="primary")clear = gr.Button("Reset")status = gr.Markdown()warning = gr.Markdown(visible=False, elem_id="lowground-warning")downloads = gr.File(label="Downloads", file_count="multiple")gr.Markdown(_DOWNLOADS_LEGEND)gr.Examples(examples=[[str(_VIEWER_ROOT / "sample" / "rgb.png"), 0.5, False]],inputs=[image, gsd, tta],label="No imagery to hand? Try a sample scene",)with gr.Column(scale=3, min_width=640):gr.Markdown("### 3D view")viewer = gr.HTML(value=_EMPTY_VIEWER_HTML, elem_id="viewer")with gr.Accordion("More outputs", open=False):gallery = gr.Gallery(label="Height & hillshade", columns=2, height=320,8 unmodified lineswith gr.Accordion("How to read the result", open=False):gr.Markdown(_VIEWER_HELP)def _mark_warning(text: str):if not text:return gr.update(value="", visible=False)html_text = ('<div style="background:#3a1f0a;border:1px solid #7a4a1e;''border-left:4px solid #e5793a;border-radius:6px;padding:10px 14px;'f'color:#f0c9a0;font-size:13px">{text}</div>')return gr.update(value=html_text, visible=True)run.click(lambda: (gr.update(interactive=False), [], None, _EMPTY_VIEWER_HTML, None,"Running…", gr.update(value="", visible=False),),outputs=[run, gallery, height_output, viewer, downloads, status, warning],).then(predict,inputs=[image, gsd, tta],outputs=[gallery, height_output, viewer, downloads, status, warning],show_progress="full",concurrency_limit=1,).then(_mark_warning, inputs=warning, outputs=warning,).then(lambda: gr.update(interactive=True), outputs=run,)clear.click(lambda: (None, 0.5, False, [], None, _EMPTY_VIEWER_HTML, None, "",gr.update(value="", visible=False),),outputs=[image, gsd, tta, gallery, height_output, viewer, downloads,status, warning],)
89 unmodified lines909192939495193 unmodified lines28929029129229329429537 unmodified lines33333433533633733833964 unmodified lines404405406407408409410411412413151 unmodified lines5655665675685695705715727 unmodified lines5805815825835845855861 unmodified line58858959059159259334 unmodified lines62862963063163263322 unmodified lines656657658659660661662663664665110 unmodified lines77677777877978078178278359 unmodified lines84384484584684784827 unmodified lines87687787887988088189 unmodified lines: [255, 255 * (1 - x * 0.55), 255 * (1 - x * 0.85)];}// ---------------------------------------------------------------------------// the loaded scene// ---------------------------------------------------------------------------193 unmodified linesreturn step;}function buildMesh() {if (mesh) {mesh.geometry.dispose();mesh.material.map?.dispose();37 unmodified linesupdateSun();buildFlyPath();resetCamera();$('vertCount').textContent = (gw * gh).toLocaleString() + ' verts (1:' + step + ')';}function applyExaggeration() {64 unmodified linesif (m === 'fp') { try { fpControls.lock(); } catch (e) { /* needs a gesture */ } }else if (fpControls.isLocked) fpControls.unlock();for (const b of document.querySelectorAll('[data-mode]')) {b.classList.toggle('on', b.dataset.mode === m);}$('hint').textContent = {orbit: 'drag = orbit · scroll = zoom · click = probe · F = first person · R = reset',fp: 'WASD = move · Shift = sprint · Space/C = up/down · mouse = look · Esc = exit',fly: 'cinematic drone orbit — press Orbit to take control',}[m];151 unmodified linesline(pred, '#2d6cdf', 1.6);g.fillStyle = '#8a949e';g.font = `${10 * devicePixelRatio}px system-ui`;g.fillText(`${hi.toFixed(1)} m`, pad, 11 * devicePixelRatio);g.fillText(`${lo.toFixed(1)} m`, pad, h - pad);}// ---------------------------------------------------------------------------7 unmodified linesg.clearRect(0, 0, w, h);if (!S.height) return;const src = layerCanvas($('layer2d').value);const sc = Math.min(w / S.W, h / S.H);const dw = S.W * sc, dh = S.H * sc;const ox = (w - dw) / 2, oy = (h - dh) / 2;1 unmodified lineg.drawImage(src, ox, oy, dw, dh);if ($('contours').checked) drawContours(g, ox, oy, sc);// everything below is an overlay on the raster, so clip it to the raster —// the camera can sit outside the scene and its indicator should not scribble34 unmodified linescv._map = { ox, oy, sc };}function drawContours(g, ox, oy, sc) {const step = Math.max(1, Math.round((S.hMax - S.hMin) / 12));g.strokeStyle = 'rgba(255,255,255,.35)';22 unmodified lines// ---------------------------------------------------------------------------// loading// ---------------------------------------------------------------------------function warn(msg) {const el = $('warn');el.style.display = 'block';el.innerHTML += (el.innerHTML ? '<br>' : '') + msg;}async function loadFromFiles(fileList) {110 unmodified lineswarn('no usable height array — nothing to render');return;}$('warn').style.display = 'none';$('warn').innerHTML = '';S.H = hgt.shape[0]; S.W = hgt.shape[1];S.height = hgt.data;S.gt = gt && gt.length === S.height.length ? gt : null;59 unmodified linesmesh.material.map = t;mesh.material.wireframe = $('wire').checked;mesh.material.needsUpdate = true;}// ---------------------------------------------------------------------------27 unmodified linesdocument.body.classList.toggle('only3d');setTimeout(resize, 60);});setMode('orbit');89 unmodified lines90919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133193 unmodified lines32732832933033133233333433533633733833934034134234334434534634734834935035137 unmodified lines38939039139239339439539639764 unmodified lines462463464465466467468469470471472473474475151 unmodified lines6276286296306316326336346356366376386396407 unmodified lines6486496506516526536546551 unmodified line65765865966066166266366466566666766866967034 unmodified lines70570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074122 unmodified lines764765766767768769770771772773774775776777778779780781782783784785786787788789110 unmodified lines90090190290390490590659 unmodified lines96696796896997097197227 unmodified lines100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102489 unmodified lines: [255, 255 * (1 - x * 0.55), 255 * (1 - x * 0.85)];}/** Draw a vertical colour scale into `wrap`'s canvas, or hide it for layers* that carry no scalar scale (optical RGB). `lo`/`hi` are in metres for the* turbo ramp, or a signed +/-limit in metres for the diverging error ramp. */function drawColorbar(wrapId, mode, lo, hi, errLim) {const wrap = $(wrapId);if (!wrap) return;const cv = wrap.querySelector('canvas');if (mode !== 'height' && mode !== 'reference' && mode !== 'error') {wrap.style.display = 'none';return;}if (mode === 'error') hi = errLim;wrap.style.display = 'flex';const w = cv.width, h = cv.height;const g = cv.getContext('2d');const img = g.createImageData(w, h);for (let y = 0; y < h; y++) {const t = 1 - y / (h - 1);const [r, gg, b] = mode === 'error' ? diverging(t * 2 - 1) : turbo(t);for (let x = 0; x < w; x++) {const i = (y * w + x) * 4;img.data[i] = r; img.data[i + 1] = gg; img.data[i + 2] = b; img.data[i + 3] = 255;}}g.putImageData(img, 0, 0);let labelHi = wrap.querySelector('.cb-hi'), labelLo = wrap.querySelector('.cb-lo');if (!labelHi) {labelHi = document.createElement('div'); labelHi.className = 'cb-hi';labelLo = document.createElement('div'); labelLo.className = 'cb-lo';labelLo.style.marginTop = '2px';wrap.insertBefore(labelHi, cv);wrap.appendChild(labelLo);}const unit = mode === 'error' ? ' m err' : ' m';labelHi.textContent = fmt(hi, 1) + unit;labelLo.textContent = fmt(mode === 'error' ? -hi : lo, 1) + unit;}// ---------------------------------------------------------------------------// the loaded scene// ---------------------------------------------------------------------------193 unmodified linesreturn step;}function build3dColorbar() {const layer = $('layer').value;let errLim = 1;if (layer === 'error' && S.gt) {for (let i = 0; i < S.height.length; i++) errLim = Math.max(errLim, Math.abs(S.height[i] - S.gt[i]));errLim = Math.max(errLim * 0.6, 1);}drawColorbar('colorbar3d', layer, S.hMin, S.hMax, errLim);}function buildMesh() {// a ~1M-vertex grid blocks the main thread for a noticeable moment; give// the spinner a frame to paint before the synchronous work below startsconst spinner = $('meshSpinner');if (spinner) spinner.classList.add('show');setTimeout(() => _buildMeshNow(), 0);}function _buildMeshNow() {if (mesh) {mesh.geometry.dispose();mesh.material.map?.dispose();37 unmodified linesupdateSun();buildFlyPath();resetCamera();build3dColorbar();$('vertCount').textContent = (gw * gh).toLocaleString() + ' verts (1:' + step + ')';$('meshSpinner')?.classList.remove('show');}function applyExaggeration() {64 unmodified linesif (m === 'fp') { try { fpControls.lock(); } catch (e) { /* needs a gesture */ } }else if (fpControls.isLocked) fpControls.unlock();for (const b of document.querySelectorAll('[data-mode]')) {const on = b.dataset.mode === m;b.classList.toggle('on', on);b.setAttribute('aria-pressed', String(on));}$('hint').innerHTML = {orbit: 'click the scene to focus it, then: drag = orbit · scroll = zoom · ' +'click = probe · F = first person · R = reset<br>' +'<span class="dim">touch: one finger = orbit · pinch = zoom · two-finger drag = pan</span>',fp: 'WASD = move · Shift = sprint · Space/C = up/down · mouse = look · Esc = exit',fly: 'cinematic drone orbit — press Orbit to take control',}[m];151 unmodified linesline(pred, '#2d6cdf', 1.6);g.fillStyle = '#8a949e';g.font = `${10 * devicePixelRatio}px system-ui`;g.textAlign = 'left';g.fillText(`${hi.toFixed(1)} m`, pad, 11 * devicePixelRatio);g.fillText(`${lo.toFixed(1)} m`, pad, h - 3 * devicePixelRatio);const groundDist = Math.hypot((S.probeB.col - S.probeA.col) * S.gsd, (S.probeB.row - S.probeA.row) * S.gsd);g.textAlign = 'right';g.fillText(`A → B · ${groundDist.toFixed(1)} m ground`, w - pad, 11 * devicePixelRatio);g.textAlign = 'left';}// ---------------------------------------------------------------------------7 unmodified linesg.clearRect(0, 0, w, h);if (!S.height) return;const layer2d = $('layer2d').value;const src = layerCanvas(layer2d);const sc = Math.min(w / S.W, h / S.H);const dw = S.W * sc, dh = S.H * sc;const ox = (w - dw) / 2, oy = (h - dh) / 2;1 unmodified lineg.drawImage(src, ox, oy, dw, dh);if ($('contours').checked) drawContours(g, ox, oy, sc);drawScaleBar(g, w, h, sc);const errLim = (() => {if (layer2d !== 'error' || !S.gt) return 1;let lim = 0;for (let i = 0; i < S.height.length; i++) lim = Math.max(lim, Math.abs(S.height[i] - S.gt[i]));return Math.max(lim * 0.6, 1);})();drawColorbar('colorbar2d', layer2d, S.hMin, S.hMax, errLim);// everything below is an overlay on the raster, so clip it to the raster —// the camera can sit outside the scene and its indicator should not scribble34 unmodified linescv._map = { ox, oy, sc };}/** A ground-distance scale bar sized to a round number of metres. */function drawScaleBar(g, canvasW, canvasH, sc) {const cv = $('scalebar');if (!cv || !S.gsd) return;const host = $('pane2d');cv.width = host.clientWidth * devicePixelRatio;cv.height = 34 * devicePixelRatio;const gg = cv.getContext('2d');gg.clearRect(0, 0, cv.width, cv.height);const pxPerMetre = sc / S.gsd;const maxBarPx = canvasW * 0.28;const niceSteps = [1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 5000];let metres = niceSteps[0];for (const step of niceSteps) {if (step * pxPerMetre <= maxBarPx) metres = step; else break;}const barPx = metres * pxPerMetre;const x0 = 10 * devicePixelRatio, y = cv.height - 12 * devicePixelRatio;gg.strokeStyle = '#e8ecf1'; gg.lineWidth = 2 * devicePixelRatio;gg.beginPath();gg.moveTo(x0, y); gg.lineTo(x0 + barPx, y);gg.moveTo(x0, y - 5 * devicePixelRatio); gg.lineTo(x0, y + 5 * devicePixelRatio);gg.moveTo(x0 + barPx, y - 5 * devicePixelRatio); gg.lineTo(x0 + barPx, y + 5 * devicePixelRatio);gg.stroke();gg.fillStyle = '#e8ecf1';gg.font = `${11 * devicePixelRatio}px system-ui`;gg.textAlign = 'center';gg.fillText(`${metres} m`, x0 + barPx / 2, y - 8 * devicePixelRatio);gg.textAlign = 'left';}function drawContours(g, ox, oy, sc) {const step = Math.max(1, Math.round((S.hMax - S.hMin) / 12));g.strokeStyle = 'rgba(255,255,255,.35)';22 unmodified lines// ---------------------------------------------------------------------------// loading// ---------------------------------------------------------------------------const _warnSeen = new Set();const _WARN_MAX = 6;function warn(msg) {const el = $('warn');if (!el || _warnSeen.has(msg)) return;_warnSeen.add(msg);el.style.display = 'block';el.classList.add('show');const line = document.createElement('div');line.textContent = msg;el.appendChild(line);while (el.children.length > _WARN_MAX) el.removeChild(el.firstChild);}function clearWarnings() {const el = $('warn');if (!el) return;el.innerHTML = '';el.style.display = 'none';el.classList.remove('show');_warnSeen.clear();}async function loadFromFiles(fileList) {110 unmodified lineswarn('no usable height array — nothing to render');return;}clearWarnings();S.H = hgt.shape[0]; S.W = hgt.shape[1];S.height = hgt.data;S.gt = gt && gt.length === S.height.length ? gt : null;59 unmodified linesmesh.material.map = t;mesh.material.wireframe = $('wire').checked;mesh.material.needsUpdate = true;build3dColorbar();}// ---------------------------------------------------------------------------27 unmodified linesdocument.body.classList.toggle('only3d');setTimeout(resize, 60);});// the host page's 760px-tall iframe is cramped on a laptop; `allowfullscreen`// is granted on it precisely so this can hand the whole screen to the scene$('fullscreen')?.addEventListener('click', () => {if (document.fullscreenElement) document.exitFullscreen();else document.documentElement.requestFullscreen().catch(() => {warn('fullscreen was blocked by the browser');});});document.addEventListener('fullscreenchange', () => {const btn = $('fullscreen');if (btn) btn.textContent = document.fullscreenElement ? 'Exit fullscreen' : 'Fullscreen';setTimeout(resize, 60);});$('warnDismiss')?.addEventListener('click', clearWarnings);$('collapseAside')?.addEventListener('click', () => {document.body.classList.toggle('collapsed');$('collapseAside').textContent = document.body.classList.contains('collapsed') ? '▸' : '◂';setTimeout(resize, 60);});setMode('orbit');
12 unmodified lines131415161718192021222324252627282930313233343536373839404142434445464748493 unmodified lines53545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181 unmodified line1201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521533 unmodified lines1571581591601611621635 unmodified lines16917017117217317417517617717817912 unmodified lines*{box-sizing:border-box}html,body{height:100%}body{margin:0;background:var(--bg);color:var(--ink);overflow:hidden;font:13px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif;display:grid;grid-template-columns:322px 1fr;}/* ---- sidebar ---- */aside{background:var(--panel);border-right:1px solid var(--line);overflow-y:auto;padding:16px 16px 40px}h1{font-size:15px;margin:0 0 2px;letter-spacing:.2px}.tag{color:var(--dim);font-size:11px;margin:0 0 16px}section{border-top:1px solid var(--line);padding:13px 0}section:first-of-type{border-top:0;padding-top:0}h2{font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:var(--dim);margin:0 0 9px;font-weight:600}label{display:block;margin:9px 0 3px;color:#b8c2cc;font-size:12px}input[type=range]{width:100%;accent-color:var(--accent)}select,input[type=file]{width:100%;background:#0f1318;color:var(--ink);border:1px solid var(--line);border-radius:6px;padding:6px 8px;font:inherit;font-size:12px}.row{display:flex;gap:8px;align-items:center;margin-top:8px}.row.chk{color:#b8c2cc;font-size:12px}.btns{display:flex;gap:6px;margin-top:10px;flex-wrap:wrap}button{flex:1 1 auto;padding:7px 9px;background:#242c35;color:var(--ink);border:1px solid var(--line);border-radius:6px;cursor:pointer;font:inherit;font-size:12px}button:hover{background:#2c3540}button.on{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}#info,#probe,#metrics{color:#b8c2cc;font-size:12px}#probe{min-height:44px}#metrics table{width:100%;border-collapse:collapse}#metrics td{padding:2px 0;font-variant-numeric:tabular-nums}#metrics td:last-child{text-align:right}.dim{color:var(--dim)}code{background:#0f1318;padding:1px 4px;border-radius:3px;font-size:11px}#warn{display:none;background:#2a1f14;border:1px solid #5a3d1e;border-left:3px solid var(--warn);border-radius:6px;padding:8px 10px;margin-top:10px;font-size:11.5px;color:#f0c9a0}#profile{width:100%;height:76px;background:#0f1318;border:1px solid var(--line);border-radius:6px;margin-top:8px;display:block}/* ---- panes ---- */3 unmodified lines.pane{position:relative;min-width:0;overflow:hidden}#pane2d{border-right:1px solid var(--line);display:flex;flex-direction:column;background:#0a0d10}.paneBar{height:34px;display:flex;align-items:center;gap:8px;padding:0 10px;border-bottom:1px solid var(--line);color:var(--dim);font-size:11px;flex:none}.paneBar select{width:auto;padding:3px 6px;font-size:11px}#map{flex:1;width:100%;min-height:0}#pane3d canvas{display:block}#hud{position:absolute;top:10px;right:12px;display:flex;gap:8px;font-size:11px;color:var(--dim);background:rgba(13,16,19,.72);padding:5px 9px;border-radius:6px;border:1px solid var(--line);font-variant-numeric:tabular-nums}#hint{position:absolute;left:12px;bottom:10px;color:var(--dim);font-size:11px;background:rgba(13,16,19,.72);padding:5px 9px;border-radius:6px;border:1px solid var(--line)}/* embedded in the Space: the model has already run, so there is nothing topick — drop the loader and promote the section that follows it */body.embedded #loadSection{display:none}body.embedded section:nth-of-type(2){border-top:0;padding-top:0}@media (max-width:900px){body{grid-template-columns:1fr;grid-template-rows:auto 1fr}aside{max-height:44vh}main{grid-template-columns:1fr}#pane2d{display:none}}</style></head><body><aside><h1>DepthWizard</h1><p class="tag">single-view DSM · 3D flythrough · SIH 2026 PS 26175</p><section id="loadSection"><h2>Load a prediction</h2><input type="file" id="files" multipleaccept=".png,.jpg,.json,.npy"title="select ndsm_m.npy, rgb.png, meta.json (and gt_ndsm_m.npy to validate)" /><p class="dim" style="margin:8px 0 0;font-size:11px">Pick the whole output folder of<br><code>python -m infer.predict …</code><br><code>ndsm_m.npy</code> + <code>meta.json</code> is the minimum;add <code>rgb.png</code> to drape the optical image and<code>gt_ndsm_m.npy</code> to score it live.</p><div id="warn"></div><div id="info" style="margin-top:10px">nothing loaded yet</div></section><section><h2>Camera</h2><div class="btns"><button data-mode="orbit" class="on">Orbit</button><button data-mode="fp">First person</button><button data-mode="fly">Drone</button></div><div class="btns"><button id="reset">Reset view</button><button id="split">2D pane</button></div></section><section><h2>Surface</h2><label>3D drape</label><select id="layer"><option value="rgb">Optical RGB (projected)</option><option value="height">Height colormap</option>1 unmodified line<option value="reference" disabled>Reference height</option><option value="error" disabled>Error vs reference</option></select><label>Vertical exaggeration <span id="vexLabel">1.0×</span></label><input type="range" id="vex" min="0.2" max="8" step="0.1" value="1" /><label>Mesh detail</label><select id="quality"><option value="150000">Fast (150k verts)</option><option value="500000" selected>Balanced (500k)</option><option value="1500000">Full (1.5M)</option></select><div class="row chk"><input type="checkbox" id="wire" /> <span>wireframe</span></div></section><section><h2>Sun</h2><label>Azimuth <span class="dim">°</span></label><input type="range" id="sunAz" min="0" max="360" step="1" value="315" /><label>Elevation <span class="dim">°</span></label><input type="range" id="sunEl" min="5" max="88" step="1" value="45" /><div class="row chk"><input type="checkbox" id="shadows" checked /> <span>cast shadows</span></div></section><section><h2>Measure</h2><div id="probe">click the terrain to probe a height; click again for slope and a profile</div><canvas id="profile"></canvas><div class="btns"><button id="clearProbe">Clear points</button></div></section><section><h2>Validation</h2><div id="metrics"><span class="dim">load <code>gt_ndsm_m.npy</code> alongside tovalidate against a reference surface</span></div>3 unmodified lines<main><div class="pane" id="pane2d"><div class="paneBar"><span>Map</span><select id="layer2d"><option value="height">Height</option><option value="hillshade">Hillshade</option>5 unmodified lines<input type="checkbox" id="contours" /> contours</label></div><canvas id="map"></canvas></div><div class="pane" id="pane3d"><div id="hud"><span id="fps">— fps</span><span id="vertCount">—</span></div><div id="hint">drag = orbit · scroll = zoom · click = probe · F = first person · R = reset</div></div></main>12 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455563 unmodified lines606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641 unmodified line1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981993 unmodified lines2032042052062072082095 unmodified lines21521621721821922022122222322422522622722822923023112 unmodified lines*{box-sizing:border-box}html,body{height:100%}body{margin:0;background:var(--bg);color:var(--ink);overflow:hidden;font:13px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif;display:grid;grid-template-columns:280px 1fr;}body.collapsed{grid-template-columns:0 1fr}body.collapsed aside{display:none}/* ---- sidebar ---- */aside{background:var(--panel);border-right:1px solid var(--line);overflow-y:auto;padding:16px 16px 40px;position:relative}#collapseAside{position:absolute;top:10px;right:10px;flex:none;width:auto;padding:3px 7px}h1{font-size:16px;margin:0 0 2px;letter-spacing:.2px}.tag{color:var(--dim);font-size:12px;margin:0 0 16px}section{border-top:1px solid var(--line);padding:13px 0}section:first-of-type{border-top:0;padding-top:0}h2{font-size:12px;text-transform:uppercase;letter-spacing:.07em;color:var(--dim);margin:0 0 9px;font-weight:600}label{display:block;margin:9px 0 3px;color:#b8c2cc;font-size:13px;cursor:pointer}input[type=range]{width:100%;accent-color:var(--accent)}select,input[type=file]{width:100%;background:#0f1318;color:var(--ink);border:1px solid var(--line);border-radius:6px;padding:6px 8px;font:inherit;font-size:13px}.row{display:flex;gap:8px;align-items:center;margin-top:8px}.row.chk{color:#b8c2cc;font-size:13px}.row.chk label{display:inline;margin:0;cursor:pointer}.btns{display:flex;gap:6px;margin-top:10px;flex-wrap:wrap}button{flex:1 1 auto;padding:7px 9px;background:#242c35;color:var(--ink);border:1px solid var(--line);border-radius:6px;cursor:pointer;font:inherit;font-size:13px}button:hover{background:#2c3540}button.on{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}button[aria-pressed=true]{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}#info,#probe,#metrics{color:#b8c2cc;font-size:13px}#probe{min-height:44px}#metrics table{width:100%;border-collapse:collapse}#metrics td{padding:2px 0;font-variant-numeric:tabular-nums}#metrics td:last-child{text-align:right}.dim{color:var(--dim)}code{background:#0f1318;padding:1px 4px;border-radius:3px;font-size:12px}#warn{display:none;background:#2a1f14;border:1px solid #5a3d1e;border-left:3px solid var(--warn);border-radius:6px;padding:8px 10px;margin-top:10px;font-size:12.5px;color:#f0c9a0}#warn div{padding:2px 0}#profile{width:100%;height:76px;background:#0f1318;border:1px solid var(--line);border-radius:6px;margin-top:8px;display:block}/* ---- panes ---- */3 unmodified lines.pane{position:relative;min-width:0;overflow:hidden}#pane2d{border-right:1px solid var(--line);display:flex;flex-direction:column;background:#0a0d10}.paneBar{height:34px;display:flex;align-items:center;gap:8px;padding:0 10px;border-bottom:1px solid var(--line);color:var(--dim);font-size:12px;flex:none}.paneBar select{width:auto;padding:3px 6px;font-size:12px}.paneBar label{display:flex;margin:0;font-size:12px}#map{flex:1;width:100%;min-height:0;touch-action:none}#pane3d canvas{display:block}#hud{position:absolute;top:10px;right:12px;display:flex;gap:8px;font-size:12px;color:var(--dim);background:rgba(13,16,19,.72);padding:5px 9px;border-radius:6px;border:1px solid var(--line);font-variant-numeric:tabular-nums}#hint{position:absolute;left:12px;bottom:10px;color:var(--dim);font-size:12px;background:rgba(13,16,19,.72);padding:5px 9px;border-radius:6px;border:1px solid var(--line);max-width:calc(100% - 24px)}/* embedded in the Space: the model has already run, so there is nothing topick — drop the loader and promote the section that follows it. The hostpage already names the product, so the viewer's own header is redundantinside the frame (and previously disagreed with it). Validation and thereference-surface options are dead weight too: there is no file picker toload gt_ndsm_m.npy from. */body.embedded h1, body.embedded .tag{display:none}body.embedded #loadSection{display:none}body.embedded #validationSection{display:none}body.embedded section:nth-of-type(2){border-top:0;padding-top:0}body.embedded #layer option[value=reference], body.embedded #layer option[value=error],body.embedded #layer2d option[value=reference], body.embedded #layer2d option[value=error]{display:none}/* This query is evaluated against the *iframe's* own width, which in a 3:1host column split is often well under 900px on an ordinary laptop eventhough the page itself is nowhere near mobile-sized — that reads as abug, not a responsive layout. Lowered so only a genuinely narrow frame(phone-embed width, or the standalone page on a small window) triggersit; `app.py` also sets a `min_width` on the host column so the frameitself stays wide on desktop. */@media (max-width:560px){body{grid-template-columns:1fr;grid-template-rows:auto 1fr}aside{max-height:44vh}main{grid-template-columns:1fr}#pane2d{display:none}}button.on{position:relative}#warn{max-height:160px;overflow-y:auto}#warnDismiss{display:none;margin-top:6px;padding:3px 8px;font-size:11px;flex:none}#warn.show + #warnDismiss{display:inline-block}.colorbar-wrap{position:absolute;display:flex;flex-direction:column;align-items:center;font-size:10px;color:var(--dim);background:rgba(13,16,19,.72);padding:6px 4px;border-radius:6px;border:1px solid var(--line);pointer-events:none}#colorbar3d{right:12px;bottom:44px}#colorbar2d{right:8px;top:40px}#scalebar{position:absolute;left:10px;bottom:10px;pointer-events:none}#meshSpinner{display:none;position:absolute;inset:0;align-items:center;justify-content:center;flex-direction:column;gap:10px;font-size:13px;color:var(--ink);background:rgba(10,13,16,.55)}#meshSpinner.show{display:flex}.spin{width:26px;height:26px;border-radius:50%;border:3px solid var(--line);border-top-color:var(--accent);animation:spin .8s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}</style></head><body><aside><button id="collapseAside" title="Hide sidebar" aria-label="Hide sidebar">◂</button><h1>DepthWizard</h1><p class="tag">single-view DSM · 3D flythrough · SIH 2026 PS 26175</p><section id="loadSection"><h2>Load a prediction</h2><label for="files">Prediction folder</label><input type="file" id="files" multipleaccept=".png,.jpg,.json,.npy"title="select ndsm_m.npy, rgb.png, meta.json (and gt_ndsm_m.npy to validate)" /><p class="dim" style="margin:8px 0 0;font-size:12px">Pick the whole output folder of<br><code>python -m infer.predict …</code><br><code>ndsm_m.npy</code> + <code>meta.json</code> is the minimum;add <code>rgb.png</code> to drape the optical image and<code>gt_ndsm_m.npy</code> to score it live.</p><div id="warn" aria-live="polite"></div><button id="warnDismiss">Dismiss</button><div id="info" style="margin-top:10px">nothing loaded yet</div></section><section><h2>Camera</h2><div class="btns" role="group" aria-label="Camera mode"><button data-mode="orbit" class="on" aria-pressed="true">Orbit</button><button data-mode="fp" aria-pressed="false">First person</button><button data-mode="fly" aria-pressed="false">Drone</button></div><div class="btns"><button id="reset">Reset view</button><button id="split">2D pane</button><button id="fullscreen">Fullscreen</button></div></section><section><h2>Surface</h2><label for="layer">3D drape</label><select id="layer"><option value="rgb">Optical RGB (projected)</option><option value="height">Height colormap</option>1 unmodified line<option value="reference" disabled>Reference height</option><option value="error" disabled>Error vs reference</option></select><label for="vex">Vertical exaggeration <span id="vexLabel">1.0×</span></label><input type="range" id="vex" min="0.2" max="8" step="0.1" value="1" /><label for="quality">Mesh detail</label><select id="quality"><option value="150000">Fast</option><option value="500000" selected>Balanced</option><option value="1500000">Full</option></select><div class="row chk"><input type="checkbox" id="wire" /> <label for="wire">wireframe</label></div></section><section><h2>Sun</h2><label for="sunAz">Azimuth <span class="dim">°</span></label><input type="range" id="sunAz" min="0" max="360" step="1" value="315" /><label for="sunEl">Elevation <span class="dim">°</span></label><input type="range" id="sunEl" min="5" max="88" step="1" value="45" /><div class="row chk"><input type="checkbox" id="shadows" checked /> <label for="shadows">cast shadows</label></div></section><section><h2>Measure</h2><div id="probe" aria-live="polite">click the terrain to probe a height; click again for slope and a profile</div><canvas id="profile"></canvas><div class="btns"><button id="clearProbe">Clear points</button></div></section><section id="validationSection"><h2>Validation</h2><div id="metrics"><span class="dim">load <code>gt_ndsm_m.npy</code> alongside tovalidate against a reference surface</span></div>3 unmodified lines<main><div class="pane" id="pane2d"><div class="paneBar"><label for="layer2d" style="margin:0">Map</label><select id="layer2d"><option value="height">Height</option><option value="hillshade">Hillshade</option>5 unmodified lines<input type="checkbox" id="contours" /> contours</label></div><canvas id="map"></canvas><canvas id="scalebar"></canvas><div class="colorbar-wrap" id="colorbar2d"><canvas width="14" height="120"></canvas></div></div><div class="pane" id="pane3d"><div id="hud"><span id="fps">— fps</span><span id="vertCount">—</span></div><div id="hint">click the scene to focus it, then: drag = orbit · scroll = zoom ·click = probe · F = first person · R = reset<br><span class="dim">touch: one finger = orbit · pinch = zoom · two-finger drag = pan</span></div><div class="colorbar-wrap" id="colorbar3d"><canvas width="14" height="120"></canvas></div><div id="meshSpinner"><div class="spin"></div>building mesh…</div></div></main>
123version https://git-lfs.github.com/spec/v1oid sha256:f4fa4f828c9f60a0968d31e9419c09ecb4a57cad44b659c17eb328fe8d6e7428size 58995212345678910111213141516171819202122232425262728293031323334{ "stem": "synthetic_city", "product": "rDSM", "units": "metres_above_ground", "height_min_m": 0.0, "height_max_m": 32.519554138183594, "height_mean_m": 4.755937576293945, "height_median_m": 0.16336360573768616, "frac_below_1m": 0.6403469509548612, "size_px": [ 384, 384 ], "scene": { "path": "synthetic", "width": 384, "height": 384, "gsd_m": 0.5, "gsd_source": "assumed", "georeferenced": false, "crs": null }, "note": "synthetic scene generated by viewer/make_sample.py \u2014 block heights are exact, so the probe read-out can be checked", "truth_blocks_m": [ 24.0, 11.0, 38.0, 8.0, 17.0, 6.0, 30.0, 13.5 ]}123version https://git-lfs.github.com/spec/v1oid sha256:d8852764e6cf9ec9a97649aabf3a0bd263eb9b562644ff536d02aba95a85dfa7size 589952UIPLAN.md+211-59
app.py+163-33
viewer/app.js+151-8
viewer/index.html+93-41
viewer/sample/gt_ndsm_m.npyDeleted-3
viewer/sample/meta.jsonDeleted-34
viewer/sample/ndsm_m.npyDeleted-3