Babu09 commited on
Commit
fdbad60
·
verified ·
1 Parent(s): 6a715e0

Mat2Bot front: one box, the story (no engine code)

Browse files
Files changed (7) hide show
  1. Dockerfile +13 -0
  2. README.md +17 -6
  3. app.py +171 -0
  4. requirements.txt +2 -0
  5. story/story.css +48 -0
  6. story/story.html +39 -0
  7. story/story.js +155 -0
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The public front page of Mat2Bot on a Hugging Face Space (Docker SDK): one box, the story. No engine code here: it
2
+ # forwards the page's calls to the private engine Space with a read token kept as the Space secret ENGINE_TOKEN.
3
+ FROM python:3.12-slim
4
+ ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1
5
+ RUN useradd -m -u 1000 user
6
+ WORKDIR /home/user/app
7
+ COPY --chown=user requirements.txt .
8
+ RUN pip install -r requirements.txt
9
+ COPY --chown=user . .
10
+ USER user
11
+ ENV HOME=/home/user
12
+ EXPOSE 7860
13
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,10 +1,21 @@
1
  ---
2
- title: Mat2Bot Ask
3
- emoji: 🐨
4
- colorFrom: pink
5
- colorTo: gray
6
  sdk: docker
7
- pinned: false
 
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Mat2Bot
3
+ emoji: 🧪
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: docker
7
+ app_port: 7860
8
+ pinned: true
9
+ license: mit
10
+ short_description: Type a material; see how Mat2Bot would make it, step by step
11
  ---
12
 
