Deploy HW3 explainer app
Browse files- README.md +27 -6
- app.py +222 -0
- calculator.py +298 -0
- explainer.py +168 -0
- requirements.txt +6 -0
- theme.py +194 -0
README.md
CHANGED
|
@@ -1,13 +1,34 @@
|
|
| 1 |
---
|
| 2 |
title: Step Response Explainer
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 6.
|
| 8 |
-
python_version:
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: Step Response Explainer
|
| 3 |
+
emoji: 📈
|
| 4 |
+
colorFrom: pink
|
| 5 |
+
colorTo: yellow
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.28.0
|
| 8 |
+
python_version: "3.13"
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
+
license: mit
|
| 12 |
+
short_description: Second-order step response, computed and explained
|
| 13 |
+
models:
|
| 14 |
+
- Qwen/Qwen3-0.6B
|
| 15 |
---
|
| 16 |
|
| 17 |
+
# Step response explainer
|
| 18 |
+
|
| 19 |
+
Enter an underdamped second-order system, either as ωn and ζ or as a physical mass, damper, and spring. The app computes its step response from first principles, checks it against optional design limits, and then asks a small language model to explain the numbers in plain words. Built for 24-679 Designing and Prototyping AI Systems, Homework 3.
|
| 20 |
+
|
| 21 |
+
## What it calculates
|
| 22 |
+
For $G(s) = K\omega_n^2 / (s^2 + 2\zeta\omega_n s + \omega_n^2)$ with a step of size $A$:
|
| 23 |
+
$c(t) = 1 - \frac{e^{-\zeta\omega_n t}}{\sqrt{1-\zeta^2}}\sin(\omega_d t + \theta)$, with $\omega_d = \omega_n\sqrt{1-\zeta^2}$ and $\theta = \tan^{-1}(\sqrt{1-\zeta^2}/\zeta)$.
|
| 24 |
+
|
| 25 |
+
The app reports percent overshoot, peak value and time, 10 to 90% and 0 to 100% rise time, settling time (exact and the textbook $4/\zeta\omega_n$ estimate), damped frequency and period, and pole locations. It also checks optional overshoot and settling limits, giving the ζ or ωn that would pass a failed check.
|
| 26 |
+
|
| 27 |
+
## Scope and valid inputs
|
| 28 |
+
Underdamped only, with $0.05 \le \zeta \le 0.95$ and $0.1 \le \omega_n \le 500$ rad/s. The system is linear, has no zeros, starts from rest, and receives an ideal step at $t = 0$. Mass-spring-damper inputs are converted with $\omega_n = \sqrt{k/m}$ and $\zeta = c/(2\sqrt{km})$, and the output is shown in mm. Out-of-scope values, such as an overdamped system, return a message saying which value to change.
|
| 29 |
+
|
| 30 |
+
## How the explanation is kept honest
|
| 31 |
+
The calculator produces a structured record. Its text form, shown in the app, is the only thing the language model ([Qwen/Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B), pinned revision, greedy decoding on CPU) receives. Two worked examples generated by the calculator itself set the style. A deterministic check then flags any number in the explanation that is not in the record, and any pass or fail statement that contradicts it. The table is always the source of truth.
|
| 32 |
+
|
| 33 |
+
## Credits
|
| 34 |
+
Calculator, app, and prompt by Jack Stevens with Claude (Anthropic) as a coding assistant. MIT licence. Qwen3 is Apache 2.0.
|
app.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gradio app: underdamped step response calculator with an LLM explanation panel."""
|
| 2 |
+
from html import escape
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from matplotlib.figure import Figure
|
| 8 |
+
|
| 9 |
+
import calculator as C
|
| 10 |
+
import explainer as E
|
| 11 |
+
import theme as T
|
| 12 |
+
|
| 13 |
+
MODES = {"Normalised (ωn, ζ)": "normalised", "Mass-spring-damper (m, c, k)": "mass-spring-damper"}
|
| 14 |
+
TABLE_COLUMNS = ["Quantity", "Value", "Unit", "Formula or method"]
|
| 15 |
+
STALE_NOTE = "_Select **Explain these results** to generate a plain-language explanation of the numbers above._"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def plot_response(record):
|
| 19 |
+
"""Response curve with final value, settling band, envelope and key markers."""
|
| 20 |
+
cv = record["_curve"]
|
| 21 |
+
t = np.linspace(0.0, cv["t_end"], 1500)
|
| 22 |
+
c = C.normalised_response(t, cv["zeta"], cv["wn"])
|
| 23 |
+
y, yf, band = cv["y_final"] * c, cv["y_final"], cv["band"]
|
| 24 |
+
root = (1 - cv["zeta"] ** 2) ** 0.5
|
| 25 |
+
env = np.exp(-cv["zeta"] * cv["wn"] * t) / root # decay envelope of the oscillation
|
| 26 |
+
|
| 27 |
+
fig = Figure(figsize=(7.2, 3.6), dpi=110)
|
| 28 |
+
fig.patch.set_facecolor(T.P["surface"])
|
| 29 |
+
ax = fig.add_subplot(111)
|
| 30 |
+
ax.set_facecolor(T.P["surface"])
|
| 31 |
+
ax.axhspan(yf * (1 - band), yf * (1 + band), color=T.P["data"], alpha=0.32, lw=0,
|
| 32 |
+
label=f"{record['settling_band']} band")
|
| 33 |
+
ax.plot(t, yf * (1 + env), color=T.P["muted"], lw=0.9, ls=":", label="Envelope")
|
| 34 |
+
ax.plot(t, yf * (1 - env), color=T.P["muted"], lw=0.9, ls=":")
|
| 35 |
+
ax.axhline(yf, color=T.P["ink"], lw=0.8, ls="--", label="Final value")
|
| 36 |
+
ax.plot(t, y, color=T.P["accent"], lw=2.2, label="Response")
|
| 37 |
+
|
| 38 |
+
m = record["metrics"]
|
| 39 |
+
tp, yp, ts = m["peak_time"]["value"], m["peak_value"]["value"], m["ts_exact"]["value"]
|
| 40 |
+
ax.plot([tp], [yp], "o", color=T.P["accent"], ms=6)
|
| 41 |
+
ax.annotate(f"Peak {C.fmt(yp)} at {C.fmt(tp)} s", (tp, yp), xytext=(8, 6),
|
| 42 |
+
textcoords="offset points", fontsize=8.5, color=T.P["ink"])
|
| 43 |
+
ax.axvline(ts, color=T.P["good"], lw=1.1)
|
| 44 |
+
ax.annotate(f"Settled {C.fmt(ts)} s", (ts, yf * (1 - band)), xytext=(4, -14),
|
| 45 |
+
textcoords="offset points", fontsize=8.5, color=T.P["good"])
|
| 46 |
+
|
| 47 |
+
unit = f" ({record['output_unit']})" if record["output_unit"] else ""
|
| 48 |
+
ax.set_xlabel("Time (s)", color=T.P["ink"])
|
| 49 |
+
ax.set_ylabel(f"{record['output_name'].capitalize()}{unit}", color=T.P["ink"])
|
| 50 |
+
lo = min(float(y.min()), 0.0, yf * (1 - band)) # works for negative steps too
|
| 51 |
+
hi = max(float(y.max()), 0.0, yf * (1 + band))
|
| 52 |
+
pad = 0.06 * (hi - lo)
|
| 53 |
+
ax.set_ylim(lo - pad, hi + pad)
|
| 54 |
+
ax.set_xlim(0, cv["t_end"])
|
| 55 |
+
for side in ("top", "right"):
|
| 56 |
+
ax.spines[side].set_visible(False)
|
| 57 |
+
for side in ("left", "bottom"):
|
| 58 |
+
ax.spines[side].set_color(T.P["line"])
|
| 59 |
+
ax.tick_params(colors=T.P["muted"], labelsize=8.5)
|
| 60 |
+
ax.legend(loc="lower right", fontsize=8, frameon=False, labelcolor=T.P["ink"])
|
| 61 |
+
fig.tight_layout()
|
| 62 |
+
return fig
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def summary_card(record):
|
| 66 |
+
"""Headline numbers plus one badge per design check."""
|
| 67 |
+
m = record["metrics"]
|
| 68 |
+
unit = f" {record['output_unit']}" if record["output_unit"] else ""
|
| 69 |
+
title = f"{C.fmt(m['overshoot']['value'])} % overshoot, settled in {C.fmt(m['ts_exact']['value'])} s"
|
| 70 |
+
sub = (f"The {escape(record['output_name'])} peaks at {C.fmt(m['peak_value']['value'])}{escape(unit)} "
|
| 71 |
+
f"after {C.fmt(m['peak_time']['value'])} s and settles at {C.fmt(m['final']['value'])}{escape(unit)}.")
|
| 72 |
+
badges = []
|
| 73 |
+
for ch in record["checks"]:
|
| 74 |
+
word = "passes" if ch["result"] == "PASS" else "fails"
|
| 75 |
+
badges.append(T.badge(f"{ch['name']} {word}", "good" if ch["result"] == "PASS" else "bad"))
|
| 76 |
+
body = " ".join(badges) if badges else T.badge("No design limits set", "warn")
|
| 77 |
+
foot = " ".join(escape(w) for w in record["warnings"]) or \
|
| 78 |
+
"Closed-form values from the standard second-order model; settling time found numerically."
|
| 79 |
+
return T.verdict_html(title, sub, f"<p>{body}</p>", foot)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def run_calculation(mode_label, wn, zeta, amplitude, gain, mass, damping, stiffness, force,
|
| 83 |
+
band, os_on, os_limit, ts_on, ts_limit):
|
| 84 |
+
"""Validate, compute, and render every numerical output. Errors clear stale results."""
|
| 85 |
+
try:
|
| 86 |
+
record = C.compute(
|
| 87 |
+
MODES.get(mode_label, ""), wn=wn, zeta=zeta, amplitude=amplitude, gain=gain,
|
| 88 |
+
mass=mass, damping=damping, stiffness=stiffness, force=force, band_name=band,
|
| 89 |
+
os_limit=os_limit if os_on else None, ts_limit=ts_limit if ts_on else None,
|
| 90 |
+
)
|
| 91 |
+
except (C.InputError, TypeError, ValueError) as exc:
|
| 92 |
+
card = T.verdict_html("Check the inputs", escape(str(exc)), empty=True)
|
| 93 |
+
return (card, None, pd.DataFrame(columns=TABLE_COLUMNS), None, "", {},
|
| 94 |
+
"_Fix the inputs above to see results and an explanation._", "")
|
| 95 |
+
public = {k: v for k, v in record.items() if not k.startswith("_")} # hide plotting internals
|
| 96 |
+
table = pd.DataFrame(C.to_rows(record), columns=TABLE_COLUMNS)
|
| 97 |
+
return (summary_card(record), plot_response(record), table, record, C.to_text(record),
|
| 98 |
+
public, STALE_NOTE, "")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def run_explanation(record):
|
| 102 |
+
"""Ask the LLM for prose, then audit it against the record."""
|
| 103 |
+
if record is None:
|
| 104 |
+
return "_There are no valid results to explain yet._", ""
|
| 105 |
+
text, source = E.explain(record)
|
| 106 |
+
report = E.grounding_check(text, record)
|
| 107 |
+
if report["grounded"]:
|
| 108 |
+
status = T.badge(f"Grounded: all {report['numbers_found']} numbers match the record", "good")
|
| 109 |
+
else:
|
| 110 |
+
issues = [f"not in record: {', '.join(report['unsupported'])}"] if report["unsupported"] else []
|
| 111 |
+
issues += report["contradictions"]
|
| 112 |
+
status = T.badge("Check this explanation against the table", "bad") + \
|
| 113 |
+
f'<p class="expl-note">{escape("; ".join(issues))}</p>'
|
| 114 |
+
status += f'<p class="expl-note">Written by {escape(source)}. The table above is the source of truth.</p>'
|
| 115 |
+
return text, status
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def toggle_mode(mode_label):
|
| 119 |
+
"""Show only the input group that matches the chosen mode."""
|
| 120 |
+
physical = MODES.get(mode_label) == "mass-spring-damper"
|
| 121 |
+
return gr.update(visible=not physical), gr.update(visible=physical)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
EXTRA_CSS = f"""
|
| 125 |
+
#explain-panel {{ border-top: 1px solid {T.P['line']}; margin-top: 8px; padding-top: 8px; }}
|
| 126 |
+
#explain-text {{ font-size: 16px; line-height: 1.6; max-width: 75ch; }}
|
| 127 |
+
.expl-note {{ color: {T.P['muted']}; font-size: 13px; margin: 6px 0 0; }}
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
with gr.Blocks(title="Step response explainer") as demo:
|
| 131 |
+
gr.HTML(T.header_html(
|
| 132 |
+
"Step response explainer",
|
| 133 |
+
"Enter an underdamped second-order system, see its step response computed from first "
|
| 134 |
+
"principles, then get a plain-language explanation checked against the numbers."))
|
| 135 |
+
|
| 136 |
+
with gr.Row(equal_height=False):
|
| 137 |
+
with gr.Column(scale=5, min_width=300):
|
| 138 |
+
mode = gr.Radio(list(MODES), value="Normalised (ωn, ζ)", label="Describe the system by",
|
| 139 |
+
info="Physical values are converted to ωn = √(k/m) and ζ = c / (2√(km)).")
|
| 140 |
+
with gr.Column(visible=True) as norm_group:
|
| 141 |
+
wn = gr.Number(2.0, label="Natural frequency ωn (rad/s)", minimum=0.1, maximum=500,
|
| 142 |
+
info="Valid range 0.1 to 500 rad/s.")
|
| 143 |
+
zeta = gr.Slider(0.05, 0.95, value=0.5, step=0.01, label="Damping ratio ζ",
|
| 144 |
+
info="Underdamped only. Below 0.05 or at 1 and above is out of scope.")
|
| 145 |
+
with gr.Row():
|
| 146 |
+
amplitude = gr.Number(1.0, label="Step size A", info="Nonzero.")
|
| 147 |
+
gain = gr.Number(1.0, label="DC gain K", info="Final value is K·A.")
|
| 148 |
+
with gr.Column(visible=False) as phys_group:
|
| 149 |
+
with gr.Row():
|
| 150 |
+
mass = gr.Number(1.0, label="Mass m (kg)", minimum=0.01, maximum=10000,
|
| 151 |
+
info="0.01 to 10,000 kg.")
|
| 152 |
+
stiffness = gr.Number(100.0, label="Spring stiffness k (N/m)", minimum=1,
|
| 153 |
+
maximum=1e7, info="1 to 10⁷ N/m.")
|
| 154 |
+
with gr.Row():
|
| 155 |
+
damping = gr.Number(4.0, label="Damping c (N·s/m)", minimum=0,
|
| 156 |
+
info="Must give 0.05 ≤ ζ ≤ 0.95.")
|
| 157 |
+
force = gr.Number(10.0, label="Step force F (N)", info="Nonzero. Output shown in mm.")
|
| 158 |
+
band = gr.Radio(list(C.BANDS), value="2%", label="Settling band",
|
| 159 |
+
info="Settled means staying within this fraction of the final value.")
|
| 160 |
+
with gr.Accordion("Design limits (optional)", open=True):
|
| 161 |
+
with gr.Row():
|
| 162 |
+
os_on = gr.Checkbox(True, label="Check overshoot")
|
| 163 |
+
os_limit = gr.Number(10.0, label="Max overshoot (%)", minimum=0.1, maximum=99)
|
| 164 |
+
with gr.Row():
|
| 165 |
+
ts_on = gr.Checkbox(True, label="Check settling time")
|
| 166 |
+
ts_limit = gr.Number(3.0, label="Max settling time (s)", minimum=0.0001)
|
| 167 |
+
|
| 168 |
+
with gr.Column(scale=6, min_width=320):
|
| 169 |
+
card = gr.HTML()
|
| 170 |
+
plot = gr.Plot(label="Step response", show_label=False)
|
| 171 |
+
table = gr.Dataframe(headers=TABLE_COLUMNS, label="Numerical results",
|
| 172 |
+
interactive=False, wrap=True)
|
| 173 |
+
|
| 174 |
+
with gr.Column(elem_id="explain-panel"):
|
| 175 |
+
gr.HTML(T.section_html("Explain the results", "A small language model reads the structured "
|
| 176 |
+
"record and describes it in plain words. It does not do any math."))
|
| 177 |
+
explain_btn = gr.Button("Explain these results", variant="primary")
|
| 178 |
+
explanation = gr.Markdown(STALE_NOTE, elem_id="explain-text")
|
| 179 |
+
grounding = gr.HTML()
|
| 180 |
+
with gr.Accordion("What the language model receives", open=False):
|
| 181 |
+
llm_input = gr.Textbox(label="Structured record as text", lines=18, interactive=False)
|
| 182 |
+
with gr.Accordion("Full structured record (JSON)", open=False):
|
| 183 |
+
record_json = gr.JSON(label="Record")
|
| 184 |
+
|
| 185 |
+
record_state = gr.State(None)
|
| 186 |
+
inputs = [mode, wn, zeta, amplitude, gain, mass, damping, stiffness, force,
|
| 187 |
+
band, os_on, os_limit, ts_on, ts_limit]
|
| 188 |
+
mode.change(toggle_mode, mode, [norm_group, phys_group], api_name=False)
|
| 189 |
+
# With no explicit triggers, gr.on runs on load and whenever an input changes
|
| 190 |
+
gr.on(fn=run_calculation, inputs=inputs,
|
| 191 |
+
outputs=[card, plot, table, record_state, llm_input, record_json, explanation, grounding],
|
| 192 |
+
trigger_mode="always_last", concurrency_limit=4, api_name="calculate")
|
| 193 |
+
explain_btn.click(run_explanation, record_state, [explanation, grounding],
|
| 194 |
+
concurrency_limit=1, api_name="explain")
|
| 195 |
+
|
| 196 |
+
gr.Examples(
|
| 197 |
+
examples=[
|
| 198 |
+
["Normalised (ωn, ζ)", 2.0, 0.5, 1.0, 1.0, 1.0, 4.0, 100.0, 10.0, "2%", True, 10.0, True, 3.0],
|
| 199 |
+
["Normalised (ωn, ζ)", 5.0, 0.7, 1.0, 1.0, 1.0, 4.0, 100.0, 10.0, "5%", False, 10.0, False, 3.0],
|
| 200 |
+
["Mass-spring-damper (m, c, k)", 2.0, 0.5, 1.0, 1.0, 250.0, 1000.0, 16000.0, 2500.0, "2%", True, 25.0, True, 1.5],
|
| 201 |
+
["Mass-spring-damper (m, c, k)", 2.0, 0.5, 1.0, 1.0, 0.5, 4.0, 2000.0, 5.0, "2%", True, 20.0, True, 0.5],
|
| 202 |
+
["Mass-spring-damper (m, c, k)", 2.0, 0.5, 1.0, 1.0, 5.0, 60.0, 50.0, 20.0, "2%", False, 10.0, False, 3.0],
|
| 203 |
+
],
|
| 204 |
+
example_labels=[
|
| 205 |
+
"Textbook case, fails both limits",
|
| 206 |
+
"ζ = 0.7, settles before its peak",
|
| 207 |
+
"Quarter-car suspension, 2.5 kN load",
|
| 208 |
+
"Lightly damped sensor mount",
|
| 209 |
+
"Door closer, overdamped (out of scope)",
|
| 210 |
+
],
|
| 211 |
+
inputs=inputs, label="Try an example",
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
gr.HTML(T.footer_html([
|
| 215 |
+
"Assumes a linear second-order system with no zeros, an ideal step at t = 0, and zero initial "
|
| 216 |
+
"conditions. Overdamped and critically damped systems are outside this calculator's scope.",
|
| 217 |
+
f'Explanations by <a href="https://huggingface.co/{E.MODEL_ID}">{E.MODEL_ID}</a> at a pinned '
|
| 218 |
+
"revision, run on CPU. 24-679 Homework 3 by Jack Stevens.",
|
| 219 |
+
]))
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
demo.launch(theme=T.build_theme(), css=T.CSS + EXTRA_CSS, footer_links=[])
|
calculator.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic backend: underdamped second-order step response.
|
| 2 |
+
|
| 3 |
+
Model: y(s)/u(s) = K * wn^2 / (s^2 + 2*zeta*wn*s + wn^2), step of size A at t = 0,
|
| 4 |
+
zero initial conditions, 0 < zeta < 1. Normalised response:
|
| 5 |
+
c(t) = 1 - exp(-zeta*wn*t) / sqrt(1 - zeta^2) * sin(wd*t + theta)
|
| 6 |
+
with wd = wn*sqrt(1 - zeta^2) and theta = atan(sqrt(1 - zeta^2) / zeta) = acos(zeta).
|
| 7 |
+
Physical output is y(t) = y_final * c(t), where y_final = K*A (or F/k for a mass-spring-damper).
|
| 8 |
+
"""
|
| 9 |
+
import math
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
VERSION = "1.0"
|
| 14 |
+
|
| 15 |
+
# Valid input ranges, enforced before any calculation runs
|
| 16 |
+
RANGES = {
|
| 17 |
+
"zeta": (0.05, 0.95), # underdamped only, away from the singular ends
|
| 18 |
+
"wn": (0.1, 500.0), # rad/s
|
| 19 |
+
"mass": (0.01, 10_000.0), # kg
|
| 20 |
+
"stiffness": (1.0, 1e7), # N/m
|
| 21 |
+
"damping": (0.0, 1e6), # N*s/m, zeta range is checked after conversion
|
| 22 |
+
"force": (-1e6, 1e6), # N, nonzero
|
| 23 |
+
"amplitude": (-1e6, 1e6), # step size in input units, nonzero
|
| 24 |
+
"gain": (-1e6, 1e6), # DC gain K, nonzero
|
| 25 |
+
"os_limit": (0.1, 99.0), # percent
|
| 26 |
+
"ts_limit": (1e-4, 1e5), # s
|
| 27 |
+
}
|
| 28 |
+
BANDS = {"2%": 0.02, "5%": 0.05} # settling band as a fraction of the final value
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class InputError(ValueError):
|
| 32 |
+
"""Raised with a user-facing message when inputs are out of scope."""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _check(name, value, label, unit=""):
|
| 36 |
+
"""Validate one numeric input against RANGES and return it as float."""
|
| 37 |
+
if value is None:
|
| 38 |
+
raise InputError(f"Enter a value for {label}.")
|
| 39 |
+
value = float(value)
|
| 40 |
+
if not math.isfinite(value):
|
| 41 |
+
raise InputError(f"{label} must be a finite number.")
|
| 42 |
+
lo, hi = RANGES[name]
|
| 43 |
+
if not lo <= value <= hi:
|
| 44 |
+
raise InputError(f"{label} must be between {lo:g} and {hi:g} {unit}".strip() + ".")
|
| 45 |
+
return value
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def normalised_response(t, zeta, wn):
|
| 49 |
+
"""Closed-form unit step response c(t) of the standard second-order system."""
|
| 50 |
+
root = math.sqrt(1.0 - zeta**2)
|
| 51 |
+
wd = wn * root # damped natural frequency
|
| 52 |
+
theta = math.acos(zeta) # phase, equals atan(root / zeta)
|
| 53 |
+
return 1.0 - np.exp(-zeta * wn * t) / root * np.sin(wd * t + theta)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _bisect(f, a, b, iters=80):
|
| 57 |
+
"""Root of f on [a, b] assuming a sign change; plain bisection for determinism."""
|
| 58 |
+
fa = f(a)
|
| 59 |
+
for _ in range(iters):
|
| 60 |
+
m = 0.5 * (a + b)
|
| 61 |
+
fm = f(m)
|
| 62 |
+
if (fm > 0) == (fa > 0):
|
| 63 |
+
a, fa = m, fm # root lies in the right half
|
| 64 |
+
else:
|
| 65 |
+
b = m # root lies in the left half
|
| 66 |
+
return 0.5 * (a + b)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _first_crossing(level, zeta, wn, t_max, n=20_000):
|
| 70 |
+
"""First time c(t) reaches a level, refined by bisection."""
|
| 71 |
+
t = np.linspace(0.0, t_max, n)
|
| 72 |
+
c = normalised_response(t, zeta, wn)
|
| 73 |
+
idx = int(np.argmax(c >= level)) # first grid point at or above the level
|
| 74 |
+
f = lambda x: float(normalised_response(np.array(x), zeta, wn)) - level
|
| 75 |
+
return _bisect(f, t[max(idx - 1, 0)], t[idx])
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _settling_time(band, zeta, wn):
|
| 79 |
+
"""Last time |c(t) - 1| exceeds the band, searched up to the envelope bound."""
|
| 80 |
+
root = math.sqrt(1.0 - zeta**2)
|
| 81 |
+
sigma = zeta * wn
|
| 82 |
+
t_env = -math.log(band * root) / sigma # envelope is inside the band after this
|
| 83 |
+
t = np.linspace(0.0, t_env, 40_000)
|
| 84 |
+
err = np.abs(normalised_response(t, zeta, wn) - 1.0)
|
| 85 |
+
outside = np.nonzero(err > band)[0]
|
| 86 |
+
last = int(outside[-1]) # last grid sample still outside the band
|
| 87 |
+
f = lambda x: abs(float(normalised_response(np.array(x), zeta, wn)) - 1.0) - band
|
| 88 |
+
return _bisect(f, t[last], t[min(last + 1, len(t) - 1)]), t_env
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _q(label, value, unit, formula=""):
|
| 92 |
+
"""One labelled quantity in the structured record."""
|
| 93 |
+
return {"label": label, "value": float(value), "unit": unit, "formula": formula}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def compute(mode, wn=None, zeta=None, amplitude=1.0, gain=1.0,
|
| 97 |
+
mass=None, damping=None, stiffness=None, force=None,
|
| 98 |
+
band_name="2%", os_limit=None, ts_limit=None):
|
| 99 |
+
"""Validate inputs, compute every metric, and return a structured record.
|
| 100 |
+
|
| 101 |
+
mode is "normalised" (wn, zeta, amplitude, gain) or "mass-spring-damper"
|
| 102 |
+
(mass, damping, stiffness, force). Design limits are optional; None skips a check.
|
| 103 |
+
"""
|
| 104 |
+
if band_name not in BANDS:
|
| 105 |
+
raise InputError("Choose a settling band of 2% or 5%.")
|
| 106 |
+
band = BANDS[band_name]
|
| 107 |
+
inputs = {}
|
| 108 |
+
|
| 109 |
+
if mode == "normalised":
|
| 110 |
+
wn = _check("wn", wn, "Natural frequency ωn", "rad/s")
|
| 111 |
+
zeta = _check("zeta", zeta, "Damping ratio ζ")
|
| 112 |
+
amplitude = _check("amplitude", amplitude, "Step size A")
|
| 113 |
+
gain = _check("gain", gain, "DC gain K")
|
| 114 |
+
if amplitude == 0 or gain == 0:
|
| 115 |
+
raise InputError("Step size and DC gain must be nonzero, otherwise the output never moves.")
|
| 116 |
+
y_final, out_unit, out_name = gain * amplitude, "", "output" # dimensionless output
|
| 117 |
+
inputs["wn"] = _q("Natural frequency ωn", wn, "rad/s")
|
| 118 |
+
inputs["zeta"] = _q("Damping ratio ζ", zeta, "")
|
| 119 |
+
inputs["amplitude"] = _q("Step size A", amplitude, "")
|
| 120 |
+
inputs["gain"] = _q("DC gain K", gain, "")
|
| 121 |
+
elif mode == "mass-spring-damper":
|
| 122 |
+
mass = _check("mass", mass, "Mass m", "kg")
|
| 123 |
+
stiffness = _check("stiffness", stiffness, "Spring stiffness k", "N/m")
|
| 124 |
+
damping = _check("damping", damping, "Damping coefficient c", "N·s/m")
|
| 125 |
+
force = _check("force", force, "Step force F", "N")
|
| 126 |
+
if force == 0:
|
| 127 |
+
raise InputError("Step force must be nonzero, otherwise the mass never moves.")
|
| 128 |
+
wn = math.sqrt(stiffness / mass) # rad/s
|
| 129 |
+
zeta = damping / (2.0 * math.sqrt(stiffness * mass))
|
| 130 |
+
lo, hi = RANGES["zeta"]
|
| 131 |
+
if not lo <= zeta <= hi:
|
| 132 |
+
kind = "overdamped or critically damped" if zeta >= 1 else "outside the supported range"
|
| 133 |
+
raise InputError(
|
| 134 |
+
f"These values give ζ = {zeta:.3f}, which is {kind}. This calculator covers "
|
| 135 |
+
f"underdamped systems with {lo} ≤ ζ ≤ {hi}; adjust c, k, or m.")
|
| 136 |
+
if not RANGES["wn"][0] <= wn <= RANGES["wn"][1]:
|
| 137 |
+
raise InputError(f"These values give ωn = {wn:.3g} rad/s, outside 0.1 to 500 rad/s.")
|
| 138 |
+
y_final, out_unit, out_name = force / stiffness * 1000.0, "mm", "displacement"
|
| 139 |
+
inputs["mass"] = _q("Mass m", mass, "kg")
|
| 140 |
+
inputs["damping"] = _q("Damping coefficient c", damping, "N·s/m")
|
| 141 |
+
inputs["stiffness"] = _q("Spring stiffness k", stiffness, "N/m")
|
| 142 |
+
inputs["force"] = _q("Step force F", force, "N")
|
| 143 |
+
else:
|
| 144 |
+
raise InputError("Choose an input mode.")
|
| 145 |
+
|
| 146 |
+
if os_limit is not None:
|
| 147 |
+
os_limit = _check("os_limit", os_limit, "Overshoot limit", "%")
|
| 148 |
+
if ts_limit is not None:
|
| 149 |
+
ts_limit = _check("ts_limit", ts_limit, "Settling time limit", "s")
|
| 150 |
+
|
| 151 |
+
# Core closed-form quantities
|
| 152 |
+
root = math.sqrt(1.0 - zeta**2)
|
| 153 |
+
sigma = zeta * wn # decay rate of the envelope
|
| 154 |
+
wd = wn * root # damped natural frequency
|
| 155 |
+
theta = math.acos(zeta) # phase angle in the formula
|
| 156 |
+
t_peak = math.pi / wd # first peak
|
| 157 |
+
os_frac = math.exp(-zeta * math.pi / root) # fractional overshoot
|
| 158 |
+
t_rise_0_100 = (math.pi - theta) / wd # first time c(t) = 1
|
| 159 |
+
ts_textbook = (4.0 if band == 0.02 else 3.0) / sigma # classic 4/σ or 3/σ rule
|
| 160 |
+
|
| 161 |
+
# Numerical quantities, still deterministic
|
| 162 |
+
ts_exact, t_env = _settling_time(band, zeta, wn)
|
| 163 |
+
t10 = _first_crossing(0.1, zeta, wn, t_peak)
|
| 164 |
+
t90 = _first_crossing(0.9, zeta, wn, t_peak)
|
| 165 |
+
|
| 166 |
+
# Self-check: sampled peak should match the closed-form peak time and height
|
| 167 |
+
grid = np.linspace(0.0, 2.0 * t_peak, 200_001)
|
| 168 |
+
c = normalised_response(grid, zeta, wn)
|
| 169 |
+
i_max = int(np.argmax(c))
|
| 170 |
+
peak_time_err = abs(grid[i_max] - t_peak)
|
| 171 |
+
peak_height_err = abs(c[i_max] - (1.0 + os_frac))
|
| 172 |
+
|
| 173 |
+
derived = {}
|
| 174 |
+
if mode == "mass-spring-damper":
|
| 175 |
+
# Only physical inputs need wn and zeta derived; normalised inputs already list them
|
| 176 |
+
derived["wn"] = _q("Natural frequency ωn", wn, "rad/s", "√(k/m)")
|
| 177 |
+
derived["zeta"] = _q("Damping ratio ζ", zeta, "", "c / (2√(km))")
|
| 178 |
+
derived.update({
|
| 179 |
+
"wd": _q("Damped frequency ωd", wd, "rad/s", "ωn√(1−ζ²)"),
|
| 180 |
+
"sigma": _q("Envelope decay rate σ", sigma, "1/s", "ζωn"),
|
| 181 |
+
"theta": _q("Phase angle θ", math.degrees(theta), "deg", "atan(√(1−ζ²)/ζ)"),
|
| 182 |
+
"period": _q("Damped period Td", 2 * math.pi / wd, "s", "2π/ωd"),
|
| 183 |
+
})
|
| 184 |
+
metrics = {
|
| 185 |
+
"final": _q(f"Final {out_name}", y_final, out_unit, "K·A" if mode == "normalised" else "F/k"),
|
| 186 |
+
"overshoot": _q("Percent overshoot", 100 * os_frac, "%", "100·exp(−ζπ/√(1−ζ²))"),
|
| 187 |
+
"peak_value": _q(f"Peak {out_name}", y_final * (1 + os_frac), out_unit, "final·(1 + OS)"),
|
| 188 |
+
"peak_time": _q("Peak time Tp", t_peak, "s", "π/ωd"),
|
| 189 |
+
"rise_10_90": _q("Rise time, 10% to 90%", t90 - t10, "s", "numerical, bisection"),
|
| 190 |
+
"rise_0_100": _q("Rise time, 0% to 100%", t_rise_0_100, "s", "(π−θ)/ωd"),
|
| 191 |
+
"ts_exact": _q(f"Settling time, {band_name} band", ts_exact, "s", "numerical, last band exit"),
|
| 192 |
+
"ts_textbook": _q("Settling time, textbook estimate", ts_textbook, "s",
|
| 193 |
+
"4/(ζωn)" if band == 0.02 else "3/(ζωn)"),
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
checks = []
|
| 197 |
+
if os_limit is not None:
|
| 198 |
+
# Minimum damping ratio that meets the overshoot limit
|
| 199 |
+
ln_os = math.log(os_limit / 100.0)
|
| 200 |
+
zeta_req = -ln_os / math.sqrt(math.pi**2 + ln_os**2)
|
| 201 |
+
ok = 100 * os_frac <= os_limit
|
| 202 |
+
checks.append({
|
| 203 |
+
"name": "Overshoot", "value": 100 * os_frac, "limit": os_limit, "unit": "%",
|
| 204 |
+
"result": "PASS" if ok else "FAIL",
|
| 205 |
+
"requirement": _q("ζ needed for this overshoot limit", zeta_req, "", "−ln(OS)/√(π²+ln²OS)"),
|
| 206 |
+
})
|
| 207 |
+
if ts_limit is not None:
|
| 208 |
+
# Envelope-based ωn that settles within the limit at the current ζ
|
| 209 |
+
wn_req = -math.log(band * root) / (zeta * ts_limit)
|
| 210 |
+
ok = ts_exact <= ts_limit
|
| 211 |
+
checks.append({
|
| 212 |
+
"name": "Settling time", "value": ts_exact, "limit": ts_limit, "unit": "s",
|
| 213 |
+
"result": "PASS" if ok else "FAIL",
|
| 214 |
+
"requirement": _q("ωn needed for this settling limit (envelope bound)", wn_req, "rad/s",
|
| 215 |
+
"−ln(band·√(1−ζ²)) / (ζ·Ts,max)"),
|
| 216 |
+
})
|
| 217 |
+
|
| 218 |
+
warnings = []
|
| 219 |
+
if zeta < 0.2:
|
| 220 |
+
warnings.append("Very light damping: many oscillations before settling; small parameter errors change results noticeably.")
|
| 221 |
+
if zeta > 0.8:
|
| 222 |
+
warnings.append("Close to critical damping: overshoot is tiny and the textbook settling estimate is least accurate here.")
|
| 223 |
+
if abs(ts_exact - ts_textbook) / ts_exact > 0.25:
|
| 224 |
+
warnings.append("The textbook settling estimate differs from the exact value by more than 25%.")
|
| 225 |
+
|
| 226 |
+
return {
|
| 227 |
+
"calculator": "Underdamped second-order step response",
|
| 228 |
+
"version": VERSION,
|
| 229 |
+
"mode": mode,
|
| 230 |
+
"output_name": out_name,
|
| 231 |
+
"output_unit": out_unit,
|
| 232 |
+
"settling_band": band_name,
|
| 233 |
+
"inputs": inputs,
|
| 234 |
+
"derived": derived,
|
| 235 |
+
"metrics": metrics,
|
| 236 |
+
"checks": checks,
|
| 237 |
+
"poles": {"real": -sigma, "imag": wd, "unit": "rad/s"},
|
| 238 |
+
"assumptions": [
|
| 239 |
+
"Linear, time-invariant second-order system with no zeros.",
|
| 240 |
+
"Ideal step applied at t = 0 with zero initial position and velocity.",
|
| 241 |
+
"Underdamped only: 0.05 ≤ ζ ≤ 0.95.",
|
| 242 |
+
"Settling time is the last exit from the band around the final value.",
|
| 243 |
+
],
|
| 244 |
+
"warnings": warnings,
|
| 245 |
+
"self_check": {"peak_time_error_s": peak_time_err, "peak_height_error": peak_height_err},
|
| 246 |
+
"_curve": {"zeta": zeta, "wn": wn, "y_final": y_final, "band": band,
|
| 247 |
+
"t_end": max(1.3 * ts_exact, 3 * t_peak)},
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def fmt(value, sig=4):
|
| 252 |
+
"""Readable number: sig figs, no scientific notation for everyday sizes."""
|
| 253 |
+
if value == 0:
|
| 254 |
+
return "0"
|
| 255 |
+
mag = math.floor(math.log10(abs(value)))
|
| 256 |
+
if -4 <= mag < 6:
|
| 257 |
+
decimals = max(sig - 1 - mag, 0)
|
| 258 |
+
text = f"{value:.{decimals}f}"
|
| 259 |
+
return text.rstrip("0").rstrip(".") if "." in text else text
|
| 260 |
+
return f"{value:.{sig - 1}e}"
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def to_text(record):
|
| 264 |
+
"""Human-readable version of the record, the exact text the LLM receives."""
|
| 265 |
+
lines = [f"{record['calculator']} (v{record['version']}, {record['mode']} inputs)", "", "Inputs:"]
|
| 266 |
+
for q in record["inputs"].values():
|
| 267 |
+
lines.append(f" {q['label']}: {fmt(q['value'])} {q['unit']}".rstrip())
|
| 268 |
+
lines.append("Derived parameters:")
|
| 269 |
+
for q in record["derived"].values():
|
| 270 |
+
lines.append(f" {q['label']}: {fmt(q['value'])} {q['unit']}".rstrip())
|
| 271 |
+
p = record["poles"]
|
| 272 |
+
lines.append(f" Poles: {fmt(p['real'])} ± j{fmt(p['imag'])} rad/s")
|
| 273 |
+
lines.append("Step response metrics:")
|
| 274 |
+
for q in record["metrics"].values():
|
| 275 |
+
lines.append(f" {q['label']}: {fmt(q['value'])} {q['unit']}".rstrip())
|
| 276 |
+
if record["checks"]:
|
| 277 |
+
lines.append("Design checks:")
|
| 278 |
+
for ch in record["checks"]:
|
| 279 |
+
req = ch["requirement"]
|
| 280 |
+
lines.append(f" {ch['name']}: {fmt(ch['value'])} {ch['unit']} vs limit {fmt(ch['limit'])} "
|
| 281 |
+
f"{ch['unit']} -> {ch['result']}; {req['label']}: {fmt(req['value'])} {req['unit']}".rstrip())
|
| 282 |
+
else:
|
| 283 |
+
lines.append("Design checks: none requested")
|
| 284 |
+
if record["warnings"]:
|
| 285 |
+
lines.append("Warnings:")
|
| 286 |
+
lines += [f" {w}" for w in record["warnings"]]
|
| 287 |
+
return "\n".join(lines)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def to_rows(record):
|
| 291 |
+
"""Table rows (quantity, value, unit, formula) for the numerical results panel."""
|
| 292 |
+
rows = []
|
| 293 |
+
for group in ("metrics", "derived"):
|
| 294 |
+
for q in record[group].values():
|
| 295 |
+
rows.append([q["label"], fmt(q["value"]), q["unit"], q["formula"]])
|
| 296 |
+
p = record["poles"]
|
| 297 |
+
rows.append(["Poles", f"{fmt(p['real'])} ± j{fmt(p['imag'])}", "rad/s", "−ζωn ± jωd"])
|
| 298 |
+
return rows
|
explainer.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM explanation layer: turns the calculator's structured record into plain prose.
|
| 2 |
+
|
| 3 |
+
The LLM never computes anything. It receives the record text, is told to reuse only
|
| 4 |
+
those numbers, and its answer is then audited by a deterministic grounding check.
|
| 5 |
+
"""
|
| 6 |
+
import re
|
| 7 |
+
|
| 8 |
+
import calculator as C
|
| 9 |
+
|
| 10 |
+
MODEL_ID = "Qwen/Qwen3-0.6B"
|
| 11 |
+
MODEL_REVISION = "c1899de289a04d12100db370d81485cdf75e47ca" # pinned, same as class notebook 05
|
| 12 |
+
MAX_NEW_TOKENS = 200
|
| 13 |
+
|
| 14 |
+
SYSTEM_PROMPT = (
|
| 15 |
+
"You explain the result of an engineering calculation to someone who is not a control "
|
| 16 |
+
"engineer. Use only numbers that appear in the record, written exactly as they appear there. "
|
| 17 |
+
"Never calculate new numbers. In 4 or 5 plain sentences, describe what the system does after "
|
| 18 |
+
"the step (rise, overshoot, oscillation, settling), say what the overshoot and settling time "
|
| 19 |
+
"mean for this output, and state the result of every design check. For a failed check, give "
|
| 20 |
+
"the requirement the record lists for passing it. If no design checks were requested, say so. "
|
| 21 |
+
"No lists, headings, or formulas."
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
# Worked examples come from real calculator runs so their numbers are exact
|
| 25 |
+
_EX_A = C.compute("mass-spring-damper", mass=2, damping=8, stiffness=200, force=20,
|
| 26 |
+
band_name="2%", os_limit=20, ts_limit=3)
|
| 27 |
+
_EX_A_ANSWER = (
|
| 28 |
+
"After the 20 N step, the mass heads toward its final displacement of 100 mm, but with a "
|
| 29 |
+
"damping ratio of only 0.2 it overshoots to a peak of 152.7 mm at 0.3206 s, a 52.66 % overshoot. "
|
| 30 |
+
"It then oscillates with a period of 0.6413 s as the swings die away, and it stays within 2% of "
|
| 31 |
+
"the final position after 1.96 s. The overshoot check fails because 52.66 % is above the 20 % "
|
| 32 |
+
"limit; the damping ratio would need to be at least 0.4559 to pass. The settling check passes, "
|
| 33 |
+
"since 1.96 s is under the 3 s limit."
|
| 34 |
+
)
|
| 35 |
+
_EX_B = C.compute("normalised", wn=5, zeta=0.7, amplitude=1, gain=1, band_name="5%")
|
| 36 |
+
_EX_B_ANSWER = (
|
| 37 |
+
"After the step, the output rises toward its final value of 1 and overshoots only slightly, "
|
| 38 |
+
"peaking at 1.046 at 0.8798 s, a 4.599 % overshoot. Because that overshoot is smaller than the "
|
| 39 |
+
"5% band, the output enters the band at 0.58 s and never leaves it, so it counts as settled "
|
| 40 |
+
"before it even reaches its peak. That is why the textbook estimate of 0.8571 s is noticeably "
|
| 41 |
+
"longer than the exact settling time. No design checks were requested."
|
| 42 |
+
)
|
| 43 |
+
FEW_SHOT = [
|
| 44 |
+
{"role": "user", "content": C.to_text(_EX_A)},
|
| 45 |
+
{"role": "assistant", "content": _EX_A_ANSWER},
|
| 46 |
+
{"role": "user", "content": C.to_text(_EX_B)},
|
| 47 |
+
{"role": "assistant", "content": _EX_B_ANSWER},
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
_tokenizer = None
|
| 51 |
+
_model = None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def load_model():
|
| 55 |
+
"""Load Qwen3-0.6B once on CPU; later calls reuse the cached objects."""
|
| 56 |
+
global _tokenizer, _model
|
| 57 |
+
if _model is None:
|
| 58 |
+
import torch
|
| 59 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 60 |
+
_tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, revision=MODEL_REVISION)
|
| 61 |
+
_model = AutoModelForCausalLM.from_pretrained(
|
| 62 |
+
MODEL_ID, revision=MODEL_REVISION, dtype=torch.float32
|
| 63 |
+
).eval() # float32 on CPU avoids half-precision kernels a free Space lacks
|
| 64 |
+
return _tokenizer, _model
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def build_messages(record):
|
| 68 |
+
"""System rules, two worked examples, then the current record text."""
|
| 69 |
+
return [{"role": "system", "content": SYSTEM_PROMPT}, *FEW_SHOT,
|
| 70 |
+
{"role": "user", "content": C.to_text(record)}]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def generate(messages, max_tokens=MAX_NEW_TOKENS):
|
| 74 |
+
"""Greedy decoding so the same record always yields the same explanation."""
|
| 75 |
+
import torch
|
| 76 |
+
from transformers import GenerationConfig
|
| 77 |
+
tokenizer, model = load_model()
|
| 78 |
+
inputs = tokenizer.apply_chat_template(
|
| 79 |
+
messages, tokenize=True, add_generation_prompt=True,
|
| 80 |
+
enable_thinking=False, return_dict=True, return_tensors="pt",
|
| 81 |
+
)
|
| 82 |
+
config = GenerationConfig(
|
| 83 |
+
max_new_tokens=max_tokens, do_sample=False,
|
| 84 |
+
eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.eos_token_id,
|
| 85 |
+
)
|
| 86 |
+
model.generation_config = config # stop repo sampling defaults overriding greedy
|
| 87 |
+
with torch.inference_mode():
|
| 88 |
+
output = model.generate(**inputs, generation_config=config)
|
| 89 |
+
new_tokens = output[0, inputs["input_ids"].shape[-1]:] # drop the prompt tokens
|
| 90 |
+
text = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
|
| 91 |
+
if new_tokens[-1].item() != tokenizer.eos_token_id:
|
| 92 |
+
text += " [Explanation hit its length limit and may be incomplete.]"
|
| 93 |
+
return text
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def template_explanation(record):
|
| 97 |
+
"""Deterministic fallback used only if the language model cannot run."""
|
| 98 |
+
m = record["metrics"]
|
| 99 |
+
unit = f" {record['output_unit']}" if record["output_unit"] else ""
|
| 100 |
+
parts = [
|
| 101 |
+
f"The {record['output_name']} rises toward its final value of {C.fmt(m['final']['value'])}{unit}, "
|
| 102 |
+
f"peaks at {C.fmt(m['peak_value']['value'])}{unit} after {C.fmt(m['peak_time']['value'])} s "
|
| 103 |
+
f"({C.fmt(m['overshoot']['value'])} % overshoot), and stays inside the "
|
| 104 |
+
f"{record['settling_band']} band after {C.fmt(m['ts_exact']['value'])} s."
|
| 105 |
+
]
|
| 106 |
+
for ch in record["checks"]:
|
| 107 |
+
req = ch["requirement"]
|
| 108 |
+
verdict = "passes" if ch["result"] == "PASS" else "fails"
|
| 109 |
+
parts.append(f"The {ch['name'].lower()} check {verdict} ({C.fmt(ch['value'])} {ch['unit']} "
|
| 110 |
+
f"against a limit of {C.fmt(ch['limit'])} {ch['unit']}).")
|
| 111 |
+
if ch["result"] == "FAIL":
|
| 112 |
+
parts.append(f"To pass, the {req['label'].lower()} is {C.fmt(req['value'])} {req['unit']}.".replace(" .", "."))
|
| 113 |
+
if not record["checks"]:
|
| 114 |
+
parts.append("No design checks were requested.")
|
| 115 |
+
return " ".join(parts)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def explain(record):
|
| 119 |
+
"""Return (explanation, source) where source says which path produced it."""
|
| 120 |
+
try:
|
| 121 |
+
return generate(build_messages(record)), f"{MODEL_ID} (greedy, few-shot)"
|
| 122 |
+
except Exception as exc: # model download or runtime failure should not break the app
|
| 123 |
+
return template_explanation(record), f"template fallback ({type(exc).__name__})"
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
_NUM = re.compile(r"\d+(?:\.\d+)?")
|
| 127 |
+
# Numbers that describe the method rather than this result (2% band, 10% to 90%, ...)
|
| 128 |
+
_METHOD_NUMBERS = {0.0, 1.0, 2.0, 5.0, 10.0, 90.0, 100.0}
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _record_numbers(record):
|
| 132 |
+
"""Every number printed in the record text, the only numbers the LLM may use."""
|
| 133 |
+
return {float(x) for x in _NUM.findall(C.to_text(record))} | _METHOD_NUMBERS
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _supported(token, allowed):
|
| 137 |
+
"""A number is supported if it equals a record number rounded to its own precision."""
|
| 138 |
+
value = float(token)
|
| 139 |
+
decimals = len(token.split(".")[1]) if "." in token else 0
|
| 140 |
+
tol = 0.5 * 10 ** (-decimals) + 1e-9 # half a unit in the last written digit
|
| 141 |
+
return any(abs(value - a) <= tol for a in allowed)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def grounding_check(text, record):
|
| 145 |
+
"""Audit the explanation: unsupported numbers and pass/fail contradictions."""
|
| 146 |
+
allowed = _record_numbers(record)
|
| 147 |
+
tokens = _NUM.findall(text)
|
| 148 |
+
unsupported = sorted({t for t in tokens if not _supported(t, allowed)}, key=float)
|
| 149 |
+
|
| 150 |
+
contradictions = []
|
| 151 |
+
sentences = re.split(r"(?<=[.!?])\s+", text.lower())
|
| 152 |
+
keywords = {"Overshoot": "overshoot", "Settling time": "settl"}
|
| 153 |
+
for ch in record["checks"]:
|
| 154 |
+
key = keywords[ch["name"]]
|
| 155 |
+
for s in sentences:
|
| 156 |
+
if key not in s or "check" not in s:
|
| 157 |
+
continue # only judge sentences that talk about this check
|
| 158 |
+
says_pass = "pass" in s and "fail" not in s
|
| 159 |
+
says_fail = "fail" in s and "pass" not in s
|
| 160 |
+
if (ch["result"] == "PASS" and says_fail) or (ch["result"] == "FAIL" and says_pass):
|
| 161 |
+
contradictions.append(f"{ch['name']} is {ch['result']} in the record, the text disagrees")
|
| 162 |
+
|
| 163 |
+
return {
|
| 164 |
+
"numbers_found": len(tokens),
|
| 165 |
+
"unsupported": unsupported,
|
| 166 |
+
"contradictions": contradictions,
|
| 167 |
+
"grounded": not unsupported and not contradictions,
|
| 168 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
torch==2.10.0
|
| 3 |
+
transformers==5.14.1
|
| 4 |
+
numpy
|
| 5 |
+
pandas
|
| 6 |
+
matplotlib
|
theme.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared visual language for the three 24-679 HW3 apps.
|
| 2 |
+
|
| 3 |
+
Warm light palette: apricot page, aubergine ink, hibiscus actions, marigold data.
|
| 4 |
+
The same file ships with every Space so the three apps read as one set.
|
| 5 |
+
"""
|
| 6 |
+
from html import escape
|
| 7 |
+
|
| 8 |
+
import gradio as gr
|
| 9 |
+
|
| 10 |
+
# Named palette tokens reused by the theme, CSS, and HTML renderers
|
| 11 |
+
P = {
|
| 12 |
+
"page": "#FBEEE2", # apricot tinted page, warm but not cream
|
| 13 |
+
"surface": "#FFF9F4", # panels sit a step lighter than the page
|
| 14 |
+
"line": "#EFD9C8", # hairlines, input borders, bar tracks
|
| 15 |
+
"track": "#F6E4D6", # empty part of score bars
|
| 16 |
+
"ink": "#3A2530", # warm aubergine body text
|
| 17 |
+
"muted": "#7A6170", # secondary text and captions
|
| 18 |
+
"accent": "#B83E62", # hibiscus, buttons and keyboard focus
|
| 19 |
+
"accent_soft": "#F7D9DF", # selected chips and soft highlights
|
| 20 |
+
"data": "#E9A03F", # marigold, bars and plotted curves
|
| 21 |
+
"good": "#4F7F55", # passing checks
|
| 22 |
+
"bad": "#A5352B", # failing checks
|
| 23 |
+
"warn": "#8A5A12", # cautions that are not failures
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
HEAD_FONT = "'Bricolage Grotesque', 'Figtree', system-ui, sans-serif"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _same_in_dark(**tokens):
|
| 30 |
+
"""Duplicate each token into its _dark twin so the palette never flips."""
|
| 31 |
+
out = {}
|
| 32 |
+
for key, value in tokens.items():
|
| 33 |
+
out[key] = value
|
| 34 |
+
out[f"{key}_dark"] = value # lock light mode even if browser asks for dark
|
| 35 |
+
return out
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def build_theme():
|
| 39 |
+
"""Gradio theme holding shared control defaults for all three apps."""
|
| 40 |
+
base = gr.themes.Base(
|
| 41 |
+
primary_hue="rose",
|
| 42 |
+
neutral_hue="stone",
|
| 43 |
+
font=[gr.themes.GoogleFont("Figtree"), "system-ui", "sans-serif"],
|
| 44 |
+
font_mono=["ui-monospace", "monospace"],
|
| 45 |
+
)
|
| 46 |
+
paired = _same_in_dark(
|
| 47 |
+
body_background_fill=P["page"],
|
| 48 |
+
body_text_color=P["ink"],
|
| 49 |
+
body_text_color_subdued=P["muted"],
|
| 50 |
+
background_fill_primary=P["surface"],
|
| 51 |
+
background_fill_secondary=P["page"],
|
| 52 |
+
border_color_primary=P["line"],
|
| 53 |
+
color_accent_soft=P["accent_soft"],
|
| 54 |
+
block_background_fill=P["surface"],
|
| 55 |
+
block_border_color=P["line"],
|
| 56 |
+
block_label_text_color=P["muted"],
|
| 57 |
+
block_label_background_fill=P["surface"],
|
| 58 |
+
block_title_text_color=P["ink"],
|
| 59 |
+
block_shadow="none",
|
| 60 |
+
input_background_fill="#FFFFFF",
|
| 61 |
+
input_border_color=P["line"],
|
| 62 |
+
input_border_color_focus=P["accent"],
|
| 63 |
+
input_shadow="none",
|
| 64 |
+
button_primary_background_fill=P["accent"],
|
| 65 |
+
button_primary_background_fill_hover="#A03455",
|
| 66 |
+
button_primary_text_color="#FFFFFF",
|
| 67 |
+
button_primary_border_color=P["accent"],
|
| 68 |
+
button_secondary_background_fill=P["surface"],
|
| 69 |
+
button_secondary_background_fill_hover=P["accent_soft"],
|
| 70 |
+
button_secondary_text_color=P["ink"],
|
| 71 |
+
button_secondary_border_color=P["line"],
|
| 72 |
+
slider_color=P["accent"],
|
| 73 |
+
checkbox_background_color_selected=P["accent"],
|
| 74 |
+
checkbox_border_color_selected=P["accent"],
|
| 75 |
+
checkbox_label_background_fill=P["surface"],
|
| 76 |
+
checkbox_label_background_fill_hover=P["accent_soft"],
|
| 77 |
+
checkbox_label_background_fill_selected=P["accent_soft"],
|
| 78 |
+
checkbox_label_text_color=P["ink"],
|
| 79 |
+
checkbox_label_text_color_selected=P["ink"],
|
| 80 |
+
link_text_color=P["accent"],
|
| 81 |
+
link_text_color_hover="#A03455",
|
| 82 |
+
table_even_background_fill=P["surface"],
|
| 83 |
+
table_odd_background_fill="#FFFFFF",
|
| 84 |
+
table_border_color=P["line"],
|
| 85 |
+
error_background_fill="#F6DEDA",
|
| 86 |
+
error_border_color=P["bad"],
|
| 87 |
+
error_text_color=P["bad"],
|
| 88 |
+
loader_color=P["accent"],
|
| 89 |
+
)
|
| 90 |
+
# Tokens without a _dark twin are set once
|
| 91 |
+
return base.set(color_accent=P["accent"], block_radius="14px", input_radius="10px",
|
| 92 |
+
block_border_width="1px", **paired)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
CSS = f"""
|
| 96 |
+
@import url('https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,650&family=Figtree:wght@400;500;600&display=swap');
|
| 97 |
+
|
| 98 |
+
/* Page frame: one centred column that stops growing at 1120px */
|
| 99 |
+
.gradio-container {{ max-width: 1120px !important; margin: auto !important; }}
|
| 100 |
+
.hw3-head, .hw3-foot {{ padding: 0; border: 0; }}
|
| 101 |
+
|
| 102 |
+
/* Header: the title carries the personality, the lede stays quiet */
|
| 103 |
+
.hw3-head h1 {{
|
| 104 |
+
font-family: {HEAD_FONT}; font-weight: 650; color: {P['ink']};
|
| 105 |
+
font-size: clamp(34px, 5vw, 52px); line-height: 1.02; letter-spacing: -0.02em;
|
| 106 |
+
margin: 12px 0 8px;
|
| 107 |
+
}}
|
| 108 |
+
.hw3-head h2 {{
|
| 109 |
+
font-family: {HEAD_FONT}; font-weight: 650; color: {P['ink']};
|
| 110 |
+
font-size: 28px; line-height: 1.1; letter-spacing: -0.01em; margin: 18px 0 6px;
|
| 111 |
+
}}
|
| 112 |
+
.hw3-head p {{ max-width: 64ch; color: {P['muted']}; font-size: 16px; line-height: 1.55; margin: 0 0 8px; }}
|
| 113 |
+
|
| 114 |
+
/* Result card: verdict line set large, evidence underneath */
|
| 115 |
+
.verdict {{
|
| 116 |
+
background: {P['surface']}; border: 1px solid {P['line']}; border-radius: 14px;
|
| 117 |
+
padding: 22px 24px; color: {P['ink']}; font-variant-numeric: tabular-nums;
|
| 118 |
+
}}
|
| 119 |
+
.verdict .v-title {{
|
| 120 |
+
font-family: {HEAD_FONT}; font-weight: 650; font-size: clamp(30px, 4vw, 44px);
|
| 121 |
+
line-height: 1.05; letter-spacing: -0.015em; margin: 0;
|
| 122 |
+
}}
|
| 123 |
+
.verdict.empty .v-title {{ color: {P['muted']}; font-size: 26px; }}
|
| 124 |
+
.verdict .v-sub {{ color: {P['muted']}; font-size: 15px; margin: 8px 0 18px; line-height: 1.5; }}
|
| 125 |
+
.verdict .v-foot {{
|
| 126 |
+
color: {P['muted']}; font-size: 13px; line-height: 1.55;
|
| 127 |
+
border-top: 1px solid {P['line']}; padding-top: 12px; margin-top: 18px;
|
| 128 |
+
}}
|
| 129 |
+
|
| 130 |
+
/* Score bars: width comes from the model output, CSS only styles it */
|
| 131 |
+
.bar-row {{ margin: 0 0 14px; }}
|
| 132 |
+
.bar-row .bar-lab {{ display: flex; justify-content: space-between; font-size: 14px; margin-bottom: 6px; }}
|
| 133 |
+
.bar-row .track {{ height: 10px; background: {P['track']}; border-radius: 999px; overflow: hidden; }}
|
| 134 |
+
.bar-row .fill {{ height: 100%; background: {P['data']}; border-radius: 999px; }}
|
| 135 |
+
.bar-row .fill.lead {{ background: {P['accent']}; }}
|
| 136 |
+
|
| 137 |
+
/* Status badges pair colour with text so meaning never relies on colour */
|
| 138 |
+
.badge {{ display: inline-block; padding: 2px 10px; border-radius: 999px; font-size: 13px; font-weight: 600; }}
|
| 139 |
+
.badge.good {{ background: #E3EFE1; color: {P['good']}; }}
|
| 140 |
+
.badge.bad {{ background: #F6DEDA; color: {P['bad']}; }}
|
| 141 |
+
.badge.warn {{ background: #FBEBCB; color: {P['warn']}; }}
|
| 142 |
+
|
| 143 |
+
/* Keep keyboard focus obvious everywhere */
|
| 144 |
+
.gradio-container *:focus-visible {{ outline: 3px solid {P['accent']} !important; outline-offset: 2px; }}
|
| 145 |
+
|
| 146 |
+
.hw3-foot p {{ color: {P['muted']}; font-size: 13px; line-height: 1.55; margin: 6px 0; }}
|
| 147 |
+
|
| 148 |
+
@media (max-width: 640px) {{
|
| 149 |
+
.verdict {{ padding: 18px; }}
|
| 150 |
+
.hw3-head p {{ font-size: 15px; }}
|
| 151 |
+
}}
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def header_html(title, lede):
|
| 156 |
+
"""Page header: one strong title and a single sentence of purpose."""
|
| 157 |
+
return f'<header class="hw3-head"><h1>{escape(title)}</h1><p>{escape(lede)}</p></header>'
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def section_html(title, lede):
|
| 161 |
+
"""Secondary heading for a major panel within the page."""
|
| 162 |
+
return f'<header class="hw3-head"><h2>{escape(title)}</h2><p>{escape(lede)}</p></header>'
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def bars_html(scores, lead=None):
|
| 166 |
+
"""Horizontal score bars; the leading class gets the accent colour."""
|
| 167 |
+
rows = []
|
| 168 |
+
for label, value in scores.items():
|
| 169 |
+
cls = "fill lead" if label == lead else "fill" # highlight the predicted class
|
| 170 |
+
rows.append(
|
| 171 |
+
f'<div class="bar-row"><div class="bar-lab"><span>{escape(str(label))}</span>'
|
| 172 |
+
f'<strong>{value:.1%}</strong></div><div class="track" aria-hidden="true">'
|
| 173 |
+
f'<div class="{cls}" style="width:{100 * value:.2f}%"></div></div></div>'
|
| 174 |
+
)
|
| 175 |
+
return "".join(rows)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def verdict_html(title, sub="", body="", foot="", empty=False):
|
| 179 |
+
"""Result card shell shared by the tabular and image apps."""
|
| 180 |
+
cls = "verdict empty" if empty else "verdict"
|
| 181 |
+
sub_html = f'<p class="v-sub">{sub}</p>' if sub else ""
|
| 182 |
+
foot_html = f'<p class="v-foot">{foot}</p>' if foot else ""
|
| 183 |
+
return (f'<section class="{cls}" aria-live="polite"><p class="v-title">{escape(title)}</p>'
|
| 184 |
+
f"{sub_html}{body}{foot_html}</section>")
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def badge(text, tone):
|
| 188 |
+
"""Small pill; tone is good, bad, or warn."""
|
| 189 |
+
return f'<span class="badge {tone}">{escape(text)}</span>'
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def footer_html(lines):
|
| 193 |
+
"""Quiet footer paragraphs for credits and links (callers escape their own HTML)."""
|
| 194 |
+
return '<footer class="hw3-foot">' + "".join(f"<p>{line}</p>" for line in lines) + "</footer>"
|