583 lignes
24 KiB
Python
583 lignes
24 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
CornafServer - Daemon de Télémétrie Système Sécurisé
|
|
---------------------------------------------------
|
|
Micro-service en lecture seule pour la supervision système.
|
|
- Aucun appel shell (pas de subprocess/os.system).
|
|
- Lecture directe des pseudo-fichiers noyau /proc.
|
|
- Écoute strictement locale sur 127.0.0.1 (inaccessible de l'extérieur sans reverse-proxy).
|
|
- Ne requiert aucune dépendance tierce (bibliothèque standard Python 3 uniquement).
|
|
- Conçu pour s'exécuter sous un utilisateur non privilégié (ex: nobody).
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
import threading
|
|
import time
|
|
import unicodedata
|
|
import urllib.request
|
|
import urllib.error
|
|
from html.parser import HTMLParser
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
HOST = os.environ.get("TELEMETRY_HOST", "127.0.0.1")
|
|
PORT = int(os.environ.get("TELEMETRY_PORT", "8085"))
|
|
NODE_NAME = os.environ.get("TELEMETRY_NODE", "cornafserver")
|
|
|
|
# LLM local (llama-server, API compatible OpenAI) qui tourne en continu.
|
|
# Configuration uniquement par variables d'environnement (aucune valeur en dur) :
|
|
# LEGAL_LLM_URL : base de l'API, se terminant par /v1 (obligatoire)
|
|
# LEGAL_LLM_MODEL : alias du modèle (défaut : VercorNaf-Flash, alias -a de llama-server)
|
|
# LEGAL_LLM_API_KEY : jeton Bearer, seulement si le serveur LLM en exige un
|
|
# LEGAL_LLM_TIMEOUT : délai max en secondes (défaut : 60)
|
|
LLM_BASE_URL = os.environ.get("LEGAL_LLM_URL", "").rstrip("/")
|
|
LLM_MODEL = os.environ.get("LEGAL_LLM_MODEL", "VercorNaf-Flash")
|
|
LLM_API_KEY = os.environ.get("LEGAL_LLM_API_KEY", "")
|
|
LLM_TIMEOUT = float(os.environ.get("LEGAL_LLM_TIMEOUT", "60"))
|
|
MAX_QUESTION_CHARS = 400
|
|
# Page publiée qui contient les CGV, la politique de confidentialité et les
|
|
# mentions légales. Les réponses s'appuient sur CE texte, relu à chaque
|
|
# modification du fichier : plus de résumé écrit à la main qui vieillit.
|
|
SITE_HTML = os.environ.get("LEGAL_SITE_HTML", "")
|
|
# Place laissée aux extraits dans le prompt (le modèle a un contexte de 8192 jetons).
|
|
CONTEXT_CHARS = int(os.environ.get("LEGAL_CONTEXT_CHARS", "4500"))
|
|
|
|
SYSTEM_PROMPT = """AVERTISSEMENT : tes réponses sont purement informatives et n'ont aucune valeur juridique ; seul le texte publié fait foi. En cas de doute ou si l'information ne figure pas dans les extraits, dis-le franchement au lieu d'inventer. N'écris AUCUNE formule de fin, AUCUN numéro de téléphone ni adresse e-mail : le contact et le rappel « seul le texte publié fait foi » sont ajoutés automatiquement après ta réponse.
|
|
|
|
Tu es l'assistant d'accueil et d'information juridique de l'espace légal de Théo Gastinel (micro-entreprise GASTINEL Richard, SIRET 10481674900014), photographe, vidéaste et développeur basé à Lans-en-Vercors (38250).
|
|
|
|
TON ET OBJECTIF :
|
|
- Ton : Très agréable, chaleureux, bienveillant, clair et professionnel.
|
|
- Longueur : Maximum 250 mots par réponse, sauf si l'utilisateur demande explicitement plus de détails ou une réponse exhaustive.
|
|
- CITATIONS CLÉ : Cite systématiquement les articles ou sections concernés avec un lien d'ancre Markdown cliquable :
|
|
* Pour les articles numérotés des CGV : [Article X (Titre court)](#article-X) (ex: [Article 21 (Conservation des fichiers)](#article-21), [Article 6 (Acompte)](#article-6)).
|
|
* Pour les rubriques RGPD : [Vos droits RGPD](#rgpd-droits), [Hébergement CornafServer & Responsable](#rgpd-responsable), [Mesure d'audience sans cookies](#rgpd-audience), [Services de l'écosystème](#rgpd-ecosysteme).
|
|
* Pour les mentions légales : [Éditeur et mentions](#mentions-identite), [Périmètre des activités](#mentions-activites).
|
|
- Sécurité des données : Ne demande jamais d'informations personnelles identifiantes (noms, coordonnées bancaires, etc.).
|
|
|
|
SOURCE UNIQUE : les EXTRAITS DU TEXTE PUBLIÉ fournis plus bas, tirés de la page en ligne au moment de la question.
|
|
- Réponds uniquement à partir de ces extraits. N'invente ni chiffre, ni délai, ni montant, ni article.
|
|
- Si les extraits ne contiennent pas la réponse, dis-le simplement et invite à consulter le texte ou à contacter Théo.
|
|
- Pour citer un article, reprends son numéro exact tel qu'il apparaît dans les extraits."""
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Texte publié : extraction des articles et sélection de ceux qui répondent
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class _Extracteur(HTMLParser):
|
|
"""Récupère les cartes d'articles (CGV) et les rubriques identifiées
|
|
(rgpd-*, mentions-*) de la page, sous forme de texte brut."""
|
|
|
|
def __init__(self):
|
|
super().__init__(convert_charrefs=True)
|
|
self.blocs = []
|
|
self._pile = None # [balise, profondeur, ancre, titre, morceaux, dans_titre]
|
|
|
|
def handle_starttag(self, tag, attrs):
|
|
d = dict(attrs)
|
|
if self._pile is not None:
|
|
if tag == self._pile[0]:
|
|
self._pile[1] += 1
|
|
if tag in ("h2", "h3", "h4") and not self._pile[3]:
|
|
self._pile[5] = True
|
|
if tag in ("p", "li", "br", "div"):
|
|
self._pile[4].append("\n")
|
|
return
|
|
classes = (d.get("class") or "").split()
|
|
ident = d.get("id") or ""
|
|
if "article-card" in classes:
|
|
self._pile = [tag, 1, "", "", [], False]
|
|
elif re.match(r"^(rgpd|mentions)-[a-z0-9-]+$", ident):
|
|
self._pile = [tag, 1, "#" + ident, "", [], False]
|
|
|
|
def handle_endtag(self, tag):
|
|
if self._pile is None:
|
|
return
|
|
if tag in ("h2", "h3", "h4"):
|
|
self._pile[5] = False
|
|
if tag == self._pile[0]:
|
|
self._pile[1] -= 1
|
|
if self._pile[1] == 0:
|
|
_, _, ancre, titre, morceaux, _ = self._pile
|
|
texte = re.sub(r"[ \t]+", " ", "".join(morceaux))
|
|
texte = re.sub(r"\s*\n\s*", "\n", texte).strip()
|
|
m = re.match(r"ARTICLE\s+(\d+)", titre.strip(), re.I)
|
|
if m:
|
|
ancre = f"#article-{m.group(1)}"
|
|
if texte:
|
|
self.blocs.append({"ancre": ancre, "titre": titre.strip() or ancre, "texte": texte})
|
|
self._pile = None
|
|
|
|
def handle_data(self, data):
|
|
if self._pile is None:
|
|
return
|
|
if self._pile[5]:
|
|
self._pile[3] += data
|
|
else:
|
|
self._pile[4].append(data)
|
|
|
|
|
|
_cache_texte = {"mtime": None, "blocs": []}
|
|
_verrou_texte = threading.Lock()
|
|
|
|
|
|
def blocs_publies():
|
|
"""Articles de la page publiée, relus seulement si le fichier a changé."""
|
|
if not SITE_HTML:
|
|
return []
|
|
try:
|
|
mtime = os.stat(SITE_HTML).st_mtime
|
|
except OSError:
|
|
return _cache_texte["blocs"]
|
|
with _verrou_texte:
|
|
if mtime != _cache_texte["mtime"]:
|
|
ex = _Extracteur()
|
|
with open(SITE_HTML, encoding="utf-8") as f:
|
|
ex.feed(f.read())
|
|
for b in ex.blocs:
|
|
b["racines"] = racines(b["titre"]), racines(b["texte"])
|
|
_cache_texte.update(mtime=mtime, blocs=ex.blocs)
|
|
return _cache_texte["blocs"]
|
|
|
|
|
|
_MOTS_VIDES = set("""avec dans pour sont cette cela comme mais plus tous tout toute quel quelle quels
|
|
quelles votre vous nous leur leurs elle elles sans chez entre aussi alors donc etre avoir fait faire
|
|
peut peux puis quoi dont ainsi apres avant article articles""".split())
|
|
|
|
|
|
def racines(texte):
|
|
t = unicodedata.normalize("NFD", texte.lower())
|
|
t = "".join(c for c in t if unicodedata.category(c) != "Mn")
|
|
return {w[:6] for w in re.findall(r"[a-z0-9]+", t) if len(w) >= 4 and w not in _MOTS_VIDES}
|
|
|
|
|
|
# Mots de tous les jours -> vocabulaire du texte juridique (racines de 6 lettres).
|
|
# Sans cela, « combien de temps gardez-vous mes photos » ne trouve pas
|
|
# l'article sur la « conservation des fichiers ».
|
|
SYNONYMES = {
|
|
"photo": ("fichie", "livrab"), "photos": ("fichie", "livrab"), "video": ("fichie", "livrab"),
|
|
"videos": ("fichie", "livrab"), "images": ("fichie",), "rushs": ("fichie", "bruts"),
|
|
"garde": ("conser", "archiv"), "gardez": ("conser", "archiv"), "garder": ("conser", "archiv"),
|
|
"gardes": ("conser",), "stocke": ("conser", "archiv"), "temps": ("duree", "delai"),
|
|
"annule": ("annula",), "annuler": ("annula",), "rembou": ("rembou", "acompt"),
|
|
"payer": ("paieme", "factur", "reglem"), "paiement": ("paieme",), "prix": ("tarif", "devis"),
|
|
"tarif": ("tarif", "devis"), "retard": ("retard", "tolera"), "donnee": ("person", "rgpd"),
|
|
"donnees": ("person", "rgpd"), "supprim": ("suppre", "effac"), "effacer": ("effac", "suppre"),
|
|
"droits": ("auteur", "cessio"), "utilis": ("cessio", "diffus"), "publie": ("diffus", "cessio"),
|
|
}
|
|
|
|
|
|
def extraits_pour(question):
|
|
"""Articles les plus proches de la question, dans la limite de CONTEXT_CHARS."""
|
|
blocs = blocs_publies()
|
|
q = racines(question)
|
|
q |= {syn for mot in list(q) for syn in SYNONYMES.get(mot, ())}
|
|
cites = set(re.findall(r"article\s*(\d+)", question.lower()))
|
|
notes = []
|
|
for b in blocs:
|
|
r_titre, r_texte = b["racines"]
|
|
score = 3 * len(q & r_titre) + len(q & r_texte)
|
|
if b["ancre"].split("-")[-1] in cites and b["ancre"].startswith("#article-"):
|
|
score += 100
|
|
if score > 0:
|
|
notes.append((score, b))
|
|
notes.sort(key=lambda x: -x[0])
|
|
choisis, taille = [], 0
|
|
for _, b in notes:
|
|
bloc = f"[{b['titre']}] (ancre {b['ancre']})\n{b['texte']}"
|
|
if taille + len(bloc) > CONTEXT_CHARS:
|
|
continue
|
|
choisis.append(bloc)
|
|
taille += len(bloc)
|
|
sommaire = "\n".join(f"- {b['titre']} ({b['ancre']})" for b in blocs if b["ancre"].startswith("#article-"))
|
|
return choisis, sommaire
|
|
|
|
|
|
def construire_messages(question):
|
|
# Ordre voulu : partie fixe (consignes + sommaire) d'abord, extraits ensuite.
|
|
# llama-server (--cache-prompt) réutilise alors le début déjà calculé et ne
|
|
# relit que les extraits : le premier mot arrive bien plus vite.
|
|
choisis, sommaire = extraits_pour(question)
|
|
fixe = SYSTEM_PROMPT + ("\n\nSOMMAIRE DES ARTICLES :\n" + sommaire if sommaire else "")
|
|
extraits = "EXTRAITS DU TEXTE PUBLIÉ :\n\n" + ("\n\n".join(choisis) if choisis else "(aucun extrait ne correspond à la question)")
|
|
return [
|
|
{"role": "system", "content": fixe + "\n\n" + extraits},
|
|
{"role": "user", "content": question},
|
|
]
|
|
|
|
|
|
# Rate limiting simple en mémoire : max 12 requêtes par minute par IP
|
|
_ip_rate_limits = {}
|
|
|
|
|
|
def check_rate_limit(ip: str) -> bool:
|
|
now = time.time()
|
|
timestamps = _ip_rate_limits.get(ip, [])
|
|
# Garde les requêtes des 60 dernières secondes
|
|
timestamps = [t for t in timestamps if now - t < 60]
|
|
if len(timestamps) >= 12:
|
|
_ip_rate_limits[ip] = timestamps
|
|
return False
|
|
timestamps.append(now)
|
|
_ip_rate_limits[ip] = timestamps
|
|
return True
|
|
|
|
|
|
def _requete_llm(question: str, flux: bool):
|
|
if not LLM_BASE_URL:
|
|
raise RuntimeError("LEGAL_LLM_URL non configurée")
|
|
payload = {
|
|
"model": LLM_MODEL,
|
|
"messages": construire_messages(question),
|
|
"max_tokens": 450,
|
|
"temperature": 0.3,
|
|
"stream": flux,
|
|
}
|
|
headers = {
|
|
"Content-Type": "application/json",
|
|
"User-Agent": "CornafServer-Assistant/2.1"
|
|
}
|
|
if LLM_API_KEY:
|
|
headers["Authorization"] = f"Bearer {LLM_API_KEY}"
|
|
req = urllib.request.Request(
|
|
LLM_BASE_URL + "/chat/completions",
|
|
headers=headers,
|
|
data=json.dumps(payload).encode("utf-8")
|
|
)
|
|
return urllib.request.urlopen(req, timeout=LLM_TIMEOUT)
|
|
|
|
|
|
# Fin de réponse écrite par le serveur, mot pour mot : le modèle déformait le
|
|
# numéro et collait les mots de sa formule finale (mesuré le 25/09/2026 :
|
|
# numéro abîmé dans 8 réponses sur 8).
|
|
FIN_DE_REPONSE = (
|
|
"\n\nThéo reste disponible pour toute question : WhatsApp au 06 36 27 64 19 ou "
|
|
"studio@gastinel.me (réponse sous 48 h). Seul le texte publié fait foi : consultez l'article cité."
|
|
)
|
|
|
|
|
|
def call_legal_assistant(question: str) -> str:
|
|
"""Réponse complète en une fois (endpoint /chat/completions compatible OpenAI)."""
|
|
with _requete_llm(question, False) as resp:
|
|
body = json.loads(resp.read().decode("utf-8"))
|
|
content = (body["choices"][0]["message"].get("content") or "").strip()
|
|
if not content:
|
|
raise RuntimeError("Réponse vide du LLM")
|
|
return content + FIN_DE_REPONSE
|
|
|
|
|
|
def stream_legal_assistant(question: str):
|
|
"""Morceaux de réponse au fil de la génération (SSE de llama-server)."""
|
|
with _requete_llm(question, True) as resp:
|
|
for ligne in resp:
|
|
ligne = ligne.decode("utf-8", "replace").strip()
|
|
if not ligne.startswith("data:"):
|
|
continue
|
|
donnee = ligne[5:].strip()
|
|
if donnee == "[DONE]":
|
|
return
|
|
try:
|
|
delta = json.loads(donnee)["choices"][0].get("delta", {})
|
|
except (ValueError, KeyError, IndexError):
|
|
continue
|
|
morceau = delta.get("content")
|
|
if morceau:
|
|
yield morceau
|
|
|
|
# État interne pour le calcul CPU différentiel (/proc/stat)
|
|
_last_cpu_time = 0.0
|
|
_last_cpu_idle = 0.0
|
|
_last_cpu_total = 0.0
|
|
_cached_cpu_pct = 0.0
|
|
|
|
|
|
def read_proc_stat():
|
|
"""Calcule le pourcentage d'utilisation CPU depuis /proc/stat."""
|
|
global _last_cpu_time, _last_cpu_idle, _last_cpu_total, _cached_cpu_pct
|
|
|
|
now = time.time()
|
|
# Met en cache pour au moins 500ms afin d'éviter les calculs sur delta nul
|
|
if (now - _last_cpu_time) < 0.5 and _last_cpu_time > 0:
|
|
return _cached_cpu_pct
|
|
|
|
try:
|
|
with open("/proc/stat", "r", encoding="utf-8") as f:
|
|
line = f.readline()
|
|
if not line.startswith("cpu "):
|
|
return _cached_cpu_pct
|
|
|
|
fields = [float(x) for x in line.strip().split()[1:]]
|
|
idle = fields[3] + (fields[4] if len(fields) > 4 else 0.0) # idle + iowait
|
|
total = sum(fields)
|
|
|
|
if _last_cpu_total > 0:
|
|
delta_total = total - _last_cpu_total
|
|
delta_idle = idle - _last_cpu_idle
|
|
if delta_total > 0:
|
|
cpu_usage = 100.0 * (1.0 - (delta_idle / delta_total))
|
|
_cached_cpu_pct = round(max(0.0, min(100.0, cpu_usage)), 1)
|
|
else:
|
|
_cached_cpu_pct = 0.0
|
|
|
|
_last_cpu_time = now
|
|
_last_cpu_idle = idle
|
|
_last_cpu_total = total
|
|
return _cached_cpu_pct
|
|
except Exception:
|
|
# Fallback pour environnement de test sans /proc (Windows/Mac)
|
|
return 1.2
|
|
|
|
|
|
def read_proc_meminfo():
|
|
"""Lit la RAM totale et disponible depuis /proc/meminfo."""
|
|
try:
|
|
mem = {}
|
|
with open("/proc/meminfo", "r", encoding="utf-8") as f:
|
|
for line in f:
|
|
parts = line.split(":")
|
|
if len(parts) == 2:
|
|
key = parts[0].strip()
|
|
val = parts[1].strip().split()[0]
|
|
mem[key] = float(val)
|
|
|
|
total_kb = mem.get("MemTotal", 0.0)
|
|
avail_kb = mem.get("MemAvailable", mem.get("MemFree", 0.0))
|
|
used_kb = max(0.0, total_kb - avail_kb)
|
|
|
|
total_gb = round(total_kb / (1024.0 * 1024.0), 2)
|
|
used_gb = round(used_kb / (1024.0 * 1024.0), 2)
|
|
pct = round((used_kb / total_kb * 100.0), 1) if total_kb > 0 else 0.0
|
|
|
|
return used_gb, total_gb, pct
|
|
except Exception:
|
|
# Fallback test
|
|
return 4.58, 15.40, 29.7
|
|
|
|
|
|
def read_proc_uptime():
|
|
"""Lit l'uptime depuis /proc/uptime et formate en chaîne lisible."""
|
|
try:
|
|
with open("/proc/uptime", "r", encoding="utf-8") as f:
|
|
raw_uptime = float(f.readline().split()[0])
|
|
|
|
seconds = int(raw_uptime)
|
|
days = seconds // 86400
|
|
hours = (seconds % 86400) // 3600
|
|
minutes = (seconds % 3600) // 60
|
|
|
|
if days > 0:
|
|
uptime_str = f"{days}j {hours:02d}h {minutes:02d}m"
|
|
else:
|
|
uptime_str = f"{hours:02d}h {minutes:02d}m"
|
|
|
|
return uptime_str, seconds
|
|
except Exception:
|
|
return "24/7 ACTIF", 86400
|
|
|
|
|
|
def read_proc_loadavg():
|
|
"""Lit la charge moyenne système depuis /proc/loadavg."""
|
|
try:
|
|
with open("/proc/loadavg", "r", encoding="utf-8") as f:
|
|
parts = f.readline().split()
|
|
loads = [float(parts[0]), float(parts[1]), float(parts[2])]
|
|
return loads
|
|
except Exception:
|
|
return [0.12, 0.08, 0.05]
|
|
|
|
|
|
def get_telemetry_payload():
|
|
"""Construit la charge utile JSON de télémétrie assainie."""
|
|
cpu_pct = read_proc_stat()
|
|
ram_used, ram_total, ram_pct = read_proc_meminfo()
|
|
uptime_str, uptime_sec = read_proc_uptime()
|
|
load_avg = read_proc_loadavg()
|
|
|
|
return {
|
|
"status": "online",
|
|
"node": NODE_NAME,
|
|
"cpu_pct": cpu_pct,
|
|
"ram_used_gb": ram_used,
|
|
"ram_total_gb": ram_total,
|
|
"ram_pct": ram_pct,
|
|
"uptime_str": uptime_str,
|
|
"uptime_seconds": uptime_sec,
|
|
"load_avg": load_avg,
|
|
"timestamp": int(time.time()),
|
|
}
|
|
|
|
|
|
class SecureTelemetryHandler(BaseHTTPRequestHandler):
|
|
"""Gestionnaire HTTP ultra-restreint : GET /api/stats uniquement."""
|
|
|
|
server_version = "CornafTelemetry/1.0"
|
|
sys_version = ""
|
|
|
|
def do_GET(self):
|
|
# Restriction stricte de chemin
|
|
if self.path in ("/api/stats", "/api/stats/"):
|
|
payload = get_telemetry_payload()
|
|
data = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
|
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.send_header("Cache-Control", "no-store, no-cache, must-revalidate")
|
|
self.send_header("X-Content-Type-Options", "nosniff")
|
|
self.send_header("Access-Control-Allow-Origin", "*")
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
else:
|
|
self.send_error(404, "Not Found")
|
|
|
|
def _send_json(self, status_code, payload):
|
|
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
self.send_response(status_code)
|
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.send_header("Cache-Control", "no-store, no-cache, must-revalidate")
|
|
self.send_header("X-Content-Type-Options", "nosniff")
|
|
self.send_header("Access-Control-Allow-Origin", "*")
|
|
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def do_OPTIONS(self):
|
|
if self.path in ("/api/stats", "/api/stats/", "/api/assistant", "/api/assistant/"):
|
|
self.send_response(204)
|
|
self.send_header("Access-Control-Allow-Origin", "*")
|
|
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
|
self.end_headers()
|
|
else:
|
|
self.send_error(404, "Not Found")
|
|
|
|
def do_POST(self):
|
|
if self.path in ("/api/assistant", "/api/assistant/"):
|
|
client_ip = (
|
|
self.headers.get("X-Real-IP")
|
|
or self.headers.get("X-Forwarded-For", "").split(",")[0].strip()
|
|
or self.client_address[0]
|
|
)
|
|
|
|
if not check_rate_limit(client_ip):
|
|
return self._send_json(429, {
|
|
"error": "Trop de requêtes envoyées. Merci de patienter quelques instants avant de poser une nouvelle question."
|
|
})
|
|
|
|
try:
|
|
content_length = int(self.headers.get("Content-Length", 0))
|
|
except ValueError:
|
|
return self._send_json(400, {"error": "En-tête Content-Length invalide."})
|
|
|
|
if content_length <= 0:
|
|
return self._send_json(400, {"error": "Requête vide."})
|
|
if content_length > 4096:
|
|
return self._send_json(413, {"error": "Question trop volumineuse (maximum 4 Ko)."})
|
|
|
|
try:
|
|
raw_body = self.rfile.read(content_length).decode("utf-8")
|
|
body = json.loads(raw_body)
|
|
except Exception:
|
|
return self._send_json(400, {"error": "Format JSON invalide."})
|
|
|
|
question = str(body.get("question", "")).strip()
|
|
if len(question) < 2:
|
|
return self._send_json(400, {"error": "Merci de saisir une question plus détaillée."})
|
|
if len(question) > MAX_QUESTION_CHARS:
|
|
return self._send_json(400, {"error": f"Votre question dépasse la limite de {MAX_QUESTION_CHARS} caractères."})
|
|
|
|
if body.get("stream") is True:
|
|
return self._repondre_en_flux(question)
|
|
try:
|
|
answer = call_legal_assistant(question)
|
|
return self._send_json(200, {"answer": answer})
|
|
except Exception:
|
|
return self._send_json(503, {
|
|
"error": "L'assistant est momentanément indisponible. Les documents ci-dessus restent consultables, et vous pouvez écrire à studio@gastinel.me."
|
|
})
|
|
else:
|
|
self.send_error(405, "Method Not Allowed")
|
|
|
|
def _repondre_en_flux(self, question):
|
|
"""Server-Sent Events : un événement par morceau, puis {"done": true}.
|
|
Si le LLM échoue avant le premier morceau, réponse 503 JSON classique."""
|
|
indispo = "L'assistant est momentanément indisponible. Les documents ci-dessus restent consultables, et vous pouvez écrire à studio@gastinel.me."
|
|
morceaux = stream_legal_assistant(question)
|
|
try:
|
|
premier = next(morceaux)
|
|
except StopIteration:
|
|
return self._send_json(503, {"error": indispo})
|
|
except Exception:
|
|
return self._send_json(503, {"error": indispo})
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/event-stream; charset=utf-8")
|
|
self.send_header("Cache-Control", "no-store, no-cache, must-revalidate")
|
|
self.send_header("X-Accel-Buffering", "no")
|
|
self.send_header("X-Content-Type-Options", "nosniff")
|
|
self.end_headers()
|
|
|
|
def envoyer(obj):
|
|
self.wfile.write(("data: " + json.dumps(obj, ensure_ascii=False) + "\n\n").encode("utf-8"))
|
|
self.wfile.flush()
|
|
|
|
try:
|
|
envoyer({"t": premier})
|
|
for m in morceaux:
|
|
envoyer({"t": m})
|
|
envoyer({"t": FIN_DE_REPONSE})
|
|
envoyer({"done": True})
|
|
except (BrokenPipeError, ConnectionResetError):
|
|
pass # visiteur parti : la génération s'arrête avec la connexion
|
|
except Exception:
|
|
try:
|
|
envoyer({"error": indispo})
|
|
except Exception:
|
|
pass
|
|
|
|
def do_PUT(self):
|
|
self.send_error(405, "Method Not Allowed")
|
|
|
|
def do_DELETE(self):
|
|
self.send_error(405, "Method Not Allowed")
|
|
|
|
def do_HEAD(self):
|
|
if self.path in ("/api/stats", "/api/stats/"):
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
self.send_header("Cache-Control", "no-store")
|
|
self.send_header("X-Content-Type-Options", "nosniff")
|
|
self.end_headers()
|
|
else:
|
|
self.send_error(404, "Not Found")
|
|
|
|
def log_message(self, format, *args):
|
|
# Désactiver les logs verbeux en console pour limiter l'empreinte disque/I/O
|
|
pass
|
|
|
|
|
|
def run_daemon():
|
|
# Initialisation de la première lecture CPU
|
|
read_proc_stat()
|
|
|
|
server_address = (HOST, PORT)
|
|
# Un fil par requête : une réponse en flux ne bloque pas les autres visiteurs.
|
|
httpd = ThreadingHTTPServer(server_address, SecureTelemetryHandler)
|
|
httpd.daemon_threads = True
|
|
print(f"[*] CornafServer Telemetry Daemon démarré sur http://{HOST}:{PORT}")
|
|
print(f"[*] Route télémétrie : http://{HOST}:{PORT}/api/stats")
|
|
print(f"[*] Route assistant IA : http://{HOST}:{PORT}/api/assistant")
|
|
|
|
try:
|
|
httpd.serve_forever()
|
|
except KeyboardInterrupt:
|
|
print("\n[*] Arrêt du démon.")
|
|
httpd.server_close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run_daemon()
|