"""CellTriage — QC operator console. An inference-only interface over the artifacts built by ``src.pipelines.build_app_artifacts``. It loads fitted models from ``outputs/models/`` and a small demo subset; **no raw cycling data is shipped**. DESIGN PRIORITIES, in order: 1. **The budget advisor**, because Phase 8's flat cost frontier and 99.17% chamber-time release is the most actionable result in the project, and a slider the user moves themselves is more convincing than a sentence. 2. **The campaign-shift alarm as a STATE CHANGE**, not a disclaimer. Phase 10 found the model becomes *confidently wrong* under campaign shift — accuracy halves while intervals narrow — so a grey footnote is not an adequate response to that failure mode. Unfamiliar data changes what the result panel looks like. 3. **Decisions rendered visually.** Whether the confidence interval crosses a grade boundary is a spatial question; asking a reader to infer it from two numbers wastes the result. 4. **Limitations one click away**, never buried. Run locally: ``python -m app.app`` """ from __future__ import annotations import json import os import sys from pathlib import Path from typing import Any # HuggingFace Spaces launches `app_file` AS A SCRIPT -- `python app/app.py` -- # which puts app/ on sys.path instead of the repository root. `import app` then # resolves to this very file and `from app import panels` fails with a circular # import, while `python -m app.app` works fine. Local module-mode runs therefore # cannot detect the one failure mode that matters for deployment, so the repo # root is put first on the path before any first-party import. if __package__ in (None, ""): # pragma: no cover - only on script launch sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import gradio as gr import numpy as np import pandas as pd from scipy import stats from app import panels, theme # --------------------------------------------------------------------------- # ZeroGPU: why NOTHING here is decorated with @spaces.GPU # # This Space runs on ZeroGPU because it is the free tier available for new # Spaces, not because the workload needs a GPU. Every model is a CPU-bound # scikit-learn pipeline -- no neural networks anywhere in the project, by hard # constraint -- and a single prediction takes ~45 ms on CPU. # # AN EARLIER VERSION DECORATED THE INFERENCE PATH WITH @spaces.GPU AND THAT WAS # A REAL BUG, caught only on the deployed Space. `@spaces.GPU` REQUESTS a GPU # slot per call and bills the declared duration against a daily quota that is # 5 minutes on a free account. The campaign-shift check alone calls predict() # once per cell to build the reference distribution -- 22 calls -- so at the # declared 15 s per call a SINGLE page load reserved 330 s and exhausted the # entire day's quota. The deployed console failed with "You have exceeded your # ZeroGPU runs limit" while every local test passed, because locally the # decorator is documented as effect-free. # # SO THE INFERENCE PATH IS NOT DECORATED. What the platform still needs is a # GPU entry point to exist at all: with no `@spaces.GPU` anywhere the Space sat # at `hardware: None` against `requested_hardware: zero-a10g`, bound its port, # and served 503 on every request -- the ZeroGPU container was never # provisioned. HuggingFace's own instructions list importing `spaces` and # decorating a GPU function as the steps that make a ZeroGPU Space work. # # The resolution is to declare ONE minimal GPU entry point that the console # never calls on any user path. It satisfies provisioning; it consumes no quota # because it is never invoked. This is a platform accommodation, stated plainly # rather than dressed up as a computational need: nothing in this project uses # a GPU, and no model was changed to pretend otherwise. try: # pragma: no cover - the Hub runtime always provides this import spaces except ImportError: # local development, CI, the test suite spaces = None if spaces is not None: # pragma: no cover - only meaningful on ZeroGPU @spaces.GPU(duration=1) def _zerogpu_provisioning_probe() -> str: """Declared so ZeroGPU provisions the Space. Never called by the UI. Every user-facing path -- prediction, grading, the shift check -- deliberately avoids this function. See the note above on why decorating the real inference path exhausted a 5-minute daily quota in one page load. """ return "cpu-bound console; no GPU work is performed" ROOT = Path(__file__).resolve().parent.parent ASSETS = ROOT / "app" / "assets" MODELS = ROOT / "outputs" / "models" FIGURES = ROOT / "outputs" / "figures" #: A KS statistic above this against the qualification cohort puts the console #: into its alarm state. Phase 10 measured D = 0.651 for the shifted campaign #: and D near zero in-distribution. This threshold is DIRECTIONAL, not #: calibrated: one shifted campaign can demonstrate the association but cannot #: establish a decision threshold, and the interface says so when it fires. KS_ALARM_THRESHOLD = 0.30 ALPHA = 0.10 #: Labels for the incoming-lot selector. The shifted option is real batch-3 #: data, not a perturbation -- the alarm has to be demonstrable on the campaign #: that actually broke the guarantee, or the console is asserting a safety #: property it never exercises. QUALIFICATION_LOT = "Qualification campaigns (batches 1–2)" SHIFTED_LOT = "New production campaign (batch 3)" #: The one capacity at which the allocation policies were actually compared #: (held_fraction = 0.2017 ± 0.0034 over 50 folds, allocation_summary.csv). EVALUATED_HELD_PERCENT = 20.2 # --------------------------------------------------------------------------- # Bundle loading (cold start) # --------------------------------------------------------------------------- class Bundle: """Everything the console needs, loaded once at import.""" def __init__(self) -> None: self.manifest = json.loads((ASSETS / "manifest.json").read_text(encoding="utf-8")) self.results = json.loads((ASSETS / "results.json").read_text(encoding="utf-8")) self.demo = pd.read_parquet(ASSETS / "demo_cells.parquet") self.budgets = [int(b) for b in self.manifest["budgets"]] self.grades = self.manifest["grades"] self.warranty = int(self.manifest["warranty_target_cycles"]) self.cost_matrix = self.manifest["cost_matrix"] self.grade_order = list(self.grades) self.boundaries = {g: float(self.grades[g]["min_cycles"]) for g in self.grade_order} # Models are loaded LAZILY and cached. ZeroGPU Spaces spin down # aggressively, so cold start matters: the constructor touches only the # small metadata bundle (~0.2 MB) and the first prediction for a budget # pays for that one model. Loading all five eagerly would add ~6 MB of # joblib deserialisation to every cold start for models a given session # may never use. self._models: dict[int, Any] = {} self.features: dict[int, list[str]] = {} self.half_widths: dict[int, float] = {} for budget in self.budgets: entry = self.manifest["models"].get(str(budget)) if entry and (MODELS / f"triage_extra_trees__budget{budget:03d}.joblib").exists(): self.features[budget] = entry["feature_names"] self.half_widths[budget] = float(entry["conformal_half_width_90"]) # Campaign membership drives the shift check. Batches 1-2 are the # qualification cohort the model and its conformal quantiles were # calibrated on; batch 3 is the genuinely shifted production campaign # (Phase 3: KS D = 0.651, p = 1.7e-11). at_reference = self.demo[self.demo["budget"] == max(self.budgets)] self.qualification_ids = sorted( at_reference.loc[at_reference["batch"] != "batch3", "cell_id"] ) self.shifted_ids = sorted( at_reference.loc[at_reference["batch"] == "batch3", "cell_id"] ) self._reference_cache: dict[int, np.ndarray] = {} self.cell_ids = sorted(self.demo["cell_id"].unique()) self.build_time = self.manifest.get("provenance", {}).get("generated_at_utc", "unknown") def model(self, budget: int): """Load and cache one budget's model on first use.""" if budget not in self._models: import joblib self._models[budget] = joblib.load( MODELS / f"triage_extra_trees__budget{budget:03d}.joblib" ) return self._models[budget] @property def models(self) -> dict[int, Any]: """Budgets with a model available (not necessarily loaded yet).""" return {b: None for b in self.features} def row(self, cell_id: str, budget: int) -> pd.Series: subset = self.demo[(self.demo["cell_id"] == cell_id) & (self.demo["budget"] == budget)] return subset.iloc[0] def predict(self, cell_id: str, budget: int) -> tuple[float, float, float]: """Point prediction and conformal interval, in log10 cycle life.""" row = self.row(cell_id, budget) columns = self.features[budget] X = pd.DataFrame([[row.get(c, np.nan) for c in columns]], columns=columns) centre = float(_infer(self.model(budget), X)) half = self.half_widths[budget] return centre, centre - half, centre + half def grade_probabilities(self, lower: float, upper: float) -> dict[str, float]: samples = np.linspace(lower, upper, 512) cycles = 10.0 ** samples ordered = sorted(self.boundaries.items(), key=lambda kv: -kv[1]) out: dict[str, float] = {} previous = np.inf for grade, floor in ordered: out[grade] = float(((cycles >= floor) & (cycles < previous)).mean()) previous = floor total = sum(out.values()) or 1.0 return {g: v / total for g, v in out.items()} def action_costs(self, probabilities: dict[str, float]) -> dict[str, float]: out: dict[str, float] = {} for j, assigned in enumerate(self.grade_order): out[assigned] = float(sum( probabilities[true] * self.cost_matrix[f"true_{true}"][j] for true in self.grade_order )) return out def lot_ids(self, campaign: str) -> list[str]: """Cell IDs making up an incoming lot from the named campaign.""" return self.shifted_ids if campaign == SHIFTED_LOT else self.qualification_ids def campaign_of(self, cell_id: str) -> str: """Which campaign a cell actually came from. The lot is a PROPERTY OF THE CELL, never an operator choice. An earlier version offered the campaign as a separate control, which let the interface show a batch-1 cell under a batch-3 lot -- an incoherent state -- and, more seriously, made the shift check something an operator could decline to apply. A safety check that the person it protects can switch off is not a safety check. """ return SHIFTED_LOT if cell_id in self.shifted_ids else QUALIFICATION_LOT def cell_choices(self) -> list[tuple[str, str]]: """Dropdown entries labelled with the campaign each cell came from.""" return [ (f"{c} · {'batch 3 — new campaign' if c in self.shifted_ids else 'qualification'}", c) for c in self.cell_ids ] def reference_predictions(self, budget: int) -> np.ndarray: """Model predictions on the qualification cohort, cached per budget. The shift check compares PREDICTIONS on both sides, never true lives. A production console has no labels for an incoming lot, so a check that needed them would be undeployable -- and comparing true reference lives against predicted incoming ones would conflate model bias with distribution shift. Both sides go through the same model, so the only thing the statistic can move on is the input distribution. """ if budget not in self._reference_cache: self._reference_cache[budget] = np.array( [self.predict(c, budget)[0] for c in self.qualification_ids] ) return self._reference_cache[budget] def grade_for(self, cycles: float) -> str: for grade in self.grade_order: if cycles >= self.boundaries[grade]: return grade return self.grade_order[-1] def _infer(model, X: pd.DataFrame) -> float: """The heaviest inference path. Runs on CPU, deliberately undecorated. See the ZeroGPU note at the top of this module: decorating this with @spaces.GPU exhausted the daily quota on one page load and broke the deployed console, because the shift check calls it once per reference cell. """ return float(model.predict(X)[0]) BUNDLE = Bundle() # --------------------------------------------------------------------------- # Campaign-shift check # --------------------------------------------------------------------------- def campaign_shift_check(campaign: str, budget: int) -> tuple[bool, float, str]: """Two-sample KS of the incoming LOT against the qualification cohort. Returns (alarm, statistic, html). The alarm is a STATE, not a message: the result panel renders differently when it fires, because Phase 10 showed the failure mode is a model that becomes confidently wrong, and a footnote is not a proportionate response to that. THIS IS A LOT-LEVEL PROPERTY AND CANNOT BE OTHERWISE. A single cell carries no distribution to test, so an earlier version that passed one prediction to a two-sample test could only ever report "not run". Shift is a statement about the population a cell arrived in, and the operator screens a cell in the context of its lot. WHAT THIS CHECK CANNOT DETECT. A shift that leaves the predicted-life distribution unchanged while moving the feature-to-life mapping -- same marginal, different conditional. That is precisely the regime where the model is wrong and the check is silent, and no univariate two-sample test on the output can see it. """ lot = BUNDLE.lot_ids(campaign) if len(lot) < 3: return False, 0.0, _nominal_html(0.0, insufficient=True) # Identity is decided on cell IDs, not predicted values. Comparing the float # arrays looked equivalent and was not: tree-ensemble reductions differ at # ~1e-15 between calls, which is enough for ks_2samp to see two distinct # samples and report D = 1/n for a cohort compared against itself. if lot == BUNDLE.qualification_ids: return False, 0.0, _nominal_html(0.0, is_reference=True, n_lot=len(lot)) values = np.array([BUNDLE.predict(c, budget)[0] for c in lot]) reference = BUNDLE.reference_predictions(budget) result = stats.ks_2samp(reference, values) statistic = float(result.statistic) if statistic >= KS_ALARM_THRESHOLD: return True, statistic, _alarm_html(statistic, float(result.pvalue), len(lot)) return False, statistic, _nominal_html(statistic, n_lot=len(lot)) def _alarm_html(statistic: float, pvalue: float, n_lot: int) -> str: return f"""
⚠ CAMPAIGN SHIFT DETECTED — THE GUARANTEE MAY NOT HOLD

