@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.
@@ -0,0 +1,189 @@
1
+ declare const FILTER_MODES: readonly ["mask", "remove", "annotate"];
2
+ type FilterMode = (typeof FILTER_MODES)[number];
3
+ type PrivacySpan = {
4
+ label: string;
5
+ start: number;
6
+ end: number;
7
+ text: string;
8
+ score: number;
9
+ };
10
+ type FilterRequest = {
11
+ text: string;
12
+ mode: FilterMode;
13
+ mask_token: string;
14
+ include_spans: boolean;
15
+ };
16
+ type FilterResponse = {
17
+ original_text: string;
18
+ filtered_text: string;
19
+ spans: PrivacySpan[];
20
+ model: string;
21
+ };
22
+
23
+ declare function normalizeApiBaseUrl(value: string): string;
24
+ declare function isFilterMode(value: unknown): value is FilterMode;
25
+ declare function validateFilterRequest(value: unknown): string | null;
26
+ declare function spanKey(span: PrivacySpan): string;
27
+ /**
28
+ * Apply a redaction mode to text. Mirrors the Python `apply_redaction` helper so
29
+ * the browser and server runtimes produce byte-identical output for the same
30
+ * spans. Spans are expected to already be normalized (non-overlapping, sorted).
31
+ */
32
+ declare function applyRedaction(text: string, spans: readonly PrivacySpan[], mode: FilterMode, maskToken: string): [string, PrivacySpan[]];
33
+
34
+ declare const MODEL_ID = "openai/privacy-filter";
35
+ declare const ID_TO_LABEL: readonly string[];
36
+ declare const SUPPORTED_LABELS: ReadonlySet<string>;
37
+ declare const IGNORE_LABELS: readonly string[];
38
+ /**
39
+ * Strip the BIOES boundary prefix. `S-private_person` and `B-private_person`
40
+ * both denote a `private_person` span.
41
+ */
42
+ declare function stripBoundary(label: string): string;
43
+ declare function isSupportedLabel(label: string): boolean;
44
+ /**
45
+ * Constrained BIOES sequence decoding over per-token argmax labels.
46
+ *
47
+ * The published Viterbi calibration ships all six transition biases at 0.0, so
48
+ * the constrained decode reduces to accepting only legal BIOES boundary
49
+ * transitions. Any span that runs to the end of the sequence without reaching
50
+ * `E-` or `S-` is truncated at the last legal token rather than discarded, so
51
+ * long inputs do not silently lose detections.
52
+ */
53
+ declare function decodeBIOESToSpans(labels: readonly string[], offsets: readonly {
54
+ start: number;
55
+ end: number;
56
+ }[]): PrivacySpan[];
57
+ /**
58
+ * Drop unsupported, inverted, and overlapping spans. Mirrors the ordering used
59
+ * by the Python `normalize_spans` helper: earliest start, then longest, then
60
+ * highest score.
61
+ */
62
+ declare function normalizeSpans(text: string, spans: readonly PrivacySpan[]): PrivacySpan[];
63
+
64
+ /**
65
+ * Chunking for the in-browser runtime.
66
+ *
67
+ * `openai/privacy-filter` uses banded attention with band size 128, giving an
68
+ * effective attention window of 257 tokens including self. Text longer than that
69
+ * would silently lose detections, so long input is split into overlapping
70
+ * windows and the per-chunk spans are mapped back to original text offsets.
71
+ */
72
+ /** Leave headroom below the 257-token window for the tokenizer's special tokens. */
73
+ declare const CHUNK_TOKEN_BUDGET = 192;
74
+ /** Overlap so a span straddling a boundary is still seen whole in one window. */
75
+ declare const CHUNK_TOKEN_OVERLAP = 48;
76
+ type TextChunk = {
77
+ text: string;
78
+ /** Character offset of `text` within the original string. */
79
+ offset: number;
80
+ };
81
+ /**
82
+ * Split text into overlapping chunks. Pure and tokenizer-free: it works on a
83
+ * conservative characters-per-token estimate, so it is testable in isolation.
84
+ *
85
+ * Chunks break on whitespace where possible to avoid splitting mid-word, but
86
+ * never exceed the character budget derived from the token budget.
87
+ */
88
+ declare function chunkText(text: string, tokenBudget?: number, tokenOverlap?: number): TextChunk[];
89
+ /**
90
+ * Map spans produced for a chunk back to original-text coordinates and drop any
91
+ * that fall in the overlap region of a later chunk, so overlapping windows do
92
+ * not yield duplicate spans.
93
+ *
94
+ * Each returned entry carries the index of the chunk it came from, so the
95
+ * caller can recover the original label and score.
96
+ */
97
+ declare function mergeChunkSpans(chunks: readonly TextChunk[], spansPerChunk: ReadonlyArray<ReadonlyArray<{
98
+ start: number;
99
+ end: number;
100
+ }>>): Array<{
101
+ start: number;
102
+ end: number;
103
+ chunkIndex: number;
104
+ }>;
105
+
106
+ /**
107
+ * Backend device preference for the browser runtime, tried in order.
108
+ *
109
+ * transformers.js / onnxruntime-web supports exactly two browser backends:
110
+ * `webgpu` and `wasm`. There is no WebGL backend — WebGL was never an
111
+ * onnxruntime execution provider, so requesting it can only fail or, worse,
112
+ * fall through silently. WASM runs everywhere (CPU), just slower.
113
+ */
114
+ declare const BROWSER_DEVICE_PREFERENCE: readonly ["webgpu", "wasm"];
115
+ type BrowserDevice = (typeof BROWSER_DEVICE_PREFERENCE)[number];
116
+ declare const BROWSER_DEFAULT_DTYPE = "q4";
117
+ /**
118
+ * Per-token output of the transformers.js token-classification pipeline,
119
+ * verified against @huggingface/transformers@4.2.0 with the real
120
+ * openai/privacy-filter model:
121
+ *
122
+ * { entity: "B-private_person", score: 0.9999, index: 3, word: " Alice" }
123
+ *
124
+ * `word` includes its leading space in the original text, so character offsets
125
+ * can be reconstructed exactly by walking tokens in order. The aggregated form
126
+ * (aggregation_strategy: "simple") returns entity_group/word/score but NO
127
+ * start/end offsets — it is useless for redaction, which is why the per-token
128
+ * form is used directly.
129
+ */
130
+ type TokenClassificationToken = {
131
+ entity?: string;
132
+ entity_group?: string;
133
+ score?: number;
134
+ index?: number;
135
+ word?: string;
136
+ };
137
+ type TokenClassifier = {
138
+ (text: string, options?: Record<string, unknown>): Promise<TokenClassificationToken[]>;
139
+ };
140
+ type LoadStage = "idle" | "loading" | "ready" | "error";
141
+ type LoadProgress = {
142
+ stage: LoadStage;
143
+ /** 0-100 when knowable, otherwise null. */
144
+ percent: number | null;
145
+ detail: string;
146
+ };
147
+ type BrowserEngineOptions = {
148
+ onProgress?: (progress: LoadProgress) => void;
149
+ preferredDevice?: string;
150
+ };
151
+ /**
152
+ * Detect the best available backend: WebGPU when the browser exposes a working
153
+ * adapter, otherwise WASM (CPU), which works everywhere.
154
+ *
155
+ * There is no WebGL branch on purpose: onnxruntime-web has no WebGL execution
156
+ * provider, so a WebGL context would tell us nothing about model support.
157
+ */
158
+ declare function detectDevice(): Promise<string>;
159
+ /**
160
+ * Load the in-browser classifier, retrying down the device chain.
161
+ *
162
+ * WebGPU is fastest but is not available in every browser; WASM (CPU) is the
163
+ * universal fallback and keeps the sandbox usable everywhere.
164
+ */
165
+ declare function loadBrowserEngine(options?: BrowserEngineOptions): Promise<TokenClassifier>;
166
+ declare function resetBrowserEngineForTests(): void;
167
+ declare function activeBrowserDevice(): string | null;
168
+ /**
169
+ * Run detection in the browser and return spans matching the API contract.
170
+ *
171
+ * Uses the pipeline's per-token output (verified against transformers.js 4.2.0
172
+ * with the real model): each non-background token carries its BIOES tag,
173
+ * score, and `word` with leading whitespace preserved. Character offsets are
174
+ * reconstructed by walking the original text alongside the tokens, then
175
+ * consecutive B-, I-, E- and S-tagged tokens of one label are grouped into
176
+ * spans.
177
+ *
178
+ * Text longer than the model's 257-token attention window is classified in
179
+ * overlapping chunks (see chunking.ts); per-chunk spans are mapped back to
180
+ * original offsets and deduplicated at the seams.
181
+ */
182
+ declare function detectSpansInBrowser(text: string, options?: BrowserEngineOptions): Promise<PrivacySpan[]>;
183
+ /**
184
+ * Convert per-token predictions with reconstructed offsets into spans.
185
+ * Pure; exported for testing.
186
+ */
187
+ declare function tokensToSpans(tokens: readonly TokenClassificationToken[], text: string): PrivacySpan[];
188
+
189
+ export { BROWSER_DEFAULT_DTYPE, BROWSER_DEVICE_PREFERENCE, type BrowserDevice, type BrowserEngineOptions, CHUNK_TOKEN_BUDGET, CHUNK_TOKEN_OVERLAP, FILTER_MODES, type FilterMode, type FilterRequest, type FilterResponse, ID_TO_LABEL, IGNORE_LABELS, type LoadProgress, type LoadStage, MODEL_ID, type PrivacySpan, SUPPORTED_LABELS, type TextChunk, type TokenClassificationToken, activeBrowserDevice, applyRedaction, chunkText, decodeBIOESToSpans, detectDevice, detectSpansInBrowser, isFilterMode, isSupportedLabel, loadBrowserEngine, mergeChunkSpans, normalizeApiBaseUrl, normalizeSpans, resetBrowserEngineForTests, spanKey, stripBoundary, tokensToSpans, validateFilterRequest };
@@ -0,0 +1,189 @@
1
+ declare const FILTER_MODES: readonly ["mask", "remove", "annotate"];
2
+ type FilterMode = (typeof FILTER_MODES)[number];
3
+ type PrivacySpan = {
4
+ label: string;
5
+ start: number;
6
+ end: number;
7
+ text: string;
8
+ score: number;
9
+ };
10
+ type FilterRequest = {
11
+ text: string;
12
+ mode: FilterMode;
13
+ mask_token: string;
14
+ include_spans: boolean;
15
+ };
16
+ type FilterResponse = {
17
+ original_text: string;
18
+ filtered_text: string;
19
+ spans: PrivacySpan[];
20
+ model: string;
21
+ };
22
+
23
+ declare function normalizeApiBaseUrl(value: string): string;
24
+ declare function isFilterMode(value: unknown): value is FilterMode;
25
+ declare function validateFilterRequest(value: unknown): string | null;
26
+ declare function spanKey(span: PrivacySpan): string;
27
+ /**
28
+ * Apply a redaction mode to text. Mirrors the Python `apply_redaction` helper so
29
+ * the browser and server runtimes produce byte-identical output for the same
30
+ * spans. Spans are expected to already be normalized (non-overlapping, sorted).
31
+ */
32
+ declare function applyRedaction(text: string, spans: readonly PrivacySpan[], mode: FilterMode, maskToken: string): [string, PrivacySpan[]];
33
+
34
+ declare const MODEL_ID = "openai/privacy-filter";
35
+ declare const ID_TO_LABEL: readonly string[];
36
+ declare const SUPPORTED_LABELS: ReadonlySet<string>;
37
+ declare const IGNORE_LABELS: readonly string[];
38
+ /**
39
+ * Strip the BIOES boundary prefix. `S-private_person` and `B-private_person`
40
+ * both denote a `private_person` span.
41
+ */
42
+ declare function stripBoundary(label: string): string;
43
+ declare function isSupportedLabel(label: string): boolean;
44
+ /**
45
+ * Constrained BIOES sequence decoding over per-token argmax labels.
46
+ *
47
+ * The published Viterbi calibration ships all six transition biases at 0.0, so
48
+ * the constrained decode reduces to accepting only legal BIOES boundary
49
+ * transitions. Any span that runs to the end of the sequence without reaching
50
+ * `E-` or `S-` is truncated at the last legal token rather than discarded, so
51
+ * long inputs do not silently lose detections.
52
+ */
53
+ declare function decodeBIOESToSpans(labels: readonly string[], offsets: readonly {
54
+ start: number;
55
+ end: number;
56
+ }[]): PrivacySpan[];
57
+ /**
58
+ * Drop unsupported, inverted, and overlapping spans. Mirrors the ordering used
59
+ * by the Python `normalize_spans` helper: earliest start, then longest, then
60
+ * highest score.
61
+ */
62
+ declare function normalizeSpans(text: string, spans: readonly PrivacySpan[]): PrivacySpan[];
63
+
64
+ /**
65
+ * Chunking for the in-browser runtime.
66
+ *
67
+ * `openai/privacy-filter` uses banded attention with band size 128, giving an
68
+ * effective attention window of 257 tokens including self. Text longer than that
69
+ * would silently lose detections, so long input is split into overlapping
70
+ * windows and the per-chunk spans are mapped back to original text offsets.
71
+ */
72
+ /** Leave headroom below the 257-token window for the tokenizer's special tokens. */
73
+ declare const CHUNK_TOKEN_BUDGET = 192;
74
+ /** Overlap so a span straddling a boundary is still seen whole in one window. */
75
+ declare const CHUNK_TOKEN_OVERLAP = 48;
76
+ type TextChunk = {
77
+ text: string;
78
+ /** Character offset of `text` within the original string. */
79
+ offset: number;
80
+ };
81
+ /**
82
+ * Split text into overlapping chunks. Pure and tokenizer-free: it works on a
83
+ * conservative characters-per-token estimate, so it is testable in isolation.
84
+ *
85
+ * Chunks break on whitespace where possible to avoid splitting mid-word, but
86
+ * never exceed the character budget derived from the token budget.
87
+ */
88
+ declare function chunkText(text: string, tokenBudget?: number, tokenOverlap?: number): TextChunk[];
89
+ /**
90
+ * Map spans produced for a chunk back to original-text coordinates and drop any
91
+ * that fall in the overlap region of a later chunk, so overlapping windows do
92
+ * not yield duplicate spans.
93
+ *
94
+ * Each returned entry carries the index of the chunk it came from, so the
95
+ * caller can recover the original label and score.
96
+ */
97
+ declare function mergeChunkSpans(chunks: readonly TextChunk[], spansPerChunk: ReadonlyArray<ReadonlyArray<{
98
+ start: number;
99
+ end: number;
100
+ }>>): Array<{
101
+ start: number;
102
+ end: number;
103
+ chunkIndex: number;
104
+ }>;
105
+
106
+ /**
107
+ * Backend device preference for the browser runtime, tried in order.
108
+ *
109
+ * transformers.js / onnxruntime-web supports exactly two browser backends:
110
+ * `webgpu` and `wasm`. There is no WebGL backend — WebGL was never an
111
+ * onnxruntime execution provider, so requesting it can only fail or, worse,
112
+ * fall through silently. WASM runs everywhere (CPU), just slower.
113
+ */
114
+ declare const BROWSER_DEVICE_PREFERENCE: readonly ["webgpu", "wasm"];
115
+ type BrowserDevice = (typeof BROWSER_DEVICE_PREFERENCE)[number];
116
+ declare const BROWSER_DEFAULT_DTYPE = "q4";
117
+ /**
118
+ * Per-token output of the transformers.js token-classification pipeline,
119
+ * verified against @huggingface/transformers@4.2.0 with the real
120
+ * openai/privacy-filter model:
121
+ *
122
+ * { entity: "B-private_person", score: 0.9999, index: 3, word: " Alice" }
123
+ *
124
+ * `word` includes its leading space in the original text, so character offsets
125
+ * can be reconstructed exactly by walking tokens in order. The aggregated form
126
+ * (aggregation_strategy: "simple") returns entity_group/word/score but NO
127
+ * start/end offsets — it is useless for redaction, which is why the per-token
128
+ * form is used directly.
129
+ */
130
+ type TokenClassificationToken = {
131
+ entity?: string;
132
+ entity_group?: string;
133
+ score?: number;
134
+ index?: number;
135
+ word?: string;
136
+ };
137
+ type TokenClassifier = {
138
+ (text: string, options?: Record<string, unknown>): Promise<TokenClassificationToken[]>;
139
+ };
140
+ type LoadStage = "idle" | "loading" | "ready" | "error";
141
+ type LoadProgress = {
142
+ stage: LoadStage;
143
+ /** 0-100 when knowable, otherwise null. */
144
+ percent: number | null;
145
+ detail: string;
146
+ };
147
+ type BrowserEngineOptions = {
148
+ onProgress?: (progress: LoadProgress) => void;
149
+ preferredDevice?: string;
150
+ };
151
+ /**
152
+ * Detect the best available backend: WebGPU when the browser exposes a working
153
+ * adapter, otherwise WASM (CPU), which works everywhere.
154
+ *
155
+ * There is no WebGL branch on purpose: onnxruntime-web has no WebGL execution
156
+ * provider, so a WebGL context would tell us nothing about model support.
157
+ */
158
+ declare function detectDevice(): Promise<string>;
159
+ /**
160
+ * Load the in-browser classifier, retrying down the device chain.
161
+ *
162
+ * WebGPU is fastest but is not available in every browser; WASM (CPU) is the
163
+ * universal fallback and keeps the sandbox usable everywhere.
164
+ */
165
+ declare function loadBrowserEngine(options?: BrowserEngineOptions): Promise<TokenClassifier>;
166
+ declare function resetBrowserEngineForTests(): void;
167
+ declare function activeBrowserDevice(): string | null;
168
+ /**
169
+ * Run detection in the browser and return spans matching the API contract.
170
+ *
171
+ * Uses the pipeline's per-token output (verified against transformers.js 4.2.0
172
+ * with the real model): each non-background token carries its BIOES tag,
173
+ * score, and `word` with leading whitespace preserved. Character offsets are
174
+ * reconstructed by walking the original text alongside the tokens, then
175
+ * consecutive B-, I-, E- and S-tagged tokens of one label are grouped into
176
+ * spans.
177
+ *
178
+ * Text longer than the model's 257-token attention window is classified in
179
+ * overlapping chunks (see chunking.ts); per-chunk spans are mapped back to
180
+ * original offsets and deduplicated at the seams.
181
+ */
182
+ declare function detectSpansInBrowser(text: string, options?: BrowserEngineOptions): Promise<PrivacySpan[]>;
183
+ /**
184
+ * Convert per-token predictions with reconstructed offsets into spans.
185
+ * Pure; exported for testing.
186
+ */
187
+ declare function tokensToSpans(tokens: readonly TokenClassificationToken[], text: string): PrivacySpan[];
188
+
189
+ export { BROWSER_DEFAULT_DTYPE, BROWSER_DEVICE_PREFERENCE, type BrowserDevice, type BrowserEngineOptions, CHUNK_TOKEN_BUDGET, CHUNK_TOKEN_OVERLAP, FILTER_MODES, type FilterMode, type FilterRequest, type FilterResponse, ID_TO_LABEL, IGNORE_LABELS, type LoadProgress, type LoadStage, MODEL_ID, type PrivacySpan, SUPPORTED_LABELS, type TextChunk, type TokenClassificationToken, activeBrowserDevice, applyRedaction, chunkText, decodeBIOESToSpans, detectDevice, detectSpansInBrowser, isFilterMode, isSupportedLabel, loadBrowserEngine, mergeChunkSpans, normalizeApiBaseUrl, normalizeSpans, resetBrowserEngineForTests, spanKey, stripBoundary, tokensToSpans, validateFilterRequest };