Gabrielkph commited on
Commit
9c45e83
·
verified ·
1 Parent(s): 0324416

Put the values back in the LLM's answer (gabrielkpo/alias feat/demo-restore)

Browse files
Files changed (3) hide show
  1. alias.js +38 -6
  2. app.js +58 -1
  3. index.html +19 -0
alias.js CHANGED
@@ -461,12 +461,17 @@ export function normalize(e) {
461
  return folded.split(/\s+/u).filter(Boolean).join(" ");
462
  }
463
 
464
- /** masking.mask with a fresh alias table: masked text, spans with their alias, counts. */
 
 
 
 
 
 
465
  export function mask(text, entities) {
466
- const reserved = new Set(
467
- [...text.matchAll(ALIAS)].map((m) => `[${m[1]}_${parseInt(m[2], 10)}]`),
468
- );
469
  const byKey = new Map();
 
470
  const counters = {};
471
  const aliasFor = (e) => {
472
  const key = `${e.type}\u0000${normalize(e)}`;
@@ -475,23 +480,50 @@ export function mask(text, entities) {
475
  do {
476
  counters[e.type] = (counters[e.type] || 0) + 1;
477
  alias = `[${e.type}_${counters[e.type]}]`;
478
- } while (reserved.has(alias));
479
  byKey.set(key, alias);
 
480
  }
481
  return byKey.get(key);
482
  };
483
  const parts = [];
484
  const spans = [];
 
485
  let cursor = 0;
486
  for (const e of resolveOverlaps(entities)) {
487
  const alias = aliasFor(e);
488
  parts.push(text.slice(cursor, e.start), alias);
489
  spans.push({ type: e.type, start: e.start, end: e.end, alias });
 
490
  cursor = e.end;
491
  }
492
  parts.push(text.slice(cursor));
493
  const report = {};
494
  for (const s of spans) report[s.type] = (report[s.type] || 0) + 1;
495
  report.total = spans.length;
496
- return { masked: parts.join(""), entities: spans, report };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497
  }
 
461
  return folded.split(/\s+/u).filter(Boolean).join(" ");
462
  }
463
 
464
+ const canonical = (m) => `[${m[1]}_${parseInt(m[2], 10)}]`;
465
+
466
+ /**
467
+ * masking.mask with a fresh alias table: masked text, spans with their alias, counts, and what
468
+ * `restore` needs. `values` (alias -> the value it hides) stays in the page's memory only: it
469
+ * is never part of the report, the spans or a request.
470
+ */
471
  export function mask(text, entities) {
472
+ const literals = new Set([...text.matchAll(ALIAS)].map(canonical));
 
 
473
  const byKey = new Map();
474
+ const values = new Map();
475
  const counters = {};
476
  const aliasFor = (e) => {
477
  const key = `${e.type}\u0000${normalize(e)}`;
 
480
  do {
481
  counters[e.type] = (counters[e.type] || 0) + 1;
482
  alias = `[${e.type}_${counters[e.type]}]`;
483
+ } while (literals.has(alias));
484
  byKey.set(key, alias);
485
+ values.set(alias, e.text);
486
  }
487
  return byKey.get(key);
488
  };
489
  const parts = [];
490
  const spans = [];
491
+ const aliases = [];
492
  let cursor = 0;
493
  for (const e of resolveOverlaps(entities)) {
494
  const alias = aliasFor(e);
495
  parts.push(text.slice(cursor, e.start), alias);
496
  spans.push({ type: e.type, start: e.start, end: e.end, alias });
497
+ if (!aliases.includes(alias)) aliases.push(alias);
498
  cursor = e.end;
499
  }
500
  parts.push(text.slice(cursor));
501
  const report = {};
502
  for (const s of spans) report[s.type] = (report[s.type] || 0) + 1;
503
  report.total = spans.length;