13
+ # Mat2Bot: how would you make it?
14
+
15
+ One box: a material by name, formula or crystal file. Mat2Bot looks for published ways to make it, checks the chemistry,
16
+ writes a recipe, says who could run it, and shows every doubt and every source, in eight plain steps, with the full
17
+ trail behind one link. When it cannot, it says so.
18
+
19
+ This page holds no engine code: it forwards the page's calls to a private engine with a key kept as a secret. The
20
+ engine's seven calibration cases and three use cases, with their reports and sealed packages, are in the public
21
+ explorer linked at the top.
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The public front page of Mat2Bot: one box, the story.
2
+
3
+ A small service with no engine code. It serves the one-box page (the same story.html/js/css the engine serves), turns a
4
+ material's name into a formula with PubChem, and forwards the few calls the page makes (/api/target, /api/plan, a
5
+ plan's trace, audit, report and package) to the private engine Space with a read token kept as a secret
6
+ (ENGINE_TOKEN). Visitors never see the token or the engine's code. A per-visitor limit keeps the small engine from
7
+ being flooded.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import html
12
+ import json
13
+ import os
14
+ import re
15
+ import time
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+ from collections import defaultdict, deque
20
+ from pathlib import Path
21
+
22
+ from fastapi import FastAPI, HTTPException, Request
23
+ from fastapi.responses import HTMLResponse, JSONResponse, Response
24
+
25
+ HERE = Path(__file__).resolve().parent
26
+ ENGINE = os.environ.get("ENGINE_URL", "https://babu09-mat2bot.hf.space").rstrip("/")
27
+ TOKEN = os.environ.get("ENGINE_TOKEN", "")
28
+ EXPLORER = os.environ.get("EXPLORER_URL", "https://babu09-mat2bot-explorer.static.hf.space")
29
+ PUBCHEM = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{}/property/MolecularFormula/JSON"
30
+ USER_AGENT = "Mat2Bot-front/1 (research software)"
31
+ PER_VISITOR, WINDOW = 6, 600.0 # plans per visitor per window
32
+ MAX_BODY = 262144
33
+ PID = re.compile(r"^web-[0-9a-f]{12}$")
34
+ _seen: dict[str, deque] = defaultdict(deque)
35
+ app = FastAPI(title="Mat2Bot", docs_url=None, redoc_url=None)
36
+
37
+
38
+ def _assets() -> dict[str, str]:
39
+ return {k: (HERE / "story" / f"story.{k}").read_text(encoding="utf-8") for k in ("html", "js", "css")}
40
+
41
+
42
+ def fill_story(assets: dict[str, str], *, api_base: str, nav: dict[str, str], engine: str) -> str:
43
+ """The same filling as mat2bot.trace.page.fill_story (kept in step by a test there)."""
44
+ cfg = json.dumps({"api_base": api_base, "engine": engine}, ensure_ascii=False).replace("</", "<\\/")
45
+ links = "".join(f'<a href="{html.escape(url)}">{html.escape(text)}</a>' for text, url in nav.items())
46
+ return (assets["html"].replace("__CSS__", assets["css"]).replace("__CONFIG__", cfg).replace("__NAV__", links)
47
+ .replace("__JS__", assets["js"].replace("</script", "<\\/script")))
48
+
49
+
50
+ def _engine(path: str, data: bytes | None = None, *, content_type: str = "application/json", timeout: float = 180.0) -> tuple[int, bytes, str]:
51
+ if not TOKEN:
52
+ raise HTTPException(503, "the engine is not connected yet (no ENGINE_TOKEN): the owner has to add the secret")
53
+ req = urllib.request.Request(ENGINE + path, data=data, method="POST" if data is not None else "GET",
54
+ headers={"Authorization": f"Bearer {TOKEN}", "User-Agent": USER_AGENT, **({"Content-Type": content_type} if data else {})})
55
+ try:
56
+ with urllib.request.urlopen(req, timeout=timeout) as r:
57
+ return r.status, r.read(), r.headers.get("Content-Type", "")
58
+ except urllib.error.HTTPError as e:
59
+ return e.code, e.read(), e.headers.get("Content-Type", "")
60
+ except urllib.error.URLError as e:
61
+ raise HTTPException(502, f"the engine did not answer: {e.reason}") from None
62
+
63
+
64
+ def _client(request: Request) -> str:
65
+ fwd = request.headers.get("x-forwarded-for", "")
66
+ return (fwd.split(",")[0].strip() if fwd else (request.client.host if request.client else "?"))[:64]
67
+
68
+
69
+ def _throttle(request: Request) -> None:
70
+ now = time.monotonic()
71
+ q = _seen[_client(request)]
72
+ while q and now - q[0] > WINDOW:
73
+ q.popleft()
74
+ if len(q) >= PER_VISITOR:
75
+ raise HTTPException(429, f"you can plan {PER_VISITOR} materials per {WINDOW / 60:g} minutes here: try again in a few minutes")
76
+ q.append(now)
77
+
78
+
79
+ def resolve_name(query: str) -> tuple[str, str]:
80
+ """(formula, name) for a material: a formula is taken as it is; a name is looked up in PubChem (its Hill formula,
81
+ which the engine reads in any element order)."""
82
+ q = query.strip()
83
+ if re.fullmatch(r"[A-Z][a-z]?\d*(?:\(?[A-Z][a-z]?\d*\)?\d*)*(?:·\d*H2O)?", q):
84
+ return q, ""
85
+ url = PUBCHEM.format(urllib.parse.quote(q))
86
+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
87
+ try:
88
+ with urllib.request.urlopen(req, timeout=20) as r:
89
+ d = json.loads(r.read())
90
+ except urllib.error.HTTPError as e:
91
+ if e.code == 404:
92
+ raise HTTPException(422, f"PubChem knows no material called {q!r}: try its formula") from None
93
+ raise HTTPException(502, f"PubChem did not answer ({e.code}): try the formula instead") from None
94
+ except urllib.error.URLError as e:
95
+ raise HTTPException(502, f"PubChem did not answer ({e.reason}): try the formula instead") from None
96
+ props = d.get("PropertyTable", {}).get("Properties", [])
97
+ if not props or not props[0].get("MolecularFormula"):
98
+ raise HTTPException(422, f"PubChem has no formula for {q!r}: try the formula")
99
+ formula = props[0]["MolecularFormula"]
100
+ if re.search(r"[+-]", formula) or "." in formula: # an ion or a mixture: not a solid to plan
101
+ raise HTTPException(422, f"{q!r} reads as {formula}: give the neutral solid's formula")
102
+ return formula, q
103
+
104
+
105
+ @app.get("/", response_class=HTMLResponse)
106
+ def home() -> HTMLResponse:
107
+ return HTMLResponse(fill_story(_assets(), api_base="", nav={"Worked examples": EXPLORER, "How it works": EXPLORER + "/#how"},
108
+ engine="Planned live by Mat2Bot (private engine); the code stays private"))
109
+
110
+
111
+ @app.get("/health")
112
+ def health() -> JSONResponse:
113
+ return JSONResponse({"status": "ok", "engine_connected": bool(TOKEN)})
114
+
115
+
116
+ @app.post("/api/target")
117
+ async def api_target(request: Request) -> Response:
118
+ raw = await request.body()
119
+ if len(raw) > MAX_BODY:
120
+ raise HTTPException(413, "too large")
121
+ try:
122
+ doc = json.loads(raw)
123
+ assert isinstance(doc, dict)
124
+ except Exception:
125
+ raise HTTPException(422, "a JSON object") from None
126
+ query = str(doc.get("query") or "").strip()[:80]
127
+ body: dict = {}
128
+ if doc.get("cif_text"):
129
+ body["cif_text"] = doc["cif_text"]
130
+ body["query"] = query
131
+ else:
132
+ if not query:
133
+ raise HTTPException(422, "give a material")
134
+ formula, name = resolve_name(query)
135
+ body["query"] = formula
136
+ status, data, ctype = _engine("/api/target", json.dumps(body).encode())
137
+ if status == 200 and not doc.get("cif_text"):
138
+ out = json.loads(data)
139
+ out["name"] = name or out.get("name", "")
140
+ return JSONResponse(out)
141
+ return Response(data, status_code=status, media_type=ctype or "application/json")
142
+
143
+
144
+ @app.post("/api/plan")
145
+ async def api_plan(request: Request) -> Response:
146
+ _throttle(request)
147
+ raw = await request.body()
148
+ if len(raw) > MAX_BODY:
149
+ raise HTTPException(413, "too large")
150
+ status, data, ctype = _engine("/api/plan", raw)
151
+ return Response(data, status_code=status, media_type=ctype or "application/json")
152
+
153
+
154
+ @app.get("/p/{pid}")
155
+ @app.get("/p/{pid}/{what}")
156
+ def plan_pages(pid: str, what: str = "") -> Response:
157
+ if not PID.match(pid) or what not in ("", "trace", "trace.json", "audit.json", "package.zip", "audit"):
158
+ raise HTTPException(404, "no such page")
159
+ status, data, ctype = _engine(f"/p/{pid}" + (f"/{what}" if what else ""), timeout=300.0)
160
+ if status != 200:
161
+ raise HTTPException(status if status in (404, 429) else 502, "the engine could not serve this page")
162
+ text_types = ("text/html", "application/json")
163
+ if any(ctype.startswith(t) for t in text_types):
164
+ page = data.decode("utf-8", "replace")
165
+ page = page.replace(f'href="/p/{pid}', f'href="/p/{pid}').replace('href="/"', 'href="./"').replace('href="/docs/', f'href="{EXPLORER}/#')
166
+ return Response(page, media_type=ctype)
167
+ headers = {"Content-Disposition": f'attachment; filename="mat2bot-{pid}.zip"'} if what == "package.zip" else {}
168
+ return Response(data, media_type=ctype or "application/octet-stream", headers=headers)
169
+
170
+
171
+ __all__ = ["app", "fill_story", "resolve_name"]
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastapi==0.162.0
2
+ uvicorn==0.54.0
story/story.css ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* The one-box page and its story: plain words, one column, phone first. Light and dark. */
2
+ :root{--bg:#fbfaf7;--fg:#1d1d1b;--muted:#5d5b55;--line:#dedad2;--card:#ffffff;--head:#f1eee7;--accent:#2f5d8a;--ok:#2e7d32;--warn:#b26a00;
3
+ --bad:#c62828;--off:#8a8780;--radius:12px}
4
+ @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#161615;--fg:#ecebe6;--muted:#a9a69e;--line:#3a3935;--card:#1f1f1d;--head:#22211f;
5
+ --accent:#8db6e0;--ok:#7bc47f;--warn:#e0a64a;--bad:#ef7b7b;--off:#8a8780}}
6
+ :root[data-theme="dark"]{--bg:#161615;--fg:#ecebe6;--muted:#a9a69e;--line:#3a3935;--card:#1f1f1d;--head:#22211f;--accent:#8db6e0;--ok:#7bc47f;
7
+ --warn:#e0a64a;--bad:#ef7b7b;--off:#8a8780}
8
+ *{box-sizing:border-box}html{-webkit-text-size-adjust:100%}
9
+ body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
10
+ a{color:var(--accent)}button{font:inherit;cursor:pointer}
11
+ #story-app{max-width:860px;margin:0 auto;padding:16px 16px 56px}
12
+ .st-head{display:flex;justify-content:space-between;align-items:baseline;flex-wrap:wrap;gap:.4em 1em;margin-bottom:1.2em}
13
+ .st-brand{font-weight:800;text-decoration:none;color:var(--fg);font-size:1.1rem}.st-nav a{margin-left:1em;text-decoration:none;font-size:.92rem}
14
+ h1{font-size:1.9rem;margin:.2em 0 .3em;line-height:1.2}.st-lead{color:var(--muted);max-width:62ch;margin:0 0 1em}
15
+ .st-box{display:grid;gap:.3em}.st-box span{font-size:.9rem;color:var(--muted)}
16
+ input,textarea{font:inherit;padding:.7em .8em;border:1px solid var(--line);border-radius:10px;background:var(--card);color:var(--fg);width:100%}
17
+ input:focus,textarea:focus{outline:2px solid var(--accent);outline-offset:1px}
18
+ #ask{display:grid;gap:.8em}#go{justify-self:start;padding:.7em 1.4em;border-radius:999px;border:1px solid var(--accent);background:var(--accent);
19
+ color:var(--bg);font-weight:700}#go[disabled]{opacity:.6;cursor:wait}
20
+ .st-cif summary{cursor:pointer;color:var(--accent);font-size:.92rem}.st-cif textarea{margin-top:.5em;font-family:ui-monospace,monospace;font-size:.85rem}
21
+ .st-cif input[type=file]{margin-top:.4em;border:0;padding:0}
22
+ .st-examples{font-size:.9rem;color:var(--muted);margin:0}.st-examples button{border:1px solid var(--line);background:var(--card);color:var(--fg);
23
+ border-radius:999px;padding:.15em .7em;margin:.15em .1em}
24
+ .st-status{min-height:1.4em;margin:.6em 0;color:var(--muted)}.st-status.err{color:var(--bad)}
25
+ .st-forms{display:grid;gap:.5em}.st-forms .q{margin:.4em 0 0;font-weight:600}
26
+ .st-forms .opts{display:flex;flex-wrap:wrap;gap:.5em}.st-forms .opts button{border:1px solid var(--line);background:var(--card);color:var(--fg);
27
+ border-radius:10px;padding:.5em .9em;text-align:left;display:grid;gap:.1em}.st-forms .opts button small{color:var(--muted)}
28
+ .st-forms .opts button.pick{border-color:var(--accent)}
29
+ /* the story */
30
+ .st-story{margin-top:1.6em;display:grid;gap:.8em}
31
+ .st-step{border:1px solid var(--line);border-radius:var(--radius);background:var(--card);padding:.9em 1em}
32
+ .st-step .n{font-size:.78rem;color:var(--muted);letter-spacing:.06em;text-transform:uppercase}
33
+ .st-step h2{font-size:1.15rem;margin:.1em 0 .4em}
34
+ .st-step .sum{margin:0 0 .4em;max-width:70ch}.st-step .sum b{font-weight:600}
35
+ .st-step details{margin-top:.4em}.st-step summary{cursor:pointer;color:var(--accent);font-size:.92rem}
36
+ .st-step ul{margin:.4em 0 0;padding-left:1.2em}.st-step li{margin:.25em 0}.st-step li small{color:var(--muted)}
37
+ .chip{display:inline-block;font-size:.8rem;padding:.12em .6em;border-radius:999px;border:1px solid var(--line);background:var(--head);white-space:nowrap;
38
+ vertical-align:middle;line-height:1.5;margin-right:.3em}
39
+ .chip.ok{border-color:var(--ok);color:var(--ok)}.chip.warn{border-color:var(--warn);color:var(--warn)}.chip.bad{border-color:var(--bad);color:var(--bad)}
40
+ .chip.off{border-color:var(--off);color:var(--off)}
41
+ .st-links{display:flex;flex-wrap:wrap;gap:.6em;margin-top:.4em}
42
+ .st-links a{text-decoration:none;padding:.55em 1em;border-radius:999px;border:1px solid var(--line);background:var(--card);color:var(--fg);font-weight:600;font-size:.92rem}
43
+ .st-links a.primary{background:var(--accent);color:var(--bg);border-color:var(--accent)}
44
+ .st-foot{color:var(--muted);font-size:.86rem;margin-top:2.4em}
45
+ .st-why{background:var(--head);border-radius:8px;padding:.4em .7em;margin:.3em 0;font-size:.92rem}
46
+ .st-muted{color:var(--muted)}
47
+ .st-pre{white-space:pre-wrap;font-family:ui-monospace,monospace;font-size:.84rem}
48
+ @media (max-width:600px){h1{font-size:1.5rem}}
story/story.html ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <title>Mat2Bot: how would you make it?</title>
7
+ <style>__CSS__</style>
8
+ </head>
9
+ <body>
10
+ <script id="story-config" type="application/json">__CONFIG__</script>
11
+ <main id="story-app">
12
+ <header class="st-head">
13
+ <a class="st-brand" href="./">Mat2Bot</a>
14
+ <nav class="st-nav">__NAV__</nav>
15
+ </header>
16
+ <section class="st-ask">
17
+ <h1>How would you make it?</h1>
18
+ <p class="st-lead">Type a material, by name or formula, or paste a crystal file (CIF). Mat2Bot looks for published ways to make it,
19
+ checks the chemistry, writes a recipe, says who could run it, and shows every doubt and every source. When it cannot, it says so.</p>
20
+ <form id="ask" autocomplete="off">
21
+ <label class="st-box"><span>Material</span>
22
+ <input id="query" name="query" placeholder="zinc oxide, KCl, CaCO3 …" maxlength="80" required></label>
23
+ <details class="st-cif"><summary>…or paste a crystal file (CIF)</summary>
24
+ <textarea id="cif" name="cif" rows="6" placeholder="data_… (paste the text of a .cif file)"></textarea>
25
+ <input id="ciffile" type="file" accept=".cif,text/plain"></details>
26
+ <button type="submit" id="go">Show me how</button>
27
+ <p class="st-examples">Try: <button type="button" data-try="zinc oxide">zinc oxide</button> <button type="button" data-try="potassium chloride">potassium chloride</button>
28
+ <button type="button" data-try="CaCO3">CaCO3</button> <button type="button" data-try="sodium peroxide">sodium peroxide</button></p>
29
+ </form>
30
+ <div id="status" class="st-status" aria-live="polite"></div>
31
+ <div id="forms" class="st-forms"></div>
32
+ </section>
33
+ <section id="story" class="st-story" hidden></section>
34
+ <footer class="st-foot">Plans are arguments with their evidence, not instructions to run: no experiment is authorized without a named person's sign-off.
35
+ <span id="st-engine"></span></footer>
36
+ </main>
37
+ <script>__JS__</script>
38
+ </body>
39
+ </html>
story/story.js ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* The one-box page: a material by name, formula or CIF -> the engine plans it -> the story, in eight plain steps, read
2
+ from the plan's own trace.json (and the live audit.json). Every sentence here is written from records the trace
3
+ holds; when the trace holds nothing for a step, the step says so. Plain JS, no library. */
4
+ (function () {
5
+ "use strict";
6
+ const CFG = JSON.parse(document.getElementById("story-config").textContent || "{}");
7
+ const API = (CFG.api_base || "").replace(/\/$/, "");
8
+ const $ = (s) => document.querySelector(s);
9
+ const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
10
+ const status = (msg, err) => { const el = $("#status"); el.textContent = msg; el.classList.toggle("err", !!err); };
11
+ if (CFG.engine) $("#st-engine").textContent = ` ${CFG.engine}.`;
12
+ // ---------------------------------------------------------------- asking
13
+ const FORMULA = /^[A-Z][a-z]?\d*(\(?[A-Z][a-z]?\d*\)?\d*)*(·\d*H2O)?$/;
14
+ async function post(path, body) {
15
+ const r = await fetch(API + path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
16
+ const text = await r.text();
17
+ let data = null;
18
+ try { data = JSON.parse(text); } catch { /* not JSON */ }
19
+ if (!r.ok) throw new Error((data && (data.detail || data.error)) || text.slice(0, 200) || `HTTP ${r.status}`);
20
+ return data;
21
+ }
22
+ let current = null; // {query, formula, cif, forms, pick}
23
+ async function ask(query, cif) {
24
+ $("#story").hidden = true; $("#forms").innerHTML = "";
25
+ $("#go").disabled = true;
26
+ try {
27
+ status(cif ? "Reading the crystal file…" : "Looking the material up…");
28
+ const t = await post("/api/target", cif ? { cif_text: cif, query } : { query });
29
+ current = { query, formula: t.formula, cif, forms: t.forms || [], pick: null, name: t.name || "", phase: t.phase || null };
30
+ if (t.message) status(t.message);
31
+ if (current.phase) { await plan(current.phase); return; } // a CIF names its own form
32
+ const ambient = current.forms.filter((f) => f.ambient);
33
+ if (current.forms.length === 0) { await plan(null); return; } // unknown to the registry: the engine says what it can
34
+ if (ambient.length === 1) { await plan(ambient[0]); return; }
35
+ askForm(ambient.length ? ambient : current.forms);
36
+ } catch (e) { status(`Could not start: ${e.message}`, true); }
37
+ finally { $("#go").disabled = false; }
38
+ }
39
+ function askForm(forms) {
40
+ status(`${current.name || current.formula} has ${forms.length} known forms. Which one do you mean?`);
41
+ $("#forms").innerHTML = `<p class="q">Which form?</p><div class="opts">${forms.map((f, i) => `<button type="button" data-form="${i}"><b>${esc(f.name)}</b><small>${esc(f.note || (f.ambient ? "forms at normal pressure" : "needs special conditions"))}${f.symbol ? ` · ${esc(f.symbol)}` : ""}</small></button>`).join("")}</div>`;
42
+ $("#forms").querySelectorAll("button[data-form]").forEach((b) => b.addEventListener("click", () => { b.classList.add("pick"); plan(forms[Number(b.dataset.form)]); }));
43
+ }
44
+ async function plan(form) {
45
+ $("#go").disabled = true;
46
+ try {
47
+ status(`Planning ${current.name || current.formula}${form ? ` (${form.name})` : ""}: this takes a few seconds…`);
48
+ const target = { formula: current.formula };
49
+ if (form) target.phase = { name: form.name, ...(form.number ? { space_group_number: form.number } : {}) };
50
+ const req = { schema: "mat2bot/request/1", request_id: "x", title: current.query.slice(0, 80), target, labs: ["bench", "vialbot"],
51
+ batch: { product_amount: "1 mmol" }, ...(current.cif ? { cif_text: current.cif } : {}) };
52
+ const out = await post("/api/plan", req);
53
+ const pid = out.report.split("/").pop();
54
+ status("Reading the plan's records…");
55
+ const trace = await (await fetch(`${API}/p/${pid}/trace.json`)).json();
56
+ let audit = null;
57
+ try { audit = await (await fetch(`${API}/p/${pid}/audit.json`, { cache: "no-store" })).json(); } catch { /* shown as not run */ }
58
+ render(trace, audit, pid, out);
59
+ status("");
60
+ $("#story").scrollIntoView({ behavior: "smooth", block: "start" });
61
+ } catch (e) { status(`Could not plan: ${e.message}`, true); }
62
+ finally { $("#go").disabled = false; }
63
+ }
64
+ $("#ask").addEventListener("submit", (ev) => { ev.preventDefault(); const q = $("#query").value.trim(); const cif = $("#cif").value.trim(); if (q || cif) ask(q || "a crystal file", cif || null); });
65
+ document.querySelectorAll("button[data-try]").forEach((b) => b.addEventListener("click", () => { $("#query").value = b.dataset.try; $("#cif").value = ""; ask(b.dataset.try, null); }));
66
+ $("#ciffile").addEventListener("change", async (ev) => { const f = ev.target.files[0]; if (f) { $("#cif").value = await f.text(); if (!$("#query").value.trim()) $("#query").value = f.name.replace(/\.cif$/i, ""); } });
67
+ // ---------------------------------------------------------------- the story
68
+ const CAT = { STRONGLY_SUPPORTED: ["strongly supported", "ok"], PARTIALLY_SUPPORTED: ["supported, with caveats", "warn"], HYPOTHETICAL: ["only a hypothesis", "warn"], BLOCKED: ["rejected", "bad"] };
69
+ const LAB = { FULLY_SUPPORTED: ["the robot could run all of it", "ok"], HYBRID: ["robot and people together", "ok"], INCOMPLETE: ["not ready: something is missing", "warn"], BLOCKED: ["cannot be done there", "bad"] };
70
+ const DOUBT = { open: ["still open", "warn"], eliminated: ["ruled out", "ok"], sustained: ["confirmed", "bad"] };
71
+ const chip = (w) => w ? `<span class="chip ${w[1]}">${esc(w[0])}</span>` : "";
72
+ const li = (items, max) => items.length ? `<ul>${items.slice(0, max || 50).map((x) => `<li>${x}</li>`).join("")}${items.length > (max || 50) ? `<li class="st-muted">and ${items.length - (max || 50)} more in the full trail</li>` : ""}</ul>` : "";
73
+ const more = (label, inner) => inner ? `<details><summary>${esc(label)}</summary>${inner}</details>` : "";
74
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
75
+ function render(t, audit, pid, out) {
76
+ const nodes = new Map(t.nodes.map((n) => [n.node_id, n]));
77
+ const byKind = (k) => t.nodes.filter((n) => n.kind === k);
78
+ const OUT = new Map(); t.edges.forEach((e) => (OUT.get(e.source) || OUT.set(e.source, []).get(e.source)).push(e));
79
+ const target = nodes.get("target") || { label: t.request_id, detail: {} };
80
+ const d = target.detail || {};
81
+ const findings = byKind("finding");
82
+ const routes = byKind("route").sort((a, b) => (a.detail.rank || 9) - (b.detail.rank || 9));
83
+ const rivals = byKind("rival");
84
+ const best = routes[0] || null;
85
+ const ofRoute = (k, n) => t.nodes.filter((x) => x.kind === k && n && x.detail && x.detail.route === n.detail.route);
86
+ const links = { trail: `${API}/p/${pid}/trace`, report: `${API}/p/${pid}`, zip: `${API}/p/${pid}/package.zip` };
87
+ const steps = [];
88
+ // 1 what you asked for
89
+ const forms = (d.known_phases || []).map((p) => esc(p.name));
90
+ const idw = { known_phase: "a known material and a known form", known_composition_phase_unspecified: "a known material", known_composition_other_phase: "a known material, but not this form",
91
+ unknown_composition: "not found in any database it checked", unresolved: "not found in the databases it holds" }[d.identity] || d.identity;
92
+ const hz = t.nodes.filter((n) => n.node_id.startsWith("hazard:target:"));
93
+ const DEMAND = { hard_fail: "never an unattended robot step", human_only: "a person handles it", flammable: "flammable", note: "a note only" };
94
+ const handling = (h) => { const d = h.detail || {}; const codes = (d.codes || []).join(", "); const dem = (d.demands || []).map((x) => DEMAND[x] || x).join("; "); return codes ? `${esc(codes)}${dem ? ` (${esc(dem)})` : ""}` : "no hazard classification found"; };
95
+ steps.push(["What you asked for", `<b>${esc(target.label)}</b>: ${esc(idw)}.${forms.length ? ` Known forms: ${forms.join(", ")}.` : ""}${hz.length ? ` Handling it, from its safety classification: ${hz.map(handling).join("; ")}.` : ""}`,
96
+ more("More about the target", `<p>${esc(d.novelty || "")}</p>${li([...(d.missing || []).map((m) => `Not available: ${esc(m)}`), ...byKind("claim").filter((c) => c.node_id.startsWith("gate:")).map((g) => `${esc(g.label)}`)])}`)]);
97
+ // 2 what it knows
98
+ const ev = byKind("evidence");
99
+ const refused = findings.find((f) => f.detail.code === "NO_SUPPORTED_FAMILY");
100
+ steps.push(["What Mat2Bot knows about it", ev.length ? `It found <b>${plural(ev.length, "published record", "published records")}</b> about this material (papers and databases it has read and checked).` : refused ? `Nothing it can use: no published way of making this material is in its evidence, and its planned recipe families do not cover it.` : "No published record about this material in its evidence.",
101
+ more("The records", li(ev.map((e) => `${esc(e.label)}${e.detail.citation ? ` <small>— ${esc(e.detail.citation)}</small>` : ""}${e.detail.doi ? ` <a href="https://doi.org/${esc(e.detail.doi)}" target="_blank" rel="noopener">doi</a>` : ""} ${chip(e.evidence === "verified" ? ["quote verified", "ok"] : ["not verified", "warn"])}`), 12))]);
102
+ // 3 routes
103
+ const why = (r) => (OUT.get(r.node_id) || []).filter((e) => e.kind === "rejected_for").map((e) => nodes.get(e.target)).filter(Boolean).map((x) => esc(x.label.replace(/^the precedent's product is a different phase from the target \(here: /, "").replace(/\)$/, "")));
104
+ const routeLine = (r) => `<b>${esc((r.detail.precursors || []).map((p) => p.split(" (")[0]).join(" + ") || r.label)}</b>${r.detail.category ? ` ${chip(CAT[r.detail.category])}` : ""} <small>${esc(r.label.replace(/^Route \d+: /, ""))}</small>`;
105
+ const noRoute = findings.find((f) => f.detail.code === "NO_ROUTE");
106
+ steps.push(["The routes it considered", routes.length ? `It proposes <b>${plural(routes.length, "route", "routes")}</b>${rivals.length ? ` and sets aside ${rivals.length}` : ""}. The best one: ${routeLine(best)}.` : noRoute ? `It proposes none: every published route it knows (${rivals.length}) makes another form of this material, and each is set aside with its reason.` : refused ? "None: it stops here rather than invent one." : "None.",
107
+ more(routes.length + rivals.length ? "All routes, and why not the others" : "", li([...routes.map(routeLine), ...rivals.map((r) => `<span class="st-muted">set aside:</span> ${esc(r.label.replace(/^Rejected: /, ""))}${why(r).length ? `<div class="st-why">Why not: ${why(r).join("; ")}</div>` : ""}`)]))]);
108
+ // 4 science
109
+ const calcs = ofRoute("calculation", best).filter((c) => c.detail && "value" in c.detail);
110
+ const models = ofRoute("model_output", best);
111
+ const refusedModels = models.filter((m) => m.execution === "refused");
112
+ steps.push(["What the science says", best ? `${calcs.length ? `<b>${plural(calcs.length, "number", "numbers")}</b> computed from cited data${refusedModels.length ? `; <b>${plural(refusedModels.length, "model", "models")}</b> refused to answer outside their validity, rather than guess` : ""}.` : refusedModels.length ? `No number: ${plural(refusedModels.length, "model", "models")} refused to answer outside their validity rather than guess.` : "No number computed for this route."}` : "Nothing to compute: there is no route.",
113
+ more(calcs.length + models.length ? "The numbers and the refusals" : "", li([...calcs.map((c) => `${esc(c.label)} <small>(${esc(c.detail.method || "")}${(c.detail.sources || []).length ? `; source: ${esc(c.detail.sources[0].citation || c.detail.sources[0].id || "")}` : ""})</small>`), ...refusedModels.map((m) => `<span class="st-muted">refused:</span> ${esc(m.label.replace(/^[^ ]+ refused: /, ""))}`)], 14))]);
114
+ // 5 recipe
115
+ const proc = t.nodes.find((n) => n.kind === "grouping" && best && n.detail.route === best.detail.route);
116
+ const stepNodes = ofRoute("step", best);
117
+ const open = stepNodes.filter((s) => s.science);
118
+ steps.push(["The recipe", best ? `<b>${plural(stepNodes.length, "step", "steps")}</b>${open.length ? `, of which ${open.length} leave a value open (no source gives it; a person must choose it)` : ", every value from a source or a stated calculation"}.` : "No recipe without a route.",
119
+ more(proc ? "The steps" : "", proc ? `${li((proc.detail.level1 || []).map((s) => esc(s)))}${(proc.detail.materials || []).length ? `<p><b>Materials:</b> ${proc.detail.materials.map(esc).join("; ")}</p>` : ""}${more("Every step", li(stepNodes.map((s) => `${esc(s.label)}${s.science ? ` ${chip(["value open", "warn"])}` : ""}`)))}` : "")]);
120
+ // 6 who can make it
121
+ const labs = ofRoute("laboratory", best);
122
+ const needs = ofRoute("capability", best).filter((c) => c.lab === "missing");
123
+ const gate = t.nodes.find((n) => n.node_id === `gateS:${best && best.detail.route}`);
124
+ const hazards = t.nodes.filter((n) => best && n.node_id.startsWith(`hazard:${best.detail.route}:`));
125
+ steps.push(["Who could make it", labs.length ? labs.map((l) => `<b>${esc(l.label.split(":")[0])}</b>: ${chip(LAB[l.lab])}`).join(" · ") : best ? "No laboratory was asked." : "Nobody is asked to make it: there is no route.",
126
+ more(labs.length ? "Why, and what each lab lacks" : "", li([...labs.map((l) => `${esc(l.label)} <small>— ${esc(l.detail.reason || "")}</small>`), ...needs.map((n) => `<span class="st-muted">missing:</span> ${esc(n.label)}`), ...(gate ? [`${esc(gate.label)}`] : []), ...hazards.map((h) => `<small>${esc(h.label)}</small>`)]))]);
127
+ // 7 how sure
128
+ const doubts = ofRoute("doubt", best).filter((x) => !x.node_id.includes(":D-route-"));
129
+ const openD = doubts.filter((x) => x.science === "open"), elim = doubts.filter((x) => x.science === "eliminated"), sus = doubts.filter((x) => x.science === "sustained");
130
+ steps.push(["How sure it is", best ? `${chip(CAT[best.detail.category])} ${esc(best.detail.reason || "")}. Doubts checked: ${openD.length} still open, ${elim.length} ruled out${sus.length ? `, ${sus.length} confirmed` : ""}.` : refused ? `${chip(["not planned", "off"])} Outside what this version plans; it declines rather than guesses.` : noRoute ? `${chip(["no documented route", "off"])} Every known route makes another form.` : "",
131
+ more(doubts.length ? "The doubts" : "", li([...openD, ...sus, ...elim].map((x) => `${chip(DOUBT[x.science])} ${esc(x.label)}`)))]);
132
+ // 8 audit
133
+ const stageAudit = nodes.get("stage:AUDIT");
134
+ const a = audit && audit.verdict ? audit : null;
135
+ steps.push(["Checked by an independent auditor", a ? `${chip(a.verdict === "PASS" ? ["audit PASS", "ok"] : a.verdict === "FAIL" ? ["audit FAIL", "bad"] : ["audit unknown", "warn"])} ${plural(a.checks.filter((c) => c.verdict === "PASS").length, "check passed", "checks passed")}${a.checks.some((c) => c.verdict === "FAIL") ? `, ${a.checks.filter((c) => c.verdict === "FAIL").length} failed` : ""}; ${esc(a.when || "")}. The auditor never calls the planner: it re-derives the numbers from the package alone.` : `${chip(["not run", "off"])} ${esc((stageAudit && stageAudit.detail.message) || "the package has not been audited")}`,
136
+ more(a ? "Every check" : "", a ? li(a.checks.map((c) => `${chip(c.verdict === "PASS" ? ["pass", "ok"] : c.verdict === "FAIL" ? ["fail", "bad"] : ["n/a", "off"])} ${esc(c.name)}${c.detail ? ` <small>— ${esc(c.detail)}</small>` : ""}`)) : "")]);
137
+ $("#story").innerHTML = steps.map(([h, sum, det], i) => `<section class="st-step"><span class="n">Step ${i + 1} of 8</span><h2>${esc(h)}</h2><p class="sum">${sum}</p>${det}</section>`).join("")
138
+ + `<div class="st-links"><a class="primary" href="${esc(links.trail)}">Open the full trail: every record, clickable</a><a href="${esc(links.report)}">Technical report</a><a href="${esc(links.zip)}" download>Download the sealed package</a></div>`;
139
+ $("#story").hidden = false;
140
+ document.title = `${target.label}: how would you make it? · Mat2Bot`;
141
+ if (history.replaceState) history.replaceState(null, "", `#plan=${encodeURIComponent(pid)}`);
142
+ }
143
+ // reopen a plan from the address bar
144
+ const m = location.hash.match(/^#plan=([\w-]+)$/);
145
+ if (m) {
146
+ (async () => {
147
+ try {
148
+ status("Loading the plan…");
149
+ const trace = await (await fetch(`${API}/p/${m[1]}/trace.json`)).json();
150
+ let audit = null; try { audit = await (await fetch(`${API}/p/${m[1]}/audit.json`, { cache: "no-store" })).json(); } catch { /* not run */ }
151
+ render(trace, audit, m[1], {}); status("");
152
+ } catch (e) { status(`This plan is no longer kept here: plan it again. (${e.message})`, true); }
153
+ })();
154
+ }
155
+ })();