This lot of {n_lot} cells does not look like the qualification cohort (KS D = {statistic:.3f}, p = {pvalue:.2e}, alarm at D ≥ {KS_ALARM_THRESHOLD}).

Conformal validity assumes calibration and production data are exchangeable. That assumption is not met here, so the escape-rate bound shown below is not guaranteed.

Measured on the one shifted campaign in this dataset: coverage fell from 90.7% to 42.5% while the prediction interval got 31.5% NARROWER and error nearly doubled. The model becomes confidently wrong — its own confidence signal moves in the reassuring direction exactly as it stops being trustworthy.

Required action: recalibrate the conformal quantiles on labelled cells from this campaign before relying on any decision here. Minimum calibration set: 19 cells for α=0.05, 99 for α=0.01.

The D ≥ {KS_ALARM_THRESHOLD} threshold is directional, not calibrated — one shifted campaign can demonstrate the association but cannot set a decision boundary.

""" def _nominal_html( statistic: float, insufficient: bool = False, is_reference: bool = False, n_lot: int = 0, ) -> str: if insufficient: return f"""
DISTRIBUTION CHECK — NOT RUN

Fewer than 3 cells in this lot; a two-sample test has nothing to compare.

""" if is_reference: return f"""
✓ DISTRIBUTION CHECK PASSED — REFERENCE LOT

