adaamko commited on
Commit
ac6bf1d
·
verified ·
1 Parent(s): 8030201

v2: customer-message PII demo with the model live (Gradio)

Browse files
Files changed (18) hide show
  1. DATA_LICENSE_TAB.txt +0 -9
  2. README.md +24 -26
  3. app.js +0 -239
  4. app.py +507 -0
  5. cascade.py +12 -6
  6. data/replay.json +0 -0
  7. data/requests.jsonl +0 -0
  8. engine.js +0 -81
  9. index.html +0 -125
  10. plain.py +107 -0
  11. prep.py +0 -73
  12. prep_pii.py +63 -0
  13. pyref.py +0 -15
  14. requirements.txt +9 -0
  15. sim.py +3 -3
  16. style.css +0 -125
  17. teacher_core.py +2 -2
  18. verify_engine.js +0 -23
DATA_LICENSE_TAB.txt DELETED
@@ -1,9 +0,0 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (C) 2021-2026 Norsk Regnesentral
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
-
7
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
-
9
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,46 +1,44 @@
1
  ---
2
  title: RuleChef Live
3
- colorFrom: gray
4
  colorTo: blue
5
- sdk: static
6
- app_file: index.html
 
 
7
  license: apache-2.0
8
- short_description: Model answers become regex rules as a stream plays
9
  models:
10
  - vllm-sr/vela3-fast
11
  datasets:
12
- - mattmdjaga/text-anonymization-benchmark-train
13
  ---
14
 
15
  # RuleChef Live
16
 