504
+ return { masked: parts.join(""), entities: spans, report, values, aliases, literals };
505
+ }
506
+
507
+ /**
508
+ * masking.restore for one exchange: puts back the values of the aliases `mask` wrote into the
509
+ * text sent to the LLM. An alias that was already literal in the input is never restored (it
510
+ * cannot be told apart from a real one); an alias the answer invents stays as it is. Returns
511
+ * the text, the aliases restored, those sent but absent from the answer (`missing`) and the
512
+ * alias-shaped tokens left as they are (`unknown`).
513
+ */
514
+ export function restore(answer, result) {
515
+ const allowed = new Set(result.aliases.filter((a) => !result.literals.has(a)));
516
+ const restored = [];
517
+ const unknown = [];
518
+ const text = answer.replace(ALIAS, (...m) => {
519
+ const alias = canonical(m);
520
+ if (!allowed.has(alias)) {
521
+ if (!result.literals.has(alias) && !unknown.includes(alias)) unknown.push(alias);
522
+ return m[0];
523
+ }
524
+ if (!restored.includes(alias)) restored.push(alias);
525
+ return result.values.get(alias);
526
+ });
527
+ const missing = [...allowed].filter((a) => !restored.includes(a));
528
+ return { text, restored, missing, unknown };
529
  }
app.js CHANGED
@@ -8,7 +8,7 @@ import {
8
  Tensor,
9
  env,
10
  } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.1/dist/transformers.min.js";
11
- import { TAGS, detect, mask } from "./alias.js";
12
 
13
  const MODEL = "Gabrielkph/alias-mmbert-small";
14
  // What the first visit downloads: the ONNX model (563 MB) and the tokenizer (34 MB).
@@ -38,6 +38,14 @@ Merci de verser la somme sur le compte FR76 3000 6000 0112 3456 7890 189.
38
 
39
  Jean Dupont`;
40
 
 
 
 
 
 
 
 
 
41
  const $ = (id) => document.getElementById(id);
42
  let detector = null; // { tokenize, predict, bos, eos } once the model is loaded
43
  let last = null;
@@ -196,6 +204,18 @@ async function maskText() {
196
  table(result.report);
197
  $("copied").textContent = "";
198
  show($("results"), true);
 
 
 
 
 
 
 
 
 
 
 
 
199
  setStatus(`Masked in ${((performance.now() - started) / 1000).toFixed(1)} s, in this browser.`);
200
  } catch (error) {
201
  console.error(error);
@@ -206,6 +226,38 @@ async function maskText() {
206
  }
207
  }
208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  async function copyMasked() {
210
  let copied = true;
211
  try {
@@ -249,6 +301,11 @@ $("input").addEventListener("keydown", (event) => {
249
  });
250
  $("copy").addEventListener("click", copyMasked);
251
  $("download").addEventListener("click", downloadReport);
 
 
 
 
 
252
  load().catch((error) => {
253
  console.error(error);
254
  show($("progress"), false);
 
8
  Tensor,
9
  env,
10
  } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.1/dist/transformers.min.js";
11
+ import { TAGS, detect, mask, restore } from "./alias.js";
12
 
13
  const MODEL = "Gabrielkph/alias-mmbert-small";
14
  // What the first visit downloads: the ONNX model (563 MB) and the tokenizer (34 MB).
 
38
 
39
  Jean Dupont`;
40
 
41
+ // What an LLM could answer to "Summarise this document" about the masked example: written with
42
+ // the aliases the example gets, so the restore step can be tried without an LLM.
43
+ const EXAMPLE_ANSWER = `Résumé : [PERSON_1], né le [BIRTH_DATE_1] et domicilié [ADDRESS_1], demande le remboursement de ses frais pour le dossier n° [IDENTIFIER_1].
44
+
45
+ - Versement demandé sur le compte [IBAN_1].
46
+ - Numéro de sécurité sociale indiqué : [NATIONAL_ID_1].
47
+ - Contact : [PHONE_1] ou [EMAIL_1].`;
48
+
49
  const $ = (id) => document.getElementById(id);
50
  let detector = null; // { tokenize, predict, bos, eos } once the model is loaded
51
  let last = null;
 
204
  table(result.report);
205
  $("copied").textContent = "";
206
  show($("results"), true);
