ask / engine.js
slabbdev's picture
Upload folder using huggingface_hub
2e72013 verified
Raw History Blame Contribute Delete
10.5 kB
// 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 };