17
- A request stream where a teacher model's answers become labelled examples and
18
- [RuleChef](https://github.com/KRLabsOrg/rulechef) turns them into regex rules. Rules answer the requests they cover, with no model
19
- call; the teacher ([vllm-sr/vela3-fast](https://huggingface.co/vllm-sr/vela3-fast)) answers the rest.
20
 
21
- - Task: dates and times, codes and reference numbers, and quantities in sentences from European Court of Human Rights judgments
22
- (TAB, public train split).
23
- - Rule learning: RuleChef search synthesis (`synth="search"`, no LLM), re-run on CPU after the first 50 labelled examples and then every 100 new ones.
24
- - The page replays one offline run of `sim.py` (`data/replay.json`). The rules run live in the browser (`engine.js`, a port of
25
- RuleChef's executor and of the gate); the teacher does not run on this static page.
26
 
27
  ## Files
28
 
29
- - `index.html`, `app.js`, `style.css`: the page. `engine.js`: rule execution and gate in the browser.
30
  - `cascade.py`: gate, rule execution (RuleChef's executor), scoring. `sim.py`: the stream run that writes `data/replay.json`.
31
- - `prep.py`, `run_teacher.py`, `teacher_core.py`: how the requests and the teacher's answers in `data/requests.jsonl` were made.
32
- - `pyref.py`, `verify_engine.js`: check that `engine.js` gives the same spans and gate decisions as the Python code.
33
 
34
- Reproduce (Python 3.12; `torch` CPU, `transformers==5.17.0`, `pyarrow`, and RuleChef from
35
- `git+https://github.com/KRLabsOrg/rulechef@8173f96f1b48cf1d66b35bc5ebe9d83be962a610`), in a fresh folder `work/`:
36
- `python prep.py <TAB parquet> work`; run `run_teacher.py` over `work/requests.jsonl` into `work/teacher.jsonl`;
37
- `python sim.py work work/replay.json`.
38
 
39
  ## Licences
40
 
41
- - Code in this Space: Apache-2.0.
42
- - RuleChef: Apache-2.0. vela3-fast: Apache-2.0.
43
- - TAB (Text Anonymization Benchmark, Pilán et al. 2022, Norsk Regnesentral): MIT, notice in `DATA_LICENSE_TAB.txt`.
44
- `data/requests.jsonl` holds sentences from its train split
45
- ([mattmdjaga/text-anonymization-benchmark-train](https://huggingface.co/datasets/mattmdjaga/text-anonymization-benchmark-train)
46
- @`f0b7eeb`), with TAB's labels for the three types and the teacher's answers.
 
1
  ---
2
  title: RuleChef Live
3
+ colorFrom: green
4
  colorTo: blue
5
+ sdk: gradio
6
+ sdk_version: 5.49.1
7
+ python_version: "3.12"
8
+ app_file: app.py
9
  license: apache-2.0
10
+ short_description: Your model teaches cheap rules while it works
11
  models:
12
  - vllm-sr/vela3-fast
13
  datasets:
14
+ - nvidia/Nemotron-PII
15
  ---
16
 
17
  # RuleChef Live
18
 
19
+ Your model teaches cheap rules while it works. Every answer the model gives becomes an example;
20
+ [RuleChef](https://github.com/KRLabsOrg/rulechef) turns the examples into plain rules that answer the next requests instantly, without
21
+ the model.
22
 
23
+ - Task: emails, phone numbers, dates and ID numbers in short customer messages (Nemotron-PII, synthetic, CC BY 4.0).
24
+ - Model: [vllm-sr/vela3-fast](https://huggingface.co/vllm-sr/vela3-fast) on CPU.
25
+ - Rules: RuleChef search synthesis (`synth="search"`, no LLM), on CPU.
26
+ - The stream on the page is a replay of one offline run of `sim.py` (`data/replay.json`). "Try it" runs the rules and the model live and
27
+ re-learns rules from your examples.
28
 
29
  ## Files
30
 
31
+ - `app.py`: the page. `plain.py`: readable form of a regex rule.
32
  - `cascade.py`: gate, rule execution (RuleChef's executor), scoring. `sim.py`: the stream run that writes `data/replay.json`.
33
+ - `prep_pii.py`, `run_teacher.py`, `teacher_core.py`: how the messages and the model's answers in `data/requests.jsonl` were made.
 
34
 
35
+ Reproduce in a fresh folder `work/`: `python prep_pii.py <Nemotron-PII train parquet> work 1500 300`; run `run_teacher.py` over
36
+ `work/requests.jsonl` into `work/teacher.jsonl`; `python sim.py work work/replay.json`.
 
 
37
 
38
  ## Licences
39
 
40
+ - Code in this Space: Apache-2.0. RuleChef: Apache-2.0. vela3-fast: Apache-2.0.
41
+ - Data: [nvidia/Nemotron-PII](https://huggingface.co/datasets/nvidia/Nemotron-PII) (revision `b70ffaf5`) by NVIDIA, licensed under
42
+ [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). All personal data in it is synthetic. Changes: sentences were cut from its train
43
+ split, its labels were mapped to four types (email, phone, date, ID number), and the model's answers were added. The result is
44
+ `data/requests.jsonl`, under the same licence.
 
app.js DELETED
@@ -1,239 +0,0 @@
1
- // RuleChef Live: replays data/replay.json (written by sim.py) and runs the rules in the browser (engine.js).
2
- (function () {
3
- "use strict";
4
- const E = window.RCEngine;
5
- const $ = (s) => document.querySelector(s);
6
- const fmt = (n) => n.toLocaleString("en-US");
7
- const pct = (a, b) => (b ? (100 * a / b).toFixed(1) + " %" : "–");
8
- const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
9
- const NAMES = { DATETIME: "date/time", CODE: "code", QUANTITY: "quantity" };
10
-
11
- let R, REQ = {}, EV, VERS, GUARD, META, N, AT, S = {}, LAB = [], HOLD = [];
12
- let k = 0, timer = null;
13
-
14
- function cum(xs) { const out = [0]; let s = 0; for (const x of xs) { s += x; out.push(s); } return out; }
15
-
16
- function versionAt(i) { let lo = 0; for (let j = 0; j < AT.length; j++) if (AT[j] <= i) lo = j; return VERS[lo]; }
17
- function blockedAt(i) { return new Set(GUARD.filter((g) => g.at < i).map((g) => g.key)); }
18
- function activeRules(v, i) { const off = blockedAt(i); return v.rules.filter((r) => r.trusted && !off.has(r.key)); }
19
-
20
- function card(t, v, s) { return `<div class="kpi"><div class="kt">${t}</div><div class="kv">${v}</div><div class="ks">${s}</div></div>`; }
21
-
22
- function renderKpis() {
23
- const v = versionAt(k);
24
- const nr = S.rules[k], ns = S.spans[k], nc = S.check[k], na = S.agree[k], calls = S.call[k];
25
- const lat = k ? S.lat[k] / k : 0, tlat = k ? S.tlat[k] / k : 0;
26
- const rm = EV.slice(0, k).filter((e) => e.by === "rules").map((e) => e.rule_ms).sort((a, b) => a - b);
27
- const med = rm.length ? rm[rm.length >> 1].toFixed(2) + " ms (median)" : "–";
28
- $("#kpis").innerHTML = [
29
- card("Requests", `${fmt(k)} / ${fmt(N)}`, `rule set v${v.v}`),
30
- card("Answered by rules", pct(nr, k), `${fmt(nr)}: ${fmt(ns)} with spans, ${fmt(nr - ns)} with nothing to extract`),
31
- card("Model calls", fmt(calls), `${fmt(k - calls)} saved (${pct(k - calls, k)}); spot checks included`),
32
- card("Mean latency", `${Math.round(lat)} ms`, `teacher on every request: ${Math.round(tlat)} ms; a rule answer: ${med}`),
33
- card("Spot-check agreement", pct(na, nc), `${na} of ${nc} checked rule answers equal the teacher's`),
34
- card("Rules answering", String(activeRules(v, k).length), `of ${v.rules.length} in v${v.v}; ${blockedAt(k).size} switched off by the guard`),
35
- ].join("");
36
- }
37
-
38
- // ------------------------------------------------------------------ charts (SVG, two series each, crosshair tooltip)
39
- const W = 360, H = 190, P = { l: 40, r: 10, t: 8, b: 22 };
40
- function lineChart(el, cfg) {
41
- const { series, yMax, yTicks, yFmt, markers } = cfg;
42
- const x = (v) => P.l + (W - P.l - P.r) * v / N, y = (v) => H - P.b - (H - P.t - P.b) * v / yMax;
43
- let g = `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(cfg.label)}">`;
44
- for (const t of yTicks) g += `<line x1="${P.l}" x2="${W - P.r}" y1="${y(t)}" y2="${y(t)}" stroke="var(--grid)"/><g class="axis"><text x="${P.l - 5}" y="${y(t) + 3}" text-anchor="end">${yFmt(t)}</text></g>`;
45
- for (let t = 0; t <= N; t += 1000) g += `<g class="axis"><text x="${x(t)}" y="${H - 6}" text-anchor="middle">${fmt(t)}</text></g>`;
46
- for (const m of markers || []) if (m.at <= k && m.at > 0) g += `<line x1="${x(m.at)}" x2="${x(m.at)}" y1="${P.t}" y2="${H - P.b}" stroke="var(--line)" stroke-dasharray="2 3"/>`;
47
- g += `<line x1="${P.l}" x2="${W - P.r}" y1="${H - P.b}" y2="${H - P.b}" stroke="var(--line)"/>`;
48
- for (const s of series) {
49
- if (s.pts.length < 2) continue;
50
- g += `<polyline fill="none" stroke="${s.color}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" points="${s.pts.map((p) => x(p[0]).toFixed(1) + "," + y(p[1]).toFixed(1)).join(" ")}"/>`;
51
- }
52
- g += `<line class="xh" x1="0" x2="0" y1="${P.t}" y2="${H - P.b}" stroke="var(--muted)" visibility="hidden"/>`;
53
- g += `<rect x="${P.l}" y="${P.t}" width="${W - P.l - P.r}" height="${H - P.t - P.b}" fill="transparent"/></svg>`;
54
- g += `<div class="legend">${series.map((s) => `<span><i style="background:${s.color}"></i>${esc(s.name)}</span>`).join("")}</div>`;
55
- el.innerHTML = g;
56
- const svg = el.querySelector("svg"), xh = el.querySelector(".xh"), tip = $("#tip");
57
- svg.addEventListener("mousemove", (ev) => {
58
- const b = svg.getBoundingClientRect();
59
- const vx = (ev.clientX - b.left) / b.width * W;
60
- const req = Math.max(0, Math.min(k, Math.round((vx - P.l) / (W - P.l - P.r) * N)));
61
- const rows = series.map((s) => { let best = null; for (const p of s.pts) if (!best || Math.abs(p[0] - req) < Math.abs(best[0] - req)) best = p; return [s, best]; }).filter((r) => r[1]);
62
- if (!rows.length) return;
63
- xh.setAttribute("x1", x(rows[0][1][0])); xh.setAttribute("x2", x(rows[0][1][0])); xh.setAttribute("visibility", "visible");
64
- tip.innerHTML = `request ${fmt(rows[0][1][0])}<br>` + rows.map(([s, p]) => `<span style="color:${s.color}">&#9644;</span> ${esc(s.name)}: <b>${cfg.tipFmt(p[1])}</b>`).join("<br>");
65
- tip.hidden = false; tip.style.left = Math.min(ev.clientX + 12, window.innerWidth - 230) + "px"; tip.style.top = (ev.clientY + 12) + "px";
66
- });
67
- svg.addEventListener("mouseleave", () => { tip.hidden = true; xh.setAttribute("visibility", "hidden"); });
68
- }
69
- function windowPts(arr, w = 200, step = 20) {
70
- const pts = [];
71
- for (let i = step; i <= k; i += step) { const lo = Math.max(0, i - w); pts.push([i, (arr[i] - arr[lo]) / (i - lo)]); }
72
- return pts;
73
- }
74
- const C1 = () => getComputedStyle(document.documentElement).getPropertyValue("--s1").trim();
75
- const C2 = () => getComputedStyle(document.documentElement).getPropertyValue("--s2").trim();
76
- function renderCharts() {
77
- const markers = VERS.slice(1);
78
- lineChart($("#c-cov"), { label: "Share of requests answered by rules", yMax: 1, yTicks: [0, 0.25, 0.5, 0.75, 1], yFmt: (t) => Math.round(t * 100) + "%",
79
- tipFmt: (v) => (100 * v).toFixed(1) + " %", markers,
80
- series: [{ name: "answered by rules", color: C1(), pts: windowPts(S.rules) }, { name: "rules found spans", color: C2(), pts: windowPts(S.spans) }] });
81
- const step = 20, a = [], b = [];
82
- for (let i = 0; i <= k; i += step) { a.push([i, S.call[i]]); b.push([i, i]); }
83
- lineChart($("#c-calls"), { label: "Model calls", yMax: N, yTicks: [0, 1000, 2000, 3000], yFmt: (t) => fmt(t), tipFmt: (v) => fmt(v), markers,
84
- series: [{ name: "with rules", color: C1(), pts: a }, { name: "teacher on every request", color: C2(), pts: b }] });
85
- lineChart($("#c-lat"), { label: "Latency per request", yMax: 500, yTicks: [0, 100, 200, 300, 400, 500], yFmt: (t) => String(t), tipFmt: (v) => Math.round(v) + " ms", markers,
86
- series: [{ name: "cascade", color: C1(), pts: windowPts(S.lat) }, { name: "teacher on every request", color: C2(), pts: windowPts(S.tlat) }] });
87
- }
88
-
89
- // ------------------------------------------------------------------ tables
90
- function renderVersions() {
91
- const cur = versionAt(k).v;
92
- const head = `<tr><th>version</th><th class="num">from request</th><th class="num">labelled examples</th><th class="num">rules answering / learned</th>
93
- <th class="num">synthesis s</th><th class="num">holdout answered by rules</th><th class="num">same answer as teacher</th>
94
- <th class="num">rule spans P / R vs teacher</th><th class="num">cascade F1 vs teacher</th><th class="num">TAB annotation F1: teacher / cascade</th></tr>`;
95
- const rows = VERS.filter((v) => v.at <= k).map((v) => {
96
- const h = v.holdout, ra = h.rules_answer;
97
- return `<tr class="${v.v === cur ? "current" : ""}"><td>v${v.v}</td><td class="num">${fmt(v.at)}</td><td class="num">${fmt(v.n_labelled)}</td>
98
- <td class="num">${v.rules.filter((r) => r.trusted).length} / ${v.rules.length}</td><td class="num">${v.synth_s.toFixed(1)}</td>
99
- <td class="num">${pct(ra, h.n)}</td><td class="num">${ra ? pct(h.exact_agree, ra) : "–"}</td>
100
- <td class="num">${ra ? h.routed_t.P.toFixed(2) + " / " + h.routed_t.R.toFixed(2) : "–"}</td>
101
- <td class="num">${h.casc_t.F1.toFixed(3)}</td><td class="num">${h.teach_g.F1.toFixed(3)} / ${h.casc_g.F1.toFixed(3)}</td></tr>`;
102
- });
103
- $("#t-vers").innerHTML = `<thead>${head}</thead><tbody>${rows.join("")}</tbody>`;
104
- }
105
-
106
- function renderRules() {
107
- const v = versionAt(k), off = blockedAt(k), used = {};
108
- for (let i = 0; i < k; i++) if (EV[i].by === "rules") for (const key of EV[i].fired) used[key] = (used[key] || 0) + 1;
109
- const rows = v.rules.map((r) => {
110
- const n = r.tp + r.fp;
111
- const st = off.has(r.key) ? ["cut", "switched off"] : r.trusted ? ["on", "answering"] : ["off", "not trusted"];
112
- return { r, st, n, used: used[r.key] || 0 };
113
- }).sort((a, b) => (a.st[0] !== "on") - (b.st[0] !== "on") || b.used - a.used || b.n - a.n);
114
- $("#rules-help").textContent = v.v === 0
115
- ? "No rule set yet: every request goes to the teacher until 50 examples are labelled."
116
- : `v${v.v}, learned from ${fmt(v.n_labelled)} labelled examples in ${v.synth_s.toFixed(1)} s. "Answering" rules matched at least ${META.trust_min} times on the labelled data with precision at least ${META.trust_prec}; the others are kept but do not answer. The last column counts requests this exact rule answered so far.`;
117
- const head = `<thead><tr><th>status</th><th>type</th><th>regex</th><th>output</th><th class="num">labelled matches (precision)</th><th class="num">requests answered</th></tr></thead>`;
118
- const tr = ({ r, st, n, used: u }) => `<tr><td><span class="st ${st[0]}">${st[1]}</span></td><td>${r.type}</td><td class="rx">${esc(r.regex)}</td>
119
- <td class="mono">${esc(r.template)}</td><td class="num">${n ? `${n} (${(r.tp / n).toFixed(2)})` : "0"}</td><td class="num">${u}</td></tr>`;
120
- const on = rows.filter((x) => x.st[0] !== "off"), rest = rows.filter((x) => x.st[0] === "off");
121
- $("#t-rules").innerHTML = head + "<tbody>" + (on.map(tr).join("") || '<tr><td colspan="6">No answering rules.</td></tr>') + "</tbody>";
122
- const det = $("#rules-rest");
123
- const open = det.open;
124
- det.innerHTML = rest.length ? `<summary>${rest.length} learned rules that do not answer (precision below ${META.trust_prec} or too few matches)</summary><div class="tablewrap"><table class="rules">${head}<tbody>${rest.map(tr).join("")}</tbody></table></div>` : "";
125
- det.open = open;
126
- const g = v.gate;
127
- let html = "";
128
- if (g) {
129
- html += `<p><b>Gate of v${v.v}.</b> A request goes to the rules only if every trigger token is covered by an answering rule or sits in a skip context.
130
- Trigger tokens: anything with a digit, plus ${g.trigger_words.length} learned words: ${g.trigger_words.map((w) => `<code>${esc(w)}</code>`).join(", ")}.</p>
131
- <p>Skip contexts (previous word + digit shape, <code>9</code> = digits) that the teacher labels at most ${Math.round(META.skip_ratio * 100)} % of the time:
132
- ${g.skip.map(([p, s]) => `<code>${esc(p || "(start)")} ${esc(s)}</code>`).join(", ") || "none"}.</p>`;
133
- }
134
- const gl = GUARD.filter((x) => x.at < k);
135
- html += gl.length
136
- ? `<p><b>Drift guard.</b> ${gl.map((x) => `at request ${x.at}: <code>${esc(x.key.split("\t")[1])}</code> switched off (spot checks ${x.tp} right, ${x.fp} wrong)`).join("; ")}.</p>`
137
- : `<p><b>Drift guard.</b> No rule switched off so far. A rule is switched off when its spot-check precision drops below ${META.guard_prec} after ${META.guard_min} checked spans; in this run none did.</p>`;
138
- $("#gate").innerHTML = html;
139
- }
140
-
141
- function highlight(text, spans) {
142
- const ss = spans.slice().sort((a, b) => a.start - b.start || b.end - a.end);
143
- let out = "", pos = 0;
144
- for (const s of ss) {
145
- if (s.start < pos) continue;
146
- out += esc(text.slice(pos, s.start)) + `<mark class="${s.type}">${esc(text.slice(s.start, s.end))}<sup>${NAMES[s.type] || s.type}</sup></mark>`;
147
- pos = s.end;
148
- }
149
- return out + esc(text.slice(pos));
150
- }
151
-
152
- function renderRecent() {
153
- const items = [];
154
- for (let i = k - 1; i >= Math.max(0, k - 6); i--) {
155
- const e = EV[i], q = REQ[e.id];
156
- let spans, by;
157
- if (e.by === "rules") {
158
- spans = E.applyRules(activeRules(versionAt(i), i).map((r) => r.dict), q.text);
159
- by = `<span class="by-rules">rules</span> (v${e.v}, ${e.rule_ms.toFixed(2)} ms)` + (e.checked ? `, spot-checked: ${e.agree ? "same as the teacher" : "differs from the teacher"}` : "");
160
- } else {
161
- spans = q.teacher;
162
- by = `<span class="by-teacher">teacher</span> (${Math.round(e.teacher_ms)} ms), answer added to the labelled examples`;
163
- }
164
- items.push(`<li value="${i + 1}"><div class="meta">#${fmt(i + 1)} answered by ${by}</div><div class="hl-inline">${highlight(q.text, spans)}${spans.length ? "" : ' <span class="meta">(nothing to extract)</span>'}</div></li>`);
165
- }
166
- $("#recent").innerHTML = items.join("") || "<li>No requests yet. Press Play.</li>";
167
- }
168
-
169
- function render() {
170
- $("#pos").value = k;
171
- $("#posout").textContent = `${fmt(k)} requests`;
172
- renderKpis(); renderCharts(); renderVersions(); renderRules(); renderRecent();
173
- }
174
-
175
- // ------------------------------------------------------------------ playback
176
- function stop() { if (timer) clearTimeout(timer); timer = null; $("#play").textContent = "Play"; }
177
- function tick() {
178
- k = Math.min(N, k + parseInt($("#speed").value, 10));
179
- render();
180
- if (k >= N) { stop(); return; }
181
- timer = setTimeout(tick, 280);
182
- }
183
- $("#play").addEventListener("click", () => {
184
- if (timer) { stop(); return; }
185
- if (k >= N) k = 0;
186
- $("#play").textContent = "Pause";
187
- tick();
188
- });
189
- $("#pos").addEventListener("input", (ev) => { stop(); k = parseInt(ev.target.value, 10); render(); });
190
-
191
- // ------------------------------------------------------------------ try your own text
192
- function tryText(text, recorded) {
193
- text = (text || "").trim().slice(0, 2000);
194
- if (!text) { $("#status").textContent = "Type or paste a sentence."; return; }
195
- let v = versionAt(k);
196
- if (!v.gate) v = VERS[VERS.length - 1];
197
- const rules = activeRules(v, Math.max(k, v.at)).map((r) => r.dict);
198
- const t0 = performance.now();
199
- const spans = E.applyRules(rules, text);
200
- const un = E.unexplained(v.gate, text, spans);
201
- const ms = performance.now() - t0;
202
- const rec = recorded || HOLD.find((q) => q.text === text);
203
- if (!un.length) {
204
- $("#status").innerHTML = `<b>Answered by rules</b> (v${v.v}, ${rules.length} answering rules) in ${ms.toFixed(2)} ms in your browser. No model call.`;
205
- $("#out").innerHTML = `<span class="lab">Answer (rules)</span>${highlight(text, spans)}`;
206
- $("#out-teacher").innerHTML = rec ? `<span class="lab">Teacher's recorded answer for this holdout sentence, for comparison</span>${highlight(rec.text, rec.teacher)}` : "";
207
- } else {
208
- $("#status").innerHTML = `<b>The gate sends this request to the teacher</b>: uncovered trigger tokens ${un.slice(0, 12).map((u) => `<code>${esc(u)}</code>`).join(", ")}. ` +
209
- `Rules took ${ms.toFixed(2)} ms. The teacher does not run on this static page` + (rec ? "; its recorded answer for this holdout sentence is shown." : ".");
210
- $("#out").innerHTML = rec ? `<span class="lab">Answer (teacher, recorded offline)</span>${highlight(rec.text, rec.teacher)}` : "";
211
- $("#out-teacher").innerHTML = `<span class="lab">What the rules found</span>${highlight(text, spans)}`;
212
- }
213
- }
214
- $("#go").addEventListener("click", () => tryText($("#inp").value));
215
- $("#pick").addEventListener("click", () => { const q = HOLD[Math.floor(Math.random() * HOLD.length)]; $("#inp").value = q.text; tryText(q.text, q); });
216
- document.querySelectorAll("button.ex").forEach((b) => b.addEventListener("click", () => { $("#inp").value = b.dataset.ex; tryText(b.dataset.ex); }));
217
- window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => R && renderCharts());
218
-
219
- // ------------------------------------------------------------------ load
220
- Promise.all([fetch("data/replay.json").then((r) => r.json()), fetch("data/requests.jsonl").then((r) => r.text())]).then(([rep, txt]) => {
221
- R = rep; META = R.meta; VERS = R.versions; EV = R.events; GUARD = R.guard; N = EV.length; AT = VERS.map((v) => v.at);
222
- for (const line of txt.trim().split("\n")) { const q = JSON.parse(line); REQ[q.id] = q; if (q.part === "holdout") HOLD.push(q); }
223
- S.rules = cum(EV.map((e) => +(e.by === "rules")));
224
- S.spans = cum(EV.map((e) => +(e.by === "rules" && e.fired.length > 0)));
225
- S.check = cum(EV.map((e) => +!!e.checked));
226
- S.agree = cum(EV.map((e) => +!!e.agree));
227
- S.call = cum(EV.map((e) => +(e.by === "teacher" || !!e.checked)));
228
- S.lat = cum(EV.map((e) => (e.by === "rules" ? e.rule_ms : e.rule_ms + e.teacher_ms)));
229
- S.tlat = cum(EV.map((e) => e.teacher_ms));
230
- document.querySelectorAll("[data-n-stream]").forEach((x) => (x.textContent = fmt(META.n_stream)));
231
- document.querySelectorAll("[data-n-holdout]").forEach((x) => (x.textContent = fmt(META.n_holdout)));
232
- const set = (sel, v) => document.querySelectorAll(sel).forEach((x) => (x.textContent = v));
233
- set("[data-trust-min]", META.trust_min); set("[data-trust-prec]", META.trust_prec); set("[data-spot]", META.spot_every);
234
- set("[data-guard-prec]", META.guard_prec); set("[data-guard-min]", META.guard_min);
235
- $("#pos").max = N; k = N;
236
- render();
237
- tryText($("#inp").value);
238
- }).catch((err) => { $("#kpis").textContent = "Could not load the replay data: " + err; });
239
- })();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RuleChef Live: your model teaches cheap rules while it works.
2
+
3
+ Plays back one run of sim.py (data/replay.json): a stream of short customer messages where the model (vela3-fast) labels
4
+ personal data, RuleChef's search synthesis turns its answers into regex rules, and the rules answer the messages they
5
+ cover. The "Try it" box runs the rules and the model live on this Space's CPU and re-learns rules from your examples.
6
+ """
7
+ import html
8
+ import json
9
+ import os
10
+ import threading
11
+ import time
12
+ from bisect import bisect_right
13
+ from itertools import accumulate
14
+
15
+ import gradio as gr
16
+ import pandas as pd
17
+
18
+ import cascade as C
19
+ from plain import plain
20
+
21
+ TEACHER_REPO, TEACHER_REV = "vllm-sr/vela3-fast", "078c42f90cabdac7964f8e206d95a6f3a1aafacb"
22
+ TEACHER_FILES = ["*.py", "*.json", "tokenizer*", "LICENSE", "model.safetensors", "span_adapter.safetensors",
23
+ "ner_adapter.safetensors", "router_adapter.safetensors"]
24
+ TYPE_NAME = {"EMAIL": "email", "PHONE": "phone", "DATE": "date", "ID": "ID number"}
25
+ TYPE_COLOR = {"EMAIL": "#4a3aa7", "PHONE": "#eb6834", "DATE": "#c98500", "ID": "#d55181"}
26
+
27
+ R = json.load(open("data/replay.json"))
28
+ REQ = {}
29
+ for line in open("data/requests.jsonl", encoding="utf-8"):
30
+ q = json.loads(line)
31
+ REQ[q["id"]] = q
32
+ META, VERS, EV, GUARD = R["meta"], R["versions"], R["events"], R["guard"]
33
+ N = len(EV)
34
+ AT = [v["at"] for v in VERS]
35
+ FIRST = VERS[1]["at"] if len(VERS) > 1 else N
36
+
37
+
38
+ def cum(xs):
39
+ return [0] + list(accumulate(xs))
40
+
41
+
42
+ S_RULES = cum(int(e["by"] == "rules") for e in EV)
43
+ S_SPANS = cum(int(e["by"] == "rules" and bool(e["fired"])) for e in EV)
44
+ S_CHECK = cum(int(bool(e.get("checked"))) for e in EV)
45
+ S_AGREE = cum(int(bool(e.get("agree"))) for e in EV)
46
+ S_CALL = cum(int(e["by"] == "teacher" or bool(e.get("checked"))) for e in EV)
47
+ S_LAT = cum(e["rule_ms"] if e["by"] == "rules" else e["rule_ms"] + e["teacher_ms"] for e in EV)
48
+ S_TLAT = cum(e["teacher_ms"] for e in EV)
49
+ LABELLED = [(REQ[e["id"]]["text"], REQ[e["id"]]["teacher"]) for e in EV if e["by"] == "teacher" or e.get("checked")]
50
+ LAST = VERS[-1]
51
+
52
+
53
+ def version_at(k):
54
+ return VERS[max(0, bisect_right(AT, k) - 1)]
55
+
56
+
57
+ def blocked_at(k):
58
+ return {g["key"] for g in GUARD if g["at"] < k}
59
+
60
+
61
+ def active(v, k):
62
+ off = blocked_at(k)
63
+ return [r for r in v["rules"] if r["trusted"] and r["key"] not in off]
64
+
65
+
66
+ def esc(s):
67
+ return html.escape(str(s))
68
+
69
+
70
+ def marked(text, spans):
71
+ out, pos = [], 0
72
+ for s in sorted(spans, key=lambda s: (s["start"], -s["end"])):
73
+ if s["start"] < pos:
74
+ continue
75
+ out.append(esc(text[pos:s["start"]]))
76
+ out.append(f'<mark class="t-{s["type"]}">{esc(text[s["start"]:s["end"]])}<small>{TYPE_NAME.get(s["type"], s["type"])}</small></mark>')
77
+ pos = s["end"]
78
+ return "".join(out) + esc(text[pos:])
79
+
80
+
81
+ def rule_line(r, used=None):
82
+ p = plain(r["regex"], r["template"]) or r["regex"]
83
+ extra = f'<span class="muted"> · answered {used} so far</span>' if used is not None else ""
84
+ return (f'<div class="rule"><span class="rt t-{r["type"]}">{TYPE_NAME[r["type"]]}</span> <b class="mono">{esc(p)}</b>{extra}'
85
+ f'<div class="rx mono">{esc(r["regex"])}</div></div>')
86
+
87
+
88
+ # ----------------------------------------------------------------------------- the story view
89
+ def steps_html(k):
90
+ v = version_at(k)
91
+ fresh = v["v"] > 0 and k - v["at"] < 25
92
+ cur = 1 if v["v"] == 0 else (2 if fresh else 3)
93
+ texts = [
94
+ ("1", "The model labels messages", "Each answer (~350 ms on CPU) is kept as an example."),
95
+ ("2", "RuleChef writes rules", f"From all examples so far, no LLM, on CPU." if not fresh else
96
+ f"Just now: v{v['v']} from {v['n_labelled']} examples in {v['synth_s']:.1f} s, {sum(r['trusted'] for r in v['rules'])} rules answer."),
97
+ ("3", "Rules answer, the model does the rest", "Green: a rule answered in under 1 ms, no model call. Blue: sent to the model, becomes a new example."),
98
+ ]
99
+ return '<div class="steps">' + "".join(
100
+ f'<div class="step{" on" if int(n) == cur else ""}"><div class="sn">{n}</div><div><b>{t}</b><div class="sd">{d}</div></div></div>'
101
+ for n, t, d in texts) + "</div>"
102
+
103
+
104
+ def counters_html(k):
105
+ calls = S_CALL[k]
106
+ saved = k - calls
107
+ t_saved = max(0.0, (S_TLAT[k] - S_LAT[k]) / 1000) # before the first rules the only difference is the gate's tiny overhead
108
+ t_pct = 100 * t_saved * 1000 / S_TLAT[k] if S_TLAT[k] else 0
109
+ v = version_at(k)
110
+ agree = f"{100 * S_AGREE[k] / S_CHECK[k]:.0f} %" if S_CHECK[k] else "–"
111
+ return (f'<div class="counters"><div class="big"><div class="bv">{saved:,}</div><div class="bl">model calls saved'
112
+ f' <span class="muted">({100 * saved / k if k else 0:.0f} % of {k:,} messages)</span></div></div>'
113
+ f'<div class="big"><div class="bv">{t_saved:,.0f} s</div><div class="bl">model time saved <span class="muted">({t_pct:.0f} %)</span></div></div></div>'
114
+ f'<div class="muted small">Messages {k:,} / {N:,} · rule set v{v["v"]} · {len(active(v, k))} rules answering · '
115
+ f'spot checks agree with the model: {agree} ({S_AGREE[k]} of {S_CHECK[k]})</div>')
116
+
117
+
118
+ def feed_html(k):
119
+ items = []
120
+ for i in range(k - 1, max(-1, k - 7), -1):
121
+ e, q = EV[i], REQ[EV[i]["id"]]
122
+ if e["by"] == "rules":
123
+ spans = C.run_rules(C.rules_from_dicts([r["dict"] for r in active(version_at(i), i)]), q["text"])
124
+ tag = f'<span class="by rules">rule</span> {e["rule_ms"]:.2f} ms, no model call'
125
+ if e.get("checked"):
126
+ tag += " · spot check: " + ("model agrees" if e.get("agree") else "model differs")
127
+ cls = "rules"
128
+ else:
129
+ spans = q["teacher"]
130
+ tag = f'<span class="by model">model</span> {e["teacher_ms"]:,.0f} ms · kept as a new example'
131
+ cls = "model"
132
+ body = marked(q["text"], spans) + ("" if spans else ' <span class="muted">(nothing to extract)</span>')
133
+ items.append(f'<div class="msg {cls}"><div class="mm">#{i + 1} · {tag}</div><div>{body}</div></div>')
134
+ if not items:
135
+ items.append('<div class="msg"><div class="muted">Press Play: messages arrive one by one.</div></div>')
136
+ return '<div class="feed">' + "".join(items) + "</div>"
137
+
138
+
139
+ def rules_html(k):
140
+ v = version_at(k)
141
+ if v["v"] == 0:
142
+ return (f'<div class="rules-box"><b>No rules yet.</b> The model answers every message. After {META["schedule"][0]} examples '
143
+ f"RuleChef writes the first rules.</div>")
144
+ used = {}
145
+ for e in EV[:k]:
146
+ if e["by"] == "rules":
147
+ for key in e["fired"]:
148
+ used[key] = used.get(key, 0) + 1
149
+ rs = sorted(active(v, k), key=lambda r: (-used.get(r["key"], 0), -r["tp"]))[:5]
150
+ n_act = len(active(v, k))
151
+ head = (f'<div class="rules-box"><b>Rules now</b> <span class="muted">v{v["v"]}, learned from {v["n_labelled"]} examples in '
152
+ f'{v["synth_s"]:.1f} s · showing {len(rs)} of {n_act} answering rules</span>')
153
+ legend = ('<div class="muted small"># = digit · word = lowercase letters · [ ] optional · ( | ) one of · { } the part kept · '
154
+ "&lt;number&gt; = digits with , or .</div>")
155
+ return head + "".join(rule_line(r, used.get(r["key"], 0)) for r in rs) + legend + "</div>"
156
+
157
+
158
+ # ----------------------------------------------------------------------------- detail view (collapsed)
159
+ def window(xs, k, w=100, step=10):
160
+ return [(i, (xs[i] - xs[max(0, i - w)]) / (i - max(0, i - w))) for i in range(step, k + 1, step)]
161
+
162
+
163
+ def plots(k):
164
+ cov = pd.DataFrame([(i, y, "answered by rules") for i, y in window(S_RULES, k)] + [(i, y, "rules found spans") for i, y in window(S_SPANS, k)]
165
+ or [(0, 0.0, "answered by rules")], columns=["message", "share (last 100)", "series"])
166
+ calls = pd.DataFrame([(i, S_CALL[i], "with rules") for i in range(0, k + 1, 10)] + [(i, i, "model on every message") for i in range(0, k + 1, 10)],
167
+ columns=["message", "model calls", "series"])
168
+ lat = pd.DataFrame([(i, y, "with rules") for i, y in window(S_LAT, k)] + [(i, y, "model on every message") for i, y in window(S_TLAT, k)]
169
+ or [(0, 0.0, "with rules")], columns=["message", "mean ms (last 100)", "series"])
170
+ return cov, calls, lat
171
+
172
+
173
+ def pct(a, b):
174
+ return f"{100 * a / b:.1f} %" if b else "–"
175
+
176
+
177
+ def versions_df(k):
178
+ rows = []
179
+ for v in VERS:
180
+ if v["at"] > k:
181
+ break
182
+ h = v["holdout"]
183
+ ra = h["rules_answer"]
184
+ rows.append({"version": f"v{v['v']}", "from message": v["at"], "examples": v["n_labelled"],
185
+ "rules answering / learned": f"{sum(r['trusted'] for r in v['rules'])} / {len(v['rules'])}",
186
+ "synthesis s": v["synth_s"], "holdout answered by rules": pct(ra, h["n"]),
187
+ "same answer as model": pct(h["exact_agree"], ra) if ra else "–",
188
+ "rule spans P / R vs model": f"{h['routed_t']['P']:.2f} / {h['routed_t']['R']:.2f}" if ra else "–",
189
+ "rules + model, F1 vs model": f"{h['casc_t']['F1']:.3f}",
190
+ "F1 vs dataset labels: model / rules + model": f"{h['teach_g']['F1']:.3f} / {h['casc_g']['F1']:.3f}"})
191
+ return pd.DataFrame(rows)
192
+
193
+
194
+ def all_rules_df(k):
195
+ v = version_at(k)
196
+ off = blocked_at(k)
197
+ rows = []
198
+ for r in v["rules"]:
199
+ n = r["tp"] + r["fp"]
200
+ rows.append({"status": "switched off" if r["key"] in off else ("answering" if r["trusted"] else "not trusted"),
201
+ "type": TYPE_NAME[r["type"]], "plain": plain(r["regex"], r["template"]) or "", "regex": r["regex"],
202
+ "examples matched (precision)": f"{n} ({r['tp'] / n:.2f})" if n else "0"})
203
+ return pd.DataFrame(rows, columns=["status", "type", "plain", "regex", "examples matched (precision)"])
204
+
205
+
206
+ def gate_md(k):
207
+ v = version_at(k)
208
+ out = []
209
+ if v["gate"]:
210
+ g = v["gate"]
211
+ out.append(f"**Gate of v{v['v']}.** Rules answer a message only if every token with a digit or an @, and every learned trigger word "
212
+ f"({', '.join('`' + w + '`' for w in g['trigger_words']) or 'none'}), is covered by an answering rule, or sits in a skip "
213
+ f"context the model rarely labels ({', '.join('`' + (p or '(start)') + ' ' + s + '`' for p, s in g['skip']) or 'none'}; 9 = digits).")
214
+ gl = [g for g in GUARD if g["at"] < k]
215
+ out.append("**Drift guard.** " + ("; ".join(
216
+ f"at message {x['at']}: `{x['key'].split(chr(9))[1]}` switched off (spot checks: {x['tp']} agree, {x['fp']} disagree)" for x in gl)
217
+ if gl else "nothing switched off yet.") + f" A rule is switched off when fewer than {int(META['guard_prec'] * 100)} % of its spot-checked "
218
+ f"spans agree with the model, after {META['guard_min']} checked spans.")
219
+ return "\n\n".join(out)
220
+
221
+
222
+ def render(k):
223
+ k = int(k)
224
+ cov, calls, lat = plots(k)
225
+ return (steps_html(k), counters_html(k), feed_html(k), rules_html(k), cov, calls, lat, versions_df(k), all_rules_df(k), gate_md(k))
226
+
227
+
228
+ # ----------------------------------------------------------------------------- live model
229
+ MODEL = {"state": "off" if os.environ.get("TEACHER_LIVE", "1") == "0" else "loading", "obj": None, "err": ""}
230
+ MODEL_LOCK = threading.Lock()
231
+
232
+
233
+ def _load_model():
234
+ try:
235
+ from huggingface_hub import snapshot_download
236
+
237
+ from teacher_core import Teacher
238
+ d = os.environ.get("TEACHER_DIR") or snapshot_download(TEACHER_REPO, revision=TEACHER_REV, allow_patterns=TEACHER_FILES)
239
+ t = Teacher(d, threads=int(os.environ.get("TEACHER_THREADS", "2")))
240
+ t("Warm-up: call 555-0100 on 12 May 2026.")
241
+ MODEL.update(obj=t, state="ready")
242
+ except Exception as e: # the page still works, rules only
243
+ MODEL.update(state="unavailable", err=repr(e)[:300])
244
+
245
+
246
+ if MODEL["state"] == "loading":
247
+ threading.Thread(target=_load_model, daemon=True).start()
248
+
249
+
250
+ # ----------------------------------------------------------------------------- try it
251
+ def base_state():
252
+ off = blocked_at(N)
253
+ rules = [dict(r, trusted=r["trusted"] and r["key"] not in off) for r in LAST["rules"]]
254
+ return {"labelled": list(LABELLED[:LAST["n_labelled"]]), "rules": rules, "gate": LAST["gate"],
255
+ "added": 0, "name": f"v{LAST['v']}"}
256
+
257
+
258
+ def hl(text, spans):
259
+ return {"text": text, "entities": [{"entity": TYPE_NAME[s["type"]], "start": s["start"], "end": s["end"]} for s in spans]}
260
+
261
+
262
+ def run_try(text, st):
263
+ st = st or base_state()
264
+ text = (text or "").strip()[:1000]
265
+ if not text:
266
+ return None, "Type a message first.", None, "", "", st, gr.update(interactive=False)
267
+ rules = [r for r in st["rules"] if r["trusted"]]
268
+ t0 = time.perf_counter()
269
+ rs = C.run_rules(C.rules_from_dicts([r["dict"] for r in rules]), text)
270
+ un = C.Gate(st["gate"]["trigger_words"], st["gate"]["skip"]).unexplained(text, rs)
271
+ ms = (time.perf_counter() - t0) * 1000
272
+ by_id = {r["dict"]["id"]: r for r in rules}
273
+ fired = {s["rule_id"] for s in rs}
274
+ lines = [f"**Rules ({st['name']})**: {ms:.2f} ms. " + ("The gate lets the rules answer this message: **no model call needed**."
275
+ if not un else "The gate would **send this message to the model**: nothing covers " + ", ".join(f"`{u}`" for u in un[:8]) + ".")]
276
+ for rid in fired:
277
+ r = by_id[rid]
278
+ lines.append(f"- {TYPE_NAME[r['type']]}: `{plain(r['regex'], r['template']) or r['regex']}`")
279
+ if not fired:
280
+ lines.append("- no rule fired")
281
+ rules_md = "\n".join(lines)
282
+ if MODEL["state"] != "ready":
283
+ note = {"loading": "The model is still loading on this Space (download and start-up take a few minutes after a restart). Try again shortly.",
284
+ "off": "The live model is switched off here.", "unavailable": "The model could not be loaded here: " + MODEL["err"]}[MODEL["state"]]
285
+ return hl(text, rs), rules_md, None, note, "", st, gr.update(interactive=False)
286
+ with MODEL_LOCK:
287
+ mspans, mms, _ = MODEL["obj"](text)
288
+ tp, fp, fn = C.match_counts(rs, mspans)
289
+ if fp == 0 and fn == 0:
290
+ verdict = f"**Rules and model agree** ({len(mspans)} spans). Rules took {ms:.2f} ms, the model {mms:,.0f} ms."
291
+ else:
292
+ verdict = (f"**Rules and model differ**: the rules missed {fn} and added {fp} span(s). Rules took {ms:.2f} ms, the model {mms:,.0f} ms. "
293
+ "Adding this message as an example teaches the rules the model's answer.")
294
+ st = dict(st, pending={"text": text, "spans": mspans})
295
+ return hl(text, rs), rules_md, hl(text, mspans), f"**Model (vela3-fast, live on this CPU)**: {mms:,.0f} ms.", verdict, st, gr.update(interactive=True)
296
+
297
+
298
+ def relearn(st):
299
+ from rulechef.search import SearchConfig, SearchSynthesizer
300
+
301
+ from sim import MIN_SUPPORT, dataset, rule_key, rule_stats
302
+ st = st or base_state()
303
+ p = st.get("pending")
304
+ if not p:
305
+ return "Run a message through the model first.", st, gr.update(interactive=False)
306
+ labelled = st["labelled"] + [(p["text"], p["spans"])]
307
+ types = [t for t in C.TYPES if any(s["type"] == t for s in p["spans"])] or list(C.TYPES)
308
+ t0 = time.perf_counter()
309
+ new = SearchSynthesizer(SearchConfig(labels=types, min_support=MIN_SUPPORT)).synthesize(dataset(labelled))
310
+ synth_s = time.perf_counter() - t0
311
+ stats = rule_stats(new, labelled)
312
+ gate = C.Gate.learn(labelled).to_dict()
313
+ new_rows = []
314
+ for x in new:
315
+ d = x.to_dict()
316
+ tp, fp = stats[x.id]
317
+ new_rows.append({"id": x.id, "key": rule_key(d), "type": d["output_template"]["type"], "regex": x.content,
318
+ "template": d["output_template"].get("text", "$0"), "tp": tp, "fp": fp,
319
+ "trusted": tp + fp >= C.TRUST_MIN and tp / (tp + fp) >= C.TRUST_PREC, "dict": d})
320
+ old_t = [r for r in st["rules"] if r["type"] in types]
321
+ merged = []
322
+ for t in C.TYPES:
323
+ merged += [r for r in new_rows if r["type"] == t] if t in types else [r for r in st["rules"] if r["type"] == t]
324
+ for i, r in enumerate(merged): # keep the executor order: type order, then the search order
325
+ r["dict"] = dict(r["dict"], priority=len(merged) - i)
326
+ ok_old = {r["key"] for r in old_t if r["trusted"]}
327
+ ok_new = {r["key"] for r in new_rows if r["trusted"]}
328
+ added = [r for r in new_rows if r["trusted"] and r["key"] not in ok_old]
329
+ gone = [r for r in old_t if r["trusted"] and r["key"] not in ok_new]
330
+ st = dict(st, labelled=labelled, rules=merged, gate=gate, added=st["added"] + 1, pending=None)
331
+ st["name"] = f"v{LAST['v']} + {st['added']} of your examples"
332
+ out = [f"Re-learned the **{', '.join(TYPE_NAME[t] for t in types)}** rules from {len(labelled):,} examples in **{synth_s:.1f} s** on this CPU "
333
+ f"(RuleChef search synthesis, no LLM). Now: {sum(r['trusted'] for r in merged)} answering rules."]
334
+ out += [f"- new: {TYPE_NAME[r['type']]} `{plain(r['regex'], r['template']) or r['regex']}`" for r in added[:6]]
335
+ out += [f"- dropped: {TYPE_NAME[r['type']]} `{plain(r['regex'], r['template']) or r['regex']}`" for r in gone[:6]]
336
+ if not added and not gone:
337
+ out.append("- the answering rules did not change; run the message again to see whether the rules now cover it.")
338
+ else:
339
+ out.append("Run the message again to see the new rules answer.")
340
+ return "\n".join(out), st, gr.update(interactive=False)
341
+
342
+
343
+ def reset():
344
+ return base_state(), "Back to the replay's last rule set.", gr.update(interactive=False)
345
+
346
+
347
+ # ----------------------------------------------------------------------------- page
348
+ CSS = """
349
+ .gradio-container {max-width: 1180px !important;}
350
+ .hero h1 {font-size: 2.1em; margin-bottom: 0.1em;}
351
+ .lede {font-size: 1.12em; line-height: 1.5;}
352
+ .steps {display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:10px;}
353
+ .step {display:flex; gap:10px; border:1px solid var(--border-color-primary); border-radius:10px; padding:10px 12px; opacity:.55;}
354
+ .step.on {opacity:1; border-color: var(--body-text-color); box-shadow: 0 0 0 1px var(--body-text-color) inset;}
355
+ .sn {font-size:1.6em; font-weight:700; line-height:1;}
356
+ .sd {font-size:.88em; color: var(--body-text-color-subdued);}
357
+ .counters {display:flex; flex-wrap:wrap; gap:28px; margin:4px 0 6px;}
358
+ .bv {font-size:2.6em; font-weight:700; line-height:1.05; font-variant-numeric: tabular-nums;}
359
+ .bl {font-size:1em;}
360
+ .muted {color: var(--body-text-color-subdued);}
361
+ .small {font-size:.85em;}
362
+ .feed {display:grid; gap:6px;}
363
+ .msg {border:1px solid var(--border-color-primary); border-left:5px solid var(--border-color-primary); border-radius:8px; padding:7px 10px; line-height:1.75;}
364
+ .msg.rules {border-left-color:#1baf7a;}
365
+ .msg.model {border-left-color:#2a78d6;}
366
+ .mm {font-size:.82em; color: var(--body-text-color-subdued); line-height:1.4;}
367
+ .by {font-weight:700; padding:0 6px; border-radius:4px; color:#fff;}
368
+ .by.rules {background:#13865d;}
369
+ .by.model {background:#2a78d6;}
370
+ mark {background: transparent; color: inherit; padding:0 2px; border-radius:3px;}
371
+ mark small {font-size:.68em; margin-left:3px; opacity:.85;}
372
+ mark.t-EMAIL {background: rgba(74,58,167,.16); box-shadow: inset 0 -2px 0 #4a3aa7;}
373
+ mark.t-PHONE {background: rgba(235,104,52,.16); box-shadow: inset 0 -2px 0 #eb6834;}
374
+ mark.t-DATE {background: rgba(201,133,0,.18); box-shadow: inset 0 -2px 0 #c98500;}
375
+ mark.t-ID {background: rgba(213,81,129,.16); box-shadow: inset 0 -2px 0 #d55181;}
376
+ .rules-box {border:1px solid var(--border-color-primary); border-radius:10px; padding:10px 12px;}
377
+ .rule {margin:8px 0;}
378
+ .rt {font-size:.8em; font-weight:600; padding:1px 7px; border-radius:10px; border:1px solid currentColor;}
379
+ .rt.t-EMAIL {color:#7b6fd6;} .rt.t-PHONE {color:#eb6834;} .rt.t-DATE {color:#c98500;} .rt.t-ID {color:#d55181;}
380
+ .mono {font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;}
381
+ .rx {font-size:.75em; color: var(--body-text-color-subdued); word-break: break-all;}
382
+ .notes {font-size:.92em; color: var(--body-text-color-subdued);}
383
+ """
384
+
385
+ HERO = """<div class="hero"><h1>RuleChef Live</h1>
386
+ <p class="lede"><b>Your model teaches cheap rules while it works.</b> Every answer the model gives becomes an example;
387
+ <a href="https://github.com/KRLabsOrg/rulechef">RuleChef</a> turns the examples into plain rules that answer the next requests instantly,
388
+ without the model.</p>
389
+ <p class="muted">Task: find emails, phone numbers, dates and ID numbers in short customer messages. Below is the end of a 1,500-message
390
+ stream; press <b>Play</b> to watch it from the first message.</p></div>"""
391
+
392
+ NOTES = """<div class="notes">
393
+ • The model is <a href="https://huggingface.co/vllm-sr/vela3-fast">vela3-fast</a> on a free CPU; that is why it takes ~350 ms per message.<br>
394
+ • Rules copy the model's mistakes too: they learn from its answers, not from human labels.<br>
395
+ • A drift guard sends every 10th rule answer to the model as well and turns off rules that stop agreeing with it.</div>"""
396
+
397
+ ABOUT = f"""### How this works and how the numbers are computed
398
+ All numbers come from this demo's own run over public data.
399
+
400
+ - **Messages.** {META['n_stream']:,} sentences of 30 to 260 characters from customer-style documents (emails, tickets, requests, complaints, ...)
401
+ in Nemotron-PII, a synthetic dataset; about 60 % of them contain one of the four types. {META['n_holdout']} more messages from other
402
+ documents form a holdout.
403
+ - **Model.** vela3-fast @`{TEACHER_REV[:8]}`, one span question per message with four label names: "email", "phone number", "date",
404
+ "ID number". In the replay its answers and times come from one offline run on CPU (16 processes, 2 threads each). In "Try it" it runs live
405
+ on this Space's CPU.
406
+ - **Rules.** RuleChef search synthesis (`synth="search"`, no LLM) re-learns all rules after {', '.join(str(x) for x in META['schedule'][:3])},
407
+ then every 100 examples. A rule answers only if it matched at least {META['trust_min']} examples with precision at least {META['trust_prec']}
408
+ against the model. Rule time is the measured time of the gate plus RuleChef's executor.
409
+ - **Gate.** The rules answer a message only when every token with a digit or an @ (and a few learned trigger words) is covered by an answering
410
+ rule, or sits in a context the model rarely labels. Otherwise the message goes to the model and its answer becomes an example.
411
+ - **Counters.** Model calls saved = messages the rules answered, minus the spot checks, which also call the model. Model time saved = model time
412
+ for every message minus the time actually spent (rules, plus the model where it was called).
413
+ - **Replay.** The stream was run once offline with the code in this Space (`sim.py`); the page plays back its log, so the rule sets and their
414
+ synthesis times are that run's. Re-running `sim.py` gives the same rule sets. "Try it" re-learns rules live.
415
+ - **Holdout table.** Each rule set, when deployed, is run on the holdout and compared with the model and with the dataset's own labels.
416
+ Matching: same text, same type.
417
+
418
+ ### Credits and licences
419
+ - **RuleChef** ([KRLabsOrg/rulechef](https://github.com/KRLabsOrg/rulechef), Apache-2.0); search synthesis installed from commit `8173f96`
420
+ of the `feat/search-synthesis` branch.
421
+ - **vela3-fast** ([vllm-sr/vela3-fast](https://huggingface.co/vllm-sr/vela3-fast), Apache-2.0).
422
+ - **Nemotron-PII** ([nvidia/Nemotron-PII](https://huggingface.co/datasets/nvidia/Nemotron-PII), revision `b70ffaf5`), NVIDIA,
423
+ CC BY 4.0. All names, emails and numbers in it are synthetic. Changes made here: sentences cut from its train split, its labels mapped to four
424
+ types, and the model's answers added (`data/requests.jsonl`).
425
+ - This Space's code: Apache-2.0.
426
+ """
427
+
428
+ EX = ["You can reach me at anna.kowalski@mailbox.org or on +48 512 334 921.",
429
+ "My order ORD-55120 from 03/09/2025 still has not arrived.",
430
+ "Please call me back at 415-555-0198 before Friday."]
431
+
432
+ INIT = render(N) # the page opens on the end of the stream; Play replays it from the start
433
+
434
+ with gr.Blocks(title="RuleChef Live", css=CSS, theme=gr.themes.Default(primary_hue="blue")) as demo:
435
+ st = gr.State(None)
436
+ gr.HTML(HERO)
437
+ steps = gr.HTML(INIT[0])
438
+ with gr.Row(equal_height=False):
439
+ play = gr.Button("Play", variant="primary", scale=0, min_width=120)
440
+ pause = gr.Button("Pause", scale=0, min_width=100)
441
+ end = gr.Button("Jump to the end", scale=0, min_width=150)
442
+ pos = gr.Slider(0, N, value=N, step=1, label="Messages processed", scale=4)
443
+ counters = gr.HTML(INIT[1])
444
+ with gr.Row(equal_height=False):
445
+ with gr.Column(scale=3):
446
+ feed = gr.HTML(INIT[2])
447
+ with gr.Column(scale=2):
448
+ rules = gr.HTML(INIT[3])
449
+ gr.HTML(NOTES)
450
+
451
+ gr.Markdown("## Try it\nType a message. The rules and the model both answer it, live on this CPU. If they differ, add it as an example: "
452
+ "RuleChef re-learns the rules on the spot.")
453
+ with gr.Row():
454
+ inp = gr.Textbox(value=EX[0], lines=2, label="Message", scale=4)
455
+ with gr.Column(scale=1, min_width=200):
456
+ go = gr.Button("Run rules and model", variant="primary")
457
+ gr.Examples(EX, inp, label="Examples")
458
+ verdict = gr.Markdown()
459
+ colors = {TYPE_NAME[t]: c for t, c in TYPE_COLOR.items()}
460
+ with gr.Row(equal_height=False):
461
+ with gr.Column():
462
+ out_r = gr.HighlightedText(label="Rules", color_map=colors, combine_adjacent=False, show_legend=False)
463
+ md_r = gr.Markdown()
464
+ with gr.Column():
465
+ out_m = gr.HighlightedText(label="Model", color_map=colors, combine_adjacent=False, show_legend=False)
466
+ md_m = gr.Markdown()
467
+ with gr.Row():
468
+ add = gr.Button("Add as example and re-learn rules", interactive=False)
469
+ rst = gr.Button("Reset rules", scale=0, min_width=130)
470
+ md_learn = gr.Markdown()
471
+
472
+ with gr.Accordion("Details: curves, every rule, the holdout table", open=False):
473
+ with gr.Row():
474
+ p1 = gr.LinePlot(x="message", y="share (last 100)", color="series", title="Share answered by rules", y_lim=[0, 1], x_lim=[0, N], height=240, value=INIT[4])
475
+ p2 = gr.LinePlot(x="message", y="model calls", color="series", title="Model calls", x_lim=[0, N], height=240, value=INIT[5])
476
+ p3 = gr.LinePlot(x="message", y="mean ms (last 100)", color="series", title="Time per message", x_lim=[0, N], height=240, value=INIT[6])
477
+ gr.Markdown("**Rule set versions, scored on the holdout when deployed**")
478
+ t_vers = gr.Dataframe(INIT[7], interactive=False, wrap=True)
479
+ gr.Markdown("**All rules of the current version**")
480
+ t_rules = gr.Dataframe(INIT[8], interactive=False, wrap=True, column_widths=["11%", "9%", "30%", "38%", "12%"])
481
+ m_gate = gr.Markdown(INIT[9])
482
+ with gr.Accordion("About, data and licences", open=False):
483
+ gr.Markdown(ABOUT)
484
+
485
+ outs = [steps, counters, feed, rules, p1, p2, p3, t_vers, t_rules, m_gate]
486
+
487
+ def run(k):
488
+ k = 0 if int(k) >= N else int(k)
489
+ while k < N:
490
+ v_before = version_at(k)["v"]
491
+ step, wait = (1, 0.35) if k < FIRST else ((3, 0.3) if k < 300 else (12, 0.25))
492
+ k = min(N, k + step)
493
+ yield (k, *render(k))
494
+ time.sleep(1.6 if version_at(k)["v"] != v_before else wait)
495
+
496
+ ev = play.click(run, pos, [pos] + outs)
497
+ pause.click(None, cancels=[ev])
498
+ end.click(lambda: (N, *render(N)), None, [pos] + outs, cancels=[ev])
499
+ pos.release(render, pos, outs)
500
+ try_outs = [out_r, md_r, out_m, md_m, verdict, st, add]
501
+ go.click(run_try, [inp, st], try_outs)
502
+ inp.submit(run_try, [inp, st], try_outs)
503
+ add.click(relearn, st, [md_learn, st, add], concurrency_limit=1)
504
+ rst.click(reset, None, [st, md_learn, add])
505
+
506
+ if __name__ == "__main__":
507
+ demo.queue(default_concurrency_limit=4).launch()
cascade.py CHANGED
@@ -1,9 +1,10 @@
1
  """The cascade's pieces, shared by the offline replay (sim.py) and the app: the gate, rule execution, scoring.
2
 
3
  Gate: a request is answered by rules only when every trigger token in it is explained. Trigger tokens are tokens
4
- with a digit, plus words the teacher often puts inside spans (learned). A trigger is explained when an active rule's
 
5
  span covers it, or when its context is a learned skip context: (previous word, digit shape) pairs the teacher has
6
- seen at least SKIP_MIN times and labelled at most SKIP_RATIO of the time, such as "Article 9" or "§ 9".
7
  """
8
  import os
9
  import re
@@ -12,8 +13,8 @@ from collections import Counter, defaultdict
12
  from rulechef.core import Rule, TaskType
13
  from rulechef.executor import RuleExecutor
14
 
15
- TYPES = ["DATETIME", "CODE", "QUANTITY"]
16
- TOK = re.compile(r"§|[A-Za-z]+|\d+(?:[.,/:-]\d+)*")
17
  _E = os.environ.get
18
  WORD_MIN, WORD_RATIO = int(_E("WORD_MIN", 3)), float(_E("WORD_RATIO", 0.3)) # a word is a trigger if >= 3 teacher spans contain it and >= 30 % of its uses are inside one
19
  SKIP_MIN, SKIP_RATIO = int(_E("SKIP_MIN", 5)), float(_E("SKIP_RATIO", 0.3)) # a (previous word, shape) context is skipped if seen >= 5 times and the teacher labels it <= 30 % of the time
@@ -26,6 +27,11 @@ def shape(tok):
26
  return re.sub(r"\d+", "9", tok)
27
 
28
 
 
 
 
 
 
29
  def tokens(text):
30
  out, prev = [], ""
31
  for m in TOK.finditer(text):
@@ -49,7 +55,7 @@ class Gate:
49
  for text, spans in labelled:
50
  for s, e, tok, prev in tokens(text):
51
  inside = any(sp["start"] < e and s < sp["end"] for sp in spans)
52
- d = ctx[(prev, shape(tok))] if tok[0].isdigit() else (words[tok] if tok.isalpha() else None)
53
  if d is not None:
54
  d[0] += 1
55
  d[1] += inside
@@ -60,7 +66,7 @@ class Gate:
60
  def unexplained(self, text, spans):
61
  out = []
62
  for s, e, tok, prev in tokens(text):
63
- digit = tok[0].isdigit()
64
  if not (digit or tok in self.trigger_words):
65
  continue
66
  if any(sp["start"] < e and s < sp["end"] for sp in spans):
 
1
  """The cascade's pieces, shared by the offline replay (sim.py) and the app: the gate, rule execution, scoring.
2
 
3
  Gate: a request is answered by rules only when every trigger token in it is explained. Trigger tokens are tokens
4
+ with a digit or an "@" (tokens are runs of letters, digits and . _ + - / : @), plus words the teacher often puts
5
+ inside spans (learned). A trigger is explained when an active rule's
6
  span covers it, or when its context is a learned skip context: (previous word, digit shape) pairs the teacher has
7
+ seen at least SKIP_MIN times and labelled at most SKIP_RATIO of the time.
8
  """
9
  import os
10
  import re
 
13
  from rulechef.core import Rule, TaskType
14
  from rulechef.executor import RuleExecutor
15
 
16
+ TYPES = ["EMAIL", "PHONE", "DATE", "ID"]
17
+ TOK = re.compile(r"§|[A-Za-z0-9][A-Za-z0-9_.+\-/:@]*[A-Za-z0-9]|[A-Za-z0-9]")
18
  _E = os.environ.get
19
  WORD_MIN, WORD_RATIO = int(_E("WORD_MIN", 3)), float(_E("WORD_RATIO", 0.3)) # a word is a trigger if >= 3 teacher spans contain it and >= 30 % of its uses are inside one
20
  SKIP_MIN, SKIP_RATIO = int(_E("SKIP_MIN", 5)), float(_E("SKIP_RATIO", 0.3)) # a (previous word, shape) context is skipped if seen >= 5 times and the teacher labels it <= 30 % of the time
 
27
  return re.sub(r"\d+", "9", tok)
28
 
29
 
30
+ def trigger_shape(tok):
31
+ """Tokens that always need explaining: anything with a digit or an @."""
32
+ return "@" in tok or any(ch.isdigit() for ch in tok)
33
+
34
+
35
  def tokens(text):
36
  out, prev = [], ""
37
  for m in TOK.finditer(text):
 
55
  for text, spans in labelled:
56
  for s, e, tok, prev in tokens(text):
57
  inside = any(sp["start"] < e and s < sp["end"] for sp in spans)
58
+ d = ctx[(prev, shape(tok))] if trigger_shape(tok) else (words[tok] if tok.isalpha() else None)
59
  if d is not None:
60
  d[0] += 1
61
  d[1] += inside
 
66
  def unexplained(self, text, spans):
67
  out = []
68
  for s, e, tok, prev in tokens(text):
69
+ digit = trigger_shape(tok)
70
  if not (digit or tok in self.trigger_words):
71
  continue
72
  if any(sp["start"] < e and s < sp["end"] for sp in spans):
data/replay.json CHANGED
The diff for this file is too large to render. See raw diff
 
data/requests.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
engine.js DELETED
@@ -1,81 +0,0 @@
1
- // Browser port of cascade.py: RuleChef's executor semantics for regex NER rules, and the gate.
2
- // Checked against the Python executor on every request and every rule set of this demo (see verify_engine.js).
3
- (function (root) {
4
- "use strict";
5
- const cache = new Map();
6
- function compile(src) {
7
- if (!cache.has(src)) {
8
- let re = null;
9
- try { re = new RegExp(src, "g"); } catch (e) { re = null; }
10
- cache.set(src, re);
11
- }
12
- return cache.get(src);
13
- }
14
- function sortKey(a, b) {
15
- const pa = a.priority ?? 5, pb = b.priority ?? 5;
16
- if (pa !== pb) return pb - pa;
17
- const qa = a.validated_precision ?? a.confidence ?? 0.5, qb = b.validated_precision ?? b.confidence ?? 0.5;
18
- if (qa !== qb) return qb - qa;
19
- const na = (a.name || "").toLowerCase(), nb = (b.name || "").toLowerCase();
20
- if (na !== nb) return na < nb ? -1 : 1;
21
- const ia = a.id || "", ib = b.id || "";
22
- return ia < ib ? -1 : ia > ib ? 1 : 0;
23
- }
24
- // rules: RuleChef rule dicts (content, priority, output_template {text, type}, ...)
25
- function applyRules(rules, text) {
26
- const out = [];
27
- for (const r of rules.slice().sort(sortKey)) {
28
- if ((r.format || "regex") !== "regex") continue;
29
- const re = compile(r.content);
30
- if (!re) continue;
31
- const tpl = r.output_template || {};
32
- const t = tpl.text || "$0";
33
- re.lastIndex = 0;
34
- for (const m of text.matchAll(re)) {
35
- const mt = m[0];
36
- let s = m.index, e = m.index + mt.length, val = mt;
37
- if (/^\$\d+$/.test(t)) {
38
- const g = parseInt(t.slice(1), 10);
39
- val = g === 0 ? mt : (m[g] ?? "");
40
- }
41
- if (val && val !== mt) {
42
- const off = mt.toLowerCase().indexOf(val.toLowerCase());
43
- if (off >= 0) { s = s + off; e = s + val.length; }
44
- }
45
- if (out.some((x) => x.start === s && x.end === e)) continue;
46
- out.push({ start: s, end: e, type: tpl.type, text: val, rule_id: r.id });
47
- }
48
- }
49
- const uniq = [];
50
- for (const it of out) {
51
- const dup = uniq.some((ex) => {
52
- const inter = Math.max(0, Math.min(it.end, ex.end) - Math.max(it.start, ex.start));
53
- const uni = (it.end - it.start) + (ex.end - ex.start) - inter;
54
- return uni > 0 && inter / uni > 0.7 && it.type === ex.type;
55
- });
56
- if (!dup) uniq.push(it);
57
- }
58
- return uniq;
59
- }
60
- const TOK = /§|[A-Za-z]+|\d+(?:[.,\/:-]\d+)*/g;
61
- function tokens(text) {
62
- const out = []; let prev = "";
63
- for (const m of text.matchAll(TOK)) { out.push([m.index, m.index + m[0].length, m[0], prev]); prev = m[0].toLowerCase(); }
64
- return out;
65
- }
66
- const shape = (tok) => tok.replace(/\d+/g, "9");
67
- // gate: {trigger_words: [...], skip: [[prev, shape], ...]}
68
- function unexplained(gate, text, spans) {
69
- const words = new Set(gate.trigger_words), skip = new Set(gate.skip.map((k) => k[0] + "\u0000" + k[1]));
70
- const out = [];
71
- for (const [s, e, tok, prev] of tokens(text)) {
72
- const digit = /^\d/.test(tok);
73
- if (!(digit || words.has(tok))) continue;
74
- if (spans.some((sp) => sp.start < e && s < sp.end)) continue;
75
- if (digit && skip.has(prev + "\u0000" + shape(tok))) continue;
76
- out.push(tok);
77
- }
78
- return out;
79
- }
80
- root.RCEngine = { applyRules, unexplained, compile };
81
- })(typeof window !== "undefined" ? window : globalThis);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
index.html DELETED
@@ -1,125 +0,0 @@
1
- <!doctype html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <title>RuleChef Live</title>
7
- <meta name="description" content="A request stream where a teacher model's answers become labelled examples and RuleChef turns them into regex rules.">
8
- <link rel="stylesheet" href="style.css">
9
- </head>
10
- <body>
11
- <main class="wrap">
12
- <header>
13
- <h1>RuleChef Live</h1>
14
- <p class="lede">Model calls turn into rules. A stream of <span data-n-stream>3,000</span> requests: sentences from European Court of
15
- Human Rights judgments (the public TAB anonymisation dataset), each asking for its dates and times, codes and reference numbers,
16
- and quantities. The current rule set tries each request first. If its gate says the rules cover the request, the rules answer
17
- and no model is called. Otherwise the teacher model, <a href="https://huggingface.co/vllm-sr/vela3-fast">vela3-fast</a>, answers,
18
- and its answer becomes a labelled example. After the first 50 examples and then every 100 new ones,
19
- <a href="https://github.com/KRLabsOrg/rulechef">RuleChef</a>'s search synthesis (no LLM) learns a new rule set from all of
20
- them on CPU.</p>
21
- <p class="note">The stream was run once offline with the code in this Space (<code>sim.py</code>); this page replays that run,
22
- so the rule sets and synthesis times are snapshots. The rules themselves run live in your browser, here and in the box at the
23
- bottom.</p>
24
- </header>
25
-
26
- <section class="controls" aria-label="Replay controls">
27
- <button id="play" class="primary" type="button">Play</button>
28
- <label class="speed">Speed
29
- <select id="speed"><option value="10">slow</option><option value="30" selected>normal</option><option value="100">fast</option></select>
30
- </label>
31
- <input id="pos" type="range" min="0" max="3000" step="1" value="3000" aria-label="Requests processed">
32
- <output id="posout" for="pos">3,000</output>
33
- </section>
34
-
35
- <section id="kpis" class="kpis" aria-live="polite"></section>
36
-
37
- <section class="charts">
38
- <figure class="chart"><figcaption>Share of requests answered by rules <span class="sub">last 200 requests</span></figcaption><div id="c-cov"></div></figure>
39
- <figure class="chart"><figcaption>Model calls <span class="sub">cumulative</span></figcaption><div id="c-calls"></div></figure>
40
- <figure class="chart"><figcaption>Latency per request <span class="sub">mean of the last 200, ms</span></figcaption><div id="c-lat"></div></figure>
41
- </section>
42
-
43
- <section>
44
- <h2>Rule set versions, scored on the holdout when deployed</h2>
45
- <p class="help">Holdout: <span data-n-holdout>400</span> sentences from other documents. Matching is RuleChef's TAB scorer (same text, same type).
46
- "Cascade" means rules where the gate lets them answer, teacher elsewhere. The last column compares with TAB's human annotation;
47
- the rules learn from the teacher, mistakes included.</p>
48
- <div class="tablewrap"><table id="t-vers"></table></div>
49
- </section>
50
-
51
- <section>
52
- <h2>Rules of the current version</h2>
53
- <p class="help" id="rules-help"></p>
54
- <div class="tablewrap"><table id="t-rules" class="rules"></table></div>
55
- <details id="rules-rest" class="rest"></details>
56
- <div id="gate" class="gate"></div>
57
- </section>
58
-
59
- <section>
60
- <h2>Latest requests</h2>
61
- <ol id="recent" class="recent" reversed></ol>
62
- </section>
63
-
64
- <section class="try">
65
- <h2>Try your own text</h2>
66
- <p class="help">The gate and the rules of the version at the slider position run in your browser. The teacher does not run on
67
- this static page: when the gate sends a request on, the page says so and shows what the rules found. For a holdout sentence
68
- it also shows the teacher's recorded answer.</p>
69
- <textarea id="inp" rows="3" aria-label="Text">On 14 March 1997 the applicant lodged application no. 36732/97 and claimed 250,000 French francs in damages.</textarea>
70
- <div class="row">
71
- <button id="go" class="primary" type="button">Run rules</button>
72
- <button id="pick" type="button">Random holdout sentence</button>
73
- <button class="ex" type="button" data-ex="He was sentenced to two years and six months' imprisonment on 3 June 2004.">Example 2</button>
74
- <button class="ex" type="button" data-ex="The hearing took place the following day in Ankara.">Example 3</button>
75
- </div>
76
- <div id="status" class="status" aria-live="polite"></div>
77
- <div id="out" class="hl"></div>
78
- <div id="out-teacher" class="hl"></div>
79
- </section>
80
-
81
- <section class="about">
82
- <h2>How the numbers are computed</h2>
83
- <p>All numbers come from this demo's own run over public data; nothing is copied from a paper. The page aggregates the run's
84
- per-request log (<code>data/replay.json</code>) as you move the slider.</p>
85
- <ul>
86
- <li><b>Stream and holdout.</b> TAB documents are split by document: <span data-n-stream>3,000</span> sentences for the stream,
87
- <span data-n-holdout>400</span> from other documents for the holdout. One request = one sentence of 40 to 400 characters.</li>
88
- <li><b>Teacher.</b> vela3-fast at revision <code>078c42f9</code>, one span question per request with three label names asked at
89
- request time: "date or time", "code or reference number", "quantity". Its answers were computed once offline on CPU (16 processes
90
- with 2 threads each); the per-request time of that run is the teacher latency shown.</li>
91
- <li><b>Rules.</b> RuleChef search synthesis (<code>synth="search"</code>, min support 2) on all labelled examples so far, with the
92
- teacher's answers as labels. A learned rule answers only if it matched at least <span data-trust-min>3</span> times on the
93
- labelled data with precision at least <span data-trust-prec>0.8</span> against the teacher. Rule latency is the measured time of the
94
- gate plus RuleChef's Python executor on one CPU core.</li>
95
- <li><b>Gate.</b> Rules answer a request only when every trigger token (anything with a digit, plus words the teacher often
96
- labels) is covered by an answering rule or sits in a learned skip context. A rule answer with no spans ("nothing to extract")
97
- means the gate saw no uncovered trigger.</li>
98
- <li><b>Spot checks and drift guard.</b> Every <span data-spot>10</span>th rule answer (by request-id hash) also goes to the teacher;
99
- it counts as a model call and becomes a labelled example. A rule whose spot-check precision drops below
100
- <span data-guard-prec>0.8</span> after <span data-guard-min>5</span> checked spans is switched off for the rest of the stream.</li>
101
- <li><b>Synthesis.</b> Times are wall-clock seconds of the offline run on one CPU core. Re-running <code>sim.py</code> gives the same
102
- rule sets in the same order (checked twice, in separate processes).</li>
103
- <li><b>Rules in your browser.</b> <code>engine.js</code> is a JavaScript port of RuleChef's executor and of the gate. On all
104
- 3,400 sentences of this demo and all rule set versions it returns the same spans and gate decisions as the Python code.</li>
105
- </ul>
106
- <h2>Credits and licences</h2>
107
- <ul>
108
- <li><b>RuleChef</b> (<a href="https://github.com/KRLabsOrg/rulechef">KRLabsOrg/rulechef</a>, Apache-2.0): rule learning from
109
- examples. The search synthesis used here was installed from commit <code>8173f96</code> of its <code>feat/search-synthesis</code> branch.</li>
110
- <li><b>vela3-fast</b> (<a href="https://huggingface.co/vllm-sr/vela3-fast">vllm-sr/vela3-fast</a>, Apache-2.0): the teacher.</li>
111
- <li><b>TAB</b>, the Text Anonymization Benchmark (Pilán et al., 2022, Norsk Regnesentral,
112
- <a href="https://github.com/NorskRegnesentral/text-anonymization-benchmark">repository</a>): MIT licence, copyright (C) 2021-2026
113
- Norsk Regnesentral, full notice in <code>DATA_LICENSE_TAB.txt</code>. Used here: its public train split as published at
114
- <a href="https://huggingface.co/datasets/mattmdjaga/text-anonymization-benchmark-train">mattmdjaga/text-anonymization-benchmark-train</a>
115
- (revision <code>f0b7eeb</code>). The sentences, TAB's labels for the three types and the teacher's answers are in
116
- <code>data/requests.jsonl</code>.</li>
117
- <li>This Space's code: Apache-2.0.</li>
118
- </ul>
119
- </section>
120
- </main>
121
- <div id="tip" class="tip" role="tooltip" hidden></div>
122
- <script src="engine.js"></script>
123
- <script src="app.js"></script>
124
- </body>
125
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plain.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Readable form of a learned regex: '#' is a digit, 'word' a run of lowercase letters, <number> digits with , or . separators, [..] optional, {..} the part kept
2
+ when the rule extracts a sub-span, (a|b|c) one of these. Falls back to the regex itself for constructs it does not know."""
3
+ try:
4
+ import re._parser as P
5
+ from re import _constants as K
6
+ except ImportError: # Python < 3.11
7
+ import sre_parse as P
8
+ import sre_constants as K
9
+
10
+ MAXR = K.MAXREPEAT
11
+
12
+
13
+ def _cls(items):
14
+ """Name a character class."""
15
+ s = set()
16
+ for op, av in items:
17
+ if op == K.CATEGORY:
18
+ s.add({K.CATEGORY_DIGIT: "d", K.CATEGORY_SPACE: "s", K.CATEGORY_WORD: "w"}.get(av, "?"))
19
+ elif op == K.RANGE:
20
+ s.add({(48, 57): "d", (97, 122): "a", (65, 90): "A"}.get(av, "?"))
21
+ elif op == K.LITERAL:
22
+ s.add(chr(av))
23
+ else:
24
+ s.add("?")
25
+ return s
26
+
27
+
28
+ def _rep(unit, lo, hi, kind):
29
+ if kind == "d":
30
+ if lo == hi:
31
+ return "#" * lo
32
+ if hi == MAXR:
33
+ return "#…" if lo <= 1 else "#" * lo + "…"
34
+ return "#" * lo + "[" + "#" * (hi - lo) + "]" if hi - lo <= 2 else f"<{lo}-{hi} digits>"
35
+ if kind == "a":
36
+ return "word"
37
+ if kind == "A":
38
+ return "ABC" if lo >= 2 else "A"
39
+ if kind == "Aa":
40
+ return "Word"
41
+ if kind == "s":
42
+ return " "
43
+ if kind == "w":
44
+ return "word"
45
+ base = unit
46
+ if lo == 0 and hi == 1:
47
+ return "[" + base + "]"
48
+ if lo == hi:
49
+ return base * lo if len(base) == 1 and lo <= 3 else f"{base}×{lo}"
50
+ return base + "…"
51
+
52
+
53
+ class Unknown(Exception):
54
+ pass
55
+
56
+
57
+ def _seq(items, capture):
58
+ out = []
59
+ for op, av in items:
60
+ if op == K.LITERAL:
61
+ out.append(chr(av))
62
+ elif op == K.AT:
63
+ continue # word boundaries, anchors
64
+ elif op in (K.ASSERT_NOT, K.ASSERT):
65
+ continue # look-arounds only refine where a match may stop
66
+ elif op == K.IN:
67
+ c = _cls(av)
68
+ out.append("#" if c == {"d"} else "a" if c == {"a"} else "A" if c == {"A"} else " " if c == {"s"}
69
+ else "(" + "|".join(sorted(c)) + ")" if all(len(x) == 1 and x not in "daAsw?" for x in c) else "x")
70
+ elif op == K.CATEGORY:
71
+ out.append({K.CATEGORY_DIGIT: "#", K.CATEGORY_SPACE: " ", K.CATEGORY_WORD: "x"}.get(av, "x"))
72
+ elif op in (K.MAX_REPEAT, K.MIN_REPEAT):
73
+ lo, hi, sub = av
74
+ sub = list(sub)
75
+ if len(sub) == 1 and sub[0][0] == K.IN:
76
+ c = _cls(sub[0][1])
77
+ kind = "d" if c == {"d"} else "a" if c == {"a"} else "A" if c == {"A"} else "s" if c == {"s"} else "w" if c <= {"a", "A", "w", "d"} else None
78
+ out.append(_rep(None, lo, hi, kind) if kind else ("[" + _seq(sub, capture) + "…]" if lo == 0 else _seq(sub, capture) + "…"))
79
+ elif len(sub) == 1 and sub[0][0] == K.CATEGORY:
80
+ kind = {K.CATEGORY_DIGIT: "d", K.CATEGORY_SPACE: "s", K.CATEGORY_WORD: "w"}.get(sub[0][1])
81
+ out.append(_rep(None, lo, hi, kind) if not (kind == "s" and lo == 0) else " ")
82
+ elif len(sub) == 1 and sub[0][0] == K.LITERAL:
83
+ ch = chr(sub[0][1])
84
+ out.append(" " if ch == " " else ("[" + ch + "]" if (lo, hi) == (0, 1) else ch * lo if lo == hi else ch + "…"))
85
+ else:
86
+ inner = _seq(sub, capture)
87
+ out.append("[" + inner + "]" if (lo, hi) == (0, 1) else inner if (lo, hi) == (1, 1) else "(" + inner + ")…")
88
+ elif op == K.SUBPATTERN:
89
+ gid, _, _, sub = av
90
+ inner = _seq(list(sub), capture)
91
+ out.append("{" + inner + "}" if gid is not None and gid == capture else inner)
92
+ elif op == K.BRANCH:
93
+ alts = [_seq(list(b), capture) for b in av[1]]
94
+ out.append("(" + ("|".join(alts) if len(alts) <= 5 else "|".join(alts[:3]) + f"|… {len(alts)} options") + ")")
95
+ else:
96
+ raise Unknown(op)
97
+ s = "".join(out).replace("#…(,|.#…)…", "<number>").replace("#…((,|.)#…)…", "<number>")
98
+ return s.replace("[A][a]…", "Word").replace("Aword", "Word").replace(" ", " ")
99
+
100
+
101
+ def plain(regex, template="$0"):
102
+ cap = int(template[1:]) if template.startswith("$") and template[1:].isdigit() and template != "$0" else None
103
+ try:
104
+ s = _seq(list(P.parse(regex)), cap).strip()
105
+ except Exception:
106
+ return None
107
+ return s or None
prep.py DELETED
@@ -1,73 +0,0 @@
1
- """Build the request stream from TAB (public train split, MIT): one request = one sentence of an ECHR judgment.
2
-
3
- Documents are shuffled (seed 0) and split by document: HOLDOUT_DOCS documents give the spot-check holdout, the rest give
4
- the stream. Gold spans (TAB annotator 1, the three format types) are kept for reference only; the demo learns from the
5
- teacher, never from gold.
6
- usage: prep.py TAB.parquet OUT_DIR
7
- """
8
- import json
9
- import random
10
- import re
11
- import sys
12
-
13
- import pyarrow.parquet as pq
14
-
15
- TYPES = {"DATETIME", "CODE", "QUANTITY"}
16
- N_STREAM, N_HOLDOUT, HOLDOUT_DOCS = 3000, 400, 120
17
- ABBR = r"(?<!\bMr)(?<!\bMrs)(?<!\bMs)(?<!\bDr)(?<!\bno)(?<!\bNo)(?<!\bnos)(?<!\bNos)(?<!\bpp)(?<!\bp)(?<!\bpara)(?<!\bparas)(?<!\bArt)(?<!\bv)(?<!\bSt)(?<!\bJr)(?<!\bi\.e)(?<!\be\.g)(?<!\bseq)(?<!\bop)(?<!\bcit)(?<!\b[A-Z])"
18
- SENT_END = re.compile(ABBR + r"[.;](?=\s+[A-Z(\"'])")
19
-
20
-
21
- def sentences(text):
22
- out = []
23
- for m in re.finditer(r"[^\n]+", text):
24
- start, para = m.start(), m.group()
25
- s = 0
26
- for e in SENT_END.finditer(para):
27
- out.append((start + s, start + e.end()))
28
- s = e.end()
29
- while s < len(para) and para[s] == " ":
30
- s += 1
31
- if s < len(para):
32
- out.append((start + s, start + len(para)))
33
- return out
34
-
35
-
36
- def mentions(ann):
37
- for v in (ann or {}).values():
38
- if isinstance(v, dict) and v.get("entity_mentions"):
39
- return v["entity_mentions"]
40
- return []
41
-
42
-
43
- def main(pqf, out):
44
- docs = pq.read_table(pqf).to_pylist()
45
- random.Random(0).shuffle(docs)
46
- rows = {"holdout": [], "stream": []}
47
- for k, d in enumerate(docs):
48
- part = "holdout" if k < HOLDOUT_DOCS else "stream"
49
- ann = d["annotations"]
50
- if isinstance(ann, str):
51
- ann = json.loads(ann)
52
- ents = [(m["start_offset"], m["end_offset"], m["entity_type"]) for m in mentions(ann) if m.get("entity_type") in TYPES]
53
- for a, b in sentences(d["text"]):
54
- t = d["text"][a:b].strip()
55
- if not (40 <= len(t) <= 400) or t.isupper():
56
- continue
57
- a2 = d["text"].index(t, a)
58
- gold = sorted({(s - a2, e - a2, ty) for s, e, ty in ents if s >= a2 and e <= a2 + len(t)})
59
- rows[part].append({"doc_id": d["doc_id"], "text": t,
60
- "gold": [{"start": s, "end": e, "type": ty, "text": t[s:e]} for s, e, ty in gold]})
61
- rng = random.Random(1)
62
- sel = {"stream": rng.sample(rows["stream"], N_STREAM), "holdout": rng.sample(rows["holdout"], N_HOLDOUT)}
63
- with open(f"{out}/requests.jsonl", "w") as f:
64
- for part, rs in sel.items():
65
- for i, r in enumerate(rs):
66
- f.write(json.dumps({"id": f"{part[0]}{i:04d}", "part": part, **r}) + "\n")
67
- for part, rs in sel.items():
68
- print(part, len(rs), "of", len(rows[part]), "docs", len({r["doc_id"] for r in rs}),
69
- "with gold", sum(1 for r in rs if r["gold"]), "gold spans", sum(len(r["gold"]) for r in rs))
70
-
71
-
72
- if __name__ == "__main__":
73
- main(sys.argv[1], sys.argv[2])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
prep_pii.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build short customer-style messages from Nemotron-PII (synthetic, CC-BY-4.0), train split.
2
+
3
+ Unstructured documents whose type reads like a customer message (email, ticket, request, complaint, inquiry, letter, message,
4
+ note, chat, form) are split into sentences; a request is one sentence of 30 to 260 characters. Documents are shuffled (seed 0)
5
+ and split by document into holdout and stream. Messages are sampled so that 60 % carry one of the four types. Gold spans of the four types are kept for reference only.
6
+ usage: prep_pii.py NEMOTRON_TRAIN.parquet OUT_DIR N_STREAM N_HOLDOUT
7
+ """
8
+ import ast
9
+ import json
10
+ import random
11
+ import re
12
+ import sys
13
+
14
+ import pyarrow.parquet as pq
15
+
16
+ GOLD = {"email": "EMAIL", "phone_number": "PHONE", "fax_number": "PHONE", "date": "DATE", "date_of_birth": "DATE",
17
+ "date_time": "DATE", "customer_id": "ID", "account_number": "ID", "employee_id": "ID", "unique_id": "ID",
18
+ "credit_debit_card": "ID", "health_plan_beneficiary_number": "ID", "medical_record_number": "ID"}
19
+ KIND = re.compile(r"email|ticket|request|complaint|inquiry|enquiry|letter|message|note|chat|support|feedback|notification|confirmation", re.I)
20
+ POS_SHARE = 0.6
21
+ SENT = re.compile(r"(?<=[.!?])\s+(?=[A-Z])|\n+")
22
+
23
+
24
+ def main(pqf, out, n_stream, n_hold):
25
+ docs = [d for d in pq.read_table(pqf).to_pylist() if d["document_format"] == "unstructured" and KIND.search(d["document_type"] or "")]
26
+ random.Random(0).shuffle(docs)
27
+ rows = {"holdout": [], "stream": []}
28
+ for k, d in enumerate(docs):
29
+ part = "holdout" if k < len(docs) // 8 else "stream"
30
+ sp = d["spans"] if isinstance(d["spans"], list) else ast.literal_eval(d["spans"])
31
+ ents = [(s["start"], s["end"], GOLD[s["label"]]) for s in sp if s["label"] in GOLD]
32
+ text, pos = d["text"], 0
33
+ for m in list(SENT.finditer(text)) + [None]:
34
+ end = m.start() if m else len(text)
35
+ a, b = pos, end
36
+ pos = m.end() if m else len(text)
37
+ seg = text[a:b]
38
+ st = seg.strip()
39
+ if not (30 <= len(st) <= 260) or st.startswith(("-", "*", "#", "|")) or ":" in st[:25]:
40
+ continue
41
+ a2 = a + seg.index(st)
42
+ gold = sorted({(s - a2, e - a2, ty) for s, e, ty in ents if s >= a2 and e <= a2 + len(st)})
43
+ rows[part].append({"doc_id": d["uid"], "doc_type": d["document_type"], "text": st,
44
+ "gold": [{"start": s, "end": e, "type": ty, "text": st[s:e]} for s, e, ty in gold]})
45
+ rng = random.Random(1)
46
+ sel = {}
47
+ for part, n in (("stream", n_stream), ("holdout", n_hold)): # about 60 % of messages carry one of the four types
48
+ pos = [r for r in rows[part] if r["gold"]]
49
+ neg = [r for r in rows[part] if not r["gold"]]
50
+ rs = rng.sample(pos, round(n * POS_SHARE)) + rng.sample(neg, n - round(n * POS_SHARE))
51
+ rng.shuffle(rs)
52
+ sel[part] = rs
53
+ with open(f"{out}/requests.jsonl", "w") as f:
54
+ for part, rs in sel.items():
55
+ for i, r in enumerate(rs):
56
+ f.write(json.dumps({"id": f"{part[0]}{i:04d}", "part": part, **r}, ensure_ascii=False) + "\n")
57
+ for part, rs in sel.items():
58
+ print(part, len(rs), "of", len(rows[part]), "docs", len({r["doc_id"] for r in rs}), "with gold", sum(1 for r in rs if r["gold"]),
59
+ "gold spans", sum(len(r["gold"]) for r in rs))
60
+
61
+
62
+ if __name__ == "__main__":
63
+ main(sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4]))
pyref.py DELETED
@@ -1,15 +0,0 @@
1
- """Python reference for the browser port: per version, RuleChef executor output (trusted rules and all rules) + gate verdict."""
2
- import json, sys
3
- import cascade as C
4
- R = json.load(open(sys.argv[1])); reqs = [json.loads(l) for l in open(sys.argv[2])]
5
- out = []
6
- for v in R["versions"][1:]:
7
- tr = C.rules_from_dicts([r["dict"] for r in v["rules"] if r["trusted"]])
8
- al = C.rules_from_dicts([r["dict"] for r in v["rules"]])
9
- g = C.Gate(v["gate"]["trigger_words"], v["gate"]["skip"])
10
- rows = {}
11
- for r in reqs:
12
- a = C.run_rules(tr, r["text"]); b = C.run_rules(al, r["text"])
13
- rows[r["id"]] = [[[s["start"], s["end"], s["type"], s["text"]] for s in a], [[s["start"], s["end"], s["type"], s["text"]] for s in b], g.unexplained(r["text"], a)]
14
- out.append(rows)
15
- json.dump(out, open(sys.argv[3], "w"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cpu
2
+ torch==2.15.0+cpu
3
+ transformers==5.17.0
4
+ safetensors
5
+ tokenizers
6
+ numpy
7
+ pandas
8
+ pyarrow
9
+ rulechef @ git+https://github.com/KRLabsOrg/rulechef@8173f96f1b48cf1d66b35bc5ebe9d83be962a610
sim.py CHANGED
@@ -4,7 +4,7 @@ For each request in order: if a rule set exists and the gate passes, the trusted
4
  otherwise the teacher answers and its answer becomes a labelled example. SPOT_EVERY-th rule answers (by request-id
5
  hash) are also sent to the teacher: that is the drift guard's evidence, and those answers are labelled too. A rule
6
  whose spot-check precision falls below GUARD_PREC after GUARD_MIN checked spans is switched off for good. Each time the
7
- labelled set reaches the next size in SCHEDULE, RuleChef's search synthesis (no LLM) re-learns the rules from all
8
  labelled examples; the new set takes over at the next request. Every rule set version is also scored on the
9
  fixed holdout against the teacher and against the TAB annotation.
10
  Teacher answers are read from teacher.jsonl (precomputed with run_teacher.py, the same code the app runs live).
@@ -25,7 +25,7 @@ import cascade as C
25
 
26
  SPOT_EVERY = 10
27
  GUARD_MIN, GUARD_PREC = int(os.environ.get("GUARD_MIN", 5)), float(os.environ.get("GUARD_PREC", 0.8))
28
- SCHEDULE = [50, 100] + list(range(200, 5001, 100))
29
  MIN_SUPPORT = 2
30
 
31
 
@@ -34,7 +34,7 @@ def spot(rid):
34
 
35
 
36
  def dataset(labelled):
37
- task = Task(name="stream", description="date / code / quantity spans", input_schema={"text": "str"},
38
  output_schema={"entities": "List[Entity]"}, type=TaskType.NER, text_field="text")
39
  ds = Dataset(name="stream", task=task)
40
  for i, (text, spans) in enumerate(labelled):
 
4
  otherwise the teacher answers and its answer becomes a labelled example. SPOT_EVERY-th rule answers (by request-id
5
  hash) are also sent to the teacher: that is the drift guard's evidence, and those answers are labelled too. A rule
6
  whose spot-check precision falls below GUARD_PREC after GUARD_MIN checked spans is switched off for good. Each time the
7
+ labelled set reaches the next size in SCHEDULE (20, 50, 100, then every 100), RuleChef's search synthesis (no LLM) re-learns the rules from all
8
  labelled examples; the new set takes over at the next request. Every rule set version is also scored on the
9
  fixed holdout against the teacher and against the TAB annotation.
10
  Teacher answers are read from teacher.jsonl (precomputed with run_teacher.py, the same code the app runs live).
 
25
 
26
  SPOT_EVERY = 10
27
  GUARD_MIN, GUARD_PREC = int(os.environ.get("GUARD_MIN", 5)), float(os.environ.get("GUARD_PREC", 0.8))
28
+ SCHEDULE = [20, 50, 100] + list(range(200, 5001, 100))
29
  MIN_SUPPORT = 2
30
 
31
 
 
34
 
35
 
36
  def dataset(labelled):
37
+ task = Task(name="stream", description="email / phone / date / ID spans", input_schema={"text": "str"},
38
  output_schema={"entities": "List[Entity]"}, type=TaskType.NER, text_field="text")
39
  ds = Dataset(name="stream", task=task)
40
  for i, (text, spans) in enumerate(labelled):
style.css DELETED
@@ -1,125 +0,0 @@
1
- :root {
2
- color-scheme: light;
3
- --bg: #fcfcfb;
4
- --panel: #ffffff;
5
- --text: #0b0b0b;
6
- --text-2: #52514e;
7
- --muted: #74736e;
8
- --line: #e4e3df;
9
- --grid: #efeeea;
10
- --s1: #2a78d6; /* rules / cascade */
11
- --s2: #eb6834; /* teacher */
12
- --t-date: rgba(42, 120, 214, 0.16);
13
- --t-code: rgba(235, 104, 52, 0.18);
14
- --t-qty: rgba(27, 175, 122, 0.18);
15
- --t-date-b: #2a78d6;
16
- --t-code-b: #eb6834;
17
- --t-qty-b: #1baf7a;
18
- --accent: #1f1f1e;
19
- --accent-text: #ffffff;
20
- }
21
- @media (prefers-color-scheme: dark) {
22
- :root:not([data-theme="light"]) {
23
- color-scheme: dark;
24
- --bg: #141413;
25
- --panel: #1a1a19;
26
- --text: #ffffff;
27
- --text-2: #c3c2b7;
28
- --muted: #9a998f;
29
- --line: #34332f;
30
- --grid: #262624;
31
- --s1: #3987e5;
32
- --s2: #d95926;
33
- --t-date: rgba(57, 135, 229, 0.26);
34
- --t-code: rgba(217, 89, 38, 0.28);
35
- --t-qty: rgba(25, 158, 112, 0.28);
36
- --t-date-b: #3987e5;
37
- --t-code-b: #d95926;
38
- --t-qty-b: #199e70;
39
- --accent: #f2f1ec;
40
- --accent-text: #141413;
41
- }
42
- }
43
- :root[data-theme="dark"] {
44
- color-scheme: dark;
45
- --bg: #141413; --panel: #1a1a19; --text: #ffffff; --text-2: #c3c2b7; --muted: #9a998f; --line: #34332f; --grid: #262624;
46
- --s1: #3987e5; --s2: #d95926; --t-date: rgba(57, 135, 229, 0.26); --t-code: rgba(217, 89, 38, 0.28); --t-qty: rgba(25, 158, 112, 0.28);
47
- --t-date-b: #3987e5; --t-code-b: #d95926; --t-qty-b: #199e70; --accent: #f2f1ec; --accent-text: #141413;
48
- }
49
- * { box-sizing: border-box; }
50
- html, body { margin: 0; background: var(--bg); color: var(--text); }
51
- body { font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
52
- code, .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 0.88em; }
53
- a { color: var(--s1); }
54
- .wrap { max-width: 1180px; margin: 0 auto; padding: 24px 16px 64px; }
55
- h1 { font-size: 30px; margin: 0 0 8px; letter-spacing: -0.01em; }
56
- h2 { font-size: 18px; margin: 32px 0 6px; }
57
- .lede { max-width: 860px; margin: 0 0 8px; }
58
- .note, .help { color: var(--text-2); max-width: 860px; margin: 0 0 10px; font-size: 14px; }
59
- section { min-width: 0; }
60
-
61
- .controls { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 14px; margin: 20px 0 14px; position: sticky; top: 0;
62
- background: var(--bg); padding: 8px 0; z-index: 2; border-bottom: 1px solid var(--line); }
63
- .controls input[type=range] { flex: 1 1 260px; min-width: 160px; accent-color: var(--s1); }
64
- .controls output { font-variant-numeric: tabular-nums; min-width: 92px; color: var(--text-2); }
65
- .speed { color: var(--text-2); font-size: 14px; display: flex; gap: 6px; align-items: center; }
66
- button, select { font: inherit; font-size: 14px; border: 1px solid var(--line); background: var(--panel); color: var(--text);
67
- border-radius: 6px; padding: 6px 14px; cursor: pointer; }
68
- button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); min-width: 84px; }
69
- button:focus-visible, select:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px solid var(--s1); outline-offset: 2px; }
70
-
71
- .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 10px; }
72
- .kpi { border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; background: var(--panel); }
73
- .kt { font-size: 12px; color: var(--text-2); }
74
- .kv { font-size: 24px; font-weight: 600; margin: 2px 0; font-variant-numeric: tabular-nums; }
75
- .ks { font-size: 12px; color: var(--muted); line-height: 1.35; }
76
-
77
- .charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 10px; margin-top: 12px; }
78
- .chart { margin: 0; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); padding: 10px 10px 4px; min-width: 0; }
79
- .chart figcaption { font-size: 14px; font-weight: 600; }
80
- .chart .sub { font-weight: 400; color: var(--muted); font-size: 12px; }
81
- .chart svg { display: block; width: 100%; height: auto; }
82
- .legend { display: flex; gap: 14px; font-size: 12px; color: var(--text-2); margin: 4px 0 2px; flex-wrap: wrap; }
83
- .legend i { display: inline-block; width: 14px; height: 2px; vertical-align: middle; margin-right: 5px; border-radius: 1px; }
84
- .axis text { fill: var(--muted); font-size: 10px; }
85
- .tip { position: fixed; pointer-events: none; background: var(--panel); color: var(--text); border: 1px solid var(--line);
86
- border-radius: 6px; padding: 6px 8px; font-size: 12px; box-shadow: 0 2px 8px rgba(0,0,0,.12); z-index: 10; white-space: nowrap; }
87
-
88
- .tablewrap { overflow-x: auto; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); }
89
- table { border-collapse: collapse; width: 100%; font-size: 13px; }
90
- th, td { text-align: left; padding: 6px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
91
- th { font-weight: 600; color: var(--text-2); font-size: 12px; background: var(--panel); }
92
- td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
93
- tr:last-child td { border-bottom: 0; }
94
- tr.current td { background: var(--grid); }
95
- table.rules td.rx { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; word-break: break-all; min-width: 260px; }
96
- .st { font-size: 12px; white-space: nowrap; }
97
- .st.on::before { content: "\25CF "; color: var(--s1); }
98
- .st.off::before { content: "\25CB "; color: var(--muted); }
99
- .st.cut::before { content: "\2715 "; color: var(--s2); }
100
- .gate { font-size: 13px; color: var(--text-2); margin-top: 10px; }
101
- .gate code { color: var(--text); }
102
-
103
- .recent { list-style: none; padding: 0; margin: 0; display: grid; gap: 6px; }
104
- .recent li { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; background: var(--panel); font-size: 14px; }
105
- .recent .meta { font-size: 12px; color: var(--muted); margin-bottom: 2px; }
106
- .by-rules { color: var(--s1); font-weight: 600; }
107
- .by-teacher { color: var(--s2); font-weight: 600; }
108
-
109
- mark { background: transparent; color: inherit; border-radius: 3px; padding: 0 2px; }
110
- mark.DATETIME { background: var(--t-date); box-shadow: inset 0 -2px 0 var(--t-date-b); }
111
- mark.CODE { background: var(--t-code); box-shadow: inset 0 -2px 0 var(--t-code-b); }
112
- mark.QUANTITY { background: var(--t-qty); box-shadow: inset 0 -2px 0 var(--t-qty-b); }
113
- mark sup { font-size: 9px; color: var(--text-2); margin-left: 3px; letter-spacing: 0.02em; }
114
-
115
- .try textarea { width: 100%; font: inherit; padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); color: var(--text); resize: vertical; }
116
- .try .row { display: flex; flex-wrap: wrap; gap: 8px; margin: 8px 0; }
117
- .status { font-size: 14px; margin: 6px 0; }
118
- .hl { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; background: var(--panel); margin: 6px 0; line-height: 1.9; }
119
- .hl:empty { display: none; }
120
- .hl .lab { display: block; font-size: 12px; color: var(--muted); line-height: 1.4; }
121
- .about ul { padding-left: 18px; max-width: 900px; }
122
- .about li { margin: 4px 0; font-size: 14px; }
123
- @media (max-width: 600px) { h1 { font-size: 24px; } .kv { font-size: 20px; } }
124
- .rest { margin-top: 8px; } .rest summary { cursor: pointer; color: var(--text-2); font-size: 14px; margin-bottom: 6px; }
125
- th.num { white-space: normal; min-width: 72px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
teacher_core.py CHANGED
@@ -1,8 +1,8 @@
1
- """vela3-fast as the teacher: spans for three label names asked at request time (names only, no descriptions)."""
2
  import sys
3
  import time
4
 
5
- LABELS = {"date or time": "DATETIME", "code or reference number": "CODE", "quantity": "QUANTITY"}
6
  QUESTION = "Which spans are named entities of these types?"
7
 
8
 
 
1
+ """vela3-fast as the teacher: spans for four label names asked at request time (names only, no descriptions)."""
2
  import sys
3
  import time
4
 
5
+ LABELS = {"email": "EMAIL", "phone number": "PHONE", "date": "DATE", "ID number": "ID"}
6
  QUESTION = "Which spans are named entities of these types?"
7
 
8
 
verify_engine.js DELETED
@@ -1,23 +0,0 @@
1
- // node verify_engine.js data/replay.json data/requests.jsonl pyref.json (pyref.json from: python pyref.py data/replay.json data/requests.jsonl pyref.json) : JS port vs Python executor, every version x request.
2
- const fs = require("fs");
3
- require("./engine.js");
4
- const E = globalThis.RCEngine;
5
- const [rp, qp, pp] = process.argv.slice(2);
6
- const R = JSON.parse(fs.readFileSync(rp)); const ref = JSON.parse(fs.readFileSync(pp));
7
- const reqs = fs.readFileSync(qp, "utf8").trim().split("\n").map(JSON.parse);
8
- let n = 0, bad = 0, badc = 0, shown = 0;
9
- R.versions.slice(1).forEach((v, i) => {
10
- for (const r of v.rules) if (!E.compile(r.regex)) { badc++; console.log("no compile", r.regex); }
11
- const tr = v.rules.filter((r) => r.trusted).map((r) => r.dict), al = v.rules.map((r) => r.dict);
12
- for (const q of reqs) {
13
- const [pa, pb, pu] = ref[i][q.id];
14
- const a = E.applyRules(tr, q.text).map((s) => [s.start, s.end, s.type, s.text]);
15
- const b = E.applyRules(al, q.text).map((s) => [s.start, s.end, s.type, s.text]);
16
- const u = E.unexplained(v.gate, q.text, E.applyRules(tr, q.text));
17
- n++;
18
- if (JSON.stringify(a) !== JSON.stringify(pa) || JSON.stringify(b) !== JSON.stringify(pb) || JSON.stringify(u) !== JSON.stringify(pu)) {
19
- bad++; if (shown++ < 5) console.log("MISMATCH v" + v.v, q.id, q.text, JSON.stringify([a, pa]), JSON.stringify([b, pb]), JSON.stringify([u, pu]));
20
- }
21
- }
22
- });
23
- console.log("checked", n, "mismatches", bad, "uncompilable", badc);