File size: 16,835 Bytes
62c375a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
"""SWR-Bench Explorer: browse multi-view hyperspectral renders and their ground truth.

Data: a small preview subset of https://huggingface.co/datasets/ming0531/SWR-Bench (CC BY 4.0), built with
build_preview.py: three test views per world, 64-band clean and noisy radiance sampled at every third pixel,
area abundances and full-resolution material maps.
"""
from __future__ import annotations

import json
from functools import lru_cache
from pathlib import Path

import gradio as gr
import numpy as np
import plotly.graph_objects as go
from PIL import Image, ImageDraw

DATA = Path(__file__).resolve().parent / "data"
META = json.load(open(DATA / "meta.json"))
WORLDS = META["worlds"]
UNITS = "W m⁻² sr⁻¹ nm⁻¹"
H, W = META["resolution"]

LINKS = {
    "Paper (arXiv)": "https://arxiv.org/abs/2610.19520",
    "Dataset": "https://huggingface.co/datasets/ming0531/SWR-Bench",
    "Code": "https://github.com/ming053l/Spectral-World-Renderer",
    "Project page": "https://ming053l.github.io/Spectral-World-Renderer/",
    "Collection": "https://huggingface.co/collections/ming0531/spectral-world-renderer-6b0fa8e8994ece823c7415ec",
}

# fixed categorical order for compared pixels (validated reference palette, slots 1-4)
PICK_COLORS = ["#257de0", "#f47230", "#00b894", "#e2a100"]
CLEAN_COLOR, NOISY_COLOR = "#257de0", "#f47230"
MAX_PICKS = 4
LAYERS = ["sRGB render", "Material ground truth", "Colour infrared (850/650/550 nm)", "Abundance of one class"]


def pretty(name: str) -> str:
    return name.replace("_", " ")


def view_label(w: str, v: dict) -> str:
    return f"{v['stem']} · test view {v['test_index'] + 1}/{WORLDS[w]['n_test']}"


def view_stem(w: str, label: str) -> str:
    for v in WORLDS[w]["views"]:
        if view_label(w, v) == label:
            return v["stem"]
    return WORLDS[w]["views"][0]["stem"]


@lru_cache(maxsize=8)
def load_view(w: str, stem: str) -> dict:
    with np.load(DATA / w / f"{stem}.npz") as z:
        d = {k: z[k] for k in z.files}
    s = float(d["scale"])
    d["clean"] = d["clean"].astype(np.float32) * s
    d["noisy"] = d["noisy"].astype(np.float32) * s
    d["abundance"] = d["abundance"].astype(np.float32)
    d["material"] = d["material"].astype(np.int16) - 1
    return d


@lru_cache(maxsize=24)
def base_image(w: str, stem: str, layer: str, cls: int) -> np.ndarray:
    if layer == LAYERS[0]:
        return np.asarray(Image.open(DATA / w / f"{stem}_rgb.jpg").convert("RGB"))
    if layer == LAYERS[1]:
        return np.asarray(Image.open(DATA / w / f"{stem}_mat.png").convert("RGB"))
    if layer == LAYERS[2]:
        return np.asarray(Image.open(DATA / w / f"{stem}_cir.jpg").convert("RGB"))
    d = load_view(w, stem)
    a = d["abundance"][..., cls]
    # sequential single-hue ramp (dark surface -> bright blue), nearest upsampling to full resolution
    lo, hi = np.array([18, 22, 30], np.float32), np.array([168, 210, 255], np.float32)
    img = (lo + a[..., None] * (hi - lo)).astype(np.uint8)
    st = int(d["stride"])
    img = np.repeat(np.repeat(img, st, 0), st, 1)[:H, :W]
    img[d["material"] < 0] = (8, 8, 10)
    return img


