ask / retriever.py
slabbdev's picture
Upload folder using huggingface_hub
2e72013 verified
Raw History Blame Contribute Delete
10.9 kB
"""normask — retrieval pur Python (BM25-lite) sur la KB + provisions + requirements.
Zéro dépendance : index inversé + score idf. 3000+ documents, réponse < 50 ms.
Les réponses sont DÉTERMINISTES : on ne génère rien, on assemble les passages
retrouvés, chacun cité avec son niveau d'autorité.
"""
from __future__ import annotations
import json
import math
import re
import unicodedata
from pathlib import Path
DATA_DIR = Path(__file__).resolve().parent / "data"
ACTE = {"RIA": "AI Act"}
def _acte(act: str) -> str:
return ACTE.get(act, act)
def _tokens(text: str) -> list[str]:
text = unicodedata.normalize("NFKD", (text or "").lower())
text = "".join(c for c in text if not unicodedata.combining(c))
return re.findall(r"[a-z0-9]{2,}", text)
# expansion légère de requêtes : le français légal a ses synonymes
SYNONYMS = {
"journalisation": ["journaux", "journal", "enregistrement", "evenements", "logs"],
"journaliser": ["journaux", "journal", "enregistrement", "evenements"],
"traçabilite": ["tracabilite", "enregistrement", "journaux"],
"suppression": ["effacement", "erase", "droit"],
"consentement": ["consent", "autorisation"],
"biais": ["biaises", "discrimination"],
"surveillance": ["biometrie", "reconnaissance"],
"evaluation": ["evaluer", "conformite", "audit"],
"documentation": ["documenter", "technique"],
"transparence": ["information", "explication"],
"gouvernance": ["gouverner", "responsabilite", "surveillance"],
"securite": ["securise", "cybersecurite"],
"informe": ["information", "divulgation", "informe"],
"informer": ["information", "divulgation"],
"impact": ["dpia", "aipd", "fria"],
"dpia": ["aipd", "fria"],
"fria": ["dpia", "aipd"],
"parlent": ["interactions", "interagit"],
"chatbot": ["conversationnel", "agent"],
"cv": ["recrutement", "candidature"],
}
def _query_tokens(text: str) -> list[str]:
toks = _tokens(text)
out = list(toks)
for t in toks:
out.extend(SYNONYMS.get(t, []))
return out
def _load_jsonl(data_dir: Path, name: str) -> list[dict]:
p = data_dir / name
if not p.exists():
return []
return [json.loads(l) for l in p.read_text(encoding="utf-8").splitlines() if l.strip()]
class Index:
"""BM25-lite sur (title pondéré x3, text)."""
def __init__(self, docs: list[dict]):
self.docs = docs
self.df: dict[str, int] = {}
self.tfs: list[dict[str, int]] = []
for d in docs:
toks = _tokens(d.get("title", "")) * 3 + _tokens(d.get("text", ""))
tf: dict[str, int] = {}
for t in toks:
tf[t] = tf.get(t, 0) + 1
self.tfs.append(tf)
for t in tf:
self.df[t] = self.df.get(t, 0) + 1
self.N = len(docs)
self.avgdl = (sum(len(t) for t in self.tfs) / self.N) if self.N else 1.0
def search(self, query: str, top_k: int = 5) -> list[tuple[dict, float]]:
q = _query_tokens(query)
# un token présent dans ≤ N/200 documents est un token « signature » :
# le document qui le contient est poussé (1 rare > 3 moyens)
sig_max = max(2, self.N // 200)
scores = []
k1, b = 1.4, 0.6
for i, tf in enumerate(self.tfs):
dl = sum(tf.values())
s = 0.0
sig = 0
for t in q:
if t in tf:
idf = math.log(1 + (self.N - self.df[t] + 0.5) / (self.df[t] + 0.5))
s += idf * (tf[t] * (k1 + 1)) / (tf[t] + k1 * (1 - b + b * dl / self.avgdl))
if self.df[t] <= sig_max:
sig += 1
if s > 0:
if sig:
s *= 1.8
scores.append((i, s))
scores.sort(key=lambda x: -x[1])
return [(self.docs[i], s) for i, s in scores[:top_k]]
class Normask:
def __init__(self, data_dir: Path | None = None):
self.data_dir = data_dir or DATA_DIR
self.kb = _load_jsonl(self.data_dir, "kb.jsonl")
self.provisions = _load_jsonl(self.data_dir, "provisions_fr.jsonl")
self.reqs = _load_jsonl(self.data_dir, "requirements.jsonl")
self.idx_kb = Index(self.kb)
self.idx_req = Index([{"title": f"{r['req_id']} {r['obligation']}",
"text": r["obligation"], **r} for r in self.reqs])
# art "12" -> provisions RGPD/AI Act correspondantes (lookup direct)
self.by_act_num: dict[tuple[str, str], dict] = {}
for p in self.provisions:
self.by_act_num.setdefault((p["act"], str(p["number"])), p)
def detect_articles(self, query: str) -> list[dict]:
"""Repère les références d'articles dans la question (« art. 12 du RGPD »)."""
q = query.lower()
found, seen = [], set()
for m in re.finditer(r"(?:article|art\.?)\s*(\d{1,3})\b", q):
num = m.group(1).lstrip("0") or "0"
for act in ("RIA", "RGPD"):
# un acte est retenu s'il est nommé, ou si aucun n'est nommé
named_rgpd = "rgpd" in q
named_ria = "ai act" in q or "aiact" in q or "ia act" in q or "r ia" in q
if named_rgpd and not named_ria and act != "RGPD":
continue
if named_ria and not named_rgpd and act != "RIA":
continue
p = self.by_act_num.get((act, num))
if p and (act, num) not in seen:
seen.add((act, num))
found.append(p)
return found[:4]
def ask(self, question: str, voice: str = "non-tech", top_k: int = 4) -> dict:
kb_hits = self.idx_kb.search(question, top_k=top_k)
req_hits = self.idx_req.search(question, top_k=5)
articles = self.detect_articles(question)
# rattache les requirements machine de l'article détecté (« art. 12 RGPD »)
by_id = {r["req_id"]: r for r, _ in req_hits}
for a in articles:
for r in self.reqs:
if (r["act"] == a["act"] and str(r["article"]) == str(a["number"])
and r["req_id"] not in by_id and len(by_id) < 6):
by_id[r["req_id"]] = r
req_hits.append((r, 0.0))
sources = [{"tier": d["tier"], "tier_label": d["tier_label"], "source": d["source"],
"title": d["title"], "snippet": d["text"][:400], "score": round(s, 2)}
for d, s in kb_hits]
requirements = []
for r, _s in req_hits:
requirements.append({
"req_id": r["req_id"], "acte": _acte(r["act"]), "ref": r["ref"],
"obligation": r["obligation"], "actor": r["actor"],
"check_type": r["check_type"], "status": r["status"],
"rule": r["rule_sketch"], "machine": r["rule_sketch"] != "manual"})
arts = [{"acte": _acte(a["act"]), "article": a["number"],
"heading": a.get("heading", ""),
"excerpt": (a.get("text") or "")[:350]} for a in articles]
answer = {"question": question, "voice": voice, "requirements": requirements,
"articles": arts, "sources": sources,
"counts": {"kb": len(self.kb), "provisions": len(self.provisions),
"requirements": len(self.reqs)}}
answer["answer"] = (self._tech_answer(answer) if voice == "tech"
else self._nontech_answer(answer))
return answer
def _tech_answer(self, a: dict) -> str:
parts = []
if a["requirements"]:
parts.append("**Requirements correspondants :**")
for r in a["requirements"]:
rule = (f" — règle : `{r['rule']}`" if r["machine"]
else " — contrôle PROCESS (artefact daté à produire)")
parts.append(f"- `{r['req_id']}` ({r['acte']} art. {r['ref']}, "
f"{r['check_type']}) : {r['obligation']}{rule}")
parts.append("\nVérification : `python3 -m normexe <systeme>` — un échec cite le "
"manquement avec l'article. Preuve : `--seal` scelle le run (chaîne de "
"hash + event NoireBox signé).")
if a["articles"]:
parts.append("\n**Texte officiel (extrait, consolidation EUR-Lex) :**")
for art in a["articles"]:
head = f" — {art['heading']}" if art["heading"] else ""
if art["excerpt"]:
parts.append(f"- **{art['acte']} art. {art['article']}**{head} : "
f"« {art['excerpt']}… »")
else:
parts.append(f"- **{art['acte']} art. {art['article']}**{head}")
if a["sources"]:
parts.append("\n**Contexte & doctrine (par niveau d'autorité) :**")
for s in a["sources"][:4]:
parts.append(f"- [{s['tier_label']}] {s['title'][:110]}")
return "\n".join(parts) if parts else (
"Aucun passage pertinent trouvé — reformule avec un article (ex. « art. 12 RGPD ») "
"ou un mot-clé (journalisation, évaluation, gouvernance…).")
def _nontech_answer(self, a: dict) -> str:
parts = []
if a["requirements"]:
parts.append("Ce qu'on te demande concrètement :")
for r in a["requirements"][:3]:
parts.append(f"- {r['obligation']} ({r['acte']} art. {r['ref']}).")
parts.append("\nEt surtout : ça doit se **prouver**, pas se promettre. Chaque point "
"ci-dessus correspond à un test automatique — si le test passe, tu as la "
"preuve ; sinon, tu sais exactement quoi corriger.")
elif a["sources"]:
parts.append("Voici ce que disent les sources, de la plus officielle à la plus "
"pratique :")
if a["articles"] and a["articles"][0]["excerpt"]:
parts.append(f"\nLe texte légal ({a['articles'][0]['acte']} art. "
f"{a['articles'][0]['article']}) dit : « "
f"{a['articles'][0]['excerpt'][:220]}… »")
if a["sources"]:
parts.append("\n**Pour aller plus loin :**")
for s in a["sources"][:3]:
parts.append(f"- {s['tier_label']} : {s['title'][:110]}")
return "\n".join(parts) if parts else (
"Aucun passage pertinent trouvé — reformule avec un article (ex. « art. 12 RGPD ») "
"ou un mot-clé (journalisation, évaluation, gouvernance…).")
_instance: Normask | None = None
def get_instance() -> Normask:
global _instance
if _instance is None:
_instance = Normask()
return _instance