bounds-gemma 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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,18 @@
1
+ bounds-gemma
2
+ Copyright 2026 Anya Chueayen
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
5
+ not use this code except in compliance with the License. You may obtain
6
+ a copy of the License at:
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ This product uses Google's Gemma 4 model family via the Gemini API, the
11
+ @mlc-ai/web-llm runtime, and Ollama. Each of those is governed by its
12
+ own licence. Gemma is provided by Google under the Gemma Prohibited
13
+ Use Policy (https://ai.google.dev/gemma/prohibited_use_policy). Users
14
+ of this toolkit are responsible for complying with Google's terms.
15
+
16
+ The contextual PHI taxonomy used in the system prompts of this toolkit
17
+ is derived from the HIPAA Safe Harbor identifier categories at 45 CFR
18
+ 164.514(b)(2), which are in the public domain.
package/README.md ADDED
@@ -0,0 +1,149 @@
1
+ # bounds-gemma
2
+
3
+ **On-device Gemma 4 contextual PHI redaction.** A small, focused TypeScript toolkit that uses Google's Gemma 4 to catch the protected-health-information shapes that regex and named-entity recognition systematically miss: inline diagnoses in clinical prose, medication mentions, treatment narratives, indirect health context, sensitive social data, and genetic references. Runs in a browser via WebLLM, locally via Ollama, or in any environment that can speak HTTP to a Gemma 4 endpoint. Never on a server.
4
+
5
+ Live demo: <https://bounds.pro>
6
+
7
+ This is the open-source pipeline that powers the contextual-PHI layer of Bounds Pro, a closed-source PDF redaction workspace. The toolkit on its own is enough to reproduce that layer end to end on your own documents.
8
+
9
+ ---
10
+
11
+ ## Why this exists
12
+
13
+ The HIPAA Safe Harbor de-identification standard at 45 CFR 164.514(b)(2) lists eighteen identifier categories. The first sixteen are structured — phone numbers, social-security numbers, medical-record numbers, dates of birth — and the long-standing rule-based redactors handle them. Identifier #17 is *"any other unique identifying number, characteristic, or code"*, and the surrounding clinical narrative is where it lives: a sentence that names a diagnosis without a label, a paragraph that mentions a medication in passing, an aside about a "therapist" or "insulin pump" that re-identifies the patient when triangulated with the rest of the document.
14
+
15
+ Existing PDF redaction tools force a choice no healthcare reviewer should have to make: send the document to a cloud API and trust their privacy posture, or use a regex-only desktop tool that demonstrably misses everything contextual. This toolkit's argument is that a small, capable on-device model — Gemma 4 E2B at int4 quantisation, ~1.5 GB on disk, running on the user's own browser via WebGPU — closes the gap without ever shipping document bytes off-device.
16
+
17
+ ## What it does
18
+
19
+ `bounds-gemma` exports a small surface area centred on a single async call:
20
+
21
+ ```ts
22
+ import { startGemmaJob, getGemmaBackend } from 'bounds-gemma/pipeline/GemmaWorker'
23
+
24
+ // Probe which backend is reachable (Ollama localhost first, WebLLM fallback,
25
+ // unavailable if neither works). Cached after first probe.
26
+ const backend = await getGemmaBackend()
27
+
28
+ // Run a page's extracted text through Gemma. Returns the contextual-PHI
29
+ // detections the regex and NER layers would have missed.
30
+ const detections = await startGemmaJob({
31
+ text: pageText,
32
+ pageIndex: 0,
33
+ })
34
+ ```
35
+
36
+ Each detection is a `{ text, type, confidence, ruleId, reason }` object. Confidence has a healthcare-only floor of 0.75; below that, the detection is silently dropped. The text field is verified to be a byte-identical substring of the input page (with NFC Unicode normalisation), so model hallucinations and paraphrases never reach the consumer.
37
+
38
+ ## Architecture
39
+
40
+ ```
41
+ Input page text
42
+
43
+
44
+ ┌─────────────────────────────────────────────────────────────────┐
45
+ │ GemmaWorker (main-thread facade) │
46
+ │ ├─ probes Ollama at localhost:11434/api/tags │
47
+ │ ├─ falls back to WebLLM via @mlc-ai/web-llm in a Worker │
48
+ │ └─ chunks long pages, dispatches one model call per chunk │
49
+ └─────────────────────────────────────────────────────────────────┘
50
+
51
+
52
+ ┌─────────────────────────────────────────────────────────────────┐
53
+ │ Gemma 4 inference │
54
+ │ ├─ Ollama: model=gemma4:e2b │
55
+ │ ├─ WebLLM: model=gemma-4-E2B-it-q4f16_1-MLC │
56
+ │ ├─ system prompt: six HIPAA Safe Harbor #17 categories │
57
+ │ └─ output contract: JSON array, no prose │
58
+ └─────────────────────────────────────────────────────────────────┘
59
+
60
+
61
+ ┌─────────────────────────────────────────────────────────────────┐
62
+ │ gemmaParse (validator) │
63
+ │ ├─ strips fences and prose preamble │
64
+ │ ├─ enforces JSON schema and confidence floor (0.75) │
65
+ │ ├─ verifies every detection text is in-corpus (NFC compared) │
66
+ │ └─ rejects hallucinations silently │
67
+ └─────────────────────────────────────────────────────────────────┘
68
+
69
+
70
+ Detection[] for downstream PDF redaction
71
+ ```
72
+
73
+ Three guardrails make this safe for healthcare paraphrase tasks:
74
+
75
+ 1. **In-corpus verification.** Every Gemma-emitted span must be a byte-identical substring of the input page text after Unicode NFC normalisation. Model hallucinations and paraphrases are dropped silently before they ever reach the review surface.
76
+ 2. **Confidence floor of 0.75.** Tuned specifically for healthcare; below it, candidates are omitted. This is a single constant in `gemmaParse.ts` and easy to lower for non-clinical use cases.
77
+ 3. **Default-off in the consumer UI.** Every Gemma detection arrives with `enabled: false`. The downstream reviewer must opt in per item. Surface-level acceptance is never automatic.
78
+
79
+ ## Two execution paths
80
+
81
+ ### Ollama (preferred for production)
82
+
83
+ ```bash
84
+ ollama pull gemma4:e2b
85
+ ollama serve
86
+ ```
87
+
88
+ Then point any consumer at `http://localhost:11434/api/chat`. The toolkit probes this URL at start-up; if reachable, it routes all subsequent calls there. Sub-second latency per chunk on consumer hardware, zero model-CDN traffic, fully offline after the model pull.
89
+
90
+ ### WebLLM (no-install, in-browser)
91
+
92
+ Serve your application under cross-origin isolation:
93
+
94
+ ```
95
+ Cross-Origin-Opener-Policy: same-origin
96
+ Cross-Origin-Embedder-Policy: require-corp
97
+ ```
98
+
99
+ The toolkit dynamic-imports `@mlc-ai/web-llm` on first use and loads `gemma-4-E2B-it-q4f16_1-MLC` from the MLC CDN. Weights are cached in browser storage; subsequent sessions are fully offline. First load is slow (~1.5 GB download); subsequent loads are instant.
100
+
101
+ ## Install
102
+
103
+ ```bash
104
+ npm install bounds-gemma
105
+ # Optional, only if you want the WebLLM browser path:
106
+ npm install @mlc-ai/web-llm
107
+ ```
108
+
109
+ The package has no required runtime dependencies. `@mlc-ai/web-llm` is a peer dependency you only pull in if you use the browser fallback. Ollama is a separate install (`brew install ollama` or equivalent).
110
+
111
+ ## Run the example
112
+
113
+ ```bash
114
+ git clone https://github.com/Aqta-ai/bounds-gemma.git
115
+ cd bounds-gemma
116
+ npm install
117
+ ollama pull gemma4:e2b
118
+ ollama serve & # in another terminal
119
+ npm run example:ollama
120
+ ```
121
+
122
+ The example runs a sample clinical-note paragraph through Gemma 4 and prints the contextual-PHI detections.
123
+
124
+ ## Run the tests
125
+
126
+ ```bash
127
+ npm install
128
+ npm test
129
+ ```
130
+
131
+ 16 unit tests in `src/__tests__/gemmaParse.test.ts` cover the parser, validator, in-corpus check, NFC normalisation, fence-stripping, malformed-JSON handling, and confidence-floor enforcement. They run in <1 second with no model required.
132
+
133
+ ## What this toolkit deliberately does NOT do
134
+
135
+ - It does not handle structured PHI (phone numbers, SSNs, dates, MRNs, addresses). Those are the regex and NER layers' job; combine this toolkit with [a regex PII detector](https://github.com/microsoft/presidio) for full Safe Harbor coverage.
136
+ - It does not draw bounding boxes on PDFs. That is the consumer's job; the toolkit returns text spans and lets the consumer resolve them to PDF coordinates.
137
+ - It does not run an auditor. The cross-check pattern in the closed-source Bounds Pro pairs Gemma 4 26B with Gemma 4 31B as paraphraser plus auditor; the on-device toolkit ships only the paraphraser side and relies on verbatim-wins-ties as the safety floor.
138
+ - It does not phone home. No analytics, no telemetry, no model-CDN ping. Verify with the Network tab.
139
+
140
+ ## Source attribution
141
+
142
+ Built and maintained by Anya Chueayen ([@anyaparanya](https://github.com/anyaparanya)). Released under Apache-2.0 (see `LICENSE`). The Gemma family and the Gemma Prohibited Use Policy are governed by their own terms; using this toolkit means you accept Google's terms for Gemma 4 as well. The HIPAA Safe Harbor identifier list is in the public domain.
143
+
144
+ ## Acknowledgements
145
+
146
+ - [Google DeepMind](https://deepmind.google/) for Gemma 4 and the open weights.
147
+ - [MLC LLM](https://llm.mlc.ai/) and [WebLLM](https://github.com/mlc-ai/web-llm) for the browser runtime.
148
+ - [Ollama](https://ollama.com/) for the local-first inference daemon.
149
+ - The [Centers for Medicare and Medicaid Services](https://www.hhs.gov/hipaa/for-professionals/privacy/special-topics/de-identification/index.html) for the public-domain HIPAA Safe Harbor specification.
@@ -0,0 +1,3 @@
1
+ export { parseAndValidate, HEALTHCARE_CONFIDENCE_FLOOR, CHUNK_MAX_CHARS, type RawGemmaDetection, } from './workers/gemmaParse.js';
2
+ export { startGemmaJob, cancelGemmaJob, getGemmaBackend, subscribeGemmaBackend, subscribeGemmaModelProgress, type GemmaBackend, } from './pipeline/GemmaWorker.js';
3
+ export type { PiiType, DetectionSource, BBox, Detection, } from './types/index.js';
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ // Public API surface for the bounds-gemma npm package.
2
+ //
3
+ // Three entry points that map to three integration shapes:
4
+ //
5
+ // 1. `bounds-gemma/parser` — pure parser + validator. No model, no
6
+ // worker, no DOM. Useful for unit tests, server-side parsing of
7
+ // a model response captured elsewhere, or building your own
8
+ // pipeline on top of the validated detection schema.
9
+ //
10
+ // 2. `bounds-gemma/pipeline` — main-thread facade that probes
11
+ // Ollama and falls back to WebLLM, dispatches jobs to the
12
+ // Worker, and returns parsed Detection[]. The standard
13
+ // consumer entry point.
14
+ //
15
+ // 3. `bounds-gemma/worker` — the Web Worker implementation. Bundle
16
+ // this directly into your application's worker chain if you
17
+ // want full control over message-passing and lifecycle.
18
+ //
19
+ // The root export is the union: parser symbols + pipeline facade +
20
+ // type names. Use the sub-path imports for tighter bundles.
21
+ export { parseAndValidate, HEALTHCARE_CONFIDENCE_FLOOR, CHUNK_MAX_CHARS, } from './workers/gemmaParse.js';
22
+ export { startGemmaJob, cancelGemmaJob, getGemmaBackend, subscribeGemmaBackend, subscribeGemmaModelProgress, } from './pipeline/GemmaWorker.js';
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,EAAE;AACF,2DAA2D;AAC3D,EAAE;AACF,qEAAqE;AACrE,qEAAqE;AACrE,iEAAiE;AACjE,0DAA0D;AAC1D,EAAE;AACF,gEAAgE;AAChE,+DAA+D;AAC/D,4DAA4D;AAC5D,6BAA6B;AAC7B,EAAE;AACF,qEAAqE;AACrE,iEAAiE;AACjE,6DAA6D;AAC7D,EAAE;AACF,mEAAmE;AACnE,4DAA4D;AAE5D,OAAO,EACL,gBAAgB,EAChB,2BAA2B,EAC3B,eAAe,GAEhB,MAAM,yBAAyB,CAAA;AAEhC,OAAO,EACL,aAAa,EACb,cAAc,EACd,eAAe,EACf,qBAAqB,EACrB,2BAA2B,GAE5B,MAAM,2BAA2B,CAAA","sourcesContent":["// Public API surface for the bounds-gemma npm package.\n//\n// Three entry points that map to three integration shapes:\n//\n// 1. `bounds-gemma/parser` — pure parser + validator. No model, no\n// worker, no DOM. Useful for unit tests, server-side parsing of\n// a model response captured elsewhere, or building your own\n// pipeline on top of the validated detection schema.\n//\n// 2. `bounds-gemma/pipeline` — main-thread facade that probes\n// Ollama and falls back to WebLLM, dispatches jobs to the\n// Worker, and returns parsed Detection[]. The standard\n// consumer entry point.\n//\n// 3. `bounds-gemma/worker` — the Web Worker implementation. Bundle\n// this directly into your application's worker chain if you\n// want full control over message-passing and lifecycle.\n//\n// The root export is the union: parser symbols + pipeline facade +\n// type names. Use the sub-path imports for tighter bundles.\n\nexport {\n parseAndValidate,\n HEALTHCARE_CONFIDENCE_FLOOR,\n CHUNK_MAX_CHARS,\n type RawGemmaDetection,\n} from './workers/gemmaParse.js'\n\nexport {\n startGemmaJob,\n cancelGemmaJob,\n getGemmaBackend,\n subscribeGemmaBackend,\n subscribeGemmaModelProgress,\n type GemmaBackend,\n} from './pipeline/GemmaWorker.js'\n\nexport type {\n PiiType,\n DetectionSource,\n BBox,\n Detection,\n} from './types/index.js'\n"]}
@@ -0,0 +1,63 @@
1
+ import type { Detection, PiiType } from '../types/index.js';
2
+ export interface RawGemmaDetection {
3
+ text: string;
4
+ type: PiiType;
5
+ confidence: number;
6
+ ruleId: string;
7
+ reason: string;
8
+ }
9
+ export type GemmaBackend = 'ollama' | 'webllm' | 'unavailable';
10
+ /**
11
+ * Subscribe to model-load progress (0..1). Returns an unsubscribe function.
12
+ * Multiple concurrent runs can subscribe; legacy `setGemmaModelProgressCallback`
13
+ * is kept for backwards compat and behaves as a single-slot subscription.
14
+ */
15
+ export declare function subscribeGemmaModelProgress(cb: (pct: number) => void): () => void;
16
+ export declare function subscribeGemmaBackend(cb: (backend: GemmaBackend) => void): () => void;
17
+ /** Returns the cached backend if the worker has already probed, else null. */
18
+ export declare function getGemmaBackend(): GemmaBackend | null;
19
+ export declare function setGemmaModelProgressCallback(cb: ((pct: number) => void) | null): void;
20
+ export declare function setGemmaBackendCallback(cb: ((backend: GemmaBackend) => void) | null): void;
21
+ /**
22
+ * Run Gemma 4 health-PHI detection over a page's extracted text.
23
+ *
24
+ * Caller responsibility:
25
+ * - Pass clean per-page text (already extracted, regex-stripped of high-
26
+ * confidence matches to avoid sending duplicate work to the model).
27
+ * - Chunk pages longer than 1800 characters before calling; the worker
28
+ * re-chunks at 800-char paragraph boundaries internally but a very
29
+ * large page increases hallucination surface area.
30
+ *
31
+ * Returns RawGemmaDetection candidates with confidence already filtered
32
+ * to >= 0.75 (the healthcare floor; raise via setGemmaConfidenceFloor if
33
+ * a more conservative deployment is needed).
34
+ *
35
+ * Returns the job id alongside the promise so callers that need a timeout
36
+ * can call cancelGemmaJob(id) to drop the pending job and prevent the
37
+ * worker reply from being mis-routed to a new caller that reuses the
38
+ * same job map slot.
39
+ */
40
+ export interface GemmaJobHandle {
41
+ jobId: number;
42
+ result: Promise<RawGemmaDetection[]>;
43
+ }
44
+ export declare function detectHealthPhi(text: string, pageIndex: number): Promise<RawGemmaDetection[]>;
45
+ export declare function startGemmaJob(text: string, pageIndex: number): GemmaJobHandle;
46
+ /**
47
+ * Drop a pending job so a late worker reply is discarded silently rather
48
+ * than being routed to a stale resolver. Safe to call on a job that has
49
+ * already settled (no-op).
50
+ */
51
+ export declare function cancelGemmaJob(jobId: number): void;
52
+ /** Tear down the worker. Used by tests and on unmount. */
53
+ export declare function disposeGemmaWorker(): void;
54
+ /**
55
+ * Convert raw Gemma detections to typed Detection records ready for
56
+ * RedactionPipeline merging. The caller still needs to resolve bounding
57
+ * boxes via findSpanBBox, generate the redaction token, and de-duplicate
58
+ * against existing regex/NER detections at >= 0.90 confidence.
59
+ *
60
+ * Detections are emitted with source='GEMMA' and enabled=false so they
61
+ * appear unchecked in the review panel (the user opts in per item).
62
+ */
63
+ export declare function rawToDetection(raw: RawGemmaDetection, pageIndex: number, id: string, token: string): Detection;
@@ -0,0 +1,158 @@
1
+ let _worker = null;
2
+ let _jobCounter = 0;
3
+ const _pendingJobs = new Map();
4
+ const _modelProgressSubs = new Set();
5
+ const _backendSubs = new Set();
6
+ // Once the worker has reported a backend, hold it. The worker probes once
7
+ // per worker lifetime; a later run can synchronously call getGemmaBackend()
8
+ // to learn the cached state instead of waiting for a re-probe message.
9
+ let _resolvedBackend = null;
10
+ /**
11
+ * Subscribe to model-load progress (0..1). Returns an unsubscribe function.
12
+ * Multiple concurrent runs can subscribe; legacy `setGemmaModelProgressCallback`
13
+ * is kept for backwards compat and behaves as a single-slot subscription.
14
+ */
15
+ export function subscribeGemmaModelProgress(cb) {
16
+ _modelProgressSubs.add(cb);
17
+ return () => _modelProgressSubs.delete(cb);
18
+ }
19
+ export function subscribeGemmaBackend(cb) {
20
+ _backendSubs.add(cb);
21
+ // Replay the cached backend immediately so a late subscriber learns the
22
+ // already-resolved state without waiting for a re-probe.
23
+ if (_resolvedBackend !== null) {
24
+ queueMicrotask(() => {
25
+ if (_backendSubs.has(cb))
26
+ cb(_resolvedBackend);
27
+ });
28
+ }
29
+ return () => _backendSubs.delete(cb);
30
+ }
31
+ /** Returns the cached backend if the worker has already probed, else null. */
32
+ export function getGemmaBackend() {
33
+ return _resolvedBackend;
34
+ }
35
+ // ---------------------------------------------------------------------------
36
+ // Legacy single-slot APIs. Kept so existing callers (and tests) keep working.
37
+ // New code should prefer subscribeGemmaBackend / subscribeGemmaModelProgress.
38
+ // ---------------------------------------------------------------------------
39
+ let _modelProgressLegacy = null;
40
+ let _backendLegacy = null;
41
+ export function setGemmaModelProgressCallback(cb) {
42
+ if (_modelProgressLegacy)
43
+ _modelProgressSubs.delete(_modelProgressLegacy);
44
+ _modelProgressLegacy = cb;
45
+ if (cb)
46
+ _modelProgressSubs.add(cb);
47
+ }
48
+ export function setGemmaBackendCallback(cb) {
49
+ if (_backendLegacy)
50
+ _backendSubs.delete(_backendLegacy);
51
+ _backendLegacy = cb;
52
+ if (cb) {
53
+ _backendSubs.add(cb);
54
+ if (_resolvedBackend !== null)
55
+ queueMicrotask(() => cb(_resolvedBackend));
56
+ }
57
+ }
58
+ function getWorker() {
59
+ if (!_worker) {
60
+ _worker = new Worker(new URL('../workers/gemma.worker.ts', import.meta.url), { type: 'module' });
61
+ _worker.onmessage = (e) => {
62
+ if (e.data.type === 'progress') {
63
+ const pct = e.data.progress ?? 0;
64
+ for (const sub of _modelProgressSubs)
65
+ sub(pct);
66
+ return;
67
+ }
68
+ if (e.data.type === 'backend') {
69
+ const backend = e.data.backend ?? 'unavailable';
70
+ // Cache the first backend resolution; ignore subsequent duplicates
71
+ // so a late race message cannot overwrite the settled value.
72
+ if (_resolvedBackend === null)
73
+ _resolvedBackend = backend;
74
+ for (const sub of _backendSubs)
75
+ sub(_resolvedBackend);
76
+ return;
77
+ }
78
+ if (e.data.ready)
79
+ return;
80
+ const id = e.data.id;
81
+ if (typeof id !== 'number')
82
+ return;
83
+ const job = _pendingJobs.get(id);
84
+ if (!job)
85
+ return;
86
+ _pendingJobs.delete(id);
87
+ if (e.data.error) {
88
+ job.reject(new Error(e.data.error));
89
+ return;
90
+ }
91
+ job.resolve(e.data.detections ?? []);
92
+ };
93
+ _worker.onerror = (e) => {
94
+ // Reject all pending jobs on worker crash.
95
+ const err = new Error(`GemmaWorker crashed: ${e.message}`);
96
+ for (const job of _pendingJobs.values()) {
97
+ job.reject(err);
98
+ }
99
+ _pendingJobs.clear();
100
+ _worker = null;
101
+ };
102
+ }
103
+ return _worker;
104
+ }
105
+ export function detectHealthPhi(text, pageIndex) {
106
+ return startGemmaJob(text, pageIndex).result;
107
+ }
108
+ export function startGemmaJob(text, pageIndex) {
109
+ const id = ++_jobCounter;
110
+ const result = new Promise((resolve, reject) => {
111
+ const job = { id, text, pageIndex, resolve, reject };
112
+ _pendingJobs.set(id, job);
113
+ getWorker().postMessage({ id, text, pageIndex });
114
+ });
115
+ return { jobId: id, result };
116
+ }
117
+ /**
118
+ * Drop a pending job so a late worker reply is discarded silently rather
119
+ * than being routed to a stale resolver. Safe to call on a job that has
120
+ * already settled (no-op).
121
+ */
122
+ export function cancelGemmaJob(jobId) {
123
+ _pendingJobs.delete(jobId);
124
+ }
125
+ /** Tear down the worker. Used by tests and on unmount. */
126
+ export function disposeGemmaWorker() {
127
+ if (_worker) {
128
+ _worker.terminate();
129
+ _worker = null;
130
+ }
131
+ _pendingJobs.clear();
132
+ _resolvedBackend = null;
133
+ }
134
+ /**
135
+ * Convert raw Gemma detections to typed Detection records ready for
136
+ * RedactionPipeline merging. The caller still needs to resolve bounding
137
+ * boxes via findSpanBBox, generate the redaction token, and de-duplicate
138
+ * against existing regex/NER detections at >= 0.90 confidence.
139
+ *
140
+ * Detections are emitted with source='GEMMA' and enabled=false so they
141
+ * appear unchecked in the review panel (the user opts in per item).
142
+ */
143
+ export function rawToDetection(raw, pageIndex, id, token) {
144
+ return {
145
+ id,
146
+ type: raw.type,
147
+ text: raw.text,
148
+ token,
149
+ pageIndex,
150
+ boundingBox: { x: 0, y: 0, width: 0, height: 0 }, // resolved later
151
+ confidence: raw.confidence,
152
+ source: 'GEMMA',
153
+ enabled: false,
154
+ ruleId: raw.ruleId,
155
+ reason: raw.reason,
156
+ };
157
+ }
158
+ //# sourceMappingURL=GemmaWorker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GemmaWorker.js","sourceRoot":"","sources":["../../src/pipeline/GemmaWorker.ts"],"names":[],"mappings":"AA8CA,IAAI,OAAO,GAAkB,IAAI,CAAA;AACjC,IAAI,WAAW,GAAG,CAAC,CAAA;AACnB,MAAM,YAAY,GAAG,IAAI,GAAG,EAAoB,CAAA;AAChD,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAyB,CAAA;AAC3D,MAAM,YAAY,GAAG,IAAI,GAAG,EAAmC,CAAA;AAC/D,0EAA0E;AAC1E,4EAA4E;AAC5E,uEAAuE;AACvE,IAAI,gBAAgB,GAAwB,IAAI,CAAA;AAEhD;;;;GAIG;AACH,MAAM,UAAU,2BAA2B,CAAC,EAAyB;IACnE,kBAAkB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IAC1B,OAAO,GAAG,EAAE,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;AAC5C,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,EAAmC;IACvE,YAAY,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IACpB,wEAAwE;IACxE,yDAAyD;IACzD,IAAI,gBAAgB,KAAK,IAAI,EAAE,CAAC;QAC9B,cAAc,CAAC,GAAG,EAAE;YAClB,IAAI,YAAY,CAAC,GAAG,CAAC,EAAE,CAAC;gBAAE,EAAE,CAAC,gBAAiB,CAAC,CAAA;QACjD,CAAC,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,GAAG,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;AACtC,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAA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G,OAAO;QACL,EAAE;QACF,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,KAAK;QACL,SAAS;QACT,WAAW,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,iBAAiB;QACnE,UAAU,EAAE,GAAG,CAAC,UAAU;QAC1B,MAAM,EAAE,OAAO;QACf,OAAO,EAAE,KAAK;QACd,MAAM,EAAE,GAAG,CAAC,MAAM;QAClB,MAAM,EAAE,GAAG,CAAC,MAAM;KACnB,CAAA;AACH,CAAC","sourcesContent":["import type { Detection, PiiType } from '../types/index.js'\n\n// ---------------------------------------------------------------------------\n// GemmaWorker, main-thread facade for the gemma.worker.ts Web Worker.\n//\n// Catches context-sensitive PHI that the regex / NER / OCR layers miss:\n// inline diagnoses without a label, medication mentions in prose,\n// indirect health context (\"my insulin pump\"), genetic data references,\n// and other HIPAA Safe Harbor catch-all (item 17) candidates that have no\n// stable surface pattern.\n//\n// Two execution paths:\n//\n// 1. Ollama at localhost:11434 (preferred for the demo audience and\n// production users who install it). Faster, better quality, smaller\n// browser footprint. Probed at startup; if reachable the worker uses\n// Ollama for all subsequent calls.\n//\n// 2. WebLLM with Gemma 4 E2B Instruct (fallback when Ollama is absent).\n// Loads model weights from the MLC CDN on first use, caches them in\n// browser storage. No additional install for the user but the first\n// call is slow.\n//\n// Privacy posture: page text never leaves the browser process or\n// localhost:11434. Model weights are read-only fetches from a model CDN\n// (one-off on first WebLLM use, never accompanied by document data).\n// ---------------------------------------------------------------------------\n\ninterface GemmaJob {\n id: number\n text: string\n pageIndex: number\n resolve: (detections: RawGemmaDetection[]) => void\n reject: (err: Error) => void\n}\n\nexport interface RawGemmaDetection {\n text: string\n type: PiiType\n confidence: number\n ruleId: string\n reason: string\n}\n\nexport type GemmaBackend = 'ollama' | 'webllm' | 'unavailable'\n\nlet _worker: Worker | null = null\nlet _jobCounter = 0\nconst _pendingJobs = new Map<number, GemmaJob>()\nconst _modelProgressSubs = new Set<(pct: number) => void>()\nconst _backendSubs = new Set<(backend: GemmaBackend) => void>()\n// Once the worker has reported a backend, hold it. The worker probes once\n// per worker lifetime; a later run can synchronously call getGemmaBackend()\n// to learn the cached state instead of waiting for a re-probe message.\nlet _resolvedBackend: GemmaBackend | null = null\n\n/**\n * Subscribe to model-load progress (0..1). Returns an unsubscribe function.\n * Multiple concurrent runs can subscribe; legacy `setGemmaModelProgressCallback`\n * is kept for backwards compat and behaves as a single-slot subscription.\n */\nexport function subscribeGemmaModelProgress(cb: (pct: number) => void): () => void {\n _modelProgressSubs.add(cb)\n return () => _modelProgressSubs.delete(cb)\n}\n\nexport function subscribeGemmaBackend(cb: (backend: GemmaBackend) => void): () => void {\n _backendSubs.add(cb)\n // Replay the cached backend immediately so a late subscriber learns the\n // already-resolved state without waiting for a re-probe.\n if (_resolvedBackend !== null) {\n queueMicrotask(() => {\n if (_backendSubs.has(cb)) cb(_resolvedBackend!)\n })\n }\n return () => _backendSubs.delete(cb)\n}\n\n/** Returns the cached backend if the worker has already probed, else null. */\nexport function getGemmaBackend(): GemmaBackend | null {\n return _resolvedBackend\n}\n\n// ---------------------------------------------------------------------------\n// Legacy single-slot APIs. Kept so existing callers (and tests) keep working.\n// New code should prefer subscribeGemmaBackend / subscribeGemmaModelProgress.\n// ---------------------------------------------------------------------------\nlet _modelProgressLegacy: ((pct: number) => void) | null = null\nlet _backendLegacy: ((backend: GemmaBackend) => void) | null = null\n\nexport function setGemmaModelProgressCallback(cb: ((pct: number) => void) | null): void {\n if (_modelProgressLegacy) _modelProgressSubs.delete(_modelProgressLegacy)\n _modelProgressLegacy = cb\n if (cb) _modelProgressSubs.add(cb)\n}\n\nexport function setGemmaBackendCallback(cb: ((backend: GemmaBackend) => void) | null): void {\n if (_backendLegacy) _backendSubs.delete(_backendLegacy)\n _backendLegacy = cb\n if (cb) {\n _backendSubs.add(cb)\n if (_resolvedBackend !== null) queueMicrotask(() => cb(_resolvedBackend!))\n }\n}\n\nfunction getWorker(): Worker {\n if (!_worker) {\n _worker = new Worker(new URL('../workers/gemma.worker.ts', import.meta.url), { type: 'module' })\n _worker.onmessage = (e: MessageEvent<{\n id?: number\n detections?: RawGemmaDetection[]\n error?: string\n ready?: boolean\n type?: string\n progress?: number\n backend?: GemmaBackend\n }>) => {\n if (e.data.type === 'progress') {\n const pct = e.data.progress ?? 0\n for (const sub of _modelProgressSubs) sub(pct)\n return\n }\n if (e.data.type === 'backend') {\n const backend = e.data.backend ?? 'unavailable'\n // Cache the first backend resolution; ignore subsequent duplicates\n // so a late race message cannot overwrite the settled value.\n if (_resolvedBackend === null) _resolvedBackend = backend\n for (const sub of _backendSubs) sub(_resolvedBackend)\n return\n }\n if (e.data.ready) return\n\n const id = e.data.id\n if (typeof id !== 'number') return\n const job = _pendingJobs.get(id)\n if (!job) return\n _pendingJobs.delete(id)\n\n if (e.data.error) {\n job.reject(new Error(e.data.error))\n return\n }\n job.resolve(e.data.detections ?? [])\n }\n _worker.onerror = (e: ErrorEvent) => {\n // Reject all pending jobs on worker crash.\n const err = new Error(`GemmaWorker crashed: ${e.message}`)\n for (const job of _pendingJobs.values()) {\n job.reject(err)\n }\n _pendingJobs.clear()\n _worker = null\n }\n }\n return _worker\n}\n\n/**\n * Run Gemma 4 health-PHI detection over a page's extracted text.\n *\n * Caller responsibility:\n * - Pass clean per-page text (already extracted, regex-stripped of high-\n * confidence matches to avoid sending duplicate work to the model).\n * - Chunk pages longer than 1800 characters before calling; the worker\n * re-chunks at 800-char paragraph boundaries internally but a very\n * large page increases hallucination surface area.\n *\n * Returns RawGemmaDetection candidates with confidence already filtered\n * to >= 0.75 (the healthcare floor; raise via setGemmaConfidenceFloor if\n * a more conservative deployment is needed).\n *\n * Returns the job id alongside the promise so callers that need a timeout\n * can call cancelGemmaJob(id) to drop the pending job and prevent the\n * worker reply from being mis-routed to a new caller that reuses the\n * same job map slot.\n */\nexport interface GemmaJobHandle {\n jobId: number\n result: Promise<RawGemmaDetection[]>\n}\n\nexport function detectHealthPhi(text: string, pageIndex: number): Promise<RawGemmaDetection[]> {\n return startGemmaJob(text, pageIndex).result\n}\n\nexport function startGemmaJob(text: string, pageIndex: number): GemmaJobHandle {\n const id = ++_jobCounter\n const result = new Promise<RawGemmaDetection[]>((resolve, reject) => {\n const job: GemmaJob = { id, text, pageIndex, resolve, reject }\n _pendingJobs.set(id, job)\n getWorker().postMessage({ id, text, pageIndex })\n })\n return { jobId: id, result }\n}\n\n/**\n * Drop a pending job so a late worker reply is discarded silently rather\n * than being routed to a stale resolver. Safe to call on a job that has\n * already settled (no-op).\n */\nexport function cancelGemmaJob(jobId: number): void {\n _pendingJobs.delete(jobId)\n}\n\n/** Tear down the worker. Used by tests and on unmount. */\nexport function disposeGemmaWorker(): void {\n if (_worker) {\n _worker.terminate()\n _worker = null\n }\n _pendingJobs.clear()\n _resolvedBackend = null\n}\n\n/**\n * Convert raw Gemma detections to typed Detection records ready for\n * RedactionPipeline merging. The caller still needs to resolve bounding\n * boxes via findSpanBBox, generate the redaction token, and de-duplicate\n * against existing regex/NER detections at >= 0.90 confidence.\n *\n * Detections are emitted with source='GEMMA' and enabled=false so they\n * appear unchecked in the review panel (the user opts in per item).\n */\nexport function rawToDetection(raw: RawGemmaDetection, pageIndex: number, id: string, token: string): Detection {\n return {\n id,\n type: raw.type,\n text: raw.text,\n token,\n pageIndex,\n boundingBox: { x: 0, y: 0, width: 0, height: 0 }, // resolved later\n confidence: raw.confidence,\n source: 'GEMMA',\n enabled: false,\n ruleId: raw.ruleId,\n reason: raw.reason,\n }\n}\n"]}
@@ -0,0 +1,32 @@
1
+ export type PiiType = 'PERSON' | 'ADDRESS' | 'EMAIL' | 'PHONE' | 'IBAN' | 'SSN' | 'PASSPORT' | 'ID_NUMBER' | 'DATE_OF_BIRTH' | 'IP_ADDRESS' | 'CREDIT_CARD' | 'URL' | 'ORG' | 'MISC' | 'HEALTH_DATA' | 'CONFIDENTIAL' | 'PROPRIETARY' | 'LEGAL_CLAUSE';
2
+ export type DetectionSource = 'NER' | 'REGEX' | 'OCR' | 'MANUAL' | 'FACE' | 'GEMMA';
3
+ export interface BBox {
4
+ x: number;
5
+ y: number;
6
+ width: number;
7
+ height: number;
8
+ }
9
+ /**
10
+ * The shape consumers of this toolkit emit and aggregate. Mirrors the
11
+ * production redaction schema. Gemma-produced detections set
12
+ * `source: 'GEMMA'`, `enabled: false` (reviewer must opt in per item),
13
+ * and `ruleId` to one of the six healthcare PHI category ids the
14
+ * worker is constrained to.
15
+ */
16
+ export interface Detection {
17
+ id: string;
18
+ type: PiiType;
19
+ text: string;
20
+ /** Replacement token used during PDF redaction, e.g. "[HEALTH_DATA_001]". */
21
+ token: string;
22
+ pageIndex: number;
23
+ boundingBox: BBox;
24
+ /** 0 to 1; healthcare detections enforce a confidence floor of 0.75. */
25
+ confidence: number;
26
+ source: DetectionSource;
27
+ /** UI default: false for Gemma; reviewer opts in per item. */
28
+ enabled: boolean;
29
+ ruleId?: string;
30
+ /** One-sentence human-readable justification surfaced in the review UI. */
31
+ reason?: string;
32
+ }
@@ -0,0 +1,5 @@
1
+ // Minimal types for the Gemma 4 PHI redaction toolkit. Mirrors the
2
+ // upstream Bounds Pro production schema so that consumers can drop
3
+ // either implementation in without changing call sites.
4
+ export {};
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,mEAAmE;AACnE,wDAAwD","sourcesContent":["// Minimal types for the Gemma 4 PHI redaction toolkit. Mirrors the\n// upstream Bounds Pro production schema so that consumers can drop\n// either implementation in without changing call sites.\n\nexport type PiiType =\n | 'PERSON'\n | 'ADDRESS'\n | 'EMAIL'\n | 'PHONE'\n | 'IBAN'\n | 'SSN'\n | 'PASSPORT'\n | 'ID_NUMBER'\n | 'DATE_OF_BIRTH'\n | 'IP_ADDRESS'\n | 'CREDIT_CARD'\n | 'URL'\n | 'ORG'\n | 'MISC'\n | 'HEALTH_DATA'\n | 'CONFIDENTIAL'\n | 'PROPRIETARY'\n | 'LEGAL_CLAUSE'\n\nexport type DetectionSource =\n | 'NER'\n | 'REGEX'\n | 'OCR'\n | 'MANUAL'\n | 'FACE'\n | 'GEMMA'\n\nexport interface BBox {\n x: number\n y: number\n width: number\n height: number\n}\n\n/**\n * The shape consumers of this toolkit emit and aggregate. Mirrors the\n * production redaction schema. Gemma-produced detections set\n * `source: 'GEMMA'`, `enabled: false` (reviewer must opt in per item),\n * and `ruleId` to one of the six healthcare PHI category ids the\n * worker is constrained to.\n */\nexport interface Detection {\n id: string\n type: PiiType\n text: string\n /** Replacement token used during PDF redaction, e.g. \"[HEALTH_DATA_001]\". */\n token: string\n pageIndex: number\n boundingBox: BBox\n /** 0 to 1; healthcare detections enforce a confidence floor of 0.75. */\n confidence: number\n source: DetectionSource\n /** UI default: false for Gemma; reviewer opts in per item. */\n enabled: boolean\n ruleId?: string\n /** One-sentence human-readable justification surfaced in the review UI. */\n reason?: string\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,202 @@
1
+ // Gemma Web Worker. Runs Gemma 4 nano either via Ollama at
2
+ // localhost:11434 (preferred) or via WebLLM in-browser (fallback).
3
+ //
4
+ // Catches the six context-sensitive health-PHI categories that the
5
+ // regex / NER / OCR layers miss:
6
+ // 1. Inline diagnosis without a structured label
7
+ // ("presents with generalised anxiety disorder")
8
+ // 2. Medication mention in running prose
9
+ // ("she is on lithium and has been taking Adderall for three years")
10
+ // 3. Treatment / procedure in narrative
11
+ // ("underwent CABG last April, followed by chemo")
12
+ // 4. Indirect health context
13
+ // ("my therapist", "my insulin pump", "my dialysis centre")
14
+ // 5. Sensitive social context
15
+ // ("gay male patient", "identifies as non-binary")
16
+ // 6. Genetic data references
17
+ // ("BRCA1-positive", "family history of Huntington's")
18
+ //
19
+ // Output contract: a JSON array of {text, type, confidence, reason}
20
+ // objects, rejected if the model emits malformed JSON or candidates
21
+ // with confidence below the healthcare floor.
22
+ import { HEALTHCARE_CONFIDENCE_FLOOR, chunkText, parseAndValidate, } from './gemmaParse.js';
23
+ let _backend = 'unavailable';
24
+ let _backendDetected = false;
25
+ const SYSTEM_PROMPT = `You are a healthcare privacy auditor. The following is text extracted from a PDF page that may contain protected health information (PHI). Your job is to flag spans that contain PHI a regex or named-entity recogniser would MISS, focusing on these six categories ONLY:
26
+
27
+ 1. inline_diagnosis Inline diagnosis without a structured label (e.g. "presents with generalised anxiety disorder").
28
+ 2. medication_mention Medication name in running prose, not after a "Medications:" label (e.g. "she is on lithium").
29
+ 3. treatment_procedure Treatment, procedure, or surgery mentioned in narrative (e.g. "underwent CABG last April").
30
+ 4. indirect_health_context Indirect references that imply health condition (e.g. "my therapist", "my insulin pump").
31
+ 5. sensitive_social Sensitive social-category data (sexuality, gender identity, religion).
32
+ 6. genetic_reference Genetic test results or family history (e.g. "BRCA1-positive", "father had Huntington's").
33
+
34
+ For each span you flag, return ONE entry in a JSON array:
35
+
36
+ {
37
+ "text": "<the exact span as it appears in the input, byte-identical>",
38
+ "type": "HEALTH_DATA",
39
+ "confidence": <0.0 to 1.0>,
40
+ "ruleId": "gemma:<one of the six category ids above>",
41
+ "reason": "<one short sentence explaining why this span is PHI a reviewer should consider>"
42
+ }
43
+
44
+ Rules:
45
+ - Return ONLY a JSON array. No prose, no markdown, no preamble.
46
+ - If no PHI is present, return [].
47
+ - Confidence MUST be at least ${HEALTHCARE_CONFIDENCE_FLOOR}. Below that, omit the span.
48
+ - The text field MUST appear verbatim in the input. Do NOT paraphrase, expand, or correct.
49
+ - DO NOT flag patient names, dates, addresses, MRNs, phone numbers, emails, or other structured PHI; the regex and NER layers handle those. Your job is contextual content only.
50
+ - If you are unsure, leave the span out. False positives in healthcare are worse than false negatives at this stage.`;
51
+ async function probeOllama() {
52
+ try {
53
+ const res = await fetch('http://localhost:11434/api/tags', {
54
+ method: 'GET',
55
+ signal: AbortSignal.timeout(1500),
56
+ });
57
+ if (!res.ok)
58
+ return false;
59
+ const data = await res.json();
60
+ if (!Array.isArray(data.models))
61
+ return false;
62
+ return data.models.some((m) => m.name.startsWith('gemma4:e2b') || m.name.startsWith('gemma4'));
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ }
68
+ async function detectBackend() {
69
+ if (_backendDetected)
70
+ return _backend;
71
+ if (await probeOllama()) {
72
+ _backend = 'ollama';
73
+ }
74
+ else if (typeof self !== 'undefined' && self.crossOriginIsolated) {
75
+ // WebLLM uses WebGPU + SharedArrayBuffer + multi-threaded WASM. All
76
+ // three require the page (and therefore this worker) to be served
77
+ // under cross-origin isolation (COOP: same-origin + COEP: require-corp).
78
+ // If the deployment skipped those headers, surface that up front rather
79
+ // than attempting a load that will fail mid-stream.
80
+ _backend = 'webllm';
81
+ }
82
+ else {
83
+ _backend = 'unavailable';
84
+ }
85
+ _backendDetected = true;
86
+ postMessage({ type: 'backend', backend: _backend });
87
+ return _backend;
88
+ }
89
+ async function callOllama(chunk) {
90
+ const res = await fetch('http://localhost:11434/api/chat', {
91
+ method: 'POST',
92
+ headers: { 'Content-Type': 'application/json' },
93
+ body: JSON.stringify({
94
+ model: 'gemma4:e2b',
95
+ messages: [
96
+ { role: 'system', content: SYSTEM_PROMPT },
97
+ { role: 'user', content: chunk },
98
+ ],
99
+ stream: false,
100
+ // Gemma 4 has chain-of-thought reasoning enabled by default in
101
+ // Ollama; those thinking tokens count against num_predict and
102
+ // truncated our test output mid-JSON-entry at the old 600 cap.
103
+ // Disable thinking (think:false) AND bump num_predict to 2048 so
104
+ // the visible JSON has room to complete on a full clinical page.
105
+ think: false,
106
+ options: {
107
+ temperature: 0.1,
108
+ num_predict: 2048,
109
+ },
110
+ format: 'json',
111
+ }),
112
+ signal: AbortSignal.timeout(90_000),
113
+ });
114
+ if (!res.ok) {
115
+ throw new Error(`Ollama returned ${res.status}: ${await res.text()}`);
116
+ }
117
+ const data = (await res.json());
118
+ const raw = data.message?.content ?? data.response ?? '';
119
+ return parseAndValidate(raw, chunk);
120
+ }
121
+ // WebLLM lazy-load state. We dynamic-import the runtime on first use so the
122
+ // model weights are not pulled into the worker startup bundle, and so a
123
+ // deployment that never lands on a Gemma-required document never pays the
124
+ // download cost.
125
+ //
126
+ // Default model id resolves to Gemma 4 E2B Instruct, q4f16_1 quantisation
127
+ // (stock community release, validated 2026-04-13). Override via the build-
128
+ // time env var VITE_BOUNDS_GEMMA_MODEL_ID to swap in a custom fine-tune;
129
+ // pointing at huggingface.co/Aqta-ai/bounds-gemma-e2b-phi-ft/resolve/...
130
+ // loads our domain-tuned model in place of stock. Requires WebGPU +
131
+ // shader-f16 feature in the browser.
132
+ const WEBLLM_MODEL_ID = (typeof import.meta !== 'undefined' &&
133
+ import.meta.env?.VITE_BOUNDS_GEMMA_MODEL_ID) ||
134
+ 'gemma-4-E2B-it-q4f16_1-MLC';
135
+ let _webllmEngine = null;
136
+ let _webllmLoading = null;
137
+ async function loadWebLLM() {
138
+ if (_webllmEngine)
139
+ return _webllmEngine;
140
+ if (_webllmLoading)
141
+ return _webllmLoading;
142
+ _webllmLoading = (async () => {
143
+ // Dynamic import keeps WebLLM out of the worker startup bundle. The
144
+ // import path is the package's runtime entry; @mlc-ai/web-llm exposes
145
+ // CreateMLCEngine for a one-call "load model + return engine" flow.
146
+ const webllm = (await import('@mlc-ai/web-llm'));
147
+ const engine = await webllm.CreateMLCEngine(WEBLLM_MODEL_ID, {
148
+ initProgressCallback: (info) => {
149
+ const pct = typeof info.progress === 'number' ? info.progress : 0;
150
+ postMessage({ type: 'progress', progress: pct });
151
+ },
152
+ });
153
+ _webllmEngine = engine;
154
+ return engine;
155
+ })();
156
+ try {
157
+ return await _webllmLoading;
158
+ }
159
+ finally {
160
+ _webllmLoading = null;
161
+ }
162
+ }
163
+ async function callWebLLM(chunk) {
164
+ const engine = await loadWebLLM();
165
+ const completion = await engine.chat.completions.create({
166
+ messages: [
167
+ { role: 'system', content: SYSTEM_PROMPT },
168
+ { role: 'user', content: chunk },
169
+ ],
170
+ temperature: 0.1,
171
+ max_tokens: 600,
172
+ });
173
+ const raw = completion.choices?.[0]?.message?.content ?? '';
174
+ return parseAndValidate(raw, chunk);
175
+ }
176
+ self.onmessage = async (e) => {
177
+ const { id, text } = e.data;
178
+ try {
179
+ const backend = await detectBackend();
180
+ if (backend === 'unavailable') {
181
+ postMessage({
182
+ id,
183
+ error: 'No Gemma 4 backend available. Install Ollama with `ollama pull gemma4:e2b` and start the daemon, or serve the app under cross-origin isolation (COOP same-origin + COEP require-corp) so the in-browser WebLLM fallback can load.',
184
+ });
185
+ return;
186
+ }
187
+ const chunks = chunkText(text);
188
+ const all = [];
189
+ for (let i = 0; i < chunks.length; i++) {
190
+ postMessage({ type: 'progress', progress: i / chunks.length });
191
+ const chunk = chunks[i];
192
+ const detections = backend === 'ollama' ? await callOllama(chunk) : await callWebLLM(chunk);
193
+ all.push(...detections);
194
+ }
195
+ postMessage({ id, detections: all });
196
+ }
197
+ catch (err) {
198
+ postMessage({ id, error: err instanceof Error ? err.message : String(err) });
199
+ }
200
+ };
201
+ postMessage({ ready: true });
202
+ //# sourceMappingURL=gemma.worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gemma.worker.js","sourceRoot":"","sources":["../../src/workers/gemma.worker.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,mEAAmE;AACnE,EAAE;AACF,mEAAmE;AACnE,iCAAiC;AACjC,mDAAmD;AACnD,sDAAsD;AACtD,2CAA2C;AAC3C,0EAA0E;AAC1E,0CAA0C;AAC1C,wDAAwD;AACxD,+BAA+B;AAC/B,iEAAiE;AACjE,gCAAgC;AAChC,wDAAwD;AACxD,+BAA+B;AAC/B,4DAA4D;AAC5D,EAAE;AACF,oEAAoE;AACpE,oEAAoE;AACpE,8CAA8C;AAE9C,OAAO,EACL,2BAA2B,EAC3B,SAAS,EACT,gBAAgB,GAEjB,MAAM,i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AAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAA;YACvB,MAAM,UAAU,GAAG,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,UAAU,CAAC,KAAK,CAAC,CAAA;YAC3F,GAAG,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC,CAAA;QACzB,CAAC;QAED,WAAW,CAAC,EAAE,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,CAAC,CAAA;IACtC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,WAAW,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IAC9E,CAAC;AACH,CAAC,CAAA;AAED,WAAW,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA","sourcesContent":["// Gemma Web Worker. Runs Gemma 4 nano either via Ollama at\n// localhost:11434 (preferred) or via WebLLM in-browser (fallback).\n//\n// Catches the six context-sensitive health-PHI categories that the\n// regex / NER / OCR layers miss:\n// 1. Inline diagnosis without a structured label\n// (\"presents with generalised anxiety disorder\")\n// 2. Medication mention in running prose\n// (\"she is on lithium and has been taking Adderall for three years\")\n// 3. Treatment / procedure in narrative\n// (\"underwent CABG last April, followed by chemo\")\n// 4. Indirect health context\n// (\"my therapist\", \"my insulin pump\", \"my dialysis centre\")\n// 5. Sensitive social context\n// (\"gay male patient\", \"identifies as non-binary\")\n// 6. Genetic data references\n// (\"BRCA1-positive\", \"family history of Huntington's\")\n//\n// Output contract: a JSON array of {text, type, confidence, reason}\n// objects, rejected if the model emits malformed JSON or candidates\n// with confidence below the healthcare floor.\n\nimport {\n HEALTHCARE_CONFIDENCE_FLOOR,\n chunkText,\n parseAndValidate,\n type RawGemmaDetection,\n} from './gemmaParse.js'\n\ntype GemmaBackend = 'ollama' | 'webllm' | 'unavailable'\n\nlet _backend: GemmaBackend = 'unavailable'\nlet _backendDetected = false\n\nconst SYSTEM_PROMPT = `You are a healthcare privacy auditor. The following is text extracted from a PDF page that may contain protected health information (PHI). Your job is to flag spans that contain PHI a regex or named-entity recogniser would MISS, focusing on these six categories ONLY:\n\n 1. inline_diagnosis Inline diagnosis without a structured label (e.g. \"presents with generalised anxiety disorder\").\n 2. medication_mention Medication name in running prose, not after a \"Medications:\" label (e.g. \"she is on lithium\").\n 3. treatment_procedure Treatment, procedure, or surgery mentioned in narrative (e.g. \"underwent CABG last April\").\n 4. indirect_health_context Indirect references that imply health condition (e.g. \"my therapist\", \"my insulin pump\").\n 5. sensitive_social Sensitive social-category data (sexuality, gender identity, religion).\n 6. genetic_reference Genetic test results or family history (e.g. \"BRCA1-positive\", \"father had Huntington's\").\n\nFor each span you flag, return ONE entry in a JSON array:\n\n {\n \"text\": \"<the exact span as it appears in the input, byte-identical>\",\n \"type\": \"HEALTH_DATA\",\n \"confidence\": <0.0 to 1.0>,\n \"ruleId\": \"gemma:<one of the six category ids above>\",\n \"reason\": \"<one short sentence explaining why this span is PHI a reviewer should consider>\"\n }\n\nRules:\n- Return ONLY a JSON array. No prose, no markdown, no preamble.\n- If no PHI is present, return [].\n- Confidence MUST be at least ${HEALTHCARE_CONFIDENCE_FLOOR}. Below that, omit the span.\n- The text field MUST appear verbatim in the input. Do NOT paraphrase, expand, or correct.\n- DO NOT flag patient names, dates, addresses, MRNs, phone numbers, emails, or other structured PHI; the regex and NER layers handle those. Your job is contextual content only.\n- If you are unsure, leave the span out. False positives in healthcare are worse than false negatives at this stage.`\n\nasync function probeOllama(): Promise<boolean> {\n try {\n const res = await fetch('http://localhost:11434/api/tags', {\n method: 'GET',\n signal: AbortSignal.timeout(1500),\n })\n if (!res.ok) return false\n const data: { models?: Array<{ name: string }> } = await res.json()\n if (!Array.isArray(data.models)) return false\n return data.models.some((m) => m.name.startsWith('gemma4:e2b') || m.name.startsWith('gemma4'))\n } catch {\n return false\n }\n}\n\nasync function detectBackend(): Promise<GemmaBackend> {\n if (_backendDetected) return _backend\n if (await probeOllama()) {\n _backend = 'ollama'\n } else if (typeof self !== 'undefined' && (self as unknown as { crossOriginIsolated?: boolean }).crossOriginIsolated) {\n // WebLLM uses WebGPU + SharedArrayBuffer + multi-threaded WASM. All\n // three require the page (and therefore this worker) to be served\n // under cross-origin isolation (COOP: same-origin + COEP: require-corp).\n // If the deployment skipped those headers, surface that up front rather\n // than attempting a load that will fail mid-stream.\n _backend = 'webllm'\n } else {\n _backend = 'unavailable'\n }\n _backendDetected = true\n postMessage({ type: 'backend', backend: _backend })\n return _backend\n}\n\ninterface OllamaResponse {\n message?: { content?: string }\n response?: string\n}\n\nasync function callOllama(chunk: string): Promise<RawGemmaDetection[]> {\n const res = await fetch('http://localhost:11434/api/chat', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: 'gemma4:e2b',\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: chunk },\n ],\n stream: false,\n // Gemma 4 has chain-of-thought reasoning enabled by default in\n // Ollama; those thinking tokens count against num_predict and\n // truncated our test output mid-JSON-entry at the old 600 cap.\n // Disable thinking (think:false) AND bump num_predict to 2048 so\n // the visible JSON has room to complete on a full clinical page.\n think: false,\n options: {\n temperature: 0.1,\n num_predict: 2048,\n },\n format: 'json',\n }),\n signal: AbortSignal.timeout(90_000),\n })\n if (!res.ok) {\n throw new Error(`Ollama returned ${res.status}: ${await res.text()}`)\n }\n const data = (await res.json()) as OllamaResponse\n const raw = data.message?.content ?? data.response ?? ''\n return parseAndValidate(raw, chunk)\n}\n\n// WebLLM lazy-load state. We dynamic-import the runtime on first use so the\n// model weights are not pulled into the worker startup bundle, and so a\n// deployment that never lands on a Gemma-required document never pays the\n// download cost.\n//\n// Default model id resolves to Gemma 4 E2B Instruct, q4f16_1 quantisation\n// (stock community release, validated 2026-04-13). Override via the build-\n// time env var VITE_BOUNDS_GEMMA_MODEL_ID to swap in a custom fine-tune;\n// pointing at huggingface.co/Aqta-ai/bounds-gemma-e2b-phi-ft/resolve/...\n// loads our domain-tuned model in place of stock. Requires WebGPU +\n// shader-f16 feature in the browser.\nconst WEBLLM_MODEL_ID =\n (typeof import.meta !== 'undefined' &&\n (import.meta as { env?: Record<string, string> }).env?.VITE_BOUNDS_GEMMA_MODEL_ID) ||\n 'gemma-4-E2B-it-q4f16_1-MLC'\n\ninterface WebLLMEngine {\n chat: {\n completions: {\n create(req: {\n messages: Array<{ role: string; content: string }>\n temperature?: number\n max_tokens?: number\n }): Promise<{\n choices: Array<{ message: { content?: string | null } }>\n }>\n }\n }\n}\n\nlet _webllmEngine: WebLLMEngine | null = null\nlet _webllmLoading: Promise<WebLLMEngine> | null = null\n\nasync function loadWebLLM(): Promise<WebLLMEngine> {\n if (_webllmEngine) return _webllmEngine\n if (_webllmLoading) return _webllmLoading\n\n _webllmLoading = (async () => {\n // Dynamic import keeps WebLLM out of the worker startup bundle. The\n // import path is the package's runtime entry; @mlc-ai/web-llm exposes\n // CreateMLCEngine for a one-call \"load model + return engine\" flow.\n const webllm = (await import('@mlc-ai/web-llm')) as unknown as {\n CreateMLCEngine: (\n modelId: string,\n opts?: {\n initProgressCallback?: (info: { progress?: number; text?: string }) => void\n },\n ) => Promise<WebLLMEngine>\n }\n\n const engine = await webllm.CreateMLCEngine(WEBLLM_MODEL_ID, {\n initProgressCallback: (info) => {\n const pct = typeof info.progress === 'number' ? info.progress : 0\n postMessage({ type: 'progress', progress: pct })\n },\n })\n\n _webllmEngine = engine\n return engine\n })()\n\n try {\n return await _webllmLoading\n } finally {\n _webllmLoading = null\n }\n}\n\nasync function callWebLLM(chunk: string): Promise<RawGemmaDetection[]> {\n const engine = await loadWebLLM()\n const completion = await engine.chat.completions.create({\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: chunk },\n ],\n temperature: 0.1,\n max_tokens: 600,\n })\n const raw = completion.choices?.[0]?.message?.content ?? ''\n return parseAndValidate(raw, chunk)\n}\n\nself.onmessage = async (e: MessageEvent<{ id: number; text: string; pageIndex: number }>) => {\n const { id, text } = e.data\n try {\n const backend = await detectBackend()\n if (backend === 'unavailable') {\n postMessage({\n id,\n error: 'No Gemma 4 backend available. Install Ollama with `ollama pull gemma4:e2b` and start the daemon, or serve the app under cross-origin isolation (COOP same-origin + COEP require-corp) so the in-browser WebLLM fallback can load.',\n })\n return\n }\n\n const chunks = chunkText(text)\n const all: RawGemmaDetection[] = []\n\n for (let i = 0; i < chunks.length; i++) {\n postMessage({ type: 'progress', progress: i / chunks.length })\n const chunk = chunks[i]\n const detections = backend === 'ollama' ? await callOllama(chunk) : await callWebLLM(chunk)\n all.push(...detections)\n }\n\n postMessage({ id, detections: all })\n } catch (err) {\n postMessage({ id, error: err instanceof Error ? err.message : String(err) })\n }\n}\n\npostMessage({ ready: true })\n\nexport {} // ensure this is treated as a module\n"]}
@@ -0,0 +1,32 @@
1
+ import type { PiiType } from '../types/index.js';
2
+ export declare const HEALTHCARE_CONFIDENCE_FLOOR = 0.75;
3
+ export declare const CHUNK_MAX_CHARS = 800;
4
+ export interface RawGemmaDetection {
5
+ text: string;
6
+ type: PiiType;
7
+ confidence: number;
8
+ ruleId: string;
9
+ reason: string;
10
+ }
11
+ /**
12
+ * Validate a model response and return the surviving detections.
13
+ *
14
+ * Rejects:
15
+ * - Malformed JSON.
16
+ * - Non-array top-level values.
17
+ * - Items with confidence below HEALTHCARE_CONFIDENCE_FLOOR (0.75).
18
+ * - Items whose text is not (after NFC normalisation) a substring of
19
+ * sourceChunk. This rejects model hallucinations and paraphrases while
20
+ * tolerating the NFC vs NFD differences that arise when text crosses
21
+ * PDF font ↔ LLM ↔ JS string boundaries (e.g. "café" vs "café").
22
+ * - Items with a type other than HEALTH_DATA.
23
+ * - Items with a ruleId outside the gemma:* namespace.
24
+ * - Items missing a reason field (the review panel surfaces it).
25
+ */
26
+ export declare function parseAndValidate(raw: string, sourceChunk: string): RawGemmaDetection[];
27
+ /**
28
+ * Split text into chunks of at most CHUNK_MAX_CHARS, preferring paragraph
29
+ * boundaries, falling back to sentence boundaries for paragraphs that
30
+ * exceed the limit.
31
+ */
32
+ export declare function chunkText(text: string): string[];
@@ -0,0 +1,103 @@
1
+ // Pure helpers for the Gemma worker. Extracted into a separate module so
2
+ // they can be unit-tested without instantiating the Web Worker (which is
3
+ // not available in the Node test environment).
4
+ export const HEALTHCARE_CONFIDENCE_FLOOR = 0.75;
5
+ export const CHUNK_MAX_CHARS = 800;
6
+ /**
7
+ * Validate a model response and return the surviving detections.
8
+ *
9
+ * Rejects:
10
+ * - Malformed JSON.
11
+ * - Non-array top-level values.
12
+ * - Items with confidence below HEALTHCARE_CONFIDENCE_FLOOR (0.75).
13
+ * - Items whose text is not (after NFC normalisation) a substring of
14
+ * sourceChunk. This rejects model hallucinations and paraphrases while
15
+ * tolerating the NFC vs NFD differences that arise when text crosses
16
+ * PDF font ↔ LLM ↔ JS string boundaries (e.g. "café" vs "café").
17
+ * - Items with a type other than HEALTH_DATA.
18
+ * - Items with a ruleId outside the gemma:* namespace.
19
+ * - Items missing a reason field (the review panel surfaces it).
20
+ */
21
+ export function parseAndValidate(raw, sourceChunk) {
22
+ let parsed;
23
+ try {
24
+ const cleaned = raw.replace(/^```(?:json)?\s*/i, '').replace(/\s*```\s*$/i, '').trim();
25
+ parsed = JSON.parse(cleaned);
26
+ }
27
+ catch {
28
+ return [];
29
+ }
30
+ if (!Array.isArray(parsed))
31
+ return [];
32
+ const sourceNfc = sourceChunk.normalize('NFC');
33
+ const out = [];
34
+ for (const item of parsed) {
35
+ if (typeof item !== 'object' || item === null)
36
+ continue;
37
+ const obj = item;
38
+ const text = typeof obj.text === 'string' ? obj.text.trim() : '';
39
+ const type = obj.type === 'HEALTH_DATA' ? 'HEALTH_DATA' : null;
40
+ const confidence = typeof obj.confidence === 'number' ? obj.confidence : 0;
41
+ const ruleId = typeof obj.ruleId === 'string' ? obj.ruleId : '';
42
+ const reason = typeof obj.reason === 'string' ? obj.reason : '';
43
+ if (!text)
44
+ continue;
45
+ if (!type)
46
+ continue;
47
+ if (confidence < HEALTHCARE_CONFIDENCE_FLOOR)
48
+ continue;
49
+ if (!ruleId.startsWith('gemma:'))
50
+ continue;
51
+ if (!reason)
52
+ continue;
53
+ if (!sourceNfc.includes(text.normalize('NFC')))
54
+ continue;
55
+ out.push({ text, type: type, confidence, ruleId, reason });
56
+ }
57
+ return out;
58
+ }
59
+ /**
60
+ * Split text into chunks of at most CHUNK_MAX_CHARS, preferring paragraph
61
+ * boundaries, falling back to sentence boundaries for paragraphs that
62
+ * exceed the limit.
63
+ */
64
+ export function chunkText(text) {
65
+ if (text.length <= CHUNK_MAX_CHARS)
66
+ return [text];
67
+ const chunks = [];
68
+ const paragraphs = text.split(/\n\s*\n/);
69
+ let current = '';
70
+ for (const p of paragraphs) {
71
+ if ((current + p).length <= CHUNK_MAX_CHARS) {
72
+ current += (current ? '\n\n' : '') + p;
73
+ }
74
+ else {
75
+ if (current)
76
+ chunks.push(current);
77
+ if (p.length <= CHUNK_MAX_CHARS) {
78
+ current = p;
79
+ }
80
+ else {
81
+ const sentences = p.split(/(?<=[.!?])\s+/);
82
+ let sentChunk = '';
83
+ for (const s of sentences) {
84
+ if ((sentChunk + s).length <= CHUNK_MAX_CHARS) {
85
+ sentChunk += (sentChunk ? ' ' : '') + s;
86
+ }
87
+ else {
88
+ if (sentChunk)
89
+ chunks.push(sentChunk);
90
+ sentChunk = s;
91
+ }
92
+ }
93
+ if (sentChunk)
94
+ chunks.push(sentChunk);
95
+ current = '';
96
+ }
97
+ }
98
+ }
99
+ if (current)
100
+ chunks.push(current);
101
+ return chunks;
102
+ }
103
+ //# sourceMappingURL=gemmaParse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gemmaParse.js","sourceRoot":"","sources":["../../src/workers/gemmaParse.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,yEAAyE;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AG,CAAC,CAAA;QACxC,CAAC;aAAM,CAAC;YACN,IAAI,OAAO;gBAAE,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YACjC,IAAI,CAAC,CAAC,MAAM,IAAI,eAAe,EAAE,CAAC;gBAChC,OAAO,GAAG,CAAC,CAAA;YACb,CAAC;iBAAM,CAAC;gBACN,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC,CAAA;gBAC1C,IAAI,SAAS,GAAG,EAAE,CAAA;gBAClB,KAAK,MAAM,CAAC,IAAI,SAAS,EAAE,CAAC;oBAC1B,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,MAAM,IAAI,eAAe,EAAE,CAAC;wBAC9C,SAAS,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAA;oBACzC,CAAC;yBAAM,CAAC;wBACN,IAAI,SAAS;4BAAE,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;wBACrC,SAAS,GAAG,CAAC,CAAA;oBACf,CAAC;gBACH,CAAC;gBACD,IAAI,SAAS;oBAAE,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;gBACrC,OAAO,GAAG,EAAE,CAAA;YACd,CAAC;QACH,CAAC;IACH,CAAC;IACD,IAAI,OAAO;QAAE,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IACjC,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["// Pure helpers for the Gemma worker. Extracted into a separate module so\n// they can be unit-tested without instantiating the Web Worker (which is\n// not available in the Node test environment).\n\nimport type { PiiType } from '../types/index.js'\n\nexport const HEALTHCARE_CONFIDENCE_FLOOR = 0.75\nexport const CHUNK_MAX_CHARS = 800\n\nexport interface RawGemmaDetection {\n text: string\n type: PiiType\n confidence: number\n ruleId: string\n reason: string\n}\n\n/**\n * Validate a model response and return the surviving detections.\n *\n * Rejects:\n * - Malformed JSON.\n * - Non-array top-level values.\n * - Items with confidence below HEALTHCARE_CONFIDENCE_FLOOR (0.75).\n * - Items whose text is not (after NFC normalisation) a substring of\n * sourceChunk. This rejects model hallucinations and paraphrases while\n * tolerating the NFC vs NFD differences that arise when text crosses\n * PDF font ↔ LLM ↔ JS string boundaries (e.g. \"café\" vs \"café\").\n * - Items with a type other than HEALTH_DATA.\n * - Items with a ruleId outside the gemma:* namespace.\n * - Items missing a reason field (the review panel surfaces it).\n */\nexport function parseAndValidate(raw: string, sourceChunk: string): RawGemmaDetection[] {\n let parsed: unknown\n try {\n const cleaned = raw.replace(/^```(?:json)?\\s*/i, '').replace(/\\s*```\\s*$/i, '').trim()\n parsed = JSON.parse(cleaned)\n } catch {\n return []\n }\n if (!Array.isArray(parsed)) return []\n\n const sourceNfc = sourceChunk.normalize('NFC')\n\n const out: RawGemmaDetection[] = []\n for (const item of parsed) {\n if (typeof item !== 'object' || item === null) continue\n const obj = item as Record<string, unknown>\n const text = typeof obj.text === 'string' ? obj.text.trim() : ''\n const type = obj.type === 'HEALTH_DATA' ? 'HEALTH_DATA' : null\n const confidence = typeof obj.confidence === 'number' ? obj.confidence : 0\n const ruleId = typeof obj.ruleId === 'string' ? obj.ruleId : ''\n const reason = typeof obj.reason === 'string' ? obj.reason : ''\n\n if (!text) continue\n if (!type) continue\n if (confidence < HEALTHCARE_CONFIDENCE_FLOOR) continue\n if (!ruleId.startsWith('gemma:')) continue\n if (!reason) continue\n if (!sourceNfc.includes(text.normalize('NFC'))) continue\n\n out.push({ text, type: type as PiiType, confidence, ruleId, reason })\n }\n return out\n}\n\n/**\n * Split text into chunks of at most CHUNK_MAX_CHARS, preferring paragraph\n * boundaries, falling back to sentence boundaries for paragraphs that\n * exceed the limit.\n */\nexport function chunkText(text: string): string[] {\n if (text.length <= CHUNK_MAX_CHARS) return [text]\n const chunks: string[] = []\n const paragraphs = text.split(/\\n\\s*\\n/)\n let current = ''\n for (const p of paragraphs) {\n if ((current + p).length <= CHUNK_MAX_CHARS) {\n current += (current ? '\\n\\n' : '') + p\n } else {\n if (current) chunks.push(current)\n if (p.length <= CHUNK_MAX_CHARS) {\n current = p\n } else {\n const sentences = p.split(/(?<=[.!?])\\s+/)\n let sentChunk = ''\n for (const s of sentences) {\n if ((sentChunk + s).length <= CHUNK_MAX_CHARS) {\n sentChunk += (sentChunk ? ' ' : '') + s\n } else {\n if (sentChunk) chunks.push(sentChunk)\n sentChunk = s\n }\n }\n if (sentChunk) chunks.push(sentChunk)\n current = ''\n }\n }\n }\n if (current) chunks.push(current)\n return chunks\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,92 @@
1
+ {
2
+ "name": "bounds-gemma",
3
+ "version": "0.1.0",
4
+ "description": "On-device Gemma 4 contextual PHI redaction toolkit for HIPAA Safe Harbor de-identification. Runs in a browser via WebLLM or locally via Ollama, never on a server.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "private": false,
8
+ "author": "Anya Chueayen <hello@aqta.ai>",
9
+ "homepage": "https://github.com/Aqta-ai/bounds-gemma#readme",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/Aqta-ai/bounds-gemma.git"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/Aqta-ai/bounds-gemma/issues"
16
+ },
17
+ "keywords": [
18
+ "gemma",
19
+ "gemma-4",
20
+ "phi",
21
+ "pii",
22
+ "hipaa",
23
+ "redaction",
24
+ "privacy",
25
+ "on-device",
26
+ "webllm",
27
+ "ollama",
28
+ "healthcare",
29
+ "ai",
30
+ "llm"
31
+ ],
32
+ "main": "./dist/index.js",
33
+ "types": "./dist/index.d.ts",
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/index.d.ts",
37
+ "import": "./dist/index.js"
38
+ },
39
+ "./parser": {
40
+ "types": "./dist/workers/gemmaParse.d.ts",
41
+ "import": "./dist/workers/gemmaParse.js"
42
+ },
43
+ "./worker": {
44
+ "types": "./dist/workers/gemma.worker.d.ts",
45
+ "import": "./dist/workers/gemma.worker.js"
46
+ },
47
+ "./pipeline": {
48
+ "types": "./dist/pipeline/GemmaWorker.d.ts",
49
+ "import": "./dist/pipeline/GemmaWorker.js"
50
+ },
51
+ "./types": {
52
+ "types": "./dist/types/index.d.ts",
53
+ "import": "./dist/types/index.js"
54
+ }
55
+ },
56
+ "files": [
57
+ "dist",
58
+ "LICENSE",
59
+ "NOTICE",
60
+ "README.md"
61
+ ],
62
+ "scripts": {
63
+ "build": "tsc --project tsconfig.build.json",
64
+ "prepublishOnly": "npm run build && npm test",
65
+ "test": "vitest run",
66
+ "test:watch": "vitest",
67
+ "typecheck": "tsc --noEmit",
68
+ "example:ollama": "tsx examples/runOllama.ts",
69
+ "example:webllm": "echo 'Open examples/webllm.html in a browser (Chrome + WebGPU + cross-origin-isolated headers)'"
70
+ },
71
+ "devDependencies": {
72
+ "@mlc-ai/web-llm": "^0.2.83",
73
+ "@types/node": "^20.12.7",
74
+ "tsx": "^4.7.0",
75
+ "typescript": "^5.4.5",
76
+ "vitest": "^1.6.0"
77
+ },
78
+ "peerDependencies": {
79
+ "@mlc-ai/web-llm": "^0.2.79"
80
+ },
81
+ "peerDependenciesMeta": {
82
+ "@mlc-ai/web-llm": {
83
+ "optional": true
84
+ }
85
+ },
86
+ "engines": {
87
+ "node": ">=20"
88
+ },
89
+ "publishConfig": {
90
+ "access": "public"
91
+ }
92
+ }