shanto268's picture
Add a Cite panel and a Citation section (#1)
56dc131
Raw History Blame Contribute Delete
26.2 kB
"""Shared look and result rendering of the flagship and paper Spaces (deploy/GNN_SPACE.md): SQuADDS theme and CSS, the header,
the Maxwell matrix view (conductor names as headers, 3 decimals shown; the CSV / JSON downloads keep full precision), the status
callout above the matrix, stale-result marking, inline errors and the layer-role editor."""
from __future__ import annotations
import base64
import html
import re
import traceback
import warnings
from pathlib import Path
import gradio as gr
import numpy as np
from tlsq_infer.layout import LayoutError
from . import api as A
STATIC = Path(__file__).parent / "static"
ROLES = ["ground", "conductor", "ground+conductor", "ignore"]
MAT = ["tl-matrix"]
REEXPORT = ("Re-export the layout as GDSII (.gds) from KLayout (File > Save As, format GDS2) or gdstk (Library.write_gds), then "
"upload it again.")
EMPTY = "<p class='tl-note'>The matrix appears here after Predict.</p>"
STALE = ("<div class='tl-status stale' role='status'><strong>Inputs changed.</strong> The matrix shown is for the previous inputs. "
"Press Predict to update it.</div>")
MATRIX_NOTE = ("<p class='tl-note'>The diagonal holds the self capacitances and the off-diagonal entries are minus the mutual "
"capacitances, in fF. The table shows 3 decimals, and the CSV and JSON keep full precision. <span class='tl-flag'>†</span> "
"The ground self term is only indicative, since it depends on the chip boundary.</p><p class='tl-note tl-scroll-hint'>"
"Swipe the matrix sideways for more columns.</p>")
GROUND_FLAG = "<span class='tl-flag'>†</span> The ground self term is only indicative, since it depends on the chip boundary."
INK = gr.themes.Color(c50="#f3f6fa", c100="#e4eaf2", c200="#c9d5e4", c300="#a3b6cf", c400="#7590b3", c500="#4f6d94", c600="#3b5a80",
c700="#2d4a6e", c800="#1e3a5f", c900="#152b47", c950="#0c1a2d", name="ink")
CSS = """
.gradio-container { --tl-ok: #14532d; --tl-ok-bg: #effaf3; --tl-ok-line: #9fd8b4; --tl-warn: #6b3d0a; --tl-warn-bg: #fff8e6;
--tl-warn-line: #e9c46a; --tl-bad: #7f1d1d; --tl-bad-bg: #fdf1f1; --tl-bad-line: #eba3a3; --tl-mute: #4b5563; --tl-mute-bg: #f3f4f6;
--tl-mute-line: #d1d5db; --tl-subtle: #4b5563; }
.dark .gradio-container, .gradio-container.dark { --tl-ok: #bbf0cf; --tl-ok-bg: #0f2a1b; --tl-ok-line: #2f6b47; --tl-warn: #f8dfa4;
--tl-warn-bg: #2d2208; --tl-warn-line: #7a5a17; --tl-bad: #f9c8c8; --tl-bad-bg: #2f1212; --tl-bad-line: #7f2d2d; --tl-mute: #cbd5e1;
--tl-mute-bg: #1f2937; --tl-mute-line: #374151; --tl-subtle: #b6bfcc; }
::selection { background: #c9d5e4; color: #0c1a2d; }
.gradio-container input, .gradio-container textarea { caret-color: #1e3a5f; }
#tl-header { display: flex; flex-direction: column; gap: 6px; margin-bottom: 4px; }
#tl-header .tl-brand { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
#tl-header img { height: 34px; width: auto; }
#tl-header .tl-logo-dark, .dark #tl-header .tl-logo-light { display: none; }
.dark #tl-header .tl-logo-dark { display: inline-block; }
#tl-header h1 { font-family: "Source Serif 4", Georgia, serif; font-weight: 600; font-size: 1.9rem; letter-spacing: -0.01em;
margin: 0; line-height: 1.15; border-left: 1px solid var(--border-color-primary); padding-left: 14px; }
#tl-header .tl-marks { gap: 0; }
#tl-header .tl-marks img.tl-product { height: 34px; margin-left: 16px; padding-left: 16px; border-left: 1px solid var(--border-color-primary);
box-sizing: content-box; }
#tl-header h1.tl-title { border-left: none; padding-left: 0; margin-top: 10px; }
#tl-header p { margin: 0; max-width: 78ch; line-height: 1.55; }
#tl-header .tl-meta { font-size: 0.875rem; color: var(--tl-subtle); }
#tl-header a { padding: 0; margin: 0; text-underline-offset: 2px; }
.gradio-container .label-wrap { text-align: left; align-items: center; gap: 12px; }
.gradio-container .label-wrap .icon { flex: 0 0 auto; }
.gradio-container button.secondary { border: 1px solid var(--button-secondary-border-color); font-size: 0.875rem; font-weight: 500;
padding: 0 16px; }
.tl-flush .html-container { padding: 0 !important; }
.gradio-container h2 { font-family: "Source Serif 4", Georgia, serif; font-weight: 600; margin-top: 18px; }
.gradio-container .prose p, .gradio-container .prose li, .gradio-container .prose blockquote { max-width: 80ch; }
.tl-status { border: 1px solid var(--tl-mute-line); background: var(--tl-mute-bg); color: var(--tl-mute); border-radius: 8px;
padding: 12px 16px; line-height: 1.5; }
.tl-status p { margin: 0; max-width: 80ch; }
.tl-status p + p { margin-top: 4px; }
.tl-status.ok { border-color: var(--tl-ok-line); background: var(--tl-ok-bg); color: var(--tl-ok); }
.tl-status.warn { border-color: var(--tl-warn-line); background: var(--tl-warn-bg); color: var(--tl-warn); }
.tl-status.bad { border-color: var(--tl-bad-line); background: var(--tl-bad-bg); color: var(--tl-bad); }
.tl-matrix table { font-variant-numeric: tabular-nums; }
.tl-matrix th:not(:first-child) .cell-wrap, .tl-matrix th:not(:first-child) .header-content { justify-content: flex-end; text-align: right;
width: 100%; }
.tl-stale { opacity: 0.4; filter: grayscale(1); transition: opacity 0.2s ease-out; }
.tl-note { font-size: 0.875rem; color: var(--tl-subtle); margin: 6px 0 0; max-width: 80ch; }
.tl-flag { font-weight: 600; }
.tl-scroll-hint { display: none; }
.gradio-container input[type=radio]:focus-visible, .gradio-container input[type=checkbox]:focus-visible {
outline: 2px solid #1e3a5f !important; outline-offset: 2px !important; }
.dark .gradio-container input[type=radio]:focus-visible, .dark .gradio-container input[type=checkbox]:focus-visible {
outline-color: #a3b6cf !important; }
.gradio-container label:has(input[type=radio]:focus-visible), .gradio-container label:has(input[type=checkbox]:focus-visible) {
box-shadow: 0 0 0 2px #1e3a5f; }
.gradio-container button:focus-visible { outline: 2px solid #1e3a5f; outline-offset: 2px; }
#tl-footer { margin-top: 1.5rem; padding-top: .8rem; border-top: 1px solid var(--border-color-primary); font-size: .85rem; color: var(--body-text-color-subdued); text-align: center; }
#tl-footer p { margin: .15rem 0; display: block !important; width: 100% !important; max-width: none !important; }
#tl-footer a { display: inline !important; margin: 0 !important; padding: 0 !important; min-height: 0 !important; }
#tl-tier label, .tl-check label, .tl-touch button, .gradio-container button.primary, .gradio-container button.secondary {
min-height: 44px !important; }
@media (max-width: 640px) { /* Gradio prefixes rules inside @media with its container: no .gradio-container here */
#tl-header h1 { font-size: 1.5rem; border-left: none; padding-left: 0; }
.tl-login > * { flex: 1 1 100% !important; } /* sign-in note under the button, full width */
.tl-login > .tl-note { padding-top: 0 !important; margin-top: 0 !important; }
.tl-scroll-hint { display: block; }
.tl-matrix table { font-size: 0.8125rem; }
.label-wrap, .gallery-item, button.sm, input[type=number] { min-height: 44px !important; }
button.icon-button { min-width: 44px !important; min-height: 44px !important; }
#tl-viewer:not(:has(img)) { display: none !important; }
#tl-viewer, #tl-ground-img { padding-top: 52px !important; }
#tl-viewer .image-container > .icon-button-wrapper, #tl-ground-img .image-container > .icon-button-wrapper { top: -52px !important; }
}
#tl-viewer:not(:has(img)) { height: 340px !important; }
.gradio-container footer, .gradio-container footer a, .gradio-container footer button, .gradio-container footer .divider {
color: var(--tl-subtle) !important; }
.gradio-container footer img { opacity: 0.75; }
.gradio-container .wrap .or { color: var(--tl-subtle) !important; }
#tl-view { flex-grow: 0; }
#tl-view .wrap { gap: 0; }
#tl-view label { min-height: 44px; border-radius: 0; margin: 0; padding: 0 16px; }
#tl-view label:first-child { border-radius: 6px 0 0 6px; }
#tl-view label:last-child { border-radius: 0 6px 6px 0; }
#tl-view input { position: absolute; opacity: 0; width: 1px; height: 1px; }
.tl-viewbar { align-items: center; gap: 8px; }
.tl-viewbar { flex-wrap: nowrap !important; }
.tl-viewbar > fieldset, .tl-viewbar > button { flex: 0 0 auto !important; width: auto !important; min-width: 0 !important; }
"""
def theme():
return gr.themes.Default(primary_hue=INK, secondary_hue=INK, neutral_hue=gr.themes.colors.gray,
font=[gr.themes.GoogleFont("Source Sans 3"), "ui-sans-serif", "system-ui", "sans-serif",
gr.themes.GoogleFont("Source Serif 4", (600,))],
font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace"]).set(
button_primary_background_fill="*primary_800", button_primary_background_fill_hover="*primary_900",
button_primary_border_color="*primary_800", button_primary_border_color_hover="*primary_900",
button_primary_text_color="white", button_primary_text_color_hover="white",
button_primary_background_fill_dark="*primary_200", button_primary_background_fill_hover_dark="*primary_100",
button_primary_border_color_dark="*primary_200", button_primary_border_color_hover_dark="*primary_100",
button_primary_text_color_dark="*primary_950", button_primary_text_color_hover_dark="*primary_950",
checkbox_background_color_selected="*primary_800", checkbox_border_color_selected="*primary_800",
checkbox_background_color_selected_dark="*primary_300", checkbox_border_color_selected_dark="*primary_300",
checkbox_label_background_fill_selected="*primary_50", checkbox_label_border_color_selected="*primary_800",
checkbox_label_text_color_selected="*primary_950", checkbox_label_background_fill_selected_dark="*primary_900",
checkbox_label_border_color_selected_dark="*primary_300", checkbox_label_text_color_selected_dark="*primary_50",
link_text_color="*primary_800", link_text_color_hover="*primary_950", link_text_color_visited="*primary_800",
link_text_color_dark="*primary_300", link_text_color_hover_dark="*primary_200", link_text_color_visited_dark="*primary_300",
color_accent="*primary_800", color_accent_soft="*primary_50", color_accent_soft_dark="*primary_900", loader_color="*primary_800",
slider_color="*primary_800", input_border_color_focus="*primary_700",
button_secondary_background_fill="*background_fill_primary", button_secondary_background_fill_hover="*primary_50",
button_secondary_border_color="*primary_300", button_secondary_border_color_hover="*primary_800",
button_secondary_text_color="*primary_900", button_secondary_text_color_hover="*primary_950",
button_secondary_background_fill_dark="*background_fill_primary", button_secondary_background_fill_hover_dark="*primary_900",
button_secondary_border_color_dark="*primary_500", button_secondary_border_color_hover_dark="*primary_300",
button_secondary_text_color_dark="*primary_100", button_secondary_text_color_hover_dark="*primary_50")
def blocks(title: str, **kw):
"""gr.Blocks with the theme and CSS (Gradio 6 reads them at launch; passing them here keeps app.py's plain launch())."""
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="The parameters have been moved", category=UserWarning)
return gr.Blocks(title=title, theme=theme(), css=CSS, **kw)
def _img(name: str, kind: str, alt: str, cls: str = "") -> str:
f = STATIC / name
mime = "image/svg+xml" if f.suffix == ".svg" else "image/png"
b = base64.b64encode(f.read_bytes()).decode()
return f"<img class='tl-logo-{kind}{cls}' src='data:{mime};base64,{b}' alt='{alt}'>"
def _logo(kind: str) -> str:
return _img(f"squadds_{kind}.png", kind, "SQuADDS")
FAVICON_PNG = STATIC / "qcap_badge16_light_32px.png" # /favicon.ico (launch favicon_path): browsers without SVG icons
def favicon_head() -> str:
"""The QCap badge as the page icon: an SVG that follows the browser's light / dark scheme (badge16 light and dark fills)."""
b = base64.b64encode((STATIC / "qcap_favicon.svg").read_bytes()).decode()
return f"<link rel='icon' type='image/svg+xml' href='data:image/svg+xml;base64,{b}'>"
def header(title: str, lede: str, meta: str | None = None, product: str | None = None) -> str:
"""Logo + title, a short lede (HTML) and an optional small meta line. product = 'qcap': the QCap lockup beside the SQuADDS
logo, with the title on its own line below."""
marks = _logo("light") + _logo("dark")
if product == "qcap":
marks += _img("qcap_compact_light.svg", "light", "QCap", " tl-product") + _img("qcap_compact_dark.svg", "dark", "QCap", " tl-product")
top = f"<div class='tl-brand tl-marks'>{marks}</div><h1 class='tl-title'>{html.escape(title)}</h1>"
else:
top = f"<div class='tl-brand'>{marks}<h1>{html.escape(title)}</h1></div>"
return f"<div id='tl-header'>{top}<p>{lede}</p>" + (f"<p class='tl-meta'>{meta}</p>" if meta else "") + "</div>"
CITE_MD = r"""If you use SQuADDS or QCap in your work, please cite:
- S. Shanto *et al.*, "SQuADDS: A validated design database and simulation workflow for superconducting qubit design," *Quantum* **8**, 1465 (2024), [doi:10.22331/q-2024-09-09-1465](https://doi.org/10.22331/q-2024-09-09-1465).
- S. A. Shanto, S. Das and E. Levenson-Falk, "QCap: a physics-corrected graph neural network for the capacitance matrix of any planar superconducting device layout," [arXiv:2611.22057](https://arxiv.org/abs/2611.22057) (2026).
```bibtex
@article{Shanto2024squaddsvalidated,
doi = {10.22331/q-2024-09-09-1465},
url = {https://doi.org/10.22331/q-2024-09-09-1465},
title = {{SQ}u{ADDS}: {A} validated design database and simulation workflow for superconducting qubit design},
author = {Shanto, Sadman and Kuo, Andre and Miyamoto, Clark and Zhang, Haimeng and Maurya, Vivek and Vlachos, Evangelos and Hecht, Malida and Shum, Chung Wa and Levenson-Falk, Eli},
journal = {{Quantum}},
issn = {2521-327X},
publisher = {{Verein zur F{\"{o}}rderung des Open Access Publizierens in den Quantenwissenschaften}},
volume = {8},
pages = {1465},
month = sep,
year = {2024}
}
@misc{Shanto2026planarcapacitance,
title = {{QCap}: a physics-corrected graph neural network for the capacitance matrix of any planar superconducting device layout},
author = {Shanto, Sadman Ahmed and Das, Saikat and Levenson-Falk, Eli},
year = {2026},
eprint = {2611.22057},
archivePrefix = {arXiv},
primaryClass = {quant-ph},
url = {https://arxiv.org/abs/2611.22057}
}
```
"""
def footer() -> str:
"""Credit and copyright, as on the SQuADDS paper page."""
site = "<a href='https://sadmanahmedshanto.com'>Sadman Ahmed Shanto</a>"
return (f"<div id='tl-footer'><p>Models and demo by {site}.</p>"
f"<p>© Copyright 2026, {site} &amp; Eli Levenson-Falk.</p></div>")
def examples(comp, paths, **kw):
"""gr.Examples whose cached copies survive delete_cache. Gradio 6.29 copies a File example into the cache with
Blocks.temp_files but does not add it to keep_in_cache (the Dataset only stores the file name), so the delete_cache sweep
removed the copy PURGE_AGE_S after startup (at the first sweep when the copy was left by an earlier run) and every later
click on the example failed with FileNotFoundError."""
e = gr.Examples([[str(p)] for p in paths], inputs=[comp], **kw)
for v in e.non_none_processed_examples.values():
for d in v:
if isinstance(d, dict) and d.get("path"):
comp.keep_in_cache.add(d["path"])
return e
def fig_files(fig, d: Path, stem: str) -> tuple[str, str]:
"""A matplotlib figure as PNG (shown, downloadable) and SVG (download), closed afterwards."""
import matplotlib.pyplot as plt
png, svg = d / f"{stem}.png", d / f"{stem}.svg"
fig.savefig(png, dpi=130)
fig.savefig(svg)
plt.close(fig)
return str(png), str(svg)
def matrix_note(res) -> str:
flag = "indicative" in str(res.get("self_capacitance", "")) and list(res.get("names") or [])[:1] == ["G"]
return ("<p class='tl-note'>The diagonal holds the self capacitances and the off-diagonal entries are minus the mutual capacitances, "
"in fF. The table shows 3 decimals, and the CSV and JSON keep full precision." + (f" {GROUND_FLAG}" if flag else "") +
"</p><p class='tl-note tl-scroll-hint'>"
"Swipe the matrix sideways for more columns.</p>")
def md(s) -> str:
"""Markdown-safe text: a pair of '~' renders as strikethrough, so approximate values use '≈'."""
return str(s or "").replace("~", "≈")
def pct(e) -> str:
"""'1.05 % median (MAE 0.132 fF, RMSE 0.188 fF)': every % with its MAE / RMSE."""
return f"{e['median_pct']:g} % median (MAE {e['mae_ff']:g} fF, RMSE {e['rmse_ff']:g} fF)"
def _inline(s: str) -> str:
return re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", html.escape(s))
def callout(kind: str, head: str, lines) -> str:
body = "".join(f"<p>{x}</p>" for x in lines if x)
return f"<div class='tl-status {kind}' role='status'><p><strong>{html.escape(head)}</strong></p>{body}</div>"
def checks_of(res) -> dict | None:
"""The result's physical checks; for arms that report none, the same checks on the matrix (entries that are None skipped)."""
c = res.get("checks") or {}
if "symmetric_max_abs" in c:
return c
C = np.array([[np.nan if x is None else float(x) for x in r] for r in res.get("matrix_fF") or []], float)
if C.ndim != 2 or len(C) < 2:
return None
off = C[~np.eye(len(C), dtype=bool)]
sig = C[1:, 1:]
return {"symmetric_max_abs": float(np.nanmax(np.abs(C - C.T))), "offdiag_all_negative": bool(np.all(off[np.isfinite(off)] < 0)),
"signal_block_min_eig": float(np.linalg.eigvalsh(sig).min()) if np.isfinite(sig).all() else None}
def _checks(c) -> str:
eig = c.get("signal_block_min_eig")
return (f"Symmetric (max |C − Cᵀ| {c['symmetric_max_abs']:.2g} fF), every off-diagonal negative"
+ (f", signal block positive definite (smallest eigenvalue {eig:.4g} fF)." if eig is not None else
". There are no self terms, so positive definiteness is not checked."))
def _offstack(res) -> str:
sub = res.get("substrate_route") or {}
e, t = res.get("eps_r"), res.get("thickness_um")
if sub.get("route") == A.FAST_ROUTE:
return (f"Substrate eps_r {e:g}, {t:g} µm. This model does not solve the physics prior at your stack. It rescales its "
f"training-stack prediction by (1 + eps_r) / (1 + 11.45) = {sub['eps_rescale_factor']:.4f} and does not model thickness. "
"Off the training stack we measured a median error of 6.4 % (MAE 1.7 fF, RMSE 2.4 fF), so use QCap for other substrates.")
head = (f"Substrate eps_r {e:g}, {t:g} µm. The physics prior was solved at this stack, and the networks (trained on Si, eps_r "
"11.45, 350 µm) are unchanged.")
if not sub.get("tested", True):
return head + f" This is outside the tested range ({A.TESTED_RANGE}), so its error is unknown."
return head + f" This combination was tested. {A.CALIBRATED_SCORE}"
def status_html(res, expected: str | None = None) -> str:
"""Callout above the matrix: red when a physical check fails (the physical_banner text), yellow off the training stack, green
otherwise with the one expected-error line for a new design."""
bad = A.physical_banner(res)
c = checks_of(res)
if not bad and c and "checks" not in res:
C = np.nan_to_num(np.array([[np.nan if x is None else float(x) for x in r] for r in res["matrix_fF"]], float))
w = A.physical_warning({**c, "signal_block_min_eig": c["signal_block_min_eig"] if c["signal_block_min_eig"] is not None else 1.0}, C)
bad = [f"> **Not a physical matrix.** {w}"] if w else []
if bad:
return callout("bad", "Not a physical matrix: do not use it", [_inline(bad[0].lstrip("> ").replace("**Not a physical matrix.** ", ""))])
chk = _checks(c) if c else None
if (res.get("substrate_route") or {}).get("route", "training stack") != "training stack":
return callout("warn", "Off the training stack" + (": physical checks passed" if chk else ""), [chk, html.escape(_offstack(res))])
if chk:
return callout("ok", "Physical checks passed", [chk, html.escape(expected) if expected else None])
return callout("", "Result", [html.escape(expected) if expected else None])
def error_text(e: BaseException) -> str:
if isinstance(e, MemoryError):
return "Out of memory: crop the layout to the region of interest and try again."
if not isinstance(e, (LayoutError, ValueError, KeyError, FileNotFoundError)):
traceback.print_exception(e)
return f"Internal error ({type(e).__name__}): {e}. Please report it with the file if you can."
msg = str(e).strip()
if msg == "upload a GDS file first":
return "No layout yet: upload a GDS file (or pick an example) in step 1, then press Predict."
if msg.startswith("not a readable GDS"):
return f"This file could not be read as GDSII ({msg.rstrip('.')}). {REEXPORT}"
return msg[:1].upper() + msg[1:]
def error_html(e: BaseException, head: str = "Could not predict") -> str:
if getattr(e, "limit_html", None): # a limit of the demo (geomgnn.access.LimitReached): its own head and the local-use link
return callout("warn", e.head, [e.limit_html])
return callout("bad", head, [html.escape(error_text(e))])
def matrix_view(res):
"""The matrix for the UI: conductor names as headers (blank top-left), 3 decimals shown, the ground self term flagged when the
result calls it indicative. The underlying values are the 4-decimal table the /predict endpoint always returned."""
if not res:
return None
import pandas as pd
names = list(res["names"])
rows = [[a] + [np.nan if x is None else round(float(x), 4) for x in row] for a, row in zip(names, res["matrix_fF"])]
df = pd.DataFrame(rows, columns=["", *names])
st = df.style.format("{:.3f}", subset=names, na_rep="").set_properties(subset=names, **{"text-align": "right"})
st = st.set_properties(subset=[""], **{"font-weight": "600"})
if "indicative" in str(res.get("self_capacitance", "")) and names and names[0] == "G" and np.isfinite(rows[0][1]):
st = st.format(lambda v: f"{v:.3f} †", subset=pd.IndexSlice[[0], [names[0]]])
return st
def stale(res):
if res is None:
return gr.update(), gr.update(), gr.update()
return STALE, gr.update(elem_classes=MAT + ["tl-stale"]), gr.update(elem_classes=["tl-stale"])
def mark_stale(res_state, status, mat, report, events):
for ev in events:
ev(stale, res_state, [status, mat, report], api_visibility="private", show_progress="hidden")
def predict_ui(fn, expected, note: bool = False):
"""Visible Predict: the /predict function plus the status callout and the result group (hidden until the first result); errors
become an inline callout instead of a toast and grey out an earlier result. note = also return the matrix note (last output)."""
def run(*a):
try:
mat, csv_f, json_f, rep, res = fn(*a)
except Exception as e: # noqa: BLE001
return (gr.update(elem_classes=MAT + ["tl-stale"]), gr.update(), gr.update(), gr.update(elem_classes=["tl-stale"]), gr.update(),
error_html(e), gr.update()) + ((gr.update(),) if note else ())
return (gr.update(value=mat, elem_classes=MAT), csv_f, json_f, gr.update(value=rep, elem_classes=[]), res,
status_html(res, expected(res)), gr.update(visible=True)) + ((matrix_note(res),) if note else ())
run.__name__ = fn.__name__ + "_ui"
return run
def _rows(table) -> list:
if table is None:
return []
rows = table.values.tolist() if hasattr(table, "values") else list(table)
return [list(r) for r in rows if len(r) >= 3 and str(r[0]).strip() not in ("", "nan", "None")]
def _key(r) -> str:
return f"{int(float(r[0]))}/{int(float(r[1]))}"
def inspect_ui(inspect_fn):
"""Inspect on every file change (upload, example, clear): layer table, plot, inline message, layer picker, role."""
def run(f):
none = gr.update(choices=[], value=None)
if f is None:
return [], None, "", none, gr.update(value=None)
try:
table, fig = inspect_fn(f)
except Exception as e: # noqa: BLE001
return [], None, error_html(e, "Could not read this file"), none, gr.update(value=None)
keys = [_key(r) for r in table]
return table, fig, "", gr.update(choices=keys, value=keys[0] if keys else None), gr.update(value=table[0][2] if table else None)
return run
def layer_editor():
with gr.Row(elem_classes="tl-roles"):
pick = gr.Dropdown([], label="layer", interactive=True, min_width=140)
role = gr.Dropdown(ROLES, value=None, label="role", interactive=True, min_width=200)
return pick, role
def wire_editor(layers, pick, role):
"""Fixed role choices instead of free text: pick a layer (or click its row), choose its role. Returns the edit event."""
def show(table, key):
r = next((r for r in _rows(table) if _key(r) == key), None)
return gr.update(value=r[2] if r else None)
def choose(table, evt: gr.SelectData):
rows = _rows(table)
return gr.update(value=_key(rows[evt.index[0]])) if rows and evt.index[0] < len(rows) else gr.update()
def edit(table, key, new):
return [r[:2] + [new] + r[3:] if _key(r) == key else r for r in _rows(table)]
pick.change(show, [layers, pick], role, api_visibility="private", show_progress="hidden")
layers.select(choose, layers, pick, api_visibility="private", show_progress="hidden")
return role.input(edit, [layers, pick, role], layers, api_visibility="private", show_progress="hidden")