Repository Public
1# =============================================================================2# SP BOUCHER | INFRASTRUCTURE & AUTOMATION3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : MacLustr LLM API7# File : src/maclustr_llm/routes_public.py8# Description : Routes publiques : santé, statut, contrat OpenAPI, portail9# de documentation (fichiers statiques).10# Module : maclustr_llm11# Repository : https://git.spboucher.ai/maclustr-llm12# Created : 2026-11-1913# Last Modified : 2026-11-1914#15# Author : Simon-Pierre Boucher16# Position : Professor of Finance17# Institution : Université du Québec en Outaouais (UQO)18# Organization : SP Boucher19# Website : https://spboucher.ai20# Git : https://git.spboucher.ai21#22# Preferred Contact: admin@spboucher.ai23# Technical Contact: dev@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Routes publiques : santé, statut, contrat OpenAPI, portail de documentation (fichiers statiques)."""4243from __future__ import annotations4445import json46import time47from pathlib import Path48from typing import Any4950from fastapi import APIRouter, FastAPI, Request51from fastapi.responses import FileResponse, JSONResponse, Response52from fastapi.staticfiles import StaticFiles5354from .config import API_VERSION, Settings55from .openapi import build_openapi5657router = APIRouter()585960@router.get("/health")61async def health() -> JSONResponse:62 """Vivacité de la passerelle (ne dépend pas du moteur)."""63 return JSONResponse({"status": "ok"})646566@router.get("/ready")67async def ready(request: Request) -> JSONResponse:68 """Prêt à servir : au moins un moteur sain pour chaque modèle public."""69 svc = request.app.state.svc70 missing = [m for m in svc.settings.models if not svc.scheduler.has_engine(m)]71 ok = not missing72 return JSONResponse(73 {"status": "ready" if ok else "unavailable", "models_unavailable": missing}, status_code=200 if ok else 50374 )757677@router.get("/api/status")78async def status(request: Request) -> JSONResponse:79 """Statut public : uniquement des informations vérifiées et non sensibles."""80 svc = request.app.state.svc81 s: Settings = svc.settings82 models = [83 {84 "id": m.id,85 "display_name": m.display_name,86 "quantization": m.quantization,87 "context_window": m.context_window,88 "available": svc.scheduler.has_engine(m.id),89 }90 for m in s.models.values()91 ]92 operational = all(m["available"] for m in models)93 updated = _last_updated(s)94 return JSONResponse(95 {96 "status": "operational" if operational else "unavailable",97 "api_version": API_VERSION,98 "models": models,99 "engine": "Apple MLX (Metal)",100 "last_updated": updated,101 "checked_at": int(time.time()),102 },103 headers={"Cache-Control": "no-store"},104 )105106107def _last_updated(s: Settings) -> str | None:108 changelog = s.web_dir / "changelog.json"109 try:110 entries: list[dict[str, Any]] = json.loads(changelog.read_text())111 return str(entries[0]["date"]) if entries else None112 except (OSError, ValueError, KeyError, IndexError):113 return None114115116@router.get("/openapi.json")117async def openapi(request: Request) -> JSONResponse:118 return JSONResponse(build_openapi(request.app.state.svc.settings), headers={"Cache-Control": "public, max-age=300"})119120121def mount_site(app: FastAPI, settings: Settings) -> None:122 """Portail statique. Les pages sont des fichiers HTML ; /docs/<section> et /admin/<vue> servent leur123 coquille respective (routage côté client). Rien d'administratif n'est contenu dans ces fichiers :124 toutes les données du Dashboard viennent de /admin/api/*, protégé par session."""125 web: Path = settings.web_dir126127 def page(name: str) -> Response:128 path = web / name129 if not path.exists():130 return JSONResponse(131 {132 "error": {133 "message": "Page indisponible.",134 "type": "not_found_error",135 "param": None,136 "code": "not_found",137 }138 },139 status_code=404,140 )141 return FileResponse(path, media_type="text/html; charset=utf-8", headers={"Cache-Control": "no-cache"})142143 @app.get("/", include_in_schema=False)144 async def home() -> Response:145 return page("index.html")146147 @app.get("/docs", include_in_schema=False)148 @app.get("/docs/{section:path}", include_in_schema=False)149 async def docs(section: str = "") -> Response:150 return page("docs.html")151152 @app.get("/playground", include_in_schema=False)153 async def playground() -> Response:154 return page("playground.html")155156 @app.get("/status", include_in_schema=False)157 async def status_page() -> Response:158 return page("status.html")159160 @app.get("/changelog", include_in_schema=False)161 async def changelog() -> Response:162 return page("docs.html")163164 @app.get("/admin", include_in_schema=False)165 @app.get("/admin/{view:path}", include_in_schema=False)166 async def admin(view: str = "") -> Response:167 if view.startswith("api/"):168 return JSONResponse(169 {"error": {"message": "Introuvable.", "type": "not_found_error", "param": None, "code": "not_found"}},170 status_code=404,171 )172 return page("admin.html")173174 @app.get("/setup/{token}", include_in_schema=False)175 async def setup(token: str) -> Response:176 return page("setup.html")177178 @app.get("/changelog.json", include_in_schema=False)179 async def changelog_json() -> Response:180 path = web / "changelog.json"181 if not path.exists():182 return JSONResponse([])183 return FileResponse(path, media_type="application/json", headers={"Cache-Control": "no-cache"})184185 @app.get("/robots.txt", include_in_schema=False)186 async def robots() -> Response:187 return Response("User-agent: *\nDisallow: /admin\nDisallow: /setup\nDisallow: /v1\n", media_type="text/plain")188189 assets = web / "assets"190 if assets.exists():191 app.mount("/assets", StaticFiles(directory=assets), name="assets")192