@shiftbloom-studio/privacy-filter 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,443 @@
1
+ // src/types.ts
2
+ var FILTER_MODES = ["mask", "remove", "annotate"];
3
+
4
+ // src/redact.ts
5
+ function normalizeApiBaseUrl(value) {
6
+ return value.replace(/\/+$/, "");
7
+ }
8
+ function isFilterMode(value) {
9
+ return typeof value === "string" && FILTER_MODES.includes(value);
10
+ }
11
+ function validateFilterRequest(value) {
12
+ if (!value || typeof value !== "object") {
13
+ return "Request body must be a JSON object.";
14
+ }
15
+ const request = value;
16
+ if (typeof request.text !== "string" || request.text.trim().length === 0) {
17
+ return "Enter text before running the privacy filter.";
18
+ }
19
+ if (request.text.length > 5e4) {
20
+ return "Text must be 50,000 characters or fewer.";
21
+ }
22
+ if (!isFilterMode(request.mode)) {
23
+ return "Choose a supported filter mode.";
24
+ }
25
+ if (typeof request.mask_token !== "string" || request.mask_token.trim().length === 0) {
26
+ return "Mask token cannot be blank.";
27
+ }
28
+ if (typeof request.include_spans !== "boolean") {
29
+ return "include_spans must be a boolean.";
30
+ }
31
+ return null;
32
+ }
33
+ function spanKey(span) {
34
+ return `${span.label}-${span.start}-${span.end}-${span.score}`;
35
+ }
36
+ function applyRedaction(text, spans, mode, maskToken) {
37
+ const pieces = [];
38
+ let cursor = 0;
39
+ for (const span of spans) {
40
+ pieces.push(text.slice(cursor, span.start));
41
+ if (mode === "remove") {
42
+ pieces.push("");
43
+ } else if (mode === "annotate") {
44
+ pieces.push(`[${span.label}:${text.slice(span.start, span.end)}]`);
45
+ } else {
46
+ pieces.push(maskToken);
47
+ }
48
+ cursor = span.end;
49
+ }
50
+ pieces.push(text.slice(cursor));
51
+ return [pieces.join(""), [...spans]];
52
+ }
53
+
54
+ // src/labels.ts
55
+ var MODEL_ID = "openai/privacy-filter";
56
+ var SPAN_LABELS = [
57
+ "account_number",
58
+ "private_address",
59
+ "private_date",
60
+ "private_email",
61
+ "private_person",
62
+ "private_phone",
63
+ "private_url",
64
+ "secret"
65
+ ];
66
+ var ID_TO_LABEL = [
67
+ "O",
68
+ ...SPAN_LABELS.flatMap((label) => [`B-${label}`, `I-${label}`, `E-${label}`, `S-${label}`])
69
+ ];
70
+ var SUPPORTED_LABELS = new Set(SPAN_LABELS);
71
+ var IGNORE_LABELS = ["O"];
72
+ function stripBoundary(label) {
73
+ const trimmed = label.trim();
74
+ if (trimmed.toUpperCase() === "O") {
75
+ return "O";
76
+ }
77
+ const cleaned = trimmed.toLowerCase();
78
+ for (const prefix of ["b-", "i-", "e-", "s-"]) {
79
+ if (cleaned.startsWith(prefix)) {
80
+ return cleaned.slice(prefix.length);
81
+ }
82
+ }
83
+ return cleaned;
84
+ }
85
+ function isSupportedLabel(label) {
86
+ return SUPPORTED_LABELS.has(stripBoundary(label));
87
+ }
88
+ function decodeBIOESToSpans(labels, offsets) {
89
+ const spans = [];
90
+ let current = null;
91
+ const closeCurrent = () => {
92
+ if (current && current.end > current.start) {
93
+ spans.push({
94
+ label: current.label,
95
+ start: current.start,
96
+ end: current.end,
97
+ text: "",
98
+ score: 1
99
+ });
100
+ }
101
+ current = null;
102
+ };
103
+ for (let index = 0; index < labels.length; index += 1) {
104
+ const raw = labels[index] ?? "O";
105
+ const offset = offsets[index];
106
+ if (!offset) {
107
+ continue;
108
+ }
109
+ const boundary = raw.slice(0, 2).toUpperCase();
110
+ const label = stripBoundary(raw);
111
+ const supported = SUPPORTED_LABELS.has(label);
112
+ if (!supported || boundary === "O-" || raw.toUpperCase() === "O") {
113
+ closeCurrent();
114
+ continue;
115
+ }
116
+ if (boundary === "B-" || boundary === "S-") {
117
+ closeCurrent();
118
+ current = { label, start: offset.start, end: offset.end };
119
+ if (boundary === "S-") {
120
+ closeCurrent();
121
+ }
122
+ continue;
123
+ }
124
+ if (boundary === "I-" || boundary === "E-") {
125
+ if (current && current.label === label) {
126
+ current.end = offset.end;
127
+ } else {
128
+ closeCurrent();
129
+ current = { label, start: offset.start, end: offset.end };
130
+ }
131
+ if (boundary === "E-") {
132
+ closeCurrent();
133
+ }
134
+ }
135
+ }
136
+ closeCurrent();
137
+ return spans;
138
+ }
139
+ function normalizeSpans(text, spans) {
140
+ const length = text.length;
141
+ const candidates = [];
142
+ for (const span of spans) {
143
+ if (!SUPPORTED_LABELS.has(span.label)) {
144
+ continue;
145
+ }
146
+ const start = Math.max(0, Math.min(span.start, length));
147
+ const end = Math.max(0, Math.min(span.end, length));
148
+ if (end <= start) {
149
+ continue;
150
+ }
151
+ candidates.push({ ...span, start, end, text: text.slice(start, end) });
152
+ }
153
+ candidates.sort(
154
+ (left, right) => left.start - right.start || right.end - right.start - (left.end - left.start) || right.score - left.score
155
+ );
156
+ const accepted = [];
157
+ let cursor = 0;
158
+ for (const span of candidates) {
159
+ if (span.start < cursor) {
160
+ continue;
161
+ }
162
+ accepted.push(span);
163
+ cursor = span.end;
164
+ }
165
+ return accepted;
166
+ }
167
+
168
+ // src/chunking.ts
169
+ var CHUNK_TOKEN_BUDGET = 192;
170
+ var CHUNK_TOKEN_OVERLAP = 48;
171
+ var CHARS_PER_TOKEN = 4;
172
+ function chunkText(text, tokenBudget = CHUNK_TOKEN_BUDGET, tokenOverlap = CHUNK_TOKEN_OVERLAP) {
173
+ if (text.length === 0) {
174
+ return [];
175
+ }
176
+ const maxChars = Math.max(1, tokenBudget * CHARS_PER_TOKEN);
177
+ if (text.length <= maxChars) {
178
+ return [{ text, offset: 0 }];
179
+ }
180
+ const overlapChars = Math.max(0, Math.min(tokenOverlap * CHARS_PER_TOKEN, Math.floor(maxChars / 2)));
181
+ const chunks = [];
182
+ let start = 0;
183
+ while (start < text.length) {
184
+ const end = Math.min(start + maxChars, text.length);
185
+ const breakAt = findBreakPoint(text, start, end);
186
+ chunks.push({ text: text.slice(start, breakAt), offset: start });
187
+ if (breakAt >= text.length) {
188
+ break;
189
+ }
190
+ const nextStart = alignToWordStart(text, Math.max(start + 1, breakAt - overlapChars), breakAt);
191
+ start = nextStart;
192
+ }
193
+ return chunks;
194
+ }
195
+ function alignToWordStart(text, candidate, limit) {
196
+ for (let index = candidate; index <= limit; index += 1) {
197
+ if (/\s/.test(text[index - 1] ?? "")) {
198
+ return index;
199
+ }
200
+ }
201
+ return candidate;
202
+ }
203
+ function findBreakPoint(text, start, hardEnd) {
204
+ if (hardEnd >= text.length) {
205
+ return text.length;
206
+ }
207
+ const searchFrom = Math.max(start + Math.floor((hardEnd - start) / 2), start + 1);
208
+ for (let index = hardEnd; index >= searchFrom; index -= 1) {
209
+ if (/\s/.test(text[index - 1] ?? "")) {
210
+ return index;
211
+ }
212
+ }
213
+ return hardEnd;
214
+ }
215
+ function mergeChunkSpans(chunks, spansPerChunk) {
216
+ const merged = [];
217
+ for (let index = 0; index < chunks.length; index += 1) {
218
+ const chunk = chunks[index];
219
+ const spans = spansPerChunk[index] ?? [];
220
+ const nextChunk = chunks[index + 1];
221
+ for (const span of spans) {
222
+ const start = chunk.offset + span.start;
223
+ const end = chunk.offset + span.end;
224
+ if (nextChunk && start >= nextChunk.offset) {
225
+ continue;
226
+ }
227
+ merged.push({ start, end, chunkIndex: index });
228
+ }
229
+ }
230
+ return merged;
231
+ }
232
+
233
+ // src/engine.ts
234
+ var BROWSER_DEVICE_PREFERENCE = ["webgpu", "wasm"];
235
+ var BROWSER_DEFAULT_DTYPE = "q4";
236
+ var pipelinePromise = null;
237
+ var activeDevice = null;
238
+ function toPercent(event) {
239
+ if (typeof event.progress === "number" && Number.isFinite(event.progress)) {
240
+ const percent = event.progress;
241
+ return Math.max(0, Math.min(100, percent <= 1 ? percent * 100 : percent));
242
+ }
243
+ if (typeof event.loaded === "number" && typeof event.total === "number" && event.total > 0) {
244
+ return Math.max(0, Math.min(100, event.loaded / event.total * 100));
245
+ }
246
+ return null;
247
+ }
248
+ async function loadPipelineFactory() {
249
+ const module = await import("@huggingface/transformers");
250
+ if (typeof module.pipeline !== "function") {
251
+ throw new Error("Transformers.js pipeline is unavailable.");
252
+ }
253
+ if (module.env) {
254
+ module.env.allowLocalModels = false;
255
+ }
256
+ return module.pipeline;
257
+ }
258
+ async function detectDevice() {
259
+ if (typeof navigator === "undefined") {
260
+ return "wasm";
261
+ }
262
+ const gpu = navigator.gpu;
263
+ if (gpu) {
264
+ try {
265
+ const adapter = await gpu.requestAdapter();
266
+ if (adapter) {
267
+ return "webgpu";
268
+ }
269
+ } catch {
270
+ }
271
+ }
272
+ return "wasm";
273
+ }
274
+ function loadBrowserEngine(options = {}) {
275
+ if (pipelinePromise) {
276
+ return pipelinePromise;
277
+ }
278
+ const { onProgress } = options;
279
+ const load = async () => {
280
+ onProgress?.({ stage: "loading", percent: 0, detail: "loading runtime" });
281
+ const pipeline = await loadPipelineFactory();
282
+ const preferred = options.preferredDevice ?? await detectDevice();
283
+ const chain = [preferred, ...BROWSER_DEVICE_PREFERENCE.filter((d) => d !== preferred)];
284
+ let lastError = null;
285
+ for (const device of chain) {
286
+ try {
287
+ onProgress?.({ stage: "loading", percent: null, detail: `loading model (${device})` });
288
+ const classifier = await pipeline("token-classification", MODEL_ID, {
289
+ device,
290
+ dtype: BROWSER_DEFAULT_DTYPE,
291
+ progress_callback: (event) => {
292
+ onProgress?.({
293
+ stage: "loading",
294
+ percent: toPercent(event),
295
+ detail: event.file ?? `loading model (${device})`
296
+ });
297
+ }
298
+ });
299
+ activeDevice = device;
300
+ onProgress?.({ stage: "ready", percent: 100, detail: `ready (${device})` });
301
+ return classifier;
302
+ } catch (error) {
303
+ lastError = error;
304
+ }
305
+ }
306
+ onProgress?.({ stage: "error", percent: null, detail: "model unavailable" });
307
+ throw lastError instanceof Error ? lastError : new Error("Model could not be loaded.");
308
+ };
309
+ pipelinePromise = load().catch((error) => {
310
+ pipelinePromise = null;
311
+ onProgress?.({ stage: "error", percent: null, detail: "model unavailable" });
312
+ throw error;
313
+ });
314
+ return pipelinePromise;
315
+ }
316
+ function resetBrowserEngineForTests() {
317
+ pipelinePromise = null;
318
+ activeDevice = null;
319
+ }
320
+ function activeBrowserDevice() {
321
+ return activeDevice;
322
+ }
323
+ async function detectSpansInBrowser(text, options = {}) {
324
+ const classifier = await loadBrowserEngine(options);
325
+ const chunks = chunkText(text);
326
+ if (chunks.length <= 1) {
327
+ const tokens = await classifier(text, { ignore_labels: IGNORE_LABELS });
328
+ return normalizeSpans(text, tokensToSpans(Array.isArray(tokens) ? tokens : [], text));
329
+ }
330
+ const spansPerChunk = [];
331
+ for (const chunk of chunks) {
332
+ const tokens = await classifier(chunk.text, { ignore_labels: IGNORE_LABELS });
333
+ spansPerChunk.push(tokensToSpans(Array.isArray(tokens) ? tokens : [], chunk.text));
334
+ }
335
+ const merged = mergeChunkSpans(chunks, spansPerChunk);
336
+ const spans = [];
337
+ for (const { start, end, chunkIndex } of merged) {
338
+ const local = spansPerChunk[chunkIndex].find(
339
+ (span) => span.start === start - chunks[chunkIndex].offset && span.end === end - chunks[chunkIndex].offset
340
+ );
341
+ if (local) {
342
+ spans.push({ ...local, start, end });
343
+ }
344
+ }
345
+ return normalizeSpans(text, spans);
346
+ }
347
+ function tokensToSpans(tokens, text) {
348
+ const spans = [];
349
+ let cursor = 0;
350
+ let open = null;
351
+ const close = () => {
352
+ if (open && open.end > open.start) {
353
+ let start = open.start;
354
+ let end = open.end;
355
+ while (start < end && /\s/.test(text[start])) {
356
+ start += 1;
357
+ }
358
+ while (end > start && /\s/.test(text[end - 1])) {
359
+ end -= 1;
360
+ }
361
+ if (end > start) {
362
+ spans.push({
363
+ label: open.label,
364
+ start,
365
+ end,
366
+ text: text.slice(start, end),
367
+ score: open.score
368
+ });
369
+ }
370
+ }
371
+ open = null;
372
+ };
373
+ for (const token of tokens) {
374
+ const rawEntity = String(token.entity ?? token.entity_group ?? "");
375
+ if (!rawEntity || rawEntity === "O") {
376
+ close();
377
+ continue;
378
+ }
379
+ const boundary = rawEntity.slice(0, 2);
380
+ const label = stripBoundary(rawEntity);
381
+ const score = Math.max(0, Math.min(1, Number(token.score ?? 0)));
382
+ const word = String(token.word ?? "");
383
+ const found = word ? text.indexOf(word, cursor) : -1;
384
+ if (found < 0) {
385
+ close();
386
+ continue;
387
+ }
388
+ const start = found;
389
+ const end = found + word.length;
390
+ cursor = end;
391
+ if (boundary === "B-" || boundary === "S-") {
392
+ close();
393
+ open = { label, start, end, score };
394
+ if (boundary === "S-") {
395
+ close();
396
+ }
397
+ } else if (boundary === "I-" || boundary === "E-") {
398
+ if (open && open.label === label) {
399
+ open.end = end;
400
+ open.score = Math.min(open.score, score);
401
+ } else {
402
+ close();
403
+ open = { label, start, end, score };
404
+ }
405
+ if (boundary === "E-") {
406
+ close();
407
+ }
408
+ } else {
409
+ close();
410
+ }
411
+ }
412
+ close();
413
+ return spans;
414
+ }
415
+ export {
416
+ BROWSER_DEFAULT_DTYPE,
417
+ BROWSER_DEVICE_PREFERENCE,
418
+ CHUNK_TOKEN_BUDGET,
419
+ CHUNK_TOKEN_OVERLAP,
420
+ FILTER_MODES,
421
+ ID_TO_LABEL,
422
+ IGNORE_LABELS,
423
+ MODEL_ID,
424
+ SUPPORTED_LABELS,
425
+ activeBrowserDevice,
426
+ applyRedaction,
427
+ chunkText,
428
+ decodeBIOESToSpans,
429
+ detectDevice,
430
+ detectSpansInBrowser,
431
+ isFilterMode,
432
+ isSupportedLabel,
433
+ loadBrowserEngine,
434
+ mergeChunkSpans,
435
+ normalizeApiBaseUrl,
436
+ normalizeSpans,
437
+ resetBrowserEngineForTests,
438
+ spanKey,
439
+ stripBoundary,
440
+ tokensToSpans,
441
+ validateFilterRequest
442
+ };
443
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/redact.ts","../src/labels.ts","../src/chunking.ts","../src/engine.ts"],"sourcesContent":["export const FILTER_MODES = [\"mask\", \"remove\", \"annotate\"] as const;\n\nexport type FilterMode = (typeof FILTER_MODES)[number];\n\nexport type PrivacySpan = {\n label: string;\n start: number;\n end: number;\n text: string;\n score: number;\n};\n\nexport type FilterRequest = {\n text: string;\n mode: FilterMode;\n mask_token: string;\n include_spans: boolean;\n};\n\nexport type FilterResponse = {\n original_text: string;\n filtered_text: string;\n spans: PrivacySpan[];\n model: string;\n};\n","import { FILTER_MODES, type FilterMode, type FilterRequest, type PrivacySpan } from \"./types\";\n\nexport function normalizeApiBaseUrl(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nexport function isFilterMode(value: unknown): value is FilterMode {\n return typeof value === \"string\" && FILTER_MODES.includes(value as FilterMode);\n}\n\nexport function validateFilterRequest(value: unknown): string | null {\n if (!value || typeof value !== \"object\") {\n return \"Request body must be a JSON object.\";\n }\n\n const request = value as Partial<FilterRequest>;\n\n if (typeof request.text !== \"string\" || request.text.trim().length === 0) {\n return \"Enter text before running the privacy filter.\";\n }\n\n if (request.text.length > 50_000) {\n return \"Text must be 50,000 characters or fewer.\";\n }\n\n if (!isFilterMode(request.mode)) {\n return \"Choose a supported filter mode.\";\n }\n\n if (typeof request.mask_token !== \"string\" || request.mask_token.trim().length === 0) {\n return \"Mask token cannot be blank.\";\n }\n\n if (typeof request.include_spans !== \"boolean\") {\n return \"include_spans must be a boolean.\";\n }\n\n return null;\n}\n\nexport function spanKey(span: PrivacySpan): string {\n return `${span.label}-${span.start}-${span.end}-${span.score}`;\n}\n\n/**\n * Apply a redaction mode to text. Mirrors the Python `apply_redaction` helper so\n * the browser and server runtimes produce byte-identical output for the same\n * spans. Spans are expected to already be normalized (non-overlapping, sorted).\n */\nexport function applyRedaction(\n text: string,\n spans: readonly PrivacySpan[],\n mode: FilterMode,\n maskToken: string\n): [string, PrivacySpan[]] {\n const pieces: string[] = [];\n let cursor = 0;\n\n for (const span of spans) {\n pieces.push(text.slice(cursor, span.start));\n\n if (mode === \"remove\") {\n pieces.push(\"\");\n } else if (mode === \"annotate\") {\n pieces.push(`[${span.label}:${text.slice(span.start, span.end)}]`);\n } else {\n pieces.push(maskToken);\n }\n\n cursor = span.end;\n }\n\n pieces.push(text.slice(cursor));\n return [pieces.join(\"\"), [...spans]];\n}\n","import type { PrivacySpan } from \"./types\";\n\nexport const MODEL_ID = \"openai/privacy-filter\";\n\n/**\n * The 8 taxonomy labels, expanded to BIOES boundary tags plus the background\n * class. Mirrors `id2label` from the model config.\n */\nconst SPAN_LABELS = [\n \"account_number\",\n \"private_address\",\n \"private_date\",\n \"private_email\",\n \"private_person\",\n \"private_phone\",\n \"private_url\",\n \"secret\"\n] as const;\n\nexport const ID_TO_LABEL: readonly string[] = [\n \"O\",\n ...SPAN_LABELS.flatMap((label) => [`B-${label}`, `I-${label}`, `E-${label}`, `S-${label}`])\n];\n\nexport const SUPPORTED_LABELS: ReadonlySet<string> = new Set(SPAN_LABELS);\n\nexport const IGNORE_LABELS: readonly string[] = [\"O\"];\n\n/**\n * Strip the BIOES boundary prefix. `S-private_person` and `B-private_person`\n * both denote a `private_person` span.\n */\nexport function stripBoundary(label: string): string {\n const trimmed = label.trim();\n if (trimmed.toUpperCase() === \"O\") {\n return \"O\";\n }\n const cleaned = trimmed.toLowerCase();\n for (const prefix of [\"b-\", \"i-\", \"e-\", \"s-\"]) {\n if (cleaned.startsWith(prefix)) {\n return cleaned.slice(prefix.length);\n }\n }\n return cleaned;\n}\n\nexport function isSupportedLabel(label: string): boolean {\n return SUPPORTED_LABELS.has(stripBoundary(label));\n}\n\n/**\n * Constrained BIOES sequence decoding over per-token argmax labels.\n *\n * The published Viterbi calibration ships all six transition biases at 0.0, so\n * the constrained decode reduces to accepting only legal BIOES boundary\n * transitions. Any span that runs to the end of the sequence without reaching\n * `E-` or `S-` is truncated at the last legal token rather than discarded, so\n * long inputs do not silently lose detections.\n */\nexport function decodeBIOESToSpans(\n labels: readonly string[],\n offsets: readonly { start: number; end: number }[]\n): PrivacySpan[] {\n const spans: PrivacySpan[] = [];\n let current: { label: string; start: number; end: number } | null = null;\n\n const closeCurrent = () => {\n if (current && current.end > current.start) {\n spans.push({\n label: current.label,\n start: current.start,\n end: current.end,\n text: \"\",\n score: 1\n });\n }\n current = null;\n };\n\n for (let index = 0; index < labels.length; index += 1) {\n const raw = labels[index] ?? \"O\";\n const offset = offsets[index];\n if (!offset) {\n continue;\n }\n\n const boundary = raw.slice(0, 2).toUpperCase();\n const label = stripBoundary(raw);\n const supported = SUPPORTED_LABELS.has(label);\n\n if (!supported || boundary === \"O-\" || raw.toUpperCase() === \"O\") {\n closeCurrent();\n continue;\n }\n\n if (boundary === \"B-\" || boundary === \"S-\") {\n closeCurrent();\n current = { label, start: offset.start, end: offset.end };\n if (boundary === \"S-\") {\n closeCurrent();\n }\n continue;\n }\n\n if (boundary === \"I-\" || boundary === \"E-\") {\n if (current && current.label === label) {\n current.end = offset.end;\n } else {\n // A continuation without a matching opening: treat it as a new span.\n closeCurrent();\n current = { label, start: offset.start, end: offset.end };\n }\n if (boundary === \"E-\") {\n closeCurrent();\n }\n }\n }\n\n closeCurrent();\n return spans;\n}\n\n/**\n * Drop unsupported, inverted, and overlapping spans. Mirrors the ordering used\n * by the Python `normalize_spans` helper: earliest start, then longest, then\n * highest score.\n */\nexport function normalizeSpans(text: string, spans: readonly PrivacySpan[]): PrivacySpan[] {\n const length = text.length;\n const candidates: PrivacySpan[] = [];\n\n for (const span of spans) {\n if (!SUPPORTED_LABELS.has(span.label)) {\n continue;\n }\n const start = Math.max(0, Math.min(span.start, length));\n const end = Math.max(0, Math.min(span.end, length));\n if (end <= start) {\n continue;\n }\n candidates.push({ ...span, start, end, text: text.slice(start, end) });\n }\n\n candidates.sort(\n (left, right) =>\n left.start - right.start ||\n right.end - right.start - (left.end - left.start) ||\n right.score - left.score\n );\n\n const accepted: PrivacySpan[] = [];\n let cursor = 0;\n for (const span of candidates) {\n if (span.start < cursor) {\n continue;\n }\n accepted.push(span);\n cursor = span.end;\n }\n return accepted;\n}\n","/**\n * Chunking for the in-browser runtime.\n *\n * `openai/privacy-filter` uses banded attention with band size 128, giving an\n * effective attention window of 257 tokens including self. Text longer than that\n * would silently lose detections, so long input is split into overlapping\n * windows and the per-chunk spans are mapped back to original text offsets.\n */\n\n/** Leave headroom below the 257-token window for the tokenizer's special tokens. */\nexport const CHUNK_TOKEN_BUDGET = 192;\n\n/** Overlap so a span straddling a boundary is still seen whole in one window. */\nexport const CHUNK_TOKEN_OVERLAP = 48;\n\nexport type TextChunk = {\n text: string;\n /** Character offset of `text` within the original string. */\n offset: number;\n};\n\n/** Rough characters-per-token ratio, used only to size windows without a tokenizer. */\nconst CHARS_PER_TOKEN = 4;\n\n/**\n * Split text into overlapping chunks. Pure and tokenizer-free: it works on a\n * conservative characters-per-token estimate, so it is testable in isolation.\n *\n * Chunks break on whitespace where possible to avoid splitting mid-word, but\n * never exceed the character budget derived from the token budget.\n */\nexport function chunkText(\n text: string,\n tokenBudget: number = CHUNK_TOKEN_BUDGET,\n tokenOverlap: number = CHUNK_TOKEN_OVERLAP\n): TextChunk[] {\n if (text.length === 0) {\n return [];\n }\n\n const maxChars = Math.max(1, tokenBudget * CHARS_PER_TOKEN);\n if (text.length <= maxChars) {\n return [{ text, offset: 0 }];\n }\n\n const overlapChars = Math.max(0, Math.min(tokenOverlap * CHARS_PER_TOKEN, Math.floor(maxChars / 2)));\n const chunks: TextChunk[] = [];\n let start = 0;\n\n while (start < text.length) {\n const end = Math.min(start + maxChars, text.length);\n const breakAt = findBreakPoint(text, start, end);\n\n chunks.push({ text: text.slice(start, breakAt), offset: start });\n\n if (breakAt >= text.length) {\n break;\n }\n\n // Step back so the next window overlaps this one, then align to a word\n // boundary so neither window splits a word at its seam.\n const nextStart = alignToWordStart(text, Math.max(start + 1, breakAt - overlapChars), breakAt);\n start = nextStart;\n }\n\n return chunks;\n}\n\n/**\n * Advance `candidate` to the first word boundary in `[candidate, limit]`.\n *\n * `limit` (the previous chunk's break point) is itself always a boundary, so\n * the search always succeeds — falling through to it only costs overlap in\n * pathologically long words, never correctness. Unbroken runs with no\n * whitespace at all return `candidate` unchanged, keeping the loop progressing.\n */\nfunction alignToWordStart(text: string, candidate: number, limit: number): number {\n for (let index = candidate; index <= limit; index += 1) {\n if (/\\s/.test(text[index - 1] ?? \"\")) {\n return index;\n }\n }\n return candidate;\n}\n\n/**\n * Choose a chunk end at or before `hardEnd`, preferring the last whitespace so\n * words are not split. Falls back to `hardEnd` for very long unbroken runs.\n */\nfunction findBreakPoint(text: string, start: number, hardEnd: number): number {\n if (hardEnd >= text.length) {\n return text.length;\n }\n\n const searchFrom = Math.max(start + Math.floor((hardEnd - start) / 2), start + 1);\n for (let index = hardEnd; index >= searchFrom; index -= 1) {\n if (/\\s/.test(text[index - 1] ?? \"\")) {\n return index;\n }\n }\n\n return hardEnd;\n}\n\n/**\n * Map spans produced for a chunk back to original-text coordinates and drop any\n * that fall in the overlap region of a later chunk, so overlapping windows do\n * not yield duplicate spans.\n *\n * Each returned entry carries the index of the chunk it came from, so the\n * caller can recover the original label and score.\n */\nexport function mergeChunkSpans(\n chunks: readonly TextChunk[],\n spansPerChunk: ReadonlyArray<ReadonlyArray<{ start: number; end: number }>>\n): Array<{ start: number; end: number; chunkIndex: number }> {\n const merged: Array<{ start: number; end: number; chunkIndex: number }> = [];\n\n for (let index = 0; index < chunks.length; index += 1) {\n const chunk = chunks[index];\n const spans = spansPerChunk[index] ?? [];\n const nextChunk = chunks[index + 1];\n\n for (const span of spans) {\n const start = chunk.offset + span.start;\n const end = chunk.offset + span.end;\n\n // Spans starting at or after the next chunk's start are owned by it.\n if (nextChunk && start >= nextChunk.offset) {\n continue;\n }\n\n merged.push({ start, end, chunkIndex: index });\n }\n }\n\n return merged;\n}\n","import { chunkText, mergeChunkSpans } from \"./chunking\";\nimport type { PrivacySpan } from \"./types\";\nimport { IGNORE_LABELS, MODEL_ID, normalizeSpans, stripBoundary } from \"./labels\";\n\n/**\n * Backend device preference for the browser runtime, tried in order.\n *\n * transformers.js / onnxruntime-web supports exactly two browser backends:\n * `webgpu` and `wasm`. There is no WebGL backend — WebGL was never an\n * onnxruntime execution provider, so requesting it can only fail or, worse,\n * fall through silently. WASM runs everywhere (CPU), just slower.\n */\nexport const BROWSER_DEVICE_PREFERENCE = [\"webgpu\", \"wasm\"] as const;\n\nexport type BrowserDevice = (typeof BROWSER_DEVICE_PREFERENCE)[number];\n\nexport const BROWSER_DEFAULT_DTYPE = \"q4\";\n\n/**\n * Per-token output of the transformers.js token-classification pipeline,\n * verified against @huggingface/transformers@4.2.0 with the real\n * openai/privacy-filter model:\n *\n * { entity: \"B-private_person\", score: 0.9999, index: 3, word: \" Alice\" }\n *\n * `word` includes its leading space in the original text, so character offsets\n * can be reconstructed exactly by walking tokens in order. The aggregated form\n * (aggregation_strategy: \"simple\") returns entity_group/word/score but NO\n * start/end offsets — it is useless for redaction, which is why the per-token\n * form is used directly.\n */\nexport type TokenClassificationToken = {\n entity?: string;\n entity_group?: string;\n score?: number;\n index?: number;\n word?: string;\n};\n\ntype TokenClassifier = {\n (text: string, options?: Record<string, unknown>): Promise<TokenClassificationToken[]>;\n};\n\ntype ProgressEvent = {\n status?: string;\n file?: string;\n progress?: number;\n loaded?: number;\n total?: number;\n};\n\ntype PipelineFactory = (\n task: \"token-classification\",\n model: string,\n options?: Record<string, unknown>\n) => Promise<TokenClassifier>;\n\nexport type LoadStage = \"idle\" | \"loading\" | \"ready\" | \"error\";\n\nexport type LoadProgress = {\n stage: LoadStage;\n /** 0-100 when knowable, otherwise null. */\n percent: number | null;\n detail: string;\n};\n\nexport type BrowserEngineOptions = {\n onProgress?: (progress: LoadProgress) => void;\n preferredDevice?: string;\n};\n\nlet pipelinePromise: Promise<TokenClassifier> | null = null;\nlet activeDevice: string | null = null;\n\nfunction toPercent(event: ProgressEvent): number | null {\n if (typeof event.progress === \"number\" && Number.isFinite(event.progress)) {\n const percent = event.progress;\n return Math.max(0, Math.min(100, percent <= 1 ? percent * 100 : percent));\n }\n if (typeof event.loaded === \"number\" && typeof event.total === \"number\" && event.total > 0) {\n return Math.max(0, Math.min(100, (event.loaded / event.total) * 100));\n }\n return null;\n}\n\nasync function loadPipelineFactory(): Promise<PipelineFactory> {\n /* Bundled from the npm package rather than imported from a CDN at runtime.\n * The previous dynamic https import of the jsDelivr bundle downloaded fine\n * (HTTP 200) but never resolved as an ES module in the production build,\n * leaving the UI stuck at \"loading runtime\". The dynamic import below still\n * code-splits the library out of the initial page bundle. */\n const module = (await import(\"@huggingface/transformers\")) as unknown as {\n pipeline?: PipelineFactory;\n env?: Record<string, unknown>;\n };\n\n if (typeof module.pipeline !== \"function\") {\n throw new Error(\"Transformers.js pipeline is unavailable.\");\n }\n\n // Model weights come from the Hugging Face CDN and stay in the browser cache\n // so repeat visits do not re-download ~900 MB.\n if (module.env) {\n module.env.allowLocalModels = false;\n }\n\n return module.pipeline;\n}\n\n/**\n * Detect the best available backend: WebGPU when the browser exposes a working\n * adapter, otherwise WASM (CPU), which works everywhere.\n *\n * There is no WebGL branch on purpose: onnxruntime-web has no WebGL execution\n * provider, so a WebGL context would tell us nothing about model support.\n */\nexport async function detectDevice(): Promise<string> {\n if (typeof navigator === \"undefined\") {\n return \"wasm\";\n }\n const gpu = (navigator as Navigator & { gpu?: { requestAdapter(): Promise<unknown> } }).gpu;\n if (gpu) {\n try {\n const adapter = await gpu.requestAdapter();\n if (adapter) {\n return \"webgpu\";\n }\n } catch {\n // Fall through to WASM.\n }\n }\n return \"wasm\";\n}\n\n/**\n * Load the in-browser classifier, retrying down the device chain.\n *\n * WebGPU is fastest but is not available in every browser; WASM (CPU) is the\n * universal fallback and keeps the sandbox usable everywhere.\n */\nexport function loadBrowserEngine(options: BrowserEngineOptions = {}): Promise<TokenClassifier> {\n if (pipelinePromise) {\n return pipelinePromise;\n }\n\n const { onProgress } = options;\n\n const load = async (): Promise<TokenClassifier> => {\n onProgress?.({ stage: \"loading\", percent: 0, detail: \"loading runtime\" });\n\n const pipeline = await loadPipelineFactory();\n const preferred = options.preferredDevice ?? (await detectDevice());\n const chain = [preferred, ...BROWSER_DEVICE_PREFERENCE.filter((d) => d !== preferred)];\n\n let lastError: unknown = null;\n\n for (const device of chain) {\n try {\n onProgress?.({ stage: \"loading\", percent: null, detail: `loading model (${device})` });\n\n const classifier = await pipeline(\"token-classification\", MODEL_ID, {\n device,\n dtype: BROWSER_DEFAULT_DTYPE,\n progress_callback: (event: ProgressEvent) => {\n onProgress?.({\n stage: \"loading\",\n percent: toPercent(event),\n detail: event.file ?? `loading model (${device})`\n });\n }\n });\n\n activeDevice = device;\n onProgress?.({ stage: \"ready\", percent: 100, detail: `ready (${device})` });\n return classifier;\n } catch (error) {\n lastError = error;\n // Keep the shared promise until the chain is exhausted: a device that\n // fails partway does not mean the load is finished, and clearing the\n // slot here would let a concurrent caller start a second 900 MB fetch.\n }\n }\n\n onProgress?.({ stage: \"error\", percent: null, detail: \"model unavailable\" });\n throw lastError instanceof Error ? lastError : new Error(\"Model could not be loaded.\");\n };\n\n pipelinePromise = load().catch((error: unknown) => {\n // Only a terminal failure clears the slot, so the next attempt can retry.\n pipelinePromise = null;\n onProgress?.({ stage: \"error\", percent: null, detail: \"model unavailable\" });\n throw error;\n });\n\n return pipelinePromise;\n}\n\nexport function resetBrowserEngineForTests(): void {\n pipelinePromise = null;\n activeDevice = null;\n}\n\nexport function activeBrowserDevice(): string | null {\n return activeDevice;\n}\n\n/**\n * Run detection in the browser and return spans matching the API contract.\n *\n * Uses the pipeline's per-token output (verified against transformers.js 4.2.0\n * with the real model): each non-background token carries its BIOES tag,\n * score, and `word` with leading whitespace preserved. Character offsets are\n * reconstructed by walking the original text alongside the tokens, then\n * consecutive B-, I-, E- and S-tagged tokens of one label are grouped into\n * spans.\n *\n * Text longer than the model's 257-token attention window is classified in\n * overlapping chunks (see chunking.ts); per-chunk spans are mapped back to\n * original offsets and deduplicated at the seams.\n */\nexport async function detectSpansInBrowser(\n text: string,\n options: BrowserEngineOptions = {}\n): Promise<PrivacySpan[]> {\n const classifier = await loadBrowserEngine(options);\n const chunks = chunkText(text);\n\n if (chunks.length <= 1) {\n const tokens = await classifier(text, { ignore_labels: IGNORE_LABELS });\n return normalizeSpans(text, tokensToSpans(Array.isArray(tokens) ? tokens : [], text));\n }\n\n const spansPerChunk: PrivacySpan[][] = [];\n for (const chunk of chunks) {\n const tokens = await classifier(chunk.text, { ignore_labels: IGNORE_LABELS });\n spansPerChunk.push(tokensToSpans(Array.isArray(tokens) ? tokens : [], chunk.text));\n }\n\n // mergeChunkSpans returns global start/end plus the owning chunk; recover\n // each span's label and score from the per-chunk result it came from.\n const merged = mergeChunkSpans(chunks, spansPerChunk);\n const spans: PrivacySpan[] = [];\n for (const { start, end, chunkIndex } of merged) {\n const local = spansPerChunk[chunkIndex].find(\n (span) =>\n span.start === start - chunks[chunkIndex].offset &&\n span.end === end - chunks[chunkIndex].offset\n );\n if (local) {\n spans.push({ ...local, start, end });\n }\n }\n\n return normalizeSpans(text, spans);\n}\n\n/**\n * Convert per-token predictions with reconstructed offsets into spans.\n * Pure; exported for testing.\n */\nexport function tokensToSpans(\n tokens: readonly TokenClassificationToken[],\n text: string\n): PrivacySpan[] {\n const spans: PrivacySpan[] = [];\n let cursor = 0;\n let open: { label: string; start: number; end: number; score: number } | null = null;\n\n const close = () => {\n if (open && open.end > open.start) {\n /* Token `word`s keep their leading space, so a span opening at a B- or\n * orphaned I-tag starts on whitespace. Shift the boundaries onto the\n * non-whitespace content so masks read \"is [REDACTED],\" not \"is[REDACTED],\". */\n let start = open.start;\n let end = open.end;\n while (start < end && /\\s/.test(text[start])) {\n start += 1;\n }\n while (end > start && /\\s/.test(text[end - 1])) {\n end -= 1;\n }\n if (end > start) {\n spans.push({\n label: open.label,\n start,\n end,\n text: text.slice(start, end),\n score: open.score\n });\n }\n }\n open = null;\n };\n\n for (const token of tokens) {\n const rawEntity = String(token.entity ?? token.entity_group ?? \"\");\n if (!rawEntity || rawEntity === \"O\") {\n close();\n continue;\n }\n\n const boundary = rawEntity.slice(0, 2);\n const label = stripBoundary(rawEntity);\n const score = Math.max(0, Math.min(1, Number(token.score ?? 0)));\n\n const word = String(token.word ?? \"\");\n const found = word ? text.indexOf(word, cursor) : -1;\n if (found < 0) {\n // Token text not locatable (normalisation artefact): close so offsets\n // cannot drift rather than guessing a position.\n close();\n continue;\n }\n\n const start = found;\n const end = found + word.length;\n cursor = end;\n\n if (boundary === \"B-\" || boundary === \"S-\") {\n close();\n open = { label, start, end, score };\n if (boundary === \"S-\") {\n close();\n }\n } else if (boundary === \"I-\" || boundary === \"E-\") {\n if (open && open.label === label) {\n open.end = end;\n open.score = Math.min(open.score, score);\n } else {\n close();\n open = { label, start, end, score };\n }\n if (boundary === \"E-\") {\n close();\n }\n } else {\n close();\n }\n }\n\n close();\n return spans;\n}\n"],"mappings":";AAAO,IAAM,eAAe,CAAC,QAAQ,UAAU,UAAU;;;ACElD,SAAS,oBAAoB,OAAuB;AACzD,SAAO,MAAM,QAAQ,QAAQ,EAAE;AACjC;AAEO,SAAS,aAAa,OAAqC;AAChE,SAAO,OAAO,UAAU,YAAY,aAAa,SAAS,KAAmB;AAC/E;AAEO,SAAS,sBAAsB,OAA+B;AACnE,MAAI,CAAC,SAAS,OAAO,UAAU,UAAU;AACvC,WAAO;AAAA,EACT;AAEA,QAAM,UAAU;AAEhB,MAAI,OAAO,QAAQ,SAAS,YAAY,QAAQ,KAAK,KAAK,EAAE,WAAW,GAAG;AACxE,WAAO;AAAA,EACT;AAEA,MAAI,QAAQ,KAAK,SAAS,KAAQ;AAChC,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,aAAa,QAAQ,IAAI,GAAG;AAC/B,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,QAAQ,eAAe,YAAY,QAAQ,WAAW,KAAK,EAAE,WAAW,GAAG;AACpF,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,QAAQ,kBAAkB,WAAW;AAC9C,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAEO,SAAS,QAAQ,MAA2B;AACjD,SAAO,GAAG,KAAK,KAAK,IAAI,KAAK,KAAK,IAAI,KAAK,GAAG,IAAI,KAAK,KAAK;AAC9D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A,MACpC;AACA,UAAI,aAAa,MAAM;AACrB,cAAM;AAAA,MACR;AAAA,IACF,OAAO;AACL,YAAM;AAAA,IACR;AAAA,EACF;AAEA,QAAM;AACN,SAAO;AACT;","names":[]}
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@shiftbloom-studio/privacy-filter",
3
+ "version": "0.1.0",
4
+ "description": "In-browser privacy-span detection with the openai/privacy-filter model via Transformers.js (WebGPU/WASM). No server compute; text never leaves the device.",
5
+ "keywords": [
6
+ "privacy",
7
+ "pii",
8
+ "redaction",
9
+ "token-classification",
10
+ "transformersjs",
11
+ "browser",
12
+ "webgpu",
13
+ "nextjs"
14
+ ],
15
+ "homepage": "https://github.com/shiftbloom-studio/openai-privacy-filter-api#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/shiftbloom-studio/openai-privacy-filter-api/issues"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/shiftbloom-studio/openai-privacy-filter-api.git",
22
+ "directory": "packages/privacy-filter"
23
+ },
24
+ "license": "Apache-2.0",
25
+ "author": "shiftbloom studio",
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "type": "module",
30
+ "main": "./dist/index.cjs",
31
+ "module": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "exports": {
34
+ ".": {
35
+ "import": {
36
+ "types": "./dist/index.d.ts",
37
+ "default": "./dist/index.js"
38
+ },
39
+ "require": {
40
+ "types": "./dist/index.d.cts",
41
+ "default": "./dist/index.cjs"
42
+ }
43
+ }
44
+ },
45
+ "files": [
46
+ "dist",
47
+ "README.md",
48
+ "LICENSE"
49
+ ],
50
+ "sideEffects": false,
51
+ "engines": {
52
+ "node": ">=20.0.0"
53
+ },
54
+ "scripts": {
55
+ "build": "tsup",
56
+ "test": "vitest run",
57
+ "typecheck": "tsc --noEmit",
58
+ "prepublishOnly": "npm run build"
59
+ },
60
+ "dependencies": {
61
+ "@huggingface/transformers": "4.2.0"
62
+ },
63
+ "devDependencies": {
64
+ "tsup": "^8.5.1",
65
+ "typescript": "npm:@typescript/typescript6@6.0.2",
66
+ "vitest": "^4.1.10"
67
+ }
68
+ }