This cell came from the qualification cohort, so the comparison is against its own campaign and passes by construction. That is shown to make the contrast legible, not as evidence the check works — select a cell marked batch 3 — new campaign to see it fire on real out-of-distribution data.

""" return f"""
✓ DISTRIBUTION CHECK PASSED

This lot of {n_lot} cells is consistent with the qualification cohort (KS D = {statistic:.3f}, alarm at D ≥ {KS_ALARM_THRESHOLD}). The conformal guarantee's exchangeability assumption is not contradicted.

""" # --------------------------------------------------------------------------- # Tab 1 — screen a cell # --------------------------------------------------------------------------- def screen_cell(cell_id: str, budget: int): campaign = BUNDLE.campaign_of(cell_id) centre, lower, upper = BUNDLE.predict(cell_id, budget) probabilities = BUNDLE.grade_probabilities(lower, upper) costs = BUNDLE.action_costs(probabilities) assigned = min(costs, key=costs.get) row = BUNDLE.row(cell_id, budget) truth = float(row["cycle_life"]) escape_probability = float(sum( p for g, p in probabilities.items() if BUNDLE.boundaries[g] < BUNDLE.warranty )) alarm, _, shift_html = campaign_shift_check(campaign, budget) css_class = {"A": "ct-accept", "B": "ct-continue", "C": "ct-reject"}.get(assigned, "") verdict = {"A": "ACCEPT — GRADE A", "B": "ACCEPT — GRADE B", "C": "REJECT — GRADE C"}[assigned] # Under alarm the escape figure is still computed and still shown -- hiding # it would be its own dishonesty -- but it is displayed as withdrawn rather # than as a bound. A green 0.0% sitting under a red shift warning is the # exact contradiction Phase 10 is about. if alarm: escape_cell = ( f'
{escape_probability:.1%}' f'not guaranteed
' ) else: escape_cell = f'
{escape_probability:.1%}
' badge = f"""
Triage decision
{verdict}
{BUNDLE.grades[assigned]['tier']}
Cell
{cell_id}
Budget observed
{budget}cycles
Predicted life
{10 ** centre:,.0f}cycles
90% interval
{10 ** lower:,.0f}–{10 ** upper:,.0f}
Escape risk
{escape_cell}
Actual (historical)
{truth:,.0f}cycles
Incoming lot
{ 'batch 3 — new campaign' if campaign == SHIFTED_LOT else 'qualification' }
""" return ( badge, shift_html, panels.decision_plot(10 ** centre, 10 ** lower, 10 ** upper, BUNDLE.boundaries, BUNDLE.warranty, assigned), panels.cost_plot(costs, assigned), panels.risk_gauge(escape_probability, ALPHA, guaranteed=not alarm), ) # --------------------------------------------------------------------------- # Tab 2 — budget advisor # --------------------------------------------------------------------------- def _frontier_costs() -> dict[int, float]: scorecard = BUNDLE.results.get("scorecard", []) return {int(r["budget"]): float(r["mean"]) for r in scorecard if r.get("metric") == "cost_per_cell"} def budget_advisor(cell_id: str, budget: int): costs = _frontier_costs() budgets = [b for b in BUNDLE.budgets if b in costs] or BUNDLE.budgets widths = [BUNDLE.half_widths[b] * 2 for b in budgets] cost_values = [costs.get(b, float("nan")) for b in budgets] frontier = BUNDLE.results.get("frontier", {}) knee = int(frontier.get("knee_budget", budgets[0])) released = float(frontier.get("percent_chamber_time_released", float("nan"))) centre, lower, upper = BUNDLE.predict(cell_id, budget) reference_centre, reference_lower, reference_upper = BUNDLE.predict(cell_id, max(budgets)) span_now = 10 ** upper - 10 ** lower span_max = 10 ** reference_upper - 10 ** reference_lower saved = 100.0 * (1 - budget / max(budgets)) summary = f"""
Budget selected
{budget}cycles
Interval width
{span_now:,.0f}cycles
At N={max(budgets)}
{span_max:,.0f}cycles
Expected cost
{costs.get(budget, float('nan')):.2f}
Chamber time saved
{saved:.0f}%vs N={max(budgets)}
Economic knee
N={knee}
Move the slider and watch the right-hand curve. The interval narrows steadily with budget — more cycles genuinely buy a tighter statement. But expected cost is flat: every budget from 5 to 100 cycles is statistically indistinguishable, so the knee sits at N={knee} and deciding early costs essentially nothing. Against cycling every cell to end of life this releases {released:.2f}% of chamber time.