207
+ // A new masked text: the previous answer and its restored version no longer apply.
208
+ $("answer").value = "";
209
+ $("restored").value = "";
210
+ $("restore-report").textContent = "";
211
+ show($("restored"), false);
212
+ show($("copy-restored"), false);
213
+ show($("back"), true);
214
+ // The example answer only fits the example, and only if every alias it uses was given.
215
+ const fits = [...EXAMPLE_ANSWER.matchAll(/\[[A-Z_]+_\d+\]/g)].every((m) =>
216
+ result.aliases.includes(m[0]),
217
+ );
218
+ show($("example-answer"), text === EXAMPLE && fits);
219
  setStatus(`Masked in ${((performance.now() - started) / 1000).toFixed(1)} s, in this browser.`);
220
  } catch (error) {
221
  console.error(error);
 
226
  }
227
  }
228
 
229
+ function restoreAnswer() {
230
+ if (!last) return;
231
+ const answer = $("answer").value;
232
+ const report = $("restore-report");
233
+ if (!answer.trim()) {
234
+ report.textContent = "Paste the LLM's answer first.";
235
+ return;
236
+ }
237
+ const back = restore(answer, last);
238
+ $("restored").value = back.text;
239
+ show($("restored"), true);
240
+ show($("copy-restored"), true);
241
+ $("copied-restored").textContent = "";
242
+ const parts = [`${back.restored.length} alias(es) replaced by their value.`];
243
+ if (back.missing.length) parts.push(`Not in the answer: ${back.missing.join(", ")}.`);
244
+ if (back.unknown.length) {
245
+ parts.push(`Left as they are (not from this text): ${back.unknown.join(", ")}.`);
246
+ }
247
+ report.textContent = parts.join(" ");
248
+ }
249
+
250
+ async function copyRestored() {
251
+ let copied = true;
252
+ try {
253
+ await navigator.clipboard.writeText($("restored").value);
254
+ } catch {
255
+ $("restored").select();
256
+ copied = document.execCommand("copy");
257
+ }
258
+ $("copied-restored").textContent = copied ? "Copied." : "Not copied: select the text and copy it.";
259
+ }
260
+
261
  async function copyMasked() {
262
  let copied = true;
263
  try {
 
301
  });
302
  $("copy").addEventListener("click", copyMasked);
303
  $("download").addEventListener("click", downloadReport);
304
+ $("restore").addEventListener("click", restoreAnswer);
305
+ $("example-answer").addEventListener("click", () => {
306
+ $("answer").value = EXAMPLE_ANSWER;
307
+ });
308
+ $("copy-restored").addEventListener("click", copyRestored);
309
  load().catch((error) => {
310
  console.error(error);
311
  show($("progress"), false);
index.html CHANGED
@@ -53,6 +53,25 @@
53
  <h2>Report <span class="muted">(counts only, never the values)</span></h2>
54
  <table id="report"><thead><tr><th>Type</th><th>Values</th></tr></thead><tbody></tbody></table>
55
  </section>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  </main>
57
 
58
  <footer class="muted">Alias, open source (MIT):
 
53
  <h2>Report <span class="muted">(counts only, never the values)</span></h2>
54
  <table id="report"><thead><tr><th>Type</th><th>Values</th></tr></thead><tbody></tbody></table>
55
  </section>
56
+
57
+ <section id="back" aria-labelledby="back-title" hidden>
58
+ <h2 id="back-title">Put the values back <span class="muted">(in this browser)</span></h2>
59
+ <p class="muted">Send the masked text to the LLM you use (Le Chat, ChatGPT…) with your
60
+ request, for instance "Summarise this document", then paste its answer here: the aliases
61
+ become the real values again, without the values ever leaving this page.</p>
62
+ <textarea id="answer" rows="8" spellcheck="false"
63
+ placeholder="Paste the LLM's answer, with its [PERSON_1], [IBAN_1]…"></textarea>
64
+ <div class="actions">
65
+ <button id="restore" type="button">Restore</button>
66
+ <button id="example-answer" type="button" class="secondary" hidden>Try an example answer</button>
67
+ </div>
68
+ <p id="restore-report" class="muted" role="status"></p>
69
+ <textarea id="restored" rows="8" readonly spellcheck="false" hidden></textarea>
70
+ <div class="actions">
71
+ <button id="copy-restored" type="button" hidden>Copy the restored answer</button>
72
+ <span id="copied-restored" class="muted" aria-live="polite"></span>
73
+ </div>
74
+ </section>
75
  </main>
76
 
77
  <footer class="muted">Alias, open source (MIT):