283 lines
8.3 KiB
Python
283 lines
8.3 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); its Support tab, the support (support.py). The Conversations page, the
|
|
LibreDesk conversations pumped by ~/aimsight-libredesk (conversations.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 conversations
|
|
import station
|
|
import support
|
|
import validity
|
|
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 = "", set_: str = Query("classic", alias="set")):
|
|
return station.detectors(station_, start, end, targets, set_)
|
|
|
|
|
|
@app.get("/api/tracked")
|
|
def tracked():
|
|
return [{"serial": s, "position": p} for s, p in station.pumping.tracked().items()]
|
|
|
|
|
|
@app.put("/api/tracked")
|
|
def save_tracked(body: dict):
|
|
return station.save_tracked(body.get("stations") or [])
|
|
|
|
|
|
@app.get("/api/pump")
|
|
def pump_state(diff: bool = False):
|
|
return station.pump_state(diff)
|
|
|
|
|
|
@app.post("/api/pump")
|
|
def pump(body: dict):
|
|
return station.pump(body)
|
|
|
|
|
|
@app.get("/api/labels")
|
|
def labels(station_: str = Query(alias="station"), folder: str = "auto"):
|
|
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}/validate")
|
|
def validate_analysis(name: str):
|
|
return analysis.validate(name)
|
|
|
|
|
|
@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))
|
|
|
|
|
|
# --- the Support tab of the Data page (support.py): the support launched by claude -p on a range, with a question
|
|
|
|
@app.post("/api/support")
|
|
def launch_support(body: dict):
|
|
return support.launch(body)
|
|
|
|
|
|
@app.get("/api/support")
|
|
def supports():
|
|
return support.list_supports()
|
|
|
|
|
|
@app.get("/api/support/{name}")
|
|
def support_state(name: str):
|
|
return support.state(name)
|
|
|
|
|
|
@app.post("/api/support/{name}/message")
|
|
def support_message(name: str, body: dict):
|
|
return support.message(name, body)
|
|
|
|
|
|
@app.get("/api/support/{name}/report.html")
|
|
def support_answer(name: str, dark: bool = False):
|
|
return HTMLResponse(support.answer(name, dark))
|
|
|
|
|
|
@app.get("/api/support/{name}/{path:path}")
|
|
def support_file(name: str, path: str):
|
|
return FileResponse(analysis.file(name, path, support.FOLDER))
|
|
|
|
|
|
# --- the Points page (validity.py): the point labels of labeling/points/, valid or not, set by the user
|
|
|
|
@app.get("/api/points")
|
|
def points_list(station_: str = Query("", alias="station")):
|
|
return validity.listing(station_)
|
|
|
|
|
|
@app.post("/api/points")
|
|
def points_create(body: dict):
|
|
return validity.create(body)
|
|
|
|
|
|
@app.get("/api/points/{name}")
|
|
def points_dataset(name: str):
|
|
return validity.dataset(name)
|
|
|
|
|
|
@app.put("/api/points/{name}")
|
|
def points_mark(name: str, body: dict):
|
|
return validity.mark(name, body)
|
|
|
|
|
|
# --- the Conversations page (conversations.py): the LibreDesk conversations, pumped read-only, and their transcripts
|
|
|
|
CSP = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'" # a client's mail: no script, no remote image
|
|
|
|
|
|
@app.get("/api/conversations/pump")
|
|
def conversations_pump_state():
|
|
return conversations.pump_state()
|
|
|
|
|
|
@app.post("/api/conversations/pump")
|
|
def conversations_pump(body: dict):
|
|
return conversations.pump(body)
|
|
|
|
|
|
@app.get("/api/conversations")
|
|
def conversations_list():
|
|
return conversations.list_conversations()
|
|
|
|
|
|
@app.get("/api/conversations/{reference}/report.html")
|
|
def conversation_transcript(reference: str, dark: bool = False):
|
|
return HTMLResponse(conversations.transcript(reference, dark), headers={"Content-Security-Policy": CSP})
|
|
|
|
|
|
@app.get("/api/conversations/{reference}/{path:path}")
|
|
def conversation_file(reference: str, path: str):
|
|
"""A plain image inline; any other attachment (an .html, an .svg) as a download: it never runs at the app's address."""
|
|
f = analysis.file(reference, path, conversations.FOLDER)
|
|
headers = {"X-Content-Type-Options": "nosniff", "Content-Security-Policy": CSP}
|
|
return FileResponse(f, headers=headers) if f.suffix.lower() in conversations.INLINE \
|
|
else FileResponse(f, filename=f.name, headers=headers)
|
|
|
|
|
|
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)
|