166 lines
5.0 KiB
Python
166 lines
5.0 KiB
Python
"""La web app : .venv/bin/python app/serveur/serveur.py → http://127.0.0.1:8770
|
|
|
|
Le serveur FastAPI sert la page React construite (app/web/dist, `npm run build` dans app/web) et l'API sous /api.
|
|
La page Data lit data/ et les étiquettes de labeling/ (station.py) ; son onglet Analysis lance l'étiqueteur, et l'optimisation
|
|
des détecteurs (analyse.py).
|
|
Réglages : AIMSIGHT_DATA (données), AIMSIGHT_LABELS (étiquettes), 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 analyse
|
|
import station
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
APP = Path(__file__).resolve().parents[1]
|
|
|
|
PORT = int(os.environ.get("AIMSIGHT_PORT", 8770))
|
|
HOTES = {"127.0.0.1", "localhost"} # contre le DNS rebinding : un autre site ne lit pas les données
|
|
PAGE = APP / "web" / "dist"
|
|
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
|
|
|
|
|
def erreur(code: int, texte: str) -> JSONResponse:
|
|
return JSONResponse({"erreur": texte}, code)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def garde(request: Request, suite):
|
|
"""Seule la page elle-même parle au serveur : bon Host ; en POST, un JSON déclaré (une page d'un autre site ne
|
|
peut l'envoyer sans requête préalable, à laquelle le serveur ne répond pas)."""
|
|
hote = request.headers.get("host", "").rsplit(":", 1)[0]
|
|
if hote not in HOTES or (request.method in ("POST", "PUT", "DELETE")
|
|
and not request.headers.get("content-type", "").startswith("application/json")):
|
|
return erreur(403, "requête refusée")
|
|
return await suite(request)
|
|
|
|
|
|
# --- la page Data (station.py)
|
|
|
|
@app.exception_handler(station.Refus)
|
|
def refus(_, e):
|
|
return erreur(400, str(e))
|
|
|
|
|
|
@app.get("/api/stations")
|
|
def stations():
|
|
return station.stations()
|
|
|
|
|
|
@app.get("/api/images")
|
|
def images(station_: str = Query(alias="station"), du: str = "", au: str = ""):
|
|
return station.images(station_, du, au)
|
|
|
|
|
|
@app.get("/api/image/{station_}/{nom}")
|
|
def image(station_: str, nom: str):
|
|
return FileResponse(station.image(station_, nom), headers={"Cache-Control": "max-age=86400"})
|
|
|
|
|
|
@app.get("/api/courbes")
|
|
def courbes(station_: str = Query(alias="station"), du: str = "", au: str = ""):
|
|
return station.courbes(station_, du, au)
|
|
|
|
|
|
@app.get("/api/detecteurs")
|
|
def detecteurs(station_: str = Query(alias="station"), du: str = "", au: str = "", cibles: str = ""):
|
|
return station.detecteurs(station_, du, au, cibles)
|
|
|
|
|
|
@app.get("/api/etiquettes")
|
|
def etiquettes(station_: str = Query(alias="station"), dossier: str = "manual"):
|
|
try:
|
|
return station.lire(station_, dossier)
|
|
except json.JSONDecodeError as e: # une ligne abîmée à la main : le dire, sans toucher au fichier
|
|
return erreur(500, f"labeling/{dossier}/{station_}.jsonl illisible : {e}")
|
|
|
|
|
|
@app.post("/api/etiquettes")
|
|
def ajouter(corps: dict):
|
|
return station.ajouter(corps)
|
|
|
|
|
|
@app.put("/api/etiquettes")
|
|
def modifier(corps: dict):
|
|
return station.modifier(corps)
|
|
|
|
|
|
@app.delete("/api/etiquettes")
|
|
def supprimer(corps: dict):
|
|
return station.supprimer(corps)
|
|
|
|
|
|
# --- l'onglet Analysis de la page Data (analyse.py) : l'étiqueteur lancé par claude -p sur une plage
|
|
|
|
@app.post("/api/analyses")
|
|
def lancer_analyse(corps: dict):
|
|
return analyse.lancer(corps)
|
|
|
|
|
|
@app.get("/api/analyses")
|
|
def analyses():
|
|
return analyse.liste()
|
|
|
|
|
|
@app.get("/api/analyses/{nom}")
|
|
def etat_analyse(nom: str):
|
|
return analyse.etat(nom)
|
|
|
|
|
|
@app.post("/api/analyses/{nom}/message")
|
|
def message_analyse(nom: str, corps: dict):
|
|
return analyse.message(nom, corps)
|
|
|
|
|
|
@app.get("/api/analyses/{nom}/rapport.html")
|
|
def rapport_analyse(nom: str, sombre: bool = False):
|
|
return HTMLResponse(analyse.rapport(nom, sombre))
|
|
|
|
|
|
@app.post("/api/analyses/{nom}/optimiser")
|
|
def optimiser_analyse(nom: str):
|
|
return analyse.optimiser(nom)
|
|
|
|
|
|
@app.get("/api/analyses/{nom}/bilan.html")
|
|
def bilan_analyse(nom: str, sombre: bool = False):
|
|
return HTMLResponse(analyse.bilan(nom, sombre))
|
|
|
|
|
|
@app.get("/api/analyses/{nom}/{chemin:path}")
|
|
def fichier_analyse(nom: str, chemin: str):
|
|
return FileResponse(analyse.fichier(nom, chemin))
|
|
|
|
|
|
if PAGE.is_dir():
|
|
app.mount("/", StaticFiles(directory=PAGE, html=True), name="page")
|
|
else:
|
|
@app.get("/")
|
|
def sans_page():
|
|
return erreur(503, "la page n'est pas construite : cd app/web && npm install && npm run build")
|
|
|
|
|
|
def ouvrir(url: str) -> None:
|
|
if "microsoft" in platform.uname().release.lower(): # WSL : le navigateur Windows
|
|
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"Diagnostic AIMsight : {url}")
|
|
if "--sans-navigateur" not in sys.argv:
|
|
threading.Timer(1, ouvrir, [url]).start()
|
|
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="warning", timeout_graceful_shutdown=1)
|