File size: 10,465 Bytes
2e72013 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | // engine.js — port JS exact de normask/retriever.py (BM25-lite + réponses déterministes).
// Parité prouvée par test/parity.mjs contre les sorties golden du Python.
// Utilisable dans le navigateur (module ESM) et sous node (tests).
const ACTE = { RIA: "AI Act" };
const acte = (a) => ACTE[a] || a;
function tokens(text) {
const s = (text || "").toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g, "");
return (s.match(/[a-z0-9]{2,}/g) || []);
}
// expansion légère de requêtes : le français légal a ses synonymes (miroir de retriever.py)
const 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"],
};
// troncature en points de code (parité str[:n] Python — les emoji comptent 1)
const cut = (s, n) => Array.from(s).slice(0, n).join("");
function queryTokens(text) {
const toks = tokens(text);
const out = toks.slice();
for (const t of toks) out.push(...(SYNONYMS[t] || []));
return out;
}
class Index {
constructor(docs) {
this.docs = docs;
this.df = new Map();
this.tfs = [];
for (const d of docs) {
const toks = [...tokens(d.title || ""), ...tokens(d.title || ""), ...tokens(d.title || ""),
...tokens(d.text || "")];
const tf = new Map();
for (const t of toks) tf.set(t, (tf.get(t) || 0) + 1);
this.tfs.push(tf);
for (const t of tf.keys()) this.df.set(t, (this.df.get(t) || 0) + 1);
}
this.N = docs.length;
// parité avec retriever.py : avgdl = moyenne des tokens UNIQUES par doc (len(dict))
this.avgdl = this.N ? this.tfs.reduce((a, tf) => a + tf.size, 0) / this.N : 1.0;
}
search(query, topK) {
const q = queryTokens(query);
const sigMax = Math.max(2, Math.floor(this.N / 200));
const scored = [];
const k1 = 1.4, b = 0.6;
this.tfs.forEach((tf, i) => {
let dl = 0;
for (const n of tf.values()) dl += n;
let s = 0, sig = 0;
for (const t of q) {
const f = tf.get(t);
if (f) {
const df = this.df.get(t);
const idf = Math.log(1 + (this.N - df + 0.5) / (df + 0.5));
s += idf * (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / this.avgdl));
if (df <= sigMax) sig += 1;
}
}
if (s > 0) {
if (sig) s *= 1.8;
scored.push([i, s]);
}
});
scored.sort((x, y) => (y[1] - x[1]) || (x[0] - y[0]));
return scored.slice(0, topK).map(([i, s]) => [this.docs[i], s]);
}
}
class Normask {
constructor({ kb, provisions, reqs }) {
this.kb = kb;
this.provisions = provisions;
this.reqs = reqs;
this.idxKb = new Index(kb);
this.idxReq = new Index(reqs.map((r) => ({ title: `${r.req_id} ${r.obligation}`,
text: r.obligation, ...r })));
this.byActNum = new Map();
for (const p of provisions) {
const k = p.act + "|" + String(p.number);
if (!this.byActNum.has(k)) this.byActNum.set(k, p);
}
}
detectArticles(query) {
const q = query.toLowerCase();
const found = [];
const seen = new Set();
const re = /(?:article|art\.?)\s*(\d{1,3})\b/g;
let m;
while ((m = re.exec(q)) !== null) {
const num = String(parseInt(m[1], 10));
for (const act of ["RIA", "RGPD"]) {
const namedRgpd = q.includes("rgpd");
const namedRia = q.includes("ai act") || q.includes("aiact") || q.includes("ia act") || q.includes("r ia");
if (namedRgpd && !namedRia && act !== "RGPD") continue;
if (namedRia && !namedRgpd && act !== "RIA") continue;
const p = this.byActNum.get(act + "|" + num);
const k = act + num;
if (p && !seen.has(k)) { seen.add(k); found.push(p); }
}
}
return found.slice(0, 4);
}
ask(question, voice = "non-tech", topK = 4) {
const kbHits = this.kb.length ? this.idxKb.search(question, topK) : [];
let reqHits = this.idxReq.search(question, 5);
const articles = this.detectArticles(question);
const byId = new Map(reqHits.map(([r]) => [r.req_id, r]));
for (const a of articles) {
for (const r of this.reqs) {
if (r.act === a.act && String(r.article) === String(a.number) &&
!byId.has(r.req_id) && byId.size < 6) {
byId.set(r.req_id, r);
reqHits.push([r, 0.0]);
}
}
}
const sources = kbHits.map(([d, s]) => ({
tier: d.tier, tier_label: d.tier_label, source: d.source,
title: d.title, snippet: cut(d.text, 400), score: Math.round(s * 100) / 100 }));
const requirements = reqHits.map(([r]) => ({
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" }));
const arts = articles.map((a) => ({
acte: acte(a.act), article: a.number, heading: a.heading || "",
excerpt: cut(a.text || "", 350) }));
const counts = { kb: this.kb.length, provisions: this.provisions.length,
requirements: this.reqs.length };
const answer = voice === "tech" ? this.techAnswer({ requirements, articles: arts, sources })
: this.nontechAnswer({ requirements, articles: arts, sources });
return { question, voice, requirements, articles: arts, sources, counts, answer };
}
// branchement différé du gros corpus de contexte (chargement en arrière-plan)
attachKb(docs) {
this.kb = docs;
this.idxKb = new Index(docs);
}
// passages pleine longueur pour la rédaction LLM (ne touche pas à ask(), parité préservée)
grounding(question, topK = 6) {
const kbHits = this.kb.length ? this.idxKb.search(question, topK) : [];
let reqHits = this.idxReq.search(question, 5);
const articles = this.detectArticles(question);
const byId = new Map(reqHits.map(([r]) => [r.req_id, r]));
for (const a of articles) {
for (const r of this.reqs) {
if (r.act === a.act && String(r.article) === String(a.number) &&
!byId.has(r.req_id) && byId.size < 6) {
byId.set(r.req_id, r);
reqHits.push([r, 0.0]);
}
}
}
return {
passages: kbHits.map(([d]) => ({ tier: d.tier, tier_label: d.tier_label,
source: d.source, title: d.title, text: cut(d.text, 800) })),
requirements: reqHits.map(([r]) => ({ req_id: r.req_id, acte: acte(r.act), ref: r.ref,
obligation: r.obligation, check_type: r.check_type,
machine: r.rule_sketch !== "manual", rule: r.rule_sketch })),
articles: articles.map((a) => ({ acte: acte(a.act), article: a.number,
heading: a.heading || "", text: cut(a.text || "", 1600) })),
};
}
techAnswer(a) {
const parts = [];
if (a.requirements.length) {
parts.push("**Requirements correspondants :**");
for (const r of a.requirements) {
const rule = r.machine ? ` — règle : \`${r.rule}\`` : " — contrôle PROCESS (artefact daté à produire)";
parts.push(`- \`${r.req_id}\` (${r.acte} art. ${r.ref}, ${r.check_type}) : ${r.obligation}${rule}`);
}
parts.push("\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.length) {
parts.push("\n**Texte officiel (extrait, consolidation EUR-Lex) :**");
for (const art of a.articles) {
const head = art.heading ? ` — ${art.heading}` : "";
if (art.excerpt) parts.push(`- **${art.acte} art. ${art.article}**${head} : « ${art.excerpt}… »`);
else parts.push(`- **${art.acte} art. ${art.article}**${head}`);
}
}
if (a.sources.length) {
parts.push("\n**Contexte & doctrine (par niveau d'autorité) :**");
for (const s of a.sources.slice(0, 4)) parts.push(`- [${s.tier_label}] ${cut(s.title, 110)}`);
}
return parts.length ? parts.join("\n") :
"Aucun passage pertinent trouvé — reformule avec un article (ex. « art. 12 RGPD ») ou un mot-clé (journalisation, évaluation, gouvernance…).";
}
nontechAnswer(a) {
const parts = [];
if (a.requirements.length) {
parts.push("Ce qu'on te demande concrètement :");
for (const r of a.requirements.slice(0, 3)) {
parts.push(`- ${r.obligation} (${r.acte} art. ${r.ref}).`);
}
parts.push("\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.");
} else if (a.sources.length) {
parts.push("Voici ce que disent les sources, de la plus officielle à la plus pratique :");
}
if (a.articles.length && a.articles[0].excerpt) {
parts.push(`\nLe texte légal (${a.articles[0].acte} art. ${a.articles[0].article}) dit : « ${cut(a.articles[0].excerpt, 220)}… »`);
}
if (a.sources.length) {
parts.push("\n**Pour aller plus loin :**");
for (const s of a.sources.slice(0, 3)) parts.push(`- ${s.tier_label} : ${cut(s.title, 110)}`);
}
return parts.length ? parts.join("\n") :
"Aucun passage pertinent trouvé — reformule avec un article (ex. « art. 12 RGPD ») ou un mot-clé (journalisation, évaluation, gouvernance…).";
}
}
export { Normask, Index, tokens, queryTokens };
|