165 lines
5.0 KiB
Python
165 lines
5.0 KiB
Python
"""The web app: .venv/bin/python app/server/server.py → http://127.0.0.1:8770
|
|||
|
|
|
||
|
|
The FastAPI server serves the built React page (app/web/dist, `npm run build` in app/web) and the API under /api.
|
||
|
|
The Data page reads data/ and the labels of labeling/ (station.py); its Analysis tab launches the analyst, and the
|
||
|
|
optimization of the detectors (analysis.py).
|
||
|
|
Settings: AIMSIGHT_DATA (data), AIMSIGHT_LABELS (labels), AIMSIGHT_PORT (port, 8770).
|
||
|
|
"""
|
||
|
|
import json
|
||
|
|
import os
|
||
|
|
import platform
|
||
|
|
import subprocess
|
||
|
|
import sys
|
||
|
|
import threading
|
||
|
|
import webbrowser
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
import uvicorn
|
||
|
|
from fastapi import FastAPI, Query, Request
|
||
|
|
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||
|
|
|
||
|
|
import analysis
|
||
|
|
import station
|
||
|
|
from fastapi.staticfiles import StaticFiles
|
||
|
|
|
||
|
|
APP = Path(__file__).resolve().parents[1]
|
||
|
|
|
||
|
|
PORT = int(os.environ.get("AIMSIGHT_PORT", 8770))
|
||
|
|
HOSTS = {"127.0.0.1", "localhost"} # against DNS rebinding: another site does not read the data
|
||
|
|
PAGE = APP / "web" / "dist"
|
||
|
|
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
||
|
|
|
||
|
|
|
||
|
|
def error(code: int, text: str) -> JSONResponse:
|
||
|
|
return JSONResponse({"error": text}, code)
|
||
|
|
|
||
|
|
|
||
|
|
@app.middleware("http")
|
||
|
|
async def guard(request: Request, call_next):
|
||
|
|
"""Only the page itself talks to the server: right Host; in POST, a declared JSON (a page of another site cannot send
|
||
|
|
it without a preflight request, to which the server does not answer)."""
|
||
|
|
host = request.headers.get("host", "").rsplit(":", 1)[0]
|
||
|
|
if host not in HOSTS or (request.method in ("POST", "PUT", "DELETE")
|
||
|
|
and not request.headers.get("content-type", "").startswith("application/json")):
|
||
|
|
return error(403, "request refused")
|
||
|
|
return await call_next(request)
|
||
|
|
|
||
|
|
|
||
|
|
# --- the Data page (station.py)
|
||
|
|
|
||
|
|
@app.exception_handler(station.Refusal)
|
||
|
|
def refusal(_, e):
|
||
|
|
return error(400, str(e))
|
||
|
|
|
||
|
|
|
||
|
|
@app.get("/api/stations")
|
||
|
|
def stations():
|
||
|
|
return station.stations()
|
||
|
|
|
||
|
|
|
||
|
|
@app.get("/api/images")
|
||
|
|
def images(station_: str = Query(alias="station"), start: str = "", end: str = ""):
|
||
|
|
return station.images(station_, start, end)
|
||
|
|
|
||
|
|
|
||
|
|
@app.get("/api/image/{station_}/{name}")
|
||
|
|
def image(station_: str, name: str):
|
||
|
|
return FileResponse(station.image(station_, name), headers={"Cache-Control": "max-age=86400"})
|
||
|
|
|
||
|
|
|
||
|
|
@app.get("/api/curves")
|
||
|
|
def curves(station_: str = Query(alias="station"), start: str = "", end: str = ""):
|
||
|
|
return station.curves(station_, start, end)
|
||
|
|
|
||
|
|
|
||
|
|
@app.get("/api/detectors")
|
||
|
|
def detectors(station_: str = Query(alias="station"), start: str = "", end: str = "", targets: str = ""):
|
||
|
|
return station.detectors(station_, start, end, targets)
|
||
|
|
|
||
|
|
|
||
|
|
@app.get("/api/labels")
|
||
|
|
def labels(station_: str = Query(alias="station"), folder: str = "manual"):
|
||
|
|
try:
|
||
|
|
return station.read(station_, folder)
|
||
|
|
except json.JSONDecodeError as e: # a line damaged by hand: say so, without touching the file
|
||
|
|
return error(500, f"labeling/{folder}/{station_}.jsonl unreadable: {e}")
|
||
|
|
|
||
|
|
|
||
|
|
@app.post("/api/labels")
|
||
|
|
def add_label(body: dict):
|
||
|
|
return station.add(body)
|
||
|
|
|
||
|
|
|
||
|
|
@app.put("/api/labels")
|
||
|
|
def update_label(body: dict):
|
||
|
|
return station.update(body)
|
||
|
|
|
||
|
|
|
||
|
|
@app.delete("/api/labels")
|
||
|
|
def delete_label(body: dict):
|
||
|
|
return station.delete(body)
|
||
|
|
|
||
|
|
|
||
|
|
# --- the Analysis tab of the Data page (analysis.py): the analyst launched by claude -p on a range
|
||
|
|
|
||
|
|
@app.post("/api/analyses")
|
||
|
|
def launch_analysis(body: dict):
|
||
|
|
return analysis.launch(body)
|
||
|
|
|
||
|
|
|
||
|
|
@app.get("/api/analyses")
|
||
|
|
def analyses():
|
||
|
|
return analysis.list_analyses()
|
||
|
|
|
||
|
|
|
||
|
|
@app.get("/api/analyses/{name}")
|
||
|
|
def analysis_state(name: str):
|
||
|
|
return analysis.state(name)
|
||
|
|
|
||
|
|
|
||
|
|
@app.post("/api/analyses/{name}/message")
|
||
|
|
def analysis_message(name: str, body: dict):
|
||
|
|
return analysis.message(name, body)
|
||
|
|
|
||
|
|
|
||
|
|
@app.get("/api/analyses/{name}/report.html")
|
||
|
|
def analysis_report(name: str, dark: bool = False):
|
||
|
|
return HTMLResponse(analysis.report(name, dark))
|
||
|
|
|
||
|
|
|
||
|
|
@app.post("/api/analyses/{name}/optimize")
|
||
|
|
def optimize_analysis(name: str):
|
||
|
|
return analysis.optimize(name)
|
||
|
|
|
||
|
|
|
||
|
|
@app.get("/api/analyses/{name}/summary.html")
|
||
|
|
def analysis_summary(name: str, dark: bool = False):
|
||
|
|
return HTMLResponse(analysis.summary(name, dark))
|
||
|
|
|
||
|
|
|
||
|
|
@app.get("/api/analyses/{name}/{path:path}")
|
||
|
|
def analysis_file(name: str, path: str):
|
||
|
|
return FileResponse(analysis.file(name, path))
|
||
|
|
|
||
|
|
|
||
|
|
if PAGE.is_dir():
|
||
|
|
app.mount("/", StaticFiles(directory=PAGE, html=True), name="page")
|
||
|
|
else:
|
||
|
|
@app.get("/")
|
||
|
|
def no_page():
|
||
|
|
return error(503, "the page is not built: cd app/web && npm install && npm run build")
|
||
|
|
|
||
|
|
|
||
|
|
def open_browser(url: str) -> None:
|
||
|
|
if "microsoft" in platform.uname().release.lower(): # WSL: the Windows browser
|
||
|
|
subprocess.Popen(["explorer.exe", url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||
|
|
else:
|
||
|
|
webbrowser.open(url)
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
url = f"http://127.0.0.1:{PORT}"
|
||
|
|
print(f"AIMsight diagnostic: {url}")
|
||
|
|
if "--no-browser" not in sys.argv:
|
||
|
|
threading.Timer(1, open_browser, [url]).start()
|
||
|
|
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="warning", timeout_graceful_shutdown=1)
|