File size: 10,067 Bytes
fdbad60
 
 
 
 
 
 
 
 
 
 
e3d7b60
fdbad60
 
 
 
 
 
 
 
 
 
 
 
 
 
67fee72
fdbad60
67fee72
fdbad60
 
 
 
 
 
 
 
 
 
bcf68b0
 
 
fdbad60
 
 
 
 
 
bcf68b0
 
fdbad60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3d7b60
 
 
 
 
 
 
 
 
 
 
 
 
 
fdbad60
e3d7b60
 
 
 
 
 
 
 
 
 
 
 
 
fdbad60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67fee72
 
 
 
1bc6c97
67fee72
 
fdbad60
 
1bc6c97
67fee72
fdbad60
 
 
e3d7b60
 
fdbad60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""The public front page of Mat2Bot: one box, the story.

A small service with no engine code. It serves the one-box page (the same story.html/js/css the engine serves), turns a
material's name into a formula with PubChem, and forwards the few calls the page makes (/api/target, /api/plan, a
plan's trace, audit, report and package) to the private engine Space with a read token kept as a secret
(ENGINE_TOKEN). Visitors never see the token or the engine's code. A per-visitor limit keeps the small engine from
being flooded.
"""
from __future__ import annotations

import html
import ipaddress
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import defaultdict, deque
from pathlib import Path

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, Response

HERE = Path(__file__).resolve().parent
ENGINE = os.environ.get("ENGINE_URL", "https://babu09-mat2bot-engine.hf.space").rstrip("/")
TOKEN = os.environ.get("ENGINE_TOKEN", "")
EXPLORER = os.environ.get("EXPLORER_URL", "/explore")
PUBCHEM = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{}/property/MolecularFormula/JSON"
USER_AGENT = "Mat2Bot-front/1 (research software)"
PER_VISITOR, WINDOW = 6, 600.0                 # plans per visitor per window
MAX_BODY = 262144
PID = re.compile(r"^web-[0-9a-f]{12}$")
_seen: dict[str, deque] = defaultdict(deque)
app = FastAPI(title="Mat2Bot", docs_url=None, redoc_url=None)


def _assets() -> dict[str, str]:
    out = {k: (HERE / "story" / f"story.{k}").read_text(encoding="utf-8") for k in ("html", "js", "css")}
    out["vjs"], out["vcss"] = (HERE / "story" / "viewer.js").read_text(encoding="utf-8"), (HERE / "story" / "viewer.css").read_text(encoding="utf-8")
    return out


def fill_story(assets: dict[str, str], *, api_base: str, nav: dict[str, str], engine: str) -> str:
    """The same filling as mat2bot.trace.page.fill_story (kept in step by a test there)."""
    cfg = json.dumps({"api_base": api_base, "engine": engine}, ensure_ascii=False).replace("</", "<\\/")
    links = "".join(f'<a href="{html.escape(url)}">{html.escape(text)}</a>' for text, url in nav.items())
    return (assets["html"].replace("__VIEWER_CSS__", assets["vcss"]).replace("__CSS__", assets["css"]).replace("__CONFIG__", cfg)
            .replace("__NAV__", links).replace("__VIEWER_JS__", assets["vjs"].replace("</script", "<\\/script"))
            .replace("__JS__", assets["js"].replace("</script", "<\\/script")))


def _engine(path: str, data: bytes | None = None, *, content_type: str = "application/json", timeout: float = 180.0) -> tuple[int, bytes, str]:
    if not TOKEN:
        raise HTTPException(503, "the engine is not connected yet (no ENGINE_TOKEN): the owner has to add the secret")
    req = urllib.request.Request(ENGINE + path, data=data, method="POST" if data is not None else "GET",
                                 headers={"Authorization": f"Bearer {TOKEN}", "User-Agent": USER_AGENT, **({"Content-Type": content_type} if data else {})})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, r.read(), r.headers.get("Content-Type", "")
    except urllib.error.HTTPError as e:
        return e.code, e.read(), e.headers.get("Content-Type", "")
    except urllib.error.URLError as e:
        raise HTTPException(502, f"the engine did not answer: {e.reason}") from None


def visitor_key(forwarded: str, client_host: str) -> str:
    """The address the per-visitor limit counts: the rightmost public entry of X-Forwarded-For. The proxy appends the
    address it saw, after anything the visitor wrote, so a visitor can prepend entries but never append one; private
    and reserved addresses (the proxy's own hops, or a spoofed one) are skipped. Without a public entry, the connection's."""
    entries = [x.strip() for x in forwarded.split(",") if x.strip()]
    for e in reversed(entries):
        try:
            if ipaddress.ip_address(e).is_global:
                return e[:64]
        except ValueError:
            continue
    return (client_host or "?")[:64]


def _client(request: Request) -> str:
    return visitor_key(request.headers.get("x-forwarded-for", ""), request.client.host if request.client else "")


def _forwarding(request: Request) -> dict:
    """Counts only (no address): how many entries the proxy chain gives and how many of them are public."""
    entries = [x.strip() for x in request.headers.get("x-forwarded-for", "").split(",") if x.strip()]
    public = 0
    for e in entries:
        try:
            public += ipaddress.ip_address(e).is_global
        except ValueError:
            pass
    return {"forwarded_entries": len(entries), "forwarded_public": public, "real_ip_header": "x-real-ip" in request.headers}


def _throttle(request: Request) -> None:
    now = time.monotonic()
    q = _seen[_client(request)]
    while q and now - q[0] > WINDOW:
        q.popleft()
    if len(q) >= PER_VISITOR:
        raise HTTPException(429, f"you can plan {PER_VISITOR} materials per {WINDOW / 60:g} minutes here: try again in a few minutes")
    q.append(now)


def resolve_name(query: str) -> tuple[str, str]:
    """(formula, name) for a material: a formula is taken as it is; a name is looked up in PubChem (its Hill formula,
    which the engine reads in any element order)."""
    q = query.strip()
    if re.fullmatch(r"[A-Z][a-z]?\d*(?:\(?[A-Z][a-z]?\d*\)?\d*)*(?:·\d*H2O)?", q):
        return q, ""
    url = PUBCHEM.format(urllib.parse.quote(q))
    req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            d = json.loads(r.read())
    except urllib.error.HTTPError as e:
        if e.code == 404:
            raise HTTPException(422, f"PubChem knows no material called {q!r}: try its formula") from None
        raise HTTPException(502, f"PubChem did not answer ({e.code}): try the formula instead") from None
    except urllib.error.URLError as e:
        raise HTTPException(502, f"PubChem did not answer ({e.reason}): try the formula instead") from None
    props = d.get("PropertyTable", {}).get("Properties", [])
    if not props or not props[0].get("MolecularFormula"):
        raise HTTPException(422, f"PubChem has no formula for {q!r}: try the formula")
    formula = props[0]["MolecularFormula"]
    if re.search(r"[+-]", formula) or "." in formula:                   # an ion or a mixture: not a solid to plan
        raise HTTPException(422, f"{q!r} reads as {formula}: give the neutral solid's formula")
    return formula, q


EXPLORE = HERE / "explore"                      # the explorer's built site, merged into this one (staged by deploy_front.py)
if EXPLORE.is_dir():
    from fastapi.staticfiles import StaticFiles
    app.mount("/explore", StaticFiles(directory=str(EXPLORE), html=True), name="explore")
NAV = {"How it works": "/explore/#how", "Test cases": "/explore/#cases", "Can you trust it?": "/explore/#honesty", "Words": "/explore/#words"}


@app.get("/", response_class=HTMLResponse)
def home() -> HTMLResponse:
    nav = NAV if EXPLORE.is_dir() else {"Test cases": EXPLORER, "How it works": EXPLORER + "/#how"}
    return HTMLResponse(fill_story(_assets(), api_base="", nav=nav, engine="Planned live by Mat2Bot (private engine); the code stays private"))


@app.get("/health")
def health(request: Request) -> JSONResponse:
    return JSONResponse({"status": "ok", "engine_connected": bool(TOKEN), "visitor": _forwarding(request)})


@app.post("/api/target")
async def api_target(request: Request) -> Response:
    raw = await request.body()
    if len(raw) > MAX_BODY:
        raise HTTPException(413, "too large")
    try:
        doc = json.loads(raw)
        assert isinstance(doc, dict)
    except Exception:
        raise HTTPException(422, "a JSON object") from None
    query = str(doc.get("query") or "").strip()[:80]
    body: dict = {}
    if doc.get("cif_text"):
        body["cif_text"] = doc["cif_text"]
        body["query"] = query
    else:
        if not query:
            raise HTTPException(422, "give a material")
        formula, name = resolve_name(query)
        body["query"] = formula
    status, data, ctype = _engine("/api/target", json.dumps(body).encode())
    if status == 200 and not doc.get("cif_text"):
        out = json.loads(data)
        out["name"] = name or out.get("name", "")
        return JSONResponse(out)
    return Response(data, status_code=status, media_type=ctype or "application/json")


@app.post("/api/plan")
async def api_plan(request: Request) -> Response:
    _throttle(request)
    raw = await request.body()
    if len(raw) > MAX_BODY:
        raise HTTPException(413, "too large")
    status, data, ctype = _engine("/api/plan", raw)
    return Response(data, status_code=status, media_type=ctype or "application/json")


@app.get("/p/{pid}")
@app.get("/p/{pid}/{what}")
def plan_pages(pid: str, what: str = "") -> Response:
    if not PID.match(pid) or what not in ("", "trace", "trace.json", "audit.json", "package.zip", "audit"):
        raise HTTPException(404, "no such page")
    status, data, ctype = _engine(f"/p/{pid}" + (f"/{what}" if what else ""), timeout=300.0)
    if status != 200:
        raise HTTPException(status if status in (404, 429) else 502, "the engine could not serve this page")
    text_types = ("text/html", "application/json")
    if any(ctype.startswith(t) for t in text_types):
        page = data.decode("utf-8", "replace")
        page = page.replace(f'href="/p/{pid}', f'href="/p/{pid}').replace('href="/"', 'href="./"').replace('href="/docs/', f'href="{EXPLORER}/#')
        return Response(page, media_type=ctype)
    headers = {"Content-Disposition": f'attachment; filename="mat2bot-{pid}.zip"'} if what == "package.zip" else {}
    return Response(data, media_type=ctype or "application/octet-stream", headers=headers)


__all__ = ["app", "fill_story", "resolve_name"]