Fareeha20Amir's picture
Static site: report, figures and sources
681be0e verified
Raw History Blame Contribute Delete
7.58 kB
"""Shared shell for the nine project demos.
Every project ships the same four-tab layout: the interactive experiment first,
then the diagram, the precomputed results and the PDF behind their own tabs.
Only the first tab differs between projects, so each app.py supplies it as a
callback and everything else is built from the files already in the folder.
"""
import glob
import json
import os
import re
import gradio as gr
HERE = os.path.dirname(os.path.abspath(__file__))
# gradio-lite ships Gradio 5 into the browser; a server install here is 6.
# One source file has to work on both.
_V = tuple(int(x) for x in gr.__version__.split('.')[:2])
_NEW_API = _V >= (6, 0)
CSS = """
.gradio-container {max-width: 1150px !important;}
#banner h1 {margin-bottom: .15em;}
#banner p {color: var(--body-text-color-subdued); margin-top: 0;}
.small-note {font-size: .9em; color: var(--body-text-color-subdued);}
"""
def _path(name):
return os.path.join(HERE, name)
def readme_text():
"""README body with the Space's YAML header and image lines removed.
The images are shown as real components in their own tab; markdown image
syntax pointing at a local file would render as a broken image here.
"""
p = _path("README.md")
if not os.path.exists(p):
return ""
md = open(p, encoding="utf-8").read().replace("\r\n", "\n")
if md.startswith("---\n"):
md = md.split("---\n", 2)[-1]
md = re.sub(r"^!\[[^\]]*\]\([^)]*\)\s*$", "", md, flags=re.M)
return md.strip()
def readme_title():
m = re.search(r"^#\s+(.+)$", readme_text(), re.M)
return m.group(1).strip() if m else "Research project"
def figure_files():
return sorted(glob.glob(_path("figure_*.png")))
def result_files():
return sorted(glob.glob(_path("results*.json")))
def _caption(path):
stem = os.path.splitext(os.path.basename(path))[0]
stem = re.sub(r"^figure_", "", stem).replace("_", " ")
return stem[:1].upper() + stem[1:]
def _results_tab():
figs = figure_files()
if figs:
gr.Markdown(
"The figures below are the output of the full experiment runs, "
"not of the interactive panel. Every number behind them is in the "
"`results*.json` files at the bottom of this tab."
)
for f in figs:
gr.Image(value=f, label=_caption(f), show_label=True,
interactive=False)
files = result_files()
if files:
gr.Markdown("### Raw result files")
gr.Files(value=files, label="results JSON", interactive=False)
def _how_tab():
arch = _path("architecture.png")
if os.path.exists(arch):
gr.Image(value=arch, label="Architecture", show_label=False,
interactive=False)
gr.Markdown(readme_text() or "_No README found._")
def _report_tab():
have = [p for p in (_path("report.pdf"), _path("architecture.pdf"))
if os.path.exists(p)]
if not have:
gr.Markdown("_No PDF in this Space._")
return
gr.Markdown(
"The full write-up, with the derivations, the complete sweeps and the "
"error trail. Download it, or open it in the Files tab of this Space."
)
for p in have:
gr.DownloadButton(label=os.path.basename(p), value=p)
def shell(subtitle, build_try, try_label="Run the experiment"):
"""Assemble the app. `build_try` is called inside the first tab.
In the browser build (gradio-lite) only the source files are loaded into
the virtual filesystem -- the figures, the README and the PDF are served by
the page around the app instead. So the extra tabs appear only when their
files are really present, and with nothing to put in them the app is just
the experiment, with no tab bar at all.
"""
title = readme_title() or "Research project"
extras = bool(figure_files() or result_files()
or os.path.exists(_path("architecture.png"))
or os.path.exists(_path("report.pdf")))
# Gradio 6 moved theme/css from Blocks() to launch(); Gradio 5, which is
# what gradio-lite runs in the browser, still wants them on Blocks().
blocks_kw = {} if _NEW_API else {"css": CSS, "theme": gr.themes.Soft()}
with gr.Blocks(title=title, **blocks_kw) as demo:
with gr.Column(elem_id="banner"):
gr.Markdown((f"# {title}\n" if extras else "") + subtitle)
if not extras:
build_try()
return demo
with gr.Tabs():
with gr.Tab(try_label):
build_try()
with gr.Tab("Full results"):
_results_tab()
with gr.Tab("How it works"):
_how_tab()
with gr.Tab("Report (PDF)"):
_report_tab()
return demo
def json_table(d):
"""Render a small dict/list of dicts as markdown, for result panels."""
def fmt(v):
return f"{v:.4g}" if isinstance(v, float) else str(v)
if isinstance(d, dict):
rows = "\n".join(f"| {k} | {fmt(v)} |" for k, v in d.items())
return "| | |\n|---|---|\n" + rows
if isinstance(d, list) and d and isinstance(d[0], dict):
cols = list(d[0].keys())
head = "| " + " | ".join(cols) + " |"
sep = "|" + "---|" * len(cols)
body = "\n".join(
"| " + " | ".join(
f"{r.get(c):.4g}" if isinstance(r.get(c), float) else str(r.get(c))
for c in cols) + " |"
for r in d)
return "\n".join([head, sep, body])
return "```\n" + json.dumps(d, indent=2) + "\n```"
LAUNCH = {"css": CSS, "theme": gr.themes.Soft()} if _NEW_API else {}
# ---------------------------------------------------------------------------
# Generic Gradio front end, generated from a project's demo_core.
# The browser build renders the same CONTROLS/ACTIONS with plain HTML, so the
# two front ends cannot drift apart.
# ---------------------------------------------------------------------------
def _widget(c):
t = c.get("type", "slider")
if t == "dropdown":
return gr.Dropdown(c["choices"], value=c.get("value"), label=c["label"])
if t == "checkbox":
return gr.Checkbox(value=bool(c.get("value")), label=c["label"])
return gr.Slider(c["min"], c["max"], value=c.get("value"),
step=c.get("step", 1), label=c["label"])
def shell_from_core(core, subtitle=None):
"""Build the whole app from core.CONTROLS / core.ACTIONS / core.call."""
ids = [c["id"] for c in core.CONTROLS]
def build():
if getattr(core, "INTRO", ""):
gr.Markdown(core.INTRO)
widgets = []
row = []
for c in core.CONTROLS:
row.append(c)
# three per row keeps the panel compact at laptop width
for i in range(0, len(row), 3):
with gr.Row():
for c in row[i:i + 3]:
widgets.append(_widget(c))
out_md = gr.Markdown()
out_fig = gr.Plot()
for a in core.ACTIONS:
btn = gr.Button(a["label"],
variant="primary" if a.get("primary") else "secondary")
def make(action_id):
def fn(*vals):
md, fig = core.call(action_id, dict(zip(ids, vals)))
return md, fig
return fn
btn.click(make(a["id"]), widgets, [out_md, out_fig])
if getattr(core, "NOTE", ""):
gr.Markdown(core.NOTE)
return shell(subtitle or getattr(core, "TITLE", ""), build, try_label="Try it")