The caveat that must travel with that: the decision is insensitive to budget where the prediction is not. Accuracy does improve with more cycles; the cost matrix is simply dominated by a few expensive misgrades rather than by average accuracy.
""" return summary, panels.budget_advisor_plot(budgets, widths, cost_values, budget, knee) # --------------------------------------------------------------------------- # Tab 3 — chamber allocation # --------------------------------------------------------------------------- def chamber_allocation(slot_percent: float): allocation = BUNDLE.results.get("allocation", []) costs = {r["policy"]: float(r["mean"]) for r in allocation if r.get("metric") == "cost_per_cell"} escape = {r["policy"]: float(r["mean"]) for r in allocation if r.get("metric") == "escape_rate"} if not costs: return "
Allocation results unavailable.
", None order = ["greedy_voi_per_cycle", "random", "uniform", "confidence_only"] costs = {k: costs[k] for k in order if k in costs} best = min(costs, key=costs.get) batch = int(BUNDLE.manifest["batch_size"]) slots = int(round(batch * slot_percent / 100)) # The policy comparison was evaluated at ONE capacity, so the slider must # not imply it was recomputed at another. Moving off the evaluated point # rescales the slot count and nothing else; a control that silently leaves # the numbers alone while looking like it changed them is worse than no # control at all. Recomputing here is not an option -- it would need the # full 50-fold allocation run, and an in-app estimate over 34 demo cells # would no longer trace to outputs/reports/allocation_summary.csv. off_point = abs(slot_percent - EVALUATED_HELD_PERCENT) > 2.5 provenance = ( f'
Cost basis
' f'
' f'held at {EVALUATED_HELD_PERCENT:.1f}%not recomputed
' if off_point else f'
Cost basis
' f'
evaluated point
' ) caveat = f"""
SLIDER MOVED OFF THE EVALUATED CAPACITY

