CurtMRosenbladWheeler's picture
Add titles to own-words boxes
d24bdf2 verified
Raw History Blame Contribute Delete
27.5 kB
"""Gradio demo: a guided walk from one decision tree to a forest of three that disagree.
Run with `uv run learning-object-02-app`. All reader-facing text lives in config.py. The trees
encode the labeling rules in model.py; they execute those rules rather than learning blame
from data. The forest is never collapsed to a majority vote: the disagreement between the
trees is the point of the demo.
"""
import random
from collections import deque
from html import escape
from itertools import product
import gradio as gr
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from learning_object_02 import config as C
from learning_object_02.loading import FEATURES, load_scenarios, load_trees
# Dark enough for white text (4.5:1 or better).
COLORS = {
"owner": "#1f5fa8",
"programmer": "#1d7a52",
"manufacturer": "#99540a",
"nobody": "#6b7280",
}
DF = load_scenarios() # from $LO_DATASET_REPO on the Hub, else ./dataset
TREES = load_trees() # from $LO_MODEL_REPO on the Hub, else ./models
ROWS = DF.to_dicts()
CHOICES = [
(
f"{r['id']:>2}. {r['scenario'][:95]}{'...' if len(r['scenario']) > 95 else ''}",
r["id"],
)
for r in ROWS
]
def chip(answer: str) -> str:
return f'<span class="chip {answer}">{answer}</span>'
def responsible(x: list[int]) -> str:
"""Who the foresee question is about: the owner if a person decided, the programmer for an
explicit rule, the manufacturer for learned behaviour."""
return "owner" if x[0] else "programmer" if x[1] else "manufacturer"
def explain(tree: DecisionTreeClassifier, x: list[int]) -> tuple[str, list[str]]:
"""Return the tree's answer and the questions it asked on the way."""
t = tree.tree_
node, steps = 0, []
while t.children_left[node] != t.children_right[node]:
name = FEATURES[t.feature[node]]
yes = x[t.feature[node]] == 1
if name == "foreseeable":
template = C.FORESEE_YES if yes else C.FORESEE_NO
text = template.format(actor=C.ACTORS[responsible(x)])
else:
text = C.PATH_PHRASES[name][0 if yes else 1]
steps.append(
f"{C.FEATURE_NAMES[name]}? "
f'<span class="yn {"y" if yes else "n"}">{C.YES if yes else C.NO}</span> {text}'
)
node = t.children_right[node] if yes else t.children_left[node]
answer = str(tree.classes_[int(np.argmax(t.value[node]))])
return answer, steps
SLOT, ROW, NODE_W, NODE_H = 150, 84, 132, 36
def tree_svg(tree: DecisionTreeClassifier, x: list[int]) -> str:
"""Draw the whole tree as inline SVG, with the path this case takes highlighted."""
t = tree.tree_
pos: dict[int, tuple[float, float]] = {}
leaves = iter(range(1000))
def place(node: int, depth: int) -> float:
left, right = t.children_left[node], t.children_right[node]
if left == right:
cx = next(leaves) * SLOT + SLOT / 2
else:
cx = (place(left, depth + 1) + place(right, depth + 1)) / 2
pos[node] = (cx, depth * ROW + NODE_H / 2 + 4)
return cx
place(0, 0)
on_path, node = {0}, 0
while t.children_left[node] != t.children_right[node]:
yes = x[t.feature[node]] == 1
node = t.children_right[node] if yes else t.children_left[node]
on_path.add(node)
width = (max(cx for cx, _ in pos.values()) + SLOT / 2) if pos else SLOT
height = max(cy for _, cy in pos.values()) + NODE_H / 2 + 4
edges, nodes = [], []
for n, (cx, cy) in pos.items():
left, right = t.children_left[n], t.children_right[n]
if left == right:
ans = str(tree.classes_[int(np.argmax(t.value[n]))])
style = (
'fill="none" stroke-dasharray="5 4"'
if ans == "nobody"
else f'fill="{COLORS[ans]}"'
)
text_fill = "currentColor" if ans == "nobody" else "#fff"
body = (
f'<rect x="{cx - NODE_W / 2 + 12}" y="{cy - NODE_H / 2}" width="{NODE_W - 24}" '
f'height="{NODE_H}" rx="18" {style} stroke="{COLORS[ans]}" stroke-width="2"/>'
f'<text x="{cx}" y="{cy + 5}" text-anchor="middle" font-weight="700" '
f'font-size="14" fill="{text_fill}">{ans}</text>'
)
else:
name = C.FEATURE_NAMES[FEATURES[t.feature[n]]]
body = (
f'<rect x="{cx - NODE_W / 2}" y="{cy - NODE_H / 2}" width="{NODE_W}" height="{NODE_H}" '
f'rx="6" fill="var(--block-background-fill)" stroke="currentColor" stroke-width="1.5"/>'
f'<text x="{cx}" y="{cy + 5}" text-anchor="middle" font-size="13" '
f'fill="currentColor">{name}?</text>'
)
for child, word in ((left, C.NO), (right, C.YES)):
px, py = pos[child]
hot = n in on_path and child in on_path
mx, my = (cx + px) / 2, (cy + py) / 2
edges.append(
f'<g opacity="{1 if hot else 0.35}">'
f'<line x1="{cx}" y1="{cy + NODE_H / 2}" x2="{px}" y2="{py - NODE_H / 2}" '
f'stroke="currentColor" stroke-width="{3.5 if hot else 1.5}"/>'
f'<text x="{mx}" y="{my}" text-anchor="middle" font-size="12" font-weight="{700 if hot else 400}" '
f'fill="currentColor" stroke="var(--block-background-fill)" stroke-width="4" '
f'paint-order="stroke">{word}</text></g>'
)
nodes.append(f'<g opacity="{1 if n in on_path else 0.4}">{body}</g>')
return (
f'<svg viewBox="0 0 {width} {height}" style="max-width:{width}px; --w:{width}px" role="img" aria-label="{C.TREE_ARIA}">'
f"{''.join(edges)}{''.join(nodes)}</svg>"
)
def row_for(x: list[int]) -> dict:
return next(r for r in ROWS if [r[k] for k in FEATURES] == x)
def answer_for(label: str, x: list[int]) -> str:
return explain(TREES[label], x)[0]
CSS = """
.gradio-container {max-width: 860px !important; margin: 0 auto !important;}
.gradio-container, .gradio-container * {line-height: 1.55;}
:focus-visible {outline: 3px solid #1f5fa8 !important; outline-offset: 2px;}
/* Answer chips: the one visual idea. Same four marks everywhere. */
.chip {display: inline-block; padding: 3px 12px; border-radius: 999px; color: #fff;
font-weight: 700; font-size: 1rem; white-space: nowrap;}
.chip.owner {background: #1f5fa8;} .chip.programmer {background: #1d7a52;}
.chip.manufacturer {background: #99540a;}
.chip.nobody {background: transparent; color: var(--body-text-color);
border: 2px dashed currentColor; padding: 1px 10px;}
/* Opening */
.lo-title {font-size: clamp(1.6rem, 4.2vw, 2.3rem); font-weight: 700; line-height: 1.2;
margin: 8px 0 18px 0;}
.lo-ideas {display: grid; grid-template-columns: 1fr 1fr; border: 1px solid var(--border-color-primary);
border-radius: 10px; overflow: hidden;}
.lo-idea {padding: 16px 18px;}
.lo-idea + .lo-idea {border-left: 1px solid var(--border-color-primary);}
.lo-idea-name {font-weight: 700; font-size: 1.15rem; margin-bottom: 4px;}
.lo-lead {font-size: 1.1rem; margin: 14px 0 6px 0;}
.lo-read {opacity: .85; max-width: 68ch; margin: 0;}
@media (max-width: 640px) {
.lo-ideas {grid-template-columns: 1fr;}
.lo-idea + .lo-idea {border-left: 0; border-top: 1px solid var(--border-color-primary);}
}
/* Progress rail */
.lo-rail {display: flex; gap: 6px; padding: 8px 0; align-items: center; margin: 0; list-style: none; flex-wrap: wrap;}
.lo-rail li {display: flex; align-items: center; gap: 6px; font-size: .9rem; opacity: .55;}
.lo-rail li .n {width: 24px; height: 24px; border-radius: 50%; display: grid; place-items: center;
border: 2px solid currentColor; font-weight: 700; font-size: .8rem;}
.lo-rail li.done {opacity: .85;}
.lo-rail li.done .n {background: var(--body-text-color); color: var(--body-background-fill);
border-color: var(--body-text-color);}
.lo-rail li.now {opacity: 1; font-weight: 700;}
.lo-rail li.now .n {background: #1f5fa8; color: #fff; border-color: #1f5fa8;}
.lo-rail li + li::before {content: ""; width: 18px; border-top: 2px solid var(--border-color-primary);}
/* Section headings and the case */
.lo-h {font-size: 1.5rem; font-weight: 700; margin: 22px 0 6px 0;}
.lo-sub {opacity: .85; max-width: 68ch; margin: 0 0 10px 0;}
.lo-case {font-size: 1.2rem; line-height: 1.5; padding: 14px 18px; max-width: 68ch;
border-left: 5px solid var(--body-text-color); background: var(--block-background-fill);}
/* Trees */
.lo-cards {display: grid; gap: 14px; grid-template-columns: minmax(0, 1fr);}
.lo-card {min-width: 0;}
.lo-card {border: 1px solid var(--border-color-primary); border-radius: 10px; padding: 16px;
background: var(--block-background-fill); display: flex; flex-wrap: wrap; gap: 18px;}
.lo-info {flex: 1 1 250px;}
.lo-graph {flex: 2 1 340px; min-width: 0; color: var(--body-text-color);}
.lo-graph svg {width: 100%; height: auto; display: block; margin: 0 auto;}
.lo-name {font-weight: 700; font-size: 1.15rem;}
.lo-q {opacity: .85; margin-bottom: 10px;}
.lo-path {margin: 10px 0 0 0; padding-left: 20px;}
.lo-path li {margin-bottom: 4px;}
.yn {font-weight: 700; padding: 0 6px; border-radius: 4px; border: 1px solid currentColor;}
.lo-ask {margin-top: 12px; padding-left: 10px; border-left: 4px solid #1f5fa8; font-size: .95rem;}
.lo-legend {font-size: .85rem; opacity: .8; margin-top: 4px;}
/* Side-by-side answers */
.lo-strip {display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 14px;}
.lo-strip > div {border: 1px solid var(--border-color-primary); border-radius: 10px; padding: 12px 14px;
background: var(--block-background-fill);}
.lo-strip .lo-q {margin: 0 0 8px 0; min-height: 3em;}
@media (max-width: 640px) {.lo-strip {grid-template-columns: 1fr;} .lo-strip .lo-q {min-height: 0;}}
.lo-banner {border-radius: 10px; padding: 12px 16px; margin-top: 14px;
border: 1px solid var(--border-color-primary); max-width: 72ch;}
.lo-banner.hot {border: 2px solid #99540a;}
/* Step 4 */
.lo-two {display: grid; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));}
.lo-two .lo-card {display: block;}
.lo-say {display: grid; grid-template-columns: 8.5rem 1fr; gap: 4px 12px; margin-top: 12px; align-items: start;}
.lo-say .who {font-weight: 700;}
.lo-say .why {grid-column: 2; margin: 0 0 6px 0;}
.lo-say .what {grid-row: auto;}
@media (max-width: 640px) {
.lo-graph {overflow-x: auto;}
.lo-graph svg {min-width: min(var(--w), 440px);}
.lo-say {grid-template-columns: 1fr;}
.lo-say .why {grid-column: 1;}
}
/* Tables, placeholders, takeaway */
.lo-table {border-collapse: collapse; width: 100%; font-size: .9rem;}
.lo-table th, .lo-table td {border: 1px solid var(--border-color-primary); padding: 5px 8px; text-align: left;}
.lo-table tr.diff td {background: color-mix(in srgb, #99540a 16%, transparent);}
.lo-table tr.gap td {background: color-mix(in srgb, #6b7280 24%, transparent);}
.lo-placeholder {border: 2px dashed var(--border-color-primary); border-radius: 10px;
padding: 12px 14px; opacity: .85; margin-bottom: 8px;}
.lo-placeholder h4 {margin: 0 0 .5em 0; font-weight: 700;}
.lo-placeholder p {margin: 0 0 .9em 0;}
.lo-placeholder p:last-child {margin-bottom: 0;}
.lo-takeaway {font-size: clamp(1.3rem, 3.4vw, 1.8rem); line-height: 1.35; font-weight: 700;
padding: 18px 20px; border: 2px solid #99540a; border-radius: 10px; max-width: 30em;}
.lo-gloss dt {font-weight: 700; margin-top: 8px;}
.lo-gloss dd {margin: 0;}
.lo-note {margin-top: 10px; font-size: .9rem; opacity: .9;}
.lo-more {margin: 14px 0 0 0; padding: 10px 14px; border: 1px dashed var(--border-color-primary);
border-radius: 10px; max-width: 72ch;}
.lo-count {margin: 0 0 10px 0; opacity: .9;}
.lo-results-h {font-weight: 700; margin: 14px 0 8px 0;}
/* The progress bar stays at the top of the window at all times. */
.lo-rail-wrap {position: fixed; top: 0; left: 0; right: 0; z-index: 1000;
background: var(--body-background-fill);
border-bottom: 1px solid var(--border-color-primary);}
.lo-rail-wrap .lo-rail {max-width: 860px; margin: 0 auto; padding: 10px 16px; flex-wrap: nowrap;
overflow-x: auto;}
.gradio-container {padding-top: 64px !important;}
[id^="step-"] {scroll-margin-top: 72px;}
@media (max-width: 640px) {
.lo-rail li:not(.now) .lbl {display: none;}
}
"""
def rail(n: int) -> str:
items = []
for i, name in enumerate(C.STEPS, 1):
state = "now" if i == n else "done" if i < n else ""
cur = ' aria-current="step"' if i == n else ""
items.append(
f'<li class="{state}"{cur}><span class="n">{i}</span><span class="lbl">{name}</span></li>'
)
return (
f'<div class="lo-rail-wrap"><ol class="lo-rail" aria-label="{C.PROGRESS_LABEL}">'
f"{''.join(items)}</ol></div>"
)
def card(label: str, x: list[int], ask: str) -> tuple[str, str]:
answer, steps = explain(TREES[label], x)
items = "".join(f"<li>{s}</li>" for s in steps)
note = f'<div class="lo-note">{C.LIABILITY_NOTE}</div>' if label == "legal" else ""
html = (
f'<div class="lo-card"><div class="lo-info">'
f'<div class="lo-name">{C.TREE_NAMES[label]}</div>'
f'<div class="lo-q">{C.TREE_QUESTIONS[label]}</div>{chip(answer)}'
f'<ol class="lo-path">{items}</ol><div class="lo-ask">{ask}</div>{note}</div>'
f'<div class="lo-graph">{tree_svg(TREES[label], x)}'
f'<div class="lo-legend">{C.TREE_LEGEND}</div></div></div>'
)
return html, answer
# ---------------------------------------------------------------------------
# Try it: a random unforeseen case
# ---------------------------------------------------------------------------
ROW_BY_ID = {r["id"]: r for r in ROWS}
_RECENT: deque[int] = deque(
maxlen=4
) # avoid showing the same case to back-to-back visitors
def features_of(row: dict) -> list[int]:
return [row[k] for k in FEATURES]
def pick_case(avoid: int | None = None) -> dict:
"""Pick an unforeseen scenario at random, favouring the ones where all three trees disagree."""
pool = [r for r in ROWS if all(r[k] == v for k, v in C.TRY_REQUIRED.items())]
fresh = [r for r in pool if r["id"] != avoid and r["id"] not in _RECENT]
rows = fresh or [r for r in pool if r["id"] != avoid] or pool
weights = [
C.TRY_PREFERRED_WEIGHT if features_of(r) in C.TRY_PREFERRED else 1 for r in rows
]
row = random.choices(rows, weights)[0]
_RECENT.append(row["id"])
return row
def case_html(row: dict) -> str:
return f'<div class="lo-case">{escape(row["scenario"])}</div>'
def answers_block(x: list[int]) -> str:
"""The three answers side by side, and the note on how they compare. No combined answer."""
answers = {lab: answer_for(lab, x) for lab in C.DISPLAY}
strip = "".join(
f'<div><div class="lo-name">{C.TREE_SHORT[lab]}</div>'
f'<div class="lo-q">{C.TREE_QUESTIONS[lab]}</div>{chip(answers[lab])}</div>'
for lab in C.DISPLAY
)
distinct = len(set(answers.values()))
if answers == {"moral": "nobody", "legal": "manufacturer", "design": "programmer"}:
head, css = C.FOREST_SIGNATURE, "lo-banner hot"
elif distinct == 1:
head = C.FOREST_AGREE.format(answer=answers["moral"])
css = "lo-banner"
else:
head, css = C.FOREST_DIFFER.format(n=distinct), "lo-banner hot"
gap = C.FOREST_GAP if answers["moral"] == "nobody" and distinct != 3 else ""
return (
f'<div class="lo-strip">{strip}</div>'
f'<div class="{css}">{head}{gap}{C.FOREST_TAIL}</div>'
)
def render_one_tree(pick: str | None, sid: int | None) -> str:
"""Step 2: the single (Kantian) tree for the Try it case, next to the reader's pick."""
if sid is None:
return ""
html, answer = card("moral", features_of(ROW_BY_ID[sid]), C.ONE_TREE_ASK)
note = C.ONE_TREE_PICKED.format(pick=chip(pick)) if pick else ""
gap = C.ONE_TREE_GAP if answer == "nobody" else ""
says = C.ONE_TREE_SAYS.format(answer=chip(answer))
return (
f'<div class="lo-cards">{html}</div>'
f'<div class="lo-banner">{note}{says}{gap}</div>'
)
def render_forest(h: bool, e: bool, f: bool, p: bool) -> str:
"""Step 3: the same case through all three trees, never combined into one answer."""
x = [int(h), int(e), int(f), int(p)]
cards = "".join(card(lab, x, C.FOREST_ASK)[0] for lab in C.DISPLAY)
return f'{answers_block(x)}<br><div class="lo-cards">{cards}</div>'
def render_tester(h: bool, e: bool, f: bool, p: bool) -> str:
"""The same three answers, shown right under the switches."""
x = [int(h), int(e), int(f), int(p)]
return f'<div class="lo-results-h">{C.TESTER_RESULTS}</div>{answers_block(x)}'
def render_all_cases() -> str:
"""A table of all 16 situations. Rows where the trees disagree are shaded."""
rows = []
for x in product([0, 1], repeat=4):
x = list(x)
a = {lab: answer_for(lab, x) for lab in C.DISPLAY}
css = "diff" if len(set(a.values())) > 1 else ""
if a["moral"] == "nobody":
css = "gap"
cells = [
C.TABLE_HUMAN if x[0] else C.TABLE_ALGORITHM,
C.TABLE_EXPLICIT if x[1] else C.TABLE_LEARNED,
C.YES if x[2] else C.NO,
C.YES if x[3] else C.NO,
*[a[lab] for lab in C.DISPLAY],
]
rows.append(
f'<tr class="{css}">' + "".join(f"<td>{c}</td>" for c in cells) + "</tr>"
)
heads = [*C.TABLE_HEADERS, *(C.TREE_SHORT[lab] for lab in C.DISPLAY)]
return (
'<table class="lo-table"><tr>'
+ "".join(f"<th>{h}</th>" for h in heads)
+ "</tr>"
+ "".join(rows)
+ "</table>"
f'<div class="lo-legend">{C.TABLE_LEGEND}</div>'
)
def render_test_case(x: list[int], heading: str) -> str:
r = row_for(x)
k, u = answer_for("moral", x), answer_for("design", x)
return (
f'<div class="lo-card"><div><div class="lo-name">{heading}</div><br>'
f'<div class="lo-case">{escape(r["scenario"])}</div>'
f'<div class="lo-say"><span class="who">{C.KANT_SAYS}</span><span>{chip(k)}</span>'
f'<p class="why">{C.BECAUSE.format(reason=C.KANT_WHY[k])}</p>'
f'<span class="who">{C.UTIL_SAYS}</span><span>{chip(u)}</span>'
f'<p class="why">{C.BECAUSE.format(reason=C.UTIL_WHY[u])}</p></div></div></div>'
)
def render_test_cases() -> str:
cards = "".join(render_test_case(x, heading) for heading, x in C.TEST_CASES)
return f'<div class="lo-two">{cards}</div>'
def examples_for(h: bool, e: bool, f: bool, p: bool) -> str:
want = [int(h), int(e), int(f), int(p)]
rows = [r for r in ROWS if features_of(r) == want]
lines = "\n".join(f"- {r['scenario']}" for r in rows)
return f"{C.EXAMPLES_LINE}\n{lines}"
def pick_scenario(sid: int | None):
if sid is None:
return [gr.update()] * 4 + [""]
r = ROW_BY_ID[sid]
return [bool(r[k]) for k in FEATURES] + [case_html(r)]
def intro_html() -> str:
ideas = "".join(
f'<div class="lo-idea"><div class="lo-idea-name">{name}</div>{text}</div>'
for name, text in C.IDEAS
)
return (
f'<div class="lo-title">{C.TITLE}</div><div class="lo-ideas">{ideas}</div>'
f'<p class="lo-lead">{C.LEAD}</p><p class="lo-read">{C.READ_NOTE}</p>'
)
def glossary_html() -> str:
items = "".join(f"<dt>{t}</dt><dd>{d}</dd>" for t, d in C.GLOSSARY)
return f'<dl class="lo-gloss">{items}</dl>'
def sources_md() -> str:
lines = "\n".join(f"- {s}" for s in C.SOURCES)
return f"{C.SOURCES_TITLE}\n{lines}\n\n{C.SOURCES_PLACEHOLDER}"
def more_steps_html() -> str:
steps = ", ".join(C.STEPS[1:])
return (
f'<p class="lo-more">{C.MORE_STEPS.format(n=len(C.STEPS) - 1, steps=steps)}</p>'
)
def scroll_js(step_id: str) -> str:
return f"""() => setTimeout(() => {{
const el = document.getElementById('{step_id}');
const calm = matchMedia('(prefers-reduced-motion: reduce)').matches;
if (el) el.scrollIntoView({{behavior: calm ? 'auto' : 'smooth', block: 'start'}});
}}, 200)"""
def heading(text: str, sub: str = "") -> str:
s = f'<p class="lo-sub">{sub}</p>' if sub else ""
return f'<div class="lo-h">{text}</div>{s}'
def reflection(label: str, placeholder: str = C.SAVED_NOTE) -> gr.Textbox:
"""A free-text box. The note that nothing is saved is always visible under the label."""
return gr.Textbox(
label=label,
info=C.SAVED_NOTE,
placeholder=placeholder,
lines=3,
interactive=True,
)
def switch(feature: str, value: bool) -> gr.Checkbox:
label, info = C.SWITCHES[feature]
return gr.Checkbox(value, label=label, info=info or None)
def build() -> gr.Blocks:
with gr.Blocks(title=C.PAGE_TITLE) as demo:
progress = gr.HTML(rail(1))
gr.HTML(intro_html())
with gr.Accordion(C.GLOSSARY_TITLE, open=C.GLOSSARY_OPEN):
gr.HTML(glossary_html())
case_id = gr.State(None)
# Step 1: try it yourself
with gr.Column(elem_id="step-1"):
gr.HTML(heading(C.TRY_HEADING, C.TRY_SUB))
case_box = gr.HTML()
pick = gr.Radio(C.ANSWER_LABELS, label=C.TRY_QUESTION)
with gr.Row():
lock = gr.Button(C.LOCK_BUTTON, variant="primary")
new_case = gr.Button(C.NEW_CASE_BUTTON)
with gr.Column(visible=False) as reflect1:
why1 = reflection(C.WHY_LABEL, C.WHY_PLACEHOLDER)
to_tree = gr.Button(C.TO_TREE_BUTTON, variant="primary")
gr.HTML(more_steps_html())
# Step 2: one tree
with gr.Column(visible=False, elem_id="step-2") as step2:
gr.HTML(heading(C.ONE_TREE_HEADING, C.ONE_TREE_SUB))
tree_out = gr.HTML()
why2 = reflection(C.ONE_TREE_LABEL)
to_forest = gr.Button(C.TO_FOREST_BUTTON, variant="primary")
# Step 3: the forest
with gr.Column(visible=False, elem_id="step-3") as step3:
gr.HTML(heading(C.FOREST_HEADING, C.FOREST_SUB))
forest_out = gr.HTML()
why3 = reflection(C.FOREST_LABEL)
with gr.Accordion(C.EXPLORE_TITLE, open=False):
gr.HTML(f'<p class="lo-count">{C.COUNT_LINE}</p>')
scenario = gr.Dropdown(CHOICES, label=C.SCENARIO_LABEL, value=None)
scenario_box = gr.HTML()
with gr.Row():
h = switch("human_decided", False)
e = switch("explicit_rule", False)
with gr.Row():
f = switch("foreseeable", False)
p = switch("patchable", True)
tester_out = gr.HTML()
examples = gr.Markdown()
with gr.Accordion(C.TABLE_TITLE, open=False):
gr.HTML(render_all_cases())
to_test = gr.Button(C.TO_TEST_BUTTON, variant="primary")
# Step 4: separating test cases
with gr.Column(visible=False, elem_id="step-4") as step4:
gr.HTML(heading(C.TEST_HEADING, C.TEST_SUB))
gr.HTML(render_test_cases())
why4 = reflection(C.TEST_LABEL)
to_end = gr.Button(C.TO_END_BUTTON, variant="primary")
# Step 5: takeaway and sources
with gr.Column(visible=False, elem_id="step-5") as step5:
gr.HTML(heading(C.TAKEAWAY_HEADING))
gr.HTML(f'<div class="lo-takeaway">{C.TAKEAWAY}</div>')
gr.Markdown(sources_md())
with gr.Accordion(C.OWN_WORDS_TITLE, open=False):
gr.HTML(
f'<div class="lo-placeholder"><h4>{C.CONFUSION_TITLE}</h4>'
f"<p>{C.CONFUSION_PLACEHOLDER}</p></div>"
)
paragraphs = "".join(
f"<p>{para}</p>" for para in C.EXPLANATION_PLACEHOLDER.split("\n\n")
)
gr.HTML(
f'<div class="lo-placeholder"><h4>{C.EXPLANATION_TITLE}</h4>'
f"{paragraphs}</div>"
)
gr.Markdown(C.FOOTER)
inputs = [h, e, f, p]
def on_lock(choice):
if choice is None:
gr.Warning(C.NEED_ANSWER_WARNING)
return gr.update(visible=choice is not None)
def refresh(h, e, f, p):
return (
render_forest(h, e, f, p),
render_tester(h, e, f, p),
examples_for(h, e, f, p),
)
def fresh_case(prev_id):
"""Pick a new unforeseen case and reset everything that came after Try it."""
row = pick_case(prev_id)
flags = [bool(v) for v in features_of(row)]
hide = gr.update(visible=False)
return [
row["id"], # case_id
case_html(row), # case_box
*flags, # h, e, f, p
None, # scenario dropdown
"", # scenario_box
None, # pick
"", # why1
hide, # reflect1
"", # tree_out
"", # why2
render_forest(*flags), # forest_out
"", # why3
render_tester(*flags), # tester_out
examples_for(*flags), # examples
"", # why4
hide,
hide,
hide,
hide, # step2 to step5
rail(1), # progress
]
fresh_outputs = [
case_id, case_box, h, e, f, p, scenario, scenario_box, pick, why1, reflect1,
tree_out, why2, forest_out, why3, tester_out, examples, why4,
step2, step3, step4, step5, progress,
] # fmt: skip
def reveal(n: int):
return lambda: (gr.update(visible=True), rail(n))
def go(button, fn, outputs, step_id, extra=None):
ev = button.click(fn, None, outputs)
if extra:
ev = ev.then(*extra)
ev.then(None, None, None, js=scroll_js(step_id))
demo.load(fresh_case, case_id, fresh_outputs)
new_case.click(fresh_case, case_id, fresh_outputs).then(
None, None, None, js=scroll_js("step-1")
)
lock.click(on_lock, pick, reflect1)
go(
to_tree,
reveal(2),
[step2, progress],
"step-2",
(render_one_tree, [pick, case_id], tree_out),
)
go(to_forest, reveal(3), [step3, progress], "step-3")
go(to_test, reveal(4), [step4, progress], "step-4")
go(to_end, reveal(5), [step5, progress], "step-5")
scenario.change(pick_scenario, scenario, [*inputs, scenario_box])
for box in inputs:
box.change(refresh, inputs, [forest_out, tester_out, examples])
return demo
def main() -> None:
theme = gr.themes.Base(
primary_hue="blue",
neutral_hue="slate",
font=[
gr.themes.GoogleFont("Atkinson Hyperlegible", weights=(400, 700)),
"system-ui",
"sans-serif",
],
)
build().launch(css=CSS, theme=theme)
if __name__ == "__main__":
main()