proef 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- proef/__init__.py +25 -0
- proef/acquisition.py +244 -0
- proef/ad.py +159 -0
- proef/adapters/__init__.py +0 -0
- proef/adapters/admet.py +196 -0
- proef/adapters/bio/__init__.py +0 -0
- proef/adapters/bio/rdkit_ops.py +52 -0
- proef/adapters/bio/safety_rules.json +146 -0
- proef/adapters/bio/seq_alerts.py +79 -0
- proef/adapters/bio/structure_score.py +85 -0
- proef/adapters/bio/tox_alerts.py +99 -0
- proef/adapters/data/__init__.py +0 -0
- proef/adapters/data/admet.py +62 -0
- proef/adapters/data/chembl.py +110 -0
- proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
- proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
- proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
- proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
- proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
- proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
- proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
- proef/adapters/data/moleculenet.py +60 -0
- proef/adapters/databases/__init__.py +0 -0
- proef/adapters/databases/chembl_gates.py +121 -0
- proef/adapters/databases/chembl_lookup.py +35 -0
- proef/adapters/databases/open_targets.py +102 -0
- proef/adapters/databases/pubmed.py +94 -0
- proef/adapters/devices/__init__.py +0 -0
- proef/adapters/devices/ezo_ph.py +251 -0
- proef/adapters/devices/hcs_microscope.py +143 -0
- proef/adapters/devices/lcms.py +123 -0
- proef/adapters/devices/scheduler.py +84 -0
- proef/adapters/devices/sila2.py +134 -0
- proef/adapters/genomics/alphagenome.py +146 -0
- proef/adapters/lab/__init__.py +0 -0
- proef/adapters/lab/bioprocess.py +32 -0
- proef/adapters/lab/devices.py +170 -0
- proef/adapters/lab/imaging.py +226 -0
- proef/adapters/lab/mhs_driver.py +124 -0
- proef/adapters/lab/opentrons.py +222 -0
- proef/adapters/lab/ot2_sim.py +174 -0
- proef/adapters/lab/plate_reader_share.py +108 -0
- proef/adapters/lab/protein_design.py +199 -0
- proef/adapters/lab/recording.py +119 -0
- proef/adapters/lab/replay.py +107 -0
- proef/adapters/lab/simulator.py +282 -0
- proef/adapters/lab/synthesis.py +92 -0
- proef/adapters/models/__init__.py +0 -0
- proef/adapters/models/anthropic_provider.py +157 -0
- proef/adapters/models/assayloop_ranker.py +67 -0
- proef/adapters/models/from_env.py +93 -0
- proef/adapters/models/gp_policy.py +93 -0
- proef/adapters/models/gp_policy_gp.py +36 -0
- proef/adapters/models/llm_policy.py +187 -0
- proef/adapters/models/openai_compat.py +150 -0
- proef/adapters/models/sklearn_policy.py +65 -0
- proef/adapters/retrosynthesis.py +247 -0
- proef/adapters/sandbox/__init__.py +20 -0
- proef/adapters/sandbox/agentenv.py +145 -0
- proef/adapters/sandbox/docker.py +217 -0
- proef/adapters/sandbox/local.py +164 -0
- proef/adapters/sandbox/opensandbox.py +122 -0
- proef/adapters/store/__init__.py +0 -0
- proef/adapters/store/sqlite.py +207 -0
- proef/adaptive.py +108 -0
- proef/advisory.py +76 -0
- proef/analysis_profiles/__init__.py +8 -0
- proef/analysis_profiles/measurements.py +266 -0
- proef/analysis_profiles/plate_assay.py +316 -0
- proef/analysis_report.py +195 -0
- proef/analysis_store.py +183 -0
- proef/anchor.py +154 -0
- proef/api/app.py +107 -0
- proef/api/launch.py +170 -0
- proef/api/v1/__init__.py +29 -0
- proef/api/v1/analyses.py +367 -0
- proef/api/v1/campaigns.py +802 -0
- proef/api/v1/deps.py +10 -0
- proef/api/v1/evals.py +16 -0
- proef/api/v1/evidence.py +132 -0
- proef/api/v1/governance.py +35 -0
- proef/api/v1/inbox.py +119 -0
- proef/api/v1/lab.py +110 -0
- proef/api/v1/pauses.py +77 -0
- proef/api/v1/programs.py +397 -0
- proef/api/v1/results.py +147 -0
- proef/api/v1/schemas.py +932 -0
- proef/api/v1/system.py +79 -0
- proef/api/v1/trees.py +216 -0
- proef/api/wizard_sessions.py +253 -0
- proef/approvals.py +102 -0
- proef/assays/__init__.py +15 -0
- proef/assays/dls.py +114 -0
- proef/assays/dsf.py +81 -0
- proef/assays/elisa.py +58 -0
- proef/assays/properties.py +65 -0
- proef/assays/simulate.py +157 -0
- proef/audit.py +152 -0
- proef/autoloop.py +1620 -0
- proef/benchmark.py +442 -0
- proef/campaign_fsm.py +151 -0
- proef/citations.py +141 -0
- proef/cli.py +1249 -0
- proef/connect.py +74 -0
- proef/core/__init__.py +0 -0
- proef/core/contracts/__init__.py +35 -0
- proef/core/contracts/analysis.py +100 -0
- proef/core/contracts/models.py +395 -0
- proef/core/device_card.py +125 -0
- proef/core/hypothesis.py +720 -0
- proef/core/interfaces.py +164 -0
- proef/core/registry.py +123 -0
- proef/core/safety.py +324 -0
- proef/core/workflow.py +159 -0
- proef/critic.py +62 -0
- proef/demo.py +164 -0
- proef/derivation.py +128 -0
- proef/diary.py +301 -0
- proef/eln.py +87 -0
- proef/evals/__init__.py +1 -0
- proef/evals/hallucination.py +86 -0
- proef/evals/harness.py +358 -0
- proef/evals/orchestration.py +254 -0
- proef/evals/tasks.py +1010 -0
- proef/evals/toolcalls.py +425 -0
- proef/experiment.py +172 -0
- proef/experiment_analysis.py +114 -0
- proef/experiments/__init__.py +0 -0
- proef/experiments/grounding_exp.py +689 -0
- proef/figures.py +218 -0
- proef/fitting.py +309 -0
- proef/fixtures.py +140 -0
- proef/flywheel.py +125 -0
- proef/followup.py +126 -0
- proef/governance.py +290 -0
- proef/groundedness.py +361 -0
- proef/grounding.py +202 -0
- proef/hypothesis_agent.py +369 -0
- proef/ingest.py +157 -0
- proef/instruments.json +173 -0
- proef/interpret.py +95 -0
- proef/kinetic.py +102 -0
- proef/labread/__init__.py +45 -0
- proef/labread/analysis.py +428 -0
- proef/labread/common.py +153 -0
- proef/labread/formats.py +190 -0
- proef/labread/layout.py +168 -0
- proef/labread/pubchem.py +179 -0
- proef/labselect.py +431 -0
- proef/materials.py +140 -0
- proef/mcp_instrument.py +396 -0
- proef/mcp_server.py +283 -0
- proef/modality.py +111 -0
- proef/model_guard.py +245 -0
- proef/output_blocks.py +183 -0
- proef/paths.py +32 -0
- proef/physfail.py +55 -0
- proef/plan.py +160 -0
- proef/plots.py +123 -0
- proef/predictors.py +217 -0
- proef/probes.py +79 -0
- proef/problem_tree.py +581 -0
- proef/program.py +308 -0
- proef/protocol_design.py +42 -0
- proef/proxy.py +78 -0
- proef/readiness.py +259 -0
- proef/reliability.py +49 -0
- proef/report.py +117 -0
- proef/reproduce.py +310 -0
- proef/reviewer.py +254 -0
- proef/sandbox_session.py +247 -0
- proef/sandboxd.py +109 -0
- proef/scaffold.py +195 -0
- proef/series.py +327 -0
- proef/skills.py +203 -0
- proef/sweep.py +83 -0
- proef/taste.py +177 -0
- proef/templates/confirmatory-followup.json +34 -0
- proef/templates/dose-response-screen.json +39 -0
- proef/templates/sar-exploration.json +38 -0
- proef/templates.py +124 -0
- proef/toolkit.py +433 -0
- proef/toolloop.py +133 -0
- proef/tools.py +441 -0
- proef/tpp.py +185 -0
- proef/views/__init__.py +14 -0
- proef/views/counts.py +102 -0
- proef/views/experiment.py +154 -0
- proef/views/ids.py +49 -0
- proef/views/narrative.py +294 -0
- proef/views/pipeline.py +370 -0
- proef/vision.py +165 -0
- proef/watch.py +790 -0
- proef/wizard_chain.py +25 -0
- proef/wizard_store.py +373 -0
- proef-0.2.0.dist-info/METADATA +662 -0
- proef-0.2.0.dist-info/RECORD +200 -0
- proef-0.2.0.dist-info/WHEEL +4 -0
- proef-0.2.0.dist-info/entry_points.txt +14 -0
- proef-0.2.0.dist-info/licenses/LICENSE +202 -0
proef/analysis_report.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Analysis report + export (generic shell, profile renderers).
|
|
2
|
+
|
|
3
|
+
The report must let a third party answer: what was the input, what
|
|
4
|
+
assumptions were confirmed, what decision rule produced each call, and
|
|
5
|
+
whether a human changed anything — without reading JSON. The generic shell
|
|
6
|
+
carries identity/digest/origin/config/dispositions; the plate profile
|
|
7
|
+
renderer adds QC, fits, and calls. Regeneration is deterministic from the
|
|
8
|
+
stored revision (source bytes + config + pinned versions).
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import html
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _esc(v: Any) -> str:
|
|
17
|
+
return html.escape(str(v), quote=True)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def generic_header(doc: dict, chain_status: str) -> list[str]:
|
|
21
|
+
src = (doc.get("artifacts") or {}).get("source") or {}
|
|
22
|
+
layout = (doc.get("artifacts") or {}).get("layout") or {}
|
|
23
|
+
dispositions = doc.get("dispositions") or []
|
|
24
|
+
cfg = doc.get("config") or {}
|
|
25
|
+
origin = (cfg.get("evidence_origin")
|
|
26
|
+
or (doc.get("result") or {}).get("evidence_origin")
|
|
27
|
+
or "unknown")
|
|
28
|
+
lines = [
|
|
29
|
+
"<h1>Experiment analysis report</h1>",
|
|
30
|
+
f"<p>Analysis <strong>{_esc(doc.get('id'))}</strong> · "
|
|
31
|
+
f"profile <strong>{_esc(doc.get('profile'))}</strong> · "
|
|
32
|
+
f"revision {doc.get('revision')} · state {_esc(doc.get('state'))}</p>",
|
|
33
|
+
"<h2>Input</h2><ul>",
|
|
34
|
+
f"<li>source: {_esc(src.get('original_name') or '(unnamed)')} "
|
|
35
|
+
f"(sha256 <code>{_esc(src.get('sha256'))}</code>"
|
|
36
|
+
+ (f", layout {_esc(layout.get('original_name'))} "
|
|
37
|
+
f"sha256 <code>{_esc(layout.get('sha256'))}</code>"
|
|
38
|
+
if layout else "") + ")</li>",
|
|
39
|
+
f"<li>evidence origin: <strong>{_esc(origin)}</strong></li>",
|
|
40
|
+
f"<li>engine version: {_esc((doc.get('result') or {}).get('engine_version', 'unknown'))}</li>",
|
|
41
|
+
"</ul>",
|
|
42
|
+
"<h2>Confirmed analysis configuration</h2><ul>",
|
|
43
|
+
"".join(f"<li><code>{_esc(k)}</code>: {_esc(v)}</li>"
|
|
44
|
+
for k, v in sorted(cfg.items())),
|
|
45
|
+
"</ul>",
|
|
46
|
+
f"<p>Provenance chain: {_esc(chain_status)}</p>",
|
|
47
|
+
]
|
|
48
|
+
if dispositions:
|
|
49
|
+
lines.append("<h2>Scientist review</h2><ul>")
|
|
50
|
+
for d in dispositions:
|
|
51
|
+
lines.append(f"<li><strong>{_esc(d.get('action'))}</strong> by "
|
|
52
|
+
f"{_esc(d.get('actor'))}"
|
|
53
|
+
+ (f": {_esc(d.get('reason'))}" if d.get("reason")
|
|
54
|
+
else "") + "</li>")
|
|
55
|
+
lines.append("</ul>")
|
|
56
|
+
else:
|
|
57
|
+
lines.append("<p><em>No human disposition recorded: the calls "
|
|
58
|
+
"are machine-derived only.</em></p>")
|
|
59
|
+
return lines
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def plate_section(result: dict) -> list[str]:
|
|
63
|
+
compounds: dict[str, Any] = result.get("compounds") or {}
|
|
64
|
+
calls = {c["entity"]: c for c in (result.get("calls") or [])}
|
|
65
|
+
inst = result.get("instrument") or {}
|
|
66
|
+
lines = [
|
|
67
|
+
"<h2>Plate analysis</h2>",
|
|
68
|
+
f"<p>{result.get('n_wells')} wells · format {_esc(result.get('format'))}"
|
|
69
|
+
f" · unit {_esc(result.get('response_unit'))} · "
|
|
70
|
+
f"Z' {_esc(result.get('z_prime'))}"
|
|
71
|
+
+ (" (heuristic)" if result.get("z_prime_kind") != "real" else " (real)")
|
|
72
|
+
+ "</p>",
|
|
73
|
+
]
|
|
74
|
+
if inst:
|
|
75
|
+
lines.append("<p class=muted>instrument: "
|
|
76
|
+
+ _esc(" · ".join(f"{k}: {v}" for k, v in
|
|
77
|
+
list(inst.items())[:5])) + "</p>")
|
|
78
|
+
if result.get("regime_refused"):
|
|
79
|
+
lines.append(f"<p><strong>REGIME REFUSED: no absolute claims:</strong> "
|
|
80
|
+
f"{_esc((result.get('regime') or {}).get('note'))}</p>")
|
|
81
|
+
if result.get("threshold_registered"):
|
|
82
|
+
lines.append(f"<p>Registered gate: metric {_esc(result.get('metric'))} "
|
|
83
|
+
f"({_esc(result.get('direction'))}); a 95% CI straddling "
|
|
84
|
+
f"the gate abstains.</p>")
|
|
85
|
+
else:
|
|
86
|
+
lines.append("<p><em>No threshold registered: estimates only, "
|
|
87
|
+
"no hit calls.</em></p>")
|
|
88
|
+
lines.append("<table border=1 cellpadding=4 style='border-collapse:collapse;"
|
|
89
|
+
"font-size:13px'><tr><th>sample</th><th>IC50 (µM)</th>"
|
|
90
|
+
"<th>95% CI</th><th>fit</th><th>call</th><th>reason</th></tr>")
|
|
91
|
+
for s, c in compounds.items():
|
|
92
|
+
call = calls.get(s)
|
|
93
|
+
lines.append(
|
|
94
|
+
f"<tr><td>{_esc(s)}</td>"
|
|
95
|
+
f"<td>{_esc(c.get('ic50_um') if c.get('ic50_um') is not None
|
|
96
|
+
else '> range')}</td>"
|
|
97
|
+
f"<td>{_esc(c['ic50_ci']) if c.get('ic50_ci') else '—'}</td>"
|
|
98
|
+
f"<td title=\"{_esc(c.get('fit_model') or '')}\">"
|
|
99
|
+
f"{_esc(c.get('fit_method'))}"
|
|
100
|
+
+ (" · right-censored" if c.get("right_censored") else "")
|
|
101
|
+
+ (" · left-censored" if c.get("left_censored") else "")
|
|
102
|
+
+ "</td>"
|
|
103
|
+
f"<td>{_esc(call['call']) if call else '—'}</td>"
|
|
104
|
+
f"<td>{_esc(call['reason']) if call else ''}</td></tr>")
|
|
105
|
+
lines.append("</table>")
|
|
106
|
+
return lines
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def measurements_section(result: dict) -> list[str]:
|
|
110
|
+
"""Per-sample n, mean, sd and 95% interval against the registered gate, with the method and its limits stated."""
|
|
111
|
+
unit = f" {_esc(result.get('unit'))}" if result.get("unit") else ""
|
|
112
|
+
calls = {c["entity"]: c for c in (result.get("calls") or [])}
|
|
113
|
+
lines = [f"<h2>Measurements: {_esc(result.get('metric'))}{unit}</h2>",
|
|
114
|
+
f"<p class='muted'>{_esc(result.get('method'))}. No plate or controls, so no Z′ or control-based QC.</p>"]
|
|
115
|
+
if not result.get("threshold_registered"):
|
|
116
|
+
lines.append("<p><em>No gate was registered: these are estimates only, no calls.</em></p>")
|
|
117
|
+
lines.append("<table border='1' cellpadding='4' cellspacing='0'><tr><th>sample</th><th>n</th><th>mean</th>"
|
|
118
|
+
"<th>sd</th><th>95% interval</th><th>call</th><th>why</th></tr>")
|
|
119
|
+
for sample, c in sorted((result.get("compounds") or {}).items()):
|
|
120
|
+
ci = c.get("ci")
|
|
121
|
+
k = calls.get(sample, {})
|
|
122
|
+
lines.append(f"<tr><td>{_esc(sample)}</td><td>{c.get('n')}</td><td>{c.get('mean'):.4g}</td>"
|
|
123
|
+
f"<td>{'' if c.get('sd') is None else format(c['sd'], '.3g')}</td>"
|
|
124
|
+
f"<td>{'' if not ci else f'{ci[0]:.4g} to {ci[1]:.4g}'}</td>"
|
|
125
|
+
f"<td>{_esc(k.get('call', ''))}</td><td>{_esc(k.get('reason', ''))}</td></tr>")
|
|
126
|
+
lines.append("</table>")
|
|
127
|
+
return lines
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def export_measurements_csv(result: dict) -> str:
|
|
131
|
+
import csv
|
|
132
|
+
import io
|
|
133
|
+
calls = {c["entity"]: c for c in (result.get("calls") or [])}
|
|
134
|
+
buf = io.StringIO()
|
|
135
|
+
w = csv.writer(buf)
|
|
136
|
+
w.writerow(["sample", "n", "mean", "sd", "ci_low", "ci_high", "metric", "unit", "call", "call_reason",
|
|
137
|
+
"evidence_origin", "engine_version", "values"])
|
|
138
|
+
for sample, c in sorted((result.get("compounds") or {}).items()):
|
|
139
|
+
ci = c.get("ci") or (None, None)
|
|
140
|
+
k = calls.get(sample, {})
|
|
141
|
+
w.writerow([sample, c.get("n"), c.get("mean"), c.get("sd"), ci[0], ci[1], result.get("metric"), result.get("unit") or "",
|
|
142
|
+
k.get("call", ""), k.get("reason", ""), result.get("evidence_origin", "unknown"),
|
|
143
|
+
result.get("engine_version", "unknown"), " ".join(str(v) for v in c.get("values") or [])])
|
|
144
|
+
return buf.getvalue()
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def render_report(doc: dict, chain_status: str) -> str:
|
|
148
|
+
body = generic_header(doc, chain_status)
|
|
149
|
+
result = doc.get("result")
|
|
150
|
+
if result is None:
|
|
151
|
+
body.append("<p><em>No analysis result stored for this revision "
|
|
152
|
+
"yet.</em></p>")
|
|
153
|
+
elif doc.get("profile") == "plate_assay":
|
|
154
|
+
body.extend(plate_section(result))
|
|
155
|
+
elif doc.get("profile") == "measurements":
|
|
156
|
+
body.extend(measurements_section(result))
|
|
157
|
+
else: # unknown future profile: dump the generic summary honestly
|
|
158
|
+
body.append(f"<p>Profile {doc.get('profile')}: state "
|
|
159
|
+
f"{_esc(doc.get('state'))}.</p>")
|
|
160
|
+
return ("<!doctype html><html><head><meta charset='utf-8'>"
|
|
161
|
+
"<title>Analysis report</title>"
|
|
162
|
+
"<style>body{font-family:system-ui;max-width:900px;margin:24px auto;"
|
|
163
|
+
"padding:0 16px;color:#111}table{font-size:13px}code{background:#f4f4f4;"
|
|
164
|
+
"padding:0 3px}.muted{color:#666}</style></head><body>"
|
|
165
|
+
+ "\n".join(body) + "</body></html>")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def export_csv(doc: dict, records: list[dict], result: dict) -> str:
|
|
169
|
+
"""Plate-profile CSV: raw + normalized values kept in separate columns,
|
|
170
|
+
well mapping, units, fits, intervals, calls, evidence origin."""
|
|
171
|
+
import csv
|
|
172
|
+
import io
|
|
173
|
+
|
|
174
|
+
calls = {c["entity"]: c for c in (result.get("calls") or [])}
|
|
175
|
+
buf = io.StringIO()
|
|
176
|
+
w = csv.writer(buf)
|
|
177
|
+
w.writerow(["well", "sample", "conc_um", "value", "value_raw", "control",
|
|
178
|
+
"batch", "channel", "response_unit", "evidence_origin",
|
|
179
|
+
"engine_version",
|
|
180
|
+
"ic50_um", "ic50_ci_low", "ic50_ci_high", "fit_method",
|
|
181
|
+
"call", "call_reason"])
|
|
182
|
+
for r in records:
|
|
183
|
+
comp = (result.get("compounds") or {}).get(r["sample"], {})
|
|
184
|
+
ci = comp.get("ic50_ci") or (None, None)
|
|
185
|
+
call = calls.get(r["sample"], {})
|
|
186
|
+
w.writerow([r.get("well", ""), r["sample"], r.get("conc_um", ""),
|
|
187
|
+
r["value"], r.get("value_raw", ""), r.get("control", False),
|
|
188
|
+
r.get("batch", ""), r.get("channel", ""),
|
|
189
|
+
result.get("response_unit", ""),
|
|
190
|
+
result.get("evidence_origin", "unknown"),
|
|
191
|
+
result.get("engine_version", "unknown"),
|
|
192
|
+
comp.get("ic50_um", ""), ci[0], ci[1],
|
|
193
|
+
comp.get("fit_method", ""),
|
|
194
|
+
call.get("call", ""), call.get("reason", "")])
|
|
195
|
+
return buf.getvalue()
|
proef/analysis_store.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Analysis-session persistence + artifact storage (generic lifecycle).
|
|
2
|
+
|
|
3
|
+
One row per analysis in the wizard store's SQLite DB (same store the
|
|
4
|
+
guided experiment registry uses), one JSON doc per session. Artifacts live
|
|
5
|
+
under DATA_DIR/analyses/<id>/ with GENERATED names — the user's filename
|
|
6
|
+
is sanitized display metadata only and never a storage path.
|
|
7
|
+
|
|
8
|
+
Immutable revisions: changing the config (or the source bytes on
|
|
9
|
+
re-upload) creates a NEW revision inside the doc; a stored analysis result
|
|
10
|
+
is never rewritten.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import time
|
|
17
|
+
import uuid
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from proef.core.contracts.analysis import (AnalysisArtifact,
|
|
22
|
+
HumanDisposition)
|
|
23
|
+
from proef.paths import DATA_DIR
|
|
24
|
+
from proef.wizard_store import WizardStore
|
|
25
|
+
|
|
26
|
+
MAX_UPLOAD_BYTES = 32 * 1024 * 1024
|
|
27
|
+
ALLOWED_SUFFIXES = {".csv", ".tsv", ".txt", ".xlsx", ".npy"}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def ensure_tables() -> None:
|
|
31
|
+
ws = _ws()
|
|
32
|
+
ws._conn.execute("""
|
|
33
|
+
CREATE TABLE IF NOT EXISTS analysis_sessions (
|
|
34
|
+
id TEXT PRIMARY KEY,
|
|
35
|
+
profile TEXT NOT NULL,
|
|
36
|
+
state TEXT NOT NULL,
|
|
37
|
+
revision INTEGER NOT NULL DEFAULT 1,
|
|
38
|
+
doc TEXT NOT NULL,
|
|
39
|
+
created_at REAL NOT NULL,
|
|
40
|
+
updated_at REAL NOT NULL
|
|
41
|
+
)""")
|
|
42
|
+
ws._conn.commit()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _ws() -> WizardStore:
|
|
46
|
+
return WizardStore()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def artifact_dir(aid: str) -> Path:
|
|
50
|
+
d = DATA_DIR / "analyses" / aid
|
|
51
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
return d
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def sha256_of(path: Path) -> str:
|
|
56
|
+
h = hashlib.sha256()
|
|
57
|
+
with path.open("rb") as f:
|
|
58
|
+
for chunk in iter(lambda: f.read(1 << 20), b""):
|
|
59
|
+
h.update(chunk)
|
|
60
|
+
return h.hexdigest()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def store_artifact(aid: str, kind: str, filename: str, content: bytes) -> AnalysisArtifact:
|
|
64
|
+
"""Persist upload bytes unchanged under a generated name; digest binds
|
|
65
|
+
the chain to the bytes. Oversized/disallowed uploads are typed errors."""
|
|
66
|
+
suffix = Path(filename).suffix.lower()
|
|
67
|
+
if suffix not in ALLOWED_SUFFIXES:
|
|
68
|
+
raise ValueError(f"unsupported upload type: {suffix or '(none)'}")
|
|
69
|
+
if len(content) > MAX_UPLOAD_BYTES:
|
|
70
|
+
raise ValueError(f"upload exceeds {MAX_UPLOAD_BYTES // (1024 * 1024)} MB limit")
|
|
71
|
+
from proef.labread import sanitize_label
|
|
72
|
+
d = artifact_dir(aid)
|
|
73
|
+
name = f"{kind}-{uuid.uuid4().hex[:8]}{suffix}"
|
|
74
|
+
path = d / name
|
|
75
|
+
path.write_bytes(content)
|
|
76
|
+
return AnalysisArtifact(
|
|
77
|
+
kind=kind, storage_path=str(path),
|
|
78
|
+
original_name=sanitize_label(Path(filename).name, 80),
|
|
79
|
+
sha256=sha256_of(path), size=len(content))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def create(aid: str, profile: str, config: dict, source: AnalysisArtifact,
|
|
83
|
+
layout: AnalysisArtifact | None, preview: dict) -> tuple[str, dict]:
|
|
84
|
+
"""Create a session (with its pre-generated id) from an upload + its
|
|
85
|
+
preview payload."""
|
|
86
|
+
ensure_tables()
|
|
87
|
+
now = time.time()
|
|
88
|
+
doc: dict[str, Any] = {
|
|
89
|
+
"profile": profile,
|
|
90
|
+
"config": config,
|
|
91
|
+
"artifacts": {"source": source.model_dump(),
|
|
92
|
+
"layout": layout.model_dump() if layout else None},
|
|
93
|
+
"dispositions": [],
|
|
94
|
+
"revisions": [{"revision": 1, "config": config,
|
|
95
|
+
"source_sha256": source.sha256,
|
|
96
|
+
"layout_sha256": layout.sha256 if layout else None,
|
|
97
|
+
"at": now}],
|
|
98
|
+
"preview": preview,
|
|
99
|
+
"result": None,
|
|
100
|
+
}
|
|
101
|
+
ws = _ws()
|
|
102
|
+
ws._conn.execute(
|
|
103
|
+
"INSERT INTO analysis_sessions VALUES (?,?,?,?,?,?,?)",
|
|
104
|
+
(aid, profile, str(preview.get("state") or "preview_ready"), 1,
|
|
105
|
+
json.dumps(doc), now, now))
|
|
106
|
+
ws._conn.commit()
|
|
107
|
+
return aid, doc
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _load_row(aid: str):
|
|
111
|
+
row = _ws()._conn.execute(
|
|
112
|
+
"SELECT profile, state, revision, doc FROM analysis_sessions "
|
|
113
|
+
"WHERE id=?", (aid,)).fetchone()
|
|
114
|
+
if not row:
|
|
115
|
+
raise KeyError(f"analysis session {aid} not found")
|
|
116
|
+
return row
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def get(aid: str) -> dict:
|
|
120
|
+
profile, state, revision, doc = _load_row(aid)
|
|
121
|
+
d = json.loads(doc)
|
|
122
|
+
return {"id": aid, "profile": profile, "state": state,
|
|
123
|
+
"revision": revision, **d}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def list_recent(limit: int = 50) -> list[dict]:
|
|
127
|
+
ensure_tables()
|
|
128
|
+
rows = _ws()._conn.execute(
|
|
129
|
+
"SELECT id, profile, state, revision, updated_at FROM "
|
|
130
|
+
"analysis_sessions ORDER BY updated_at DESC LIMIT ?",
|
|
131
|
+
(limit,)).fetchall()
|
|
132
|
+
return [{"id": r[0], "profile": r[1], "state": r[2], "revision": r[3],
|
|
133
|
+
"updated_at": r[4]} for r in rows]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def update(aid: str, state: str, doc_mutate=None, bump_revision: bool = False
|
|
137
|
+
) -> dict:
|
|
138
|
+
"""Persist a transition. doc_mutate(d) edits the doc in place;
|
|
139
|
+
bump_revision opens a NEW immutable revision for a config change."""
|
|
140
|
+
profile, _state, revision, doc = _load_row(aid)
|
|
141
|
+
d = json.loads(doc)
|
|
142
|
+
if doc_mutate:
|
|
143
|
+
doc_mutate(d)
|
|
144
|
+
if bump_revision:
|
|
145
|
+
revision += 1
|
|
146
|
+
d["revisions"].append({
|
|
147
|
+
"revision": revision, "config": d.get("config"),
|
|
148
|
+
"source_sha256": (d.get("artifacts", {}).get("source") or {}).get("sha256"),
|
|
149
|
+
"layout_sha256": (d.get("artifacts", {}).get("layout") or {}).get("sha256"),
|
|
150
|
+
"at": time.time()})
|
|
151
|
+
ws = _ws()
|
|
152
|
+
ws._conn.execute(
|
|
153
|
+
"UPDATE analysis_sessions SET state=?, revision=?, doc=?, "
|
|
154
|
+
"updated_at=? WHERE id=?",
|
|
155
|
+
(state, revision, json.dumps(d), time.time(), aid))
|
|
156
|
+
ws._conn.commit()
|
|
157
|
+
return {"id": aid, "profile": profile, "state": state,
|
|
158
|
+
"revision": revision, **d}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def add_disposition(aid: str, disposition: HumanDisposition) -> dict:
|
|
162
|
+
def _mutate(d: dict):
|
|
163
|
+
d.setdefault("dispositions", []).append(disposition.model_dump())
|
|
164
|
+
return update(aid, "reviewed", _mutate)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def reconfigure(aid: str, config: dict, new_preview: dict) -> dict:
|
|
168
|
+
"""A changed scientific configuration opens a NEW revision; the stored
|
|
169
|
+
result stays with the revision that produced it."""
|
|
170
|
+
def _mutate(d: dict):
|
|
171
|
+
d["config"] = config
|
|
172
|
+
d["preview"] = new_preview
|
|
173
|
+
d["result"] = None
|
|
174
|
+
# a confirmed config advances the session; a profile hold passes through
|
|
175
|
+
pstate = str(new_preview.get("state") or "preview_ready")
|
|
176
|
+
state = "configured" if pstate == "preview_ready" else pstate
|
|
177
|
+
return update(aid, state, _mutate, bump_revision=True)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def store_result(aid: str, result: dict) -> dict:
|
|
181
|
+
def _mutate(d: dict):
|
|
182
|
+
d["result"] = result
|
|
183
|
+
return update(aid, str(result.get("state") or "analyzed"), _mutate)
|
proef/anchor.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Merkle anchoring — make the hash chain tamper-evident to others.
|
|
2
|
+
|
|
3
|
+
Per-branch chains prove internal consistency; a Merkle root over ALL record
|
|
4
|
+
hashes lets a third party verify the entire store's state at a point in
|
|
5
|
+
time with one number. Publishing the root somewhere you don't control
|
|
6
|
+
(public repo, gist, certificate log, timestamping service) turns "trust me"
|
|
7
|
+
into "check me". We anchor locally; publishing is an operator choice via
|
|
8
|
+
--publish-cmd.
|
|
9
|
+
|
|
10
|
+
Stated limits (this is a physics claim, so say what the physics covers):
|
|
11
|
+
verification RECOMPUTES every hash from its payload — editing record
|
|
12
|
+
content breaks the root even if the hash column is left untouched. What
|
|
13
|
+
remains outside this mechanism: anchors.json itself is an ordinary local
|
|
14
|
+
file (an attacker with write access to BOTH the db and the anchors file
|
|
15
|
+
can rewrite history before the first publish), and a signature over the
|
|
16
|
+
anchor is exactly what --publish-cmd to an external transparency channel
|
|
17
|
+
provides. Tamper-evidence = recompute on read + at least one EXTERNALLY
|
|
18
|
+
PUBLISHED root.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import sqlite3
|
|
25
|
+
import shlex
|
|
26
|
+
import subprocess
|
|
27
|
+
import time
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
ANCHORS = Path(".data/anchors.json")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _h(s: str) -> str:
|
|
34
|
+
return hashlib.sha256(s.encode()).hexdigest()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def merkle_root(leaf_hashes: list[str]) -> str:
|
|
38
|
+
"""Standard pairwise SHA-256 Merkle root; odd nodes promote."""
|
|
39
|
+
level = [_h(x) for x in leaf_hashes]
|
|
40
|
+
if not level:
|
|
41
|
+
return _h("")
|
|
42
|
+
while len(level) > 1:
|
|
43
|
+
level = [_h(level[i] + level[i + 1]) if i + 1 < len(level)
|
|
44
|
+
else level[i] for i in range(0, len(level), 2)]
|
|
45
|
+
return level[0]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _require_store(db_path: str) -> None:
|
|
49
|
+
"""A clear error instead of 'no such table' — and never create the file."""
|
|
50
|
+
msg = (f"no provenance database at {db_path} — run a campaign first "
|
|
51
|
+
"(or pass --db)")
|
|
52
|
+
if not Path(db_path).exists():
|
|
53
|
+
raise FileNotFoundError(msg)
|
|
54
|
+
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
|
|
55
|
+
try:
|
|
56
|
+
has = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' "
|
|
57
|
+
"AND name='provenance'").fetchone()
|
|
58
|
+
finally:
|
|
59
|
+
conn.close()
|
|
60
|
+
if not has:
|
|
61
|
+
raise FileNotFoundError(msg)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def store_hashes(db_path: str) -> list[str]:
|
|
65
|
+
conn = sqlite3.connect(db_path)
|
|
66
|
+
try:
|
|
67
|
+
return [row[0] for row in conn.execute(
|
|
68
|
+
"SELECT record_hash FROM provenance ORDER BY rowid"
|
|
69
|
+
).fetchall() if row[0]]
|
|
70
|
+
finally:
|
|
71
|
+
conn.close()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def recomputed_hashes(db_path: str) -> tuple[list[str], list[dict]]:
|
|
75
|
+
"""Recompute every record hash FROM ITS PAYLOAD — the anchor verifies
|
|
76
|
+
content, not copied metadata. Returns (hashes, problems)."""
|
|
77
|
+
from proef.adapters.store.sqlite import SqliteProvenanceStore
|
|
78
|
+
from proef.core.contracts import ProvenanceRecord
|
|
79
|
+
|
|
80
|
+
conn = sqlite3.connect(db_path)
|
|
81
|
+
try:
|
|
82
|
+
rows = conn.execute(
|
|
83
|
+
"SELECT record_id, branch_id, record_hash, payload "
|
|
84
|
+
"FROM provenance ORDER BY rowid").fetchall()
|
|
85
|
+
finally:
|
|
86
|
+
conn.close()
|
|
87
|
+
hashes, problems = [], []
|
|
88
|
+
for rid, br, col_hash, payload in rows:
|
|
89
|
+
rec = ProvenanceRecord.model_validate_json(payload)
|
|
90
|
+
h = SqliteProvenanceStore._hash(rec)
|
|
91
|
+
if h != rec.record_hash or h != col_hash:
|
|
92
|
+
problems.append({"record_id": rid, "branch": br,
|
|
93
|
+
"problem": "hash-mismatch"})
|
|
94
|
+
hashes.append(h or col_hash or "")
|
|
95
|
+
return hashes, problems
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def anchor(db_path: str = "proef.db",
|
|
99
|
+
publish_cmd: str | None = None) -> dict:
|
|
100
|
+
"""Compute + append the store's Merkle anchor; optionally publish.
|
|
101
|
+
|
|
102
|
+
The root is computed over RECOMPUTED payload hashes: an anchor
|
|
103
|
+
commits to what the records actually contain, so a published root
|
|
104
|
+
also pins content integrity, not just copied metadata."""
|
|
105
|
+
_require_store(db_path)
|
|
106
|
+
hashes, problems = recomputed_hashes(db_path)
|
|
107
|
+
entry = {"ts": time.time(), "records": len(hashes),
|
|
108
|
+
"merkle_root": merkle_root(hashes),
|
|
109
|
+
"content_issues": len(problems)}
|
|
110
|
+
ANCHORS.parent.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
existing = json.loads(ANCHORS.read_text()) if ANCHORS.exists() else []
|
|
112
|
+
existing.append(entry)
|
|
113
|
+
ANCHORS.write_text(json.dumps(existing, indent=1))
|
|
114
|
+
if publish_cmd:
|
|
115
|
+
proc = subprocess.run(shlex.split(publish_cmd), input=json.dumps(entry),
|
|
116
|
+
capture_output=True, text=True, timeout=120)
|
|
117
|
+
entry["published"] = proc.returncode == 0
|
|
118
|
+
if proc.returncode:
|
|
119
|
+
entry["publish_error"] = (proc.stderr or proc.stdout)[-200:]
|
|
120
|
+
return entry
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def verify(db_path: str = "proef.db", root: str | None = None) -> dict:
|
|
124
|
+
"""Recompute and compare against the latest (or given) anchor.
|
|
125
|
+
|
|
126
|
+
The current root is computed over RECOMPUTED payload hashes, so an
|
|
127
|
+
edit that rewrites a record's content (leaving the hash column
|
|
128
|
+
untouched) changes the root and breaks the match. `content_tampered`
|
|
129
|
+
flags divergence between stored column hashes and recomputed ones
|
|
130
|
+
even before anyone compares to an anchor."""
|
|
131
|
+
_require_store(db_path)
|
|
132
|
+
hashes = store_hashes(db_path)
|
|
133
|
+
recomputed, problems = recomputed_hashes(db_path)
|
|
134
|
+
current = merkle_root(recomputed)
|
|
135
|
+
stored_root = merkle_root(hashes)
|
|
136
|
+
anchors = json.loads(ANCHORS.read_text()) if ANCHORS.exists() else []
|
|
137
|
+
target = root or (anchors[-1]["merkle_root"] if anchors else None)
|
|
138
|
+
entry = next((a for a in reversed(anchors)
|
|
139
|
+
if a.get("merkle_root") == target), None)
|
|
140
|
+
# the anchor commits to the FIRST n records; appends after anchoring are
|
|
141
|
+
# legitimate, so compare the anchored PREFIX, not the whole store
|
|
142
|
+
n = entry.get("records") if entry else None
|
|
143
|
+
if isinstance(n, int) and 0 <= n <= len(recomputed):
|
|
144
|
+
prefix_root = merkle_root(recomputed[:n])
|
|
145
|
+
appended = len(recomputed) - n
|
|
146
|
+
else:
|
|
147
|
+
prefix_root, appended = current, 0
|
|
148
|
+
return {"current_root": current, "anchored_root": target,
|
|
149
|
+
"records": len(recomputed),
|
|
150
|
+
"appended_since_anchor": appended,
|
|
151
|
+
"stored_root": stored_root,
|
|
152
|
+
"content_tampered": stored_root != current or bool(problems),
|
|
153
|
+
"problems": problems[:10],
|
|
154
|
+
"match": target is not None and prefix_root == target}
|
proef/api/app.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Proef web API: a thin FastAPI layer over the engine.
|
|
2
|
+
|
|
3
|
+
One uvicorn process serves the typed REST contract (`/api/v1`, see
|
|
4
|
+
`api/v1/schemas.py`) and the built SPA. All state lives in the existing
|
|
5
|
+
registry and provenance stores; nothing here owns logic.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hmac
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
13
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
14
|
+
from fastapi.responses import FileResponse
|
|
15
|
+
|
|
16
|
+
from contextlib import asynccontextmanager # noqa: E402
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@asynccontextmanager
|
|
20
|
+
async def _lifespan(_app):
|
|
21
|
+
from proef.paths import migrate_legacy_workspace
|
|
22
|
+
migrate_legacy_workspace() # a workspace from the BioNexus days keeps its ledger
|
|
23
|
+
yield
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
app = FastAPI(title="Proef API", version="1.0.0", lifespan=_lifespan)
|
|
27
|
+
app.add_middleware(
|
|
28
|
+
CORSMiddleware, allow_origins=["http://localhost:5173"],
|
|
29
|
+
allow_methods=["*"], allow_headers=["*"])
|
|
30
|
+
|
|
31
|
+
# ---- state-changing-request guard (approvals, halt, launch, delete ...)
|
|
32
|
+
# The API is a local control surface with no user accounts. Two cheap
|
|
33
|
+
# defences against drive-by browser attacks on localhost: a request that
|
|
34
|
+
# carries an Origin/Host must be local, and when PROEF_API_TOKEN is set
|
|
35
|
+
# every mutating call must present it (X-Proef-Token).
|
|
36
|
+
_LOCAL_HOSTS = {"localhost", "127.0.0.1", "[::1]", "::1", "testserver"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@app.middleware("http")
|
|
40
|
+
async def _guard_mutations(request: Request, call_next):
|
|
41
|
+
import os
|
|
42
|
+
from urllib.parse import urlparse
|
|
43
|
+
from fastapi.responses import JSONResponse
|
|
44
|
+
host = (request.headers.get("host") or "").rsplit(":", 1)[0].strip("[]")
|
|
45
|
+
if host and host not in _LOCAL_HOSTS and \
|
|
46
|
+
not os.environ.get("PROEF_ALLOW_REMOTE"):
|
|
47
|
+
return JSONResponse({"detail": "non-local Host refused"}, 403)
|
|
48
|
+
if request.method in ("POST", "PUT", "PATCH", "DELETE"):
|
|
49
|
+
origin = request.headers.get("origin")
|
|
50
|
+
if origin and (urlparse(origin).hostname or "") not in _LOCAL_HOSTS:
|
|
51
|
+
return JSONResponse({"detail": "cross-origin write refused"}, 403)
|
|
52
|
+
users = _api_tokens()
|
|
53
|
+
if users:
|
|
54
|
+
presented = (request.headers.get("x-proef-token")
|
|
55
|
+
or request.headers.get("x-bionexus-token") or "")
|
|
56
|
+
who = next((u for t, u in users.items()
|
|
57
|
+
if hmac.compare_digest(t, presented)), None)
|
|
58
|
+
if who is None:
|
|
59
|
+
return JSONResponse({"detail": "API token required"}, 401)
|
|
60
|
+
request.state.user = who
|
|
61
|
+
return await call_next(request)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _api_tokens() -> dict[str, str]:
|
|
65
|
+
"""token -> person. PROEF_API_TOKENS="alice:tok1,bob:tok2" gives
|
|
66
|
+
per-person identity (approvals are attributed to the token's owner);
|
|
67
|
+
the single PROEF_API_TOKEN maps to the user 'operator'. No tokens
|
|
68
|
+
configured = open local mode."""
|
|
69
|
+
import os
|
|
70
|
+
out: dict[str, str] = {}
|
|
71
|
+
for part in (os.environ.get("PROEF_API_TOKENS") or "").split(","):
|
|
72
|
+
name, sep, tok = part.strip().partition(":")
|
|
73
|
+
if sep and name and tok:
|
|
74
|
+
out[tok] = name
|
|
75
|
+
single = os.environ.get("PROEF_API_TOKEN")
|
|
76
|
+
if single:
|
|
77
|
+
out.setdefault(single, "operator")
|
|
78
|
+
return out
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
from proef.api.v1 import router as v1_router # noqa: E402
|
|
82
|
+
app.include_router(v1_router)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@app.get("/api/system/health")
|
|
86
|
+
def health() -> dict:
|
|
87
|
+
return {"ok": True, "provenance_db": Path("proef.db").exists()}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
_web_dist = Path(__file__).resolve().parents[3] / "web" / "dist"
|
|
91
|
+
if _web_dist.exists(): # pragma: no cover
|
|
92
|
+
from fastapi.staticfiles import StaticFiles
|
|
93
|
+
app.mount("/assets", StaticFiles(directory=str(_web_dist / "assets")),
|
|
94
|
+
name="spa-assets")
|
|
95
|
+
|
|
96
|
+
@app.get("/{full_path:path}", include_in_schema=False)
|
|
97
|
+
def spa(full_path: str):
|
|
98
|
+
"""BrowserRouter deep links: real files serve, everything else
|
|
99
|
+
(non-API client routes like /experiments/<eid>) gets the SPA shell.
|
|
100
|
+
Registered last — concrete /api routes above always win."""
|
|
101
|
+
if full_path.startswith("api/") or full_path == "api":
|
|
102
|
+
raise HTTPException(404, "no such endpoint")
|
|
103
|
+
candidate = (_web_dist / full_path).resolve()
|
|
104
|
+
if (full_path and candidate.is_file()
|
|
105
|
+
and candidate.is_relative_to(_web_dist.resolve())):
|
|
106
|
+
return FileResponse(candidate)
|
|
107
|
+
return FileResponse(_web_dist / "index.html")
|