The policy comparison below was measured at a held fraction of 20.2% ± 0.3 across 50 folds and has not been recomputed at {slot_percent:.0f}%. Only the slot count above responds to this control. Treat the ranking as evidence at the evaluated capacity, not as a capacity sweep.

""" if off_point else "" summary = f"""
Batch size
{batch:,}cells
Chamber slots
{slots:,}
Best policy
{costs[best]:.3f}
vs confidence-only
{costs.get('confidence_only', 0) - costs[best]:+.3f}
{provenance}
{caveat}
Uncertainty is not a ranking signal on its own. Every policy here holds the same number of cells and incurs identical chamber cost, so this compares only which cells were chosen. Holding the most uncertain cells (confidence_only) is the worst policy — worse than random — because the most uncertain cells are often ones where more testing will not change the decision.

Greedy and confidence-only consume identical uncertainty estimates and differ only in whether the cost matrix enters the ranking, so the gap between them is attributable to the cost matrix specifically. Greedy does not significantly beat random at this evaluation's fold size (25/50 folds, p = 0.32); a real 1000-cell batch would wash that variance out, but this dataset cannot demonstrate it.
""" return summary, panels.allocation_plot(costs, escape) # --------------------------------------------------------------------------- # Tab 4 — explain # --------------------------------------------------------------------------- def explain_cell(cell_id: str, budget: int): sheets_path = ROOT / "outputs" / "reports" / "audit_sheets.json" drivers: list[dict[str, Any]] = [] if sheets_path.exists(): for sheet in json.loads(sheets_path.read_text(encoding="utf-8")): if sheet["cell_id"] == cell_id: drivers = sheet["drivers"] break if not drivers: return (f"
No stored attribution for " f"{cell_id}. Attribution sheets are " f"precomputed for a representative subset; pick one of: " f"{', '.join(_sheet_cells())}.
", None, "") centre, _, _ = BUNDLE.predict(cell_id, budget) figure = panels.shap_waterfall(drivers, base=centre, predicted=centre) rows = [] for i, driver in enumerate(drivers, start=1): raw = driver.get("raw_value") median = driver.get("cohort_median") comparison = "" if raw is not None and median is not None: comparison = (f"{raw:,.4g} " f"(typical {median:,.4g} — " f"{'above' if raw > median else 'below'} typical)") direction = "raised" if driver["shap"] > 0 else "lowered" rows.append( f"
  • {driver['description'].capitalize()}
    " f"{comparison}
    " f"" f"this {direction} the predicted cycle life; a high value means " f"{driver['high_means']}
  • " ) plain = ("

    Top drivers, in plain language

    " "
    ") takeaway = ("
    Values are shown in physical " "units against the cohort median, not standardised " "scores — an audit sheet that reports z-scores is unusable by the " "engineer it exists for.
    ") return takeaway, figure, plain def _sheet_cells() -> list[str]: path = ROOT / "outputs" / "reports" / "audit_sheets.json" if not path.exists(): return [] return [s["cell_id"] for s in json.loads(path.read_text(encoding="utf-8"))] # --------------------------------------------------------------------------- # Interface # --------------------------------------------------------------------------- def _figure(name: str) -> str | None: path = FIGURES / name return str(path) if path.exists() else None def _plate(name: str, takeaway_html: str) -> None: """Mount a generated figure with its source path stated underneath. These are the CANONICAL artifacts -- byte-identical to the files the README and docs cite -- rather than dark-theme copies rendered for the console. That is a deliberate trade of visual uniformity for traceability: a reviewer can check the claim against the exact file that produced it, and a restyled duplicate would be one more thing that can silently drift from its source. The path caption makes the provenance explicit rather than merely true. """ path = _figure(name) if path is None: return gr.Image(path, label=None, show_label=False, container=False) gr.HTML(takeaway_html) gr.HTML(f'
    source · outputs/figures/{name}
    ') def build_interface() -> gr.Blocks: # Gradio 6 moved `theme` and `css` from the Blocks constructor to launch(). with gr.Blocks(title="CellTriage - QC operator console") as demo: gr.HTML(f"""

    CellTriage · QC OPERATOR CONSOLE

    Cost-optimal, risk-controlled end-of-line screening for lithium-ion cells — grade assignment with a conformal bound on the escape rate.

    model build {BUNDLE.build_time}  ·  {len(BUNDLE.models)} budgets  ·  recipe descriptors excluded per Phase 10  ·  inference only, CPU

    """) with gr.Tabs(): # ---------------- budget advisor (first: most actionable) -------- with gr.Tab("Budget advisor"): gr.Markdown( "### How many cycles do you actually need?\n" "Aging chambers are the throughput bottleneck. Move the " "slider and watch what more testing buys — and what it does not." ) with gr.Row(): ba_cell = gr.Dropdown(BUNDLE.cell_choices(), value=BUNDLE.cell_ids[0], label="Demo cell", scale=1) # The slider reads in CYCLES, the unit the operator schedules # chamber time in. It snaps to the nearest budget a model was # fitted for; showing a list index instead would make the one # number on the control meaningless. ba_budget = gr.Slider( minimum=min(BUNDLE.budgets), maximum=max(BUNDLE.budgets), step=5, value=max(BUNDLE.budgets), label=f"Diagnostic budget — cycles observed " f"(snaps to {', '.join(str(b) for b in BUNDLE.budgets)})", scale=2) ba_summary = gr.HTML() ba_plot = gr.Plot() def _advise(cell_id, cycles): nearest = min(BUNDLE.budgets, key=lambda b: abs(b - float(cycles))) return budget_advisor(cell_id, nearest) for control in (ba_cell, ba_budget): control.change(_advise, [ba_cell, ba_budget], [ba_summary, ba_plot]) demo.load(_advise, [ba_cell, ba_budget], [ba_summary, ba_plot]) # ---------------- screen a cell --------------------------------- with gr.Tab("Screen a cell"): gr.Markdown( "### Screen one cell\n" "Cells marked *batch 3 — new campaign* are real " "out-of-distribution data, not a simulated shift. Select one " "to see the console change state." ) with gr.Row(): sc_cell = gr.Dropdown(BUNDLE.cell_choices(), value=BUNDLE.cell_ids[0], label="Cell", scale=1) sc_budget = gr.Radio([str(b) for b in BUNDLE.budgets], value=str(BUNDLE.budgets[-1]), label="Cycles observed", scale=2) sc_badge = gr.HTML() sc_shift = gr.HTML() sc_decision = gr.Plot() with gr.Row(): sc_cost = gr.Plot() sc_risk = gr.Plot() def _screen(cell_id, budget): return screen_cell(cell_id, int(budget)) sc_inputs = [sc_cell, sc_budget] sc_outputs = [sc_badge, sc_shift, sc_decision, sc_cost, sc_risk] for control in sc_inputs: control.change(_screen, sc_inputs, sc_outputs) demo.load(_screen, sc_inputs, sc_outputs) # ---------------- chamber allocation ---------------------------- with gr.Tab("Chamber allocation"): gr.Markdown( "### Which cells deserve the scarce slots?\n" "You cannot hold every cell. Given a fixed number of chamber " "slots, the question is which cells to hold." ) ca_slots = gr.Slider( 5, 40, value=20, step=5, label=f"Chamber slots as % of batch — policies were compared " f"at {EVALUATED_HELD_PERCENT}% only") ca_summary = gr.HTML() ca_plot = gr.Plot() ca_slots.change(chamber_allocation, ca_slots, [ca_summary, ca_plot]) demo.load(chamber_allocation, ca_slots, [ca_summary, ca_plot]) # ---------------- explain --------------------------------------- with gr.Tab("Explain this decision"): gr.Markdown( "### Why did the system decide that?\n" "A scrap decision must be defensible to a process engineer " "who does not read SHAP plots." ) ex_cell = gr.Dropdown(_sheet_cells() or BUNDLE.cell_ids, value=(_sheet_cells() or BUNDLE.cell_ids)[0], label="Cell (attribution precomputed)") ex_note = gr.HTML() ex_plot = gr.Plot() ex_plain = gr.HTML() def _explain(cell_id): return explain_cell(cell_id, BUNDLE.budgets[-1]) ex_cell.change(_explain, ex_cell, [ex_note, ex_plot, ex_plain]) demo.load(_explain, ex_cell, [ex_note, ex_plot, ex_plain]) # ---------------- the science ------------------------------------ with gr.Tab("The science"): gr.Markdown("### The physical basis, and the operating frontier") gr.HTML(f"""
    Why these figures are light against a dark console. They are the canonical artifacts — byte-identical to the files the README and docs/ cite, and each states its source path below. Rendering dark duplicates for the console would look tidier and give a reviewer a second copy that can silently drift from the one the claims were made against. Traceability was judged worth more than visual uniformity.
    """) _plate("fig05_dqv_variance_canary.png", """
    This one plot is why early prediction works. The variance of ΔQ(V) — how the discharge curve's shape changes between cycles 10 and 100 — predicts cycle life at R² = 0.859 before any meaningful capacity fade is visible. Reproducing the published relationship (ρ = −0.93) was the gate every later result depended on.
    """) _plate("fig15_budget_frontier.png", """
    Cost is flat across the budget range; escape rate is not. The left panel shows expected cost per cell against the baselines it must beat; the right is the Pareto frontier of escape rate against diagnostic cost. Down and left is better.
    """) _plate("fig13_conformal_coverage_and_width.png", """
    The guarantee holds in-distribution and fails under campaign shift. Solid lines sit on the diagonal; dashed lines — a new production campaign — fall far below it, in places beneath the uncalibrated baseline the method exists to improve on.
    """) # ---------------- method and limitations ------------------------- with gr.Tab("Method & limitations"): gr.HTML(f"""

    Read this first

    Method in brief

    """) gr.HTML(f"""

    CellTriage · inference-only console · no raw cycling data is shipped · demo subset of {len(BUNDLE.cell_ids)} cells

    """) return demo def main() -> None: """Launch the console. Theme and CSS are passed to launch() rather than to Blocks: Gradio 6 moved them there, and `show_api` was removed in the same release. DELIBERATELY PLAIN. Successive attempts to out-guess the Spaces runner -- exposing a module-level `demo`, wrapping `launch` to re-inject styling, ceding the port, forcing `block_thread()` -- each fixed an imagined problem and left the Space unprovisioned at `hardware: None`. The structure below is the one that actually reached RUNNING on ZeroGPU with the theme intact. """ build_interface().launch( server_name="0.0.0.0", server_port=7860, theme=theme.build_theme(), css=theme.CSS, ) if __name__ == "__main__": main()