def draw_picks(img: np.ndarray, picks: list) -> np.ndarray:
    im = Image.fromarray(img.copy())
    dr = ImageDraw.Draw(im)
    for k, (x, y) in enumerate(picks):
        c = PICK_COLORS[k % len(PICK_COLORS)] if len(picks) > 1 else "#ffffff"
        r = 9
        dr.ellipse([x - r - 2, y - r - 2, x + r + 2, y + r + 2], outline="#000000", width=2)
        dr.ellipse([x - r, y - r, x + r, y + r], outline=c, width=3)
        dr.line([x - r - 6, y, x - r + 3, y], fill=c, width=2)
        dr.line([x + r - 3, y, x + r + 6, y], fill=c, width=2)
        dr.line([x, y - r - 6, x, y - r + 3], fill=c, width=2)
        dr.line([x, y + r - 3, x, y + r + 6], fill=c, width=2)
    return np.asarray(im)


def sample(d: dict, x: int, y: int):
    st, o = int(d["stride"]), int(d["offset"])
    hh, ww = d["clean"].shape[:2]
    i = int(np.clip(round((y - o) / st), 0, hh - 1))
    j = int(np.clip(round((x - o) / st), 0, ww - 1))
    return i, j, st * j + o, st * i + o  # cube index and the full-resolution pixel it samples


def class_name(w: str, c: int) -> str:
    return "background (no surface)" if c < 0 else pretty(WORLDS[w]["classes"][c])


def spectrum_fig(w: str, stem: str, picks: list) -> go.Figure:
    d = load_view(w, stem)
    wl = np.asarray(WORLDS[w]["wavelengths"])
    fig = go.Figure()
    fig.add_vrect(x0=wl[0], x1=700, fillcolor="rgba(127,127,127,0.06)", line_width=0, layer="below")
    fig.add_annotation(x=560, y=1.0, yref="paper", text="visible", showarrow=False,
                       font=dict(size=11, color="#888"), yanchor="bottom")
    fig.add_annotation(x=840, y=1.0, yref="paper", text="near infrared", showarrow=False,
                       font=dict(size=11, color="#888"), yanchor="bottom")
    if len(picks) == 1:
        x, y = picks[0]
        i, j, px, py = sample(d, x, y)
        fig.add_trace(go.Scatter(x=wl, y=d["noisy"][i, j], name="noisy observation", mode="lines",
                                 line=dict(color=NOISY_COLOR, width=1.2), opacity=0.8,
                                 hovertemplate="%{x:.1f} nm<br>%{y:.4g}<extra>noisy</extra>"))
        fig.add_trace(go.Scatter(x=wl, y=d["clean"][i, j], name="clean radiance", mode="lines",
                                 line=dict(color=CLEAN_COLOR, width=2.2),
                                 hovertemplate="%{x:.1f} nm<br>%{y:.4g}<extra>clean</extra>"))
    else:
        for k, (x, y) in enumerate(picks):
            i, j, px, py = sample(d, x, y)
            c = int(d["material"][py, px])
            fig.add_trace(go.Scatter(x=wl, y=d["clean"][i, j], mode="lines",
                                     name=f"#{k + 1} {class_name(w, c)}",
                                     line=dict(color=PICK_COLORS[k % len(PICK_COLORS)], width=2.2),
                                     hovertemplate="%{x:.1f} nm<br>%{y:.4g}<extra>#" + str(k + 1) + "</extra>"))
    fig.update_layout(
        template="plotly_white", height=330, margin=dict(l=64, r=16, t=30, b=58),
        xaxis=dict(title="wavelength (nm)", range=[wl[0] - 4, wl[-1] + 4], showgrid=False,
                   ticks="outside", tickcolor="#bbb"),
        yaxis=dict(title=f"radiance ({UNITS})", gridcolor="rgba(127,127,127,0.18)", zeroline=False,
                   rangemode="tozero"),
        legend=dict(orientation="h", yanchor="top", y=-0.26, x=0, font=dict(size=11)),
        hovermode="x unified", paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
        font=dict(size=12),
    )
    return fig


def abundance_fig(w: str, stem: str, pick) -> go.Figure:
    d = load_view(w, stem)
    i, j, px, py = sample(d, *pick)
    a = d["abundance"][i, j]
    names, pal = WORLDS[w]["classes"], WORLDS[w]["palette"]
    idx = [c for c in np.argsort(-a) if a[c] > 1e-3]
    fig = go.Figure()
    if idx:
        fig.add_trace(go.Bar(
            y=[pretty(names[c]) for c in idx][::-1], x=[float(a[c]) for c in idx][::-1], orientation="h",
            marker=dict(color=[pal[c] for c in idx][::-1], line=dict(color="rgba(0,0,0,0.35)", width=1)),
            text=[f"{a[c]:.2f}" for c in idx][::-1], textposition="outside", cliponaxis=False,
            hovertemplate="%{y}: %{x:.3f}<extra></extra>"))
    else:
        fig.add_annotation(text="no surface at this pixel", x=0.5, y=0.5, xref="paper", yref="paper",
                           showarrow=False, font=dict(color="#888"))
    fig.update_layout(
        template="plotly_white", height=max(150, 60 + 30 * max(len(idx), 1)),
        margin=dict(l=10, r=40, t=10, b=34),
        xaxis=dict(range=[0, 1.12], title="area abundance (16 sub-pixel samples)", tickvals=[0, 0.5, 1],
                   gridcolor="rgba(127,127,127,0.18)"),
        yaxis=dict(automargin=True), bargap=0.35, showlegend=False,
        paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", font=dict(size=12))
    return fig


def legend_html(w: str, stem: str) -> str:
    v = next(v for v in WORLDS[w]["views"] if v["stem"] == stem)
    names, pal = WORLDS[w]["classes"], WORLDS[w]["palette"]
    items = "".join(
        f'<span class="swr-chip"><span class="swr-sw" style="background:{pal[c]}"></span>{pretty(names[c])}</span>'
        for c in range(len(names)) if c in v["present_classes"])
    return f'<div class="swr-legend">{items}</div>'


def info_md(w: str, stem: str, picks: list) -> str:
    d = load_view(w, stem)
    wl = np.asarray(WORLDS[w]["wavelengths"])
    rows = []
    for k, (x, y) in enumerate(picks):
        i, j, px, py = sample(d, x, y)
        c = int(d["material"][py, px])
        cl = d["clean"][i, j]
        tag = f"**#{k + 1}** · " if len(picks) > 1 else ""
        rows.append(f"{tag}pixel **(x={px}, y={py})** · material **{class_name(w, c)}** · "
                    f"peak {cl.max():.3g} at {wl[int(cl.argmax())]:.0f} nm")
    return "<br>".join(rows)


def world_md(w: str) -> str:
    m = WORLDS[w]
    return (f"**{m['name']}** — {m['setting']} · {len(m['classes'])} material classes · "
            f"[browse files](https://huggingface.co/datasets/ming0531/SWR-Bench/tree/main/{w})")


def code_md(w: str, stem: str) -> str:
    return f"""```python
from huggingface_hub import hf_hub_download
import numpy as np

repo = "ming0531/SWR-Bench"
cube = np.load(hf_hub_download(repo, "{w}/hsi_noisy/{stem}.npy", repo_type="dataset"))  # (540, 960, 64) float32
gt = np.load(hf_hub_download(repo, "{w}/gt/{stem}.npz", repo_type="dataset"))           # material, abundances, ...
```
For whole worlds and the unified ground-truth reader (`SWRScene`), see the [dataset card]({LINKS['Dataset']})."""


# ------------------------------------------------------------------------------------------------- callbacks
def render(w, stem, layer, cls_label, picks):
    cls = int(cls_label) if layer == LAYERS[3] and cls_label is not None else 0
    img = draw_picks(base_image(w, stem, layer, cls), picks)
    pick = picks[-1]
    return (img, spectrum_fig(w, stem, picks), abundance_fig(w, stem, pick), info_md(w, stem, picks))


def default_pick():
    return [(W // 2, int(H * 0.62))]


def on_world(w):
    views = [view_label(w, v) for v in WORLDS[w]["views"]]
    classes = [(pretty(c), i) for i, c in enumerate(WORLDS[w]["classes"])]
    stem = WORLDS[w]["views"][0]["stem"]
    picks = default_pick()
    return (gr.update(choices=views, value=views[0]), gr.update(choices=classes, value=0),
            world_md(w), legend_html(w, stem), code_md(w, stem), picks,
            *render(w, stem, LAYERS[0], 0, picks), LAYERS[0])


def on_view(w, view, layer, cls_label):
    stem = view_stem(w, view)
    picks = default_pick()
    return (legend_html(w, stem), code_md(w, stem), picks, *render(w, stem, layer, cls_label, picks))


def on_layer(w, view, layer, cls_label, picks):
    return (gr.update(visible=layer == LAYERS[3]),
            *render(w, view_stem(w, view), layer, cls_label, picks))


def on_click(w, view, layer, cls_label, compare, picks, evt: gr.SelectData):
    x, y = int(evt.index[0]), int(evt.index[1])
    picks = (list(picks) + [(x, y)])[-MAX_PICKS:] if compare else [(x, y)]
    return (picks, *render(w, view_stem(w, view), layer, cls_label, picks))


def on_compare(w, view, layer, cls_label, compare, picks):
    picks = list(picks)[-1:] if not compare else list(picks)
    return (picks, *render(w, view_stem(w, view), layer, cls_label, picks))


# ------------------------------------------------------------------------------------------------- layout
CSS = """
.gradio-container {max-width: 1320px !important; margin: 0 auto;}
#swr-head h1 {font-size: 1.75rem; margin: 0.2rem 0 0.1rem 0; letter-spacing: -0.01em;}
#swr-head p {margin: 0.25rem 0; opacity: 0.85;}
.swr-links a {display: inline-block; margin: 0.25rem 0.35rem 0 0; padding: 0.22rem 0.7rem; border-radius: 999px;
  border: 1px solid var(--border-color-primary); text-decoration: none !important; font-size: 0.86rem;}
.swr-links a:hover {background: var(--background-fill-secondary);}
.swr-legend {display: flex; flex-wrap: wrap; gap: 0.35rem 0.9rem; font-size: 0.85rem; padding: 0.2rem 0;}
.swr-chip {display: inline-flex; align-items: center; gap: 0.35rem;}
.swr-sw {width: 0.85rem; height: 0.85rem; border-radius: 3px; border: 1px solid rgba(127,127,127,0.5);}
#swr-img img {cursor: crosshair;}
.swr-foot {font-size: 0.8rem; opacity: 0.8; line-height: 1.45;}
"""

HEAD = f"""<div id="swr-head">
<h1>SWR-Bench Explorer</h1>
<p>Multi-view <b>hyperspectral</b> renders (64 bands, 420–980 nm) with pixel-aligned material and sub-pixel abundance
ground truth, from <i>Spectral World Renderer: Unified 3D Hyperspectral Unmixing</i>.
Pick a world and a view, then <b>click any pixel</b> to see its spectrum.</p>
<div class="swr-links">{''.join(f'<a href="{u}" target="_blank">{k}</a>' for k, u in LINKS.items())}</div>
</div>"""

FOOT = """<div class="swr-foot">
<b>About this preview.</b> Three test views per world; spectra and abundances are those of the full-resolution pixel
nearest to the click on a 3-pixel grid (no averaging), stored as float16. The full dataset (12 datasets, 2,364 views,
960×540 float32 noisy and clean cubes, shading coefficients, instances, depth, normals, cameras) is at
<a href="https://huggingface.co/datasets/ming0531/SWR-Bench">ming0531/SWR-Bench</a>. The NVIDIA HQ world is not shown here.<br>
<b>Licence and attribution.</b> Rendered data and ground truth: CC BY 4.0. Material spectra come from the
<b>ECOSTRESS Spectral Library</b>, courtesy of the Jet Propulsion Laboratory, California Institute of Technology
(© 2017 Caltech, <a href="https://speclib.jpl.nasa.gov/">speclib.jpl.nasa.gov</a>; Meerdink et al., 2019; Baldridge et al., 2009;
not covered by CC BY 4.0), and the <b>USGS Spectral Library Version 7</b> (public domain; Kokaly et al., 2017,
<a href="https://doi.org/10.5066/F7RR1WDJ">doi:10.5066/F7RR1WDJ</a>).<br>
<b>Citation.</b> Lee, Hsiao, Chang, Li, Liu, Hsu. <i>Spectral World Renderer: Unified 3D Hyperspectral Unmixing.</i>
arXiv:2610.19520, 2026.
</div>"""

W0 = "market" if "market" in WORLDS else next(iter(WORLDS))
PICK0 = [(193, 271)] if W0 == "market" else default_pick()  # vegetation pixel: clear red-edge in the first spectrum
STEM0 = WORLDS[W0]["views"][0]["stem"]
CLASSES0 = [(pretty(c), i) for i, c in enumerate(WORLDS[W0]["classes"])]
VIEWS0 = [view_label(W0, v) for v in WORLDS[W0]["views"]]
IMG0, SPEC0, AB0, INFO0 = render(W0, STEM0, LAYERS[0], 0, PICK0)

theme = gr.themes.Soft(primary_hue="blue", neutral_hue="slate",
                       font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"])

with gr.Blocks(title="SWR-Bench Explorer", theme=theme, css=CSS) as demo:
    picks = gr.State(PICK0)
    gr.HTML(HEAD)
    with gr.Row(equal_height=False):
        with gr.Column(scale=3):
            with gr.Row():
                world = gr.Dropdown([(m["name"], k) for k, m in WORLDS.items()], value=W0, label="World", scale=2)
                view = gr.Dropdown(VIEWS0, value=VIEWS0[0], label="View", scale=2)
            wmd = gr.Markdown(world_md(W0))
            layer = gr.Radio(LAYERS, value=LAYERS[0], label="Layer", container=False)
            cls = gr.Dropdown(CLASSES0, value=0, label="Abundance class", visible=False,
                              info="Area fraction per pixel: dark = 0, light blue = 1; black = no surface.")
            img = gr.Image(IMG0, label="Click a pixel", interactive=False, elem_id="swr-img",
                           show_download_button=False, show_fullscreen_button=True, show_share_button=False,
                           format="jpeg")
            legend = gr.HTML(legend_html(W0, STEM0))
        with gr.Column(scale=2):
            info = gr.Markdown(INFO0)
            gr.Markdown("#### Radiance spectrum")
            spec = gr.Plot(SPEC0, show_label=False)
            compare = gr.Checkbox(False, label=f"Compare mode: keep up to {MAX_PICKS} clicked pixels (clean spectra)")
            gr.Markdown("#### Ground-truth abundances at the last clicked pixel")
            ab = gr.Plot(AB0, show_label=False)
    with gr.Accordion("Load this view from the dataset", open=False):
        code = gr.Markdown(code_md(W0, STEM0))
    gr.HTML(FOOT)

    outs = [img, spec, ab, info]
    world.change(on_world, [world], [view, cls, wmd, legend, code, picks, *outs, layer])
    view.input(on_view, [world, view, layer, cls], [legend, code, picks, *outs])
    layer.change(on_layer, [world, view, layer, cls, picks], [cls, *outs])
    cls.change(on_layer, [world, view, layer, cls, picks], [cls, *outs])
    img.select(on_click, [world, view, layer, cls, compare, picks], [picks, *outs])
    compare.change(on_compare, [world, view, layer, cls, compare, picks], [picks, *outs])

if __name__ == "__main__":
    demo.launch()