localscrub 0.1.0__tar.gz

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.
Files changed (67) hide show
  1. localscrub-0.1.0/.github/workflows/ci.yml +18 -0
  2. localscrub-0.1.0/.gitignore +26 -0
  3. localscrub-0.1.0/LICENSE +202 -0
  4. localscrub-0.1.0/PKG-INFO +103 -0
  5. localscrub-0.1.0/README.md +79 -0
  6. localscrub-0.1.0/ROADMAP.md +83 -0
  7. localscrub-0.1.0/docs/benchmark.md +106 -0
  8. localscrub-0.1.0/docs/decisions/0001-stage1-engine.md +51 -0
  9. localscrub-0.1.0/docs/decisions/0002-stage2-llm-interface.md +59 -0
  10. localscrub-0.1.0/docs/finetune.md +60 -0
  11. localscrub-0.1.0/docs/notes/dbmi-access-request.md +68 -0
  12. localscrub-0.1.0/docs/notes/m2-testing-notes.md +355 -0
  13. localscrub-0.1.0/docs/quickstart.md +90 -0
  14. localscrub-0.1.0/docs/results.md +140 -0
  15. localscrub-0.1.0/docs/threat-model.md +123 -0
  16. localscrub-0.1.0/pyproject.toml +74 -0
  17. localscrub-0.1.0/scripts/bench_presidio.py +118 -0
  18. localscrub-0.1.0/scripts/eval_lora.py +143 -0
  19. localscrub-0.1.0/scripts/finetune_lora.py +87 -0
  20. localscrub-0.1.0/src/localscrub/__init__.py +40 -0
  21. localscrub-0.1.0/src/localscrub/analyzer.py +175 -0
  22. localscrub-0.1.0/src/localscrub/cli.py +395 -0
  23. localscrub-0.1.0/src/localscrub/config.py +36 -0
  24. localscrub-0.1.0/src/localscrub/corpus/__init__.py +37 -0
  25. localscrub-0.1.0/src/localscrub/corpus/diversify.py +143 -0
  26. localscrub-0.1.0/src/localscrub/corpus/generator.py +212 -0
  27. localscrub-0.1.0/src/localscrub/corpus/mtsamples.py +146 -0
  28. localscrub-0.1.0/src/localscrub/corpus/sft.py +48 -0
  29. localscrub-0.1.0/src/localscrub/corpus/templates.py +197 -0
  30. localscrub-0.1.0/src/localscrub/corpus/values.py +151 -0
  31. localscrub-0.1.0/src/localscrub/entities.py +98 -0
  32. localscrub-0.1.0/src/localscrub/evaluation.py +267 -0
  33. localscrub-0.1.0/src/localscrub/llm.py +80 -0
  34. localscrub-0.1.0/src/localscrub/py.typed +0 -0
  35. localscrub-0.1.0/src/localscrub/recognizers/__init__.py +50 -0
  36. localscrub-0.1.0/src/localscrub/recognizers/base.py +106 -0
  37. localscrub-0.1.0/src/localscrub/recognizers/contact.py +56 -0
  38. localscrub-0.1.0/src/localscrub/recognizers/dates.py +105 -0
  39. localscrub-0.1.0/src/localscrub/recognizers/financial.py +78 -0
  40. localscrub-0.1.0/src/localscrub/recognizers/government.py +42 -0
  41. localscrub-0.1.0/src/localscrub/recognizers/medical.py +47 -0
  42. localscrub-0.1.0/src/localscrub/recognizers/ner.py +160 -0
  43. localscrub-0.1.0/src/localscrub/recognizers/network.py +57 -0
  44. localscrub-0.1.0/src/localscrub/redact.py +40 -0
  45. localscrub-0.1.0/src/localscrub/report.py +96 -0
  46. localscrub-0.1.0/src/localscrub/stage2.py +200 -0
  47. localscrub-0.1.0/tests/conftest.py +17 -0
  48. localscrub-0.1.0/tests/test_analyzer.py +125 -0
  49. localscrub-0.1.0/tests/test_cli.py +143 -0
  50. localscrub-0.1.0/tests/test_corpus.py +127 -0
  51. localscrub-0.1.0/tests/test_corpus_diversify.py +88 -0
  52. localscrub-0.1.0/tests/test_corpus_mtsamples.py +110 -0
  53. localscrub-0.1.0/tests/test_corpus_sft.py +35 -0
  54. localscrub-0.1.0/tests/test_entities.py +57 -0
  55. localscrub-0.1.0/tests/test_evaluation.py +115 -0
  56. localscrub-0.1.0/tests/test_recognizer_base.py +73 -0
  57. localscrub-0.1.0/tests/test_recognizers_contact.py +63 -0
  58. localscrub-0.1.0/tests/test_recognizers_dates.py +60 -0
  59. localscrub-0.1.0/tests/test_recognizers_financial.py +54 -0
  60. localscrub-0.1.0/tests/test_recognizers_government.py +44 -0
  61. localscrub-0.1.0/tests/test_recognizers_medical.py +42 -0
  62. localscrub-0.1.0/tests/test_recognizers_ner.py +118 -0
  63. localscrub-0.1.0/tests/test_recognizers_network.py +45 -0
  64. localscrub-0.1.0/tests/test_redact.py +78 -0
  65. localscrub-0.1.0/tests/test_report.py +45 -0
  66. localscrub-0.1.0/tests/test_stage2.py +173 -0
  67. localscrub-0.1.0/uv.lock +2626 -0
@@ -0,0 +1,18 @@
1
+ name: ci
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: astral-sh/setup-uv@v5
14
+ with:
15
+ python-version: "3.12"
16
+ - run: uv sync
17
+ - run: uv run ruff check .
18
+ - run: uv run pytest -q
@@ -0,0 +1,26 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ .venv/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+
11
+ # Models & data — never commit weights or corpora
12
+ models/
13
+ data/corpora/
14
+ # MTSamples is public but downloaded, not redistributed
15
+ data/mtsamples/
16
+ *.gguf
17
+ *.safetensors
18
+
19
+ # i2b2/n2c2 licensed data must NEVER enter the repo
20
+ data/i2b2/
21
+ data/n2c2/
22
+
23
+ # Local
24
+ .env
25
+ .idea/
26
+ .vscode/
@@ -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.
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: localscrub
3
+ Version: 0.1.0
4
+ Summary: Local-first PHI/PII de-identification: rule/NER cascade + local LLM. Your data never leaves your machine.
5
+ Project-URL: Repository, https://github.com/valbarov/localscrub
6
+ Project-URL: Documentation, https://github.com/valbarov/localscrub/blob/main/docs/quickstart.md
7
+ Project-URL: Changelog, https://github.com/valbarov/localscrub/blob/main/ROADMAP.md
8
+ Author-email: Vadim Albarov <albarov.vadim@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: de-identification,deidentification,hipaa,local-llm,phi,pii,privacy,redaction
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Healthcare Industry
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Security
17
+ Classifier: Topic :: Text Processing :: Filters
18
+ Requires-Python: >=3.12
19
+ Requires-Dist: typer>=0.12
20
+ Provides-Extra: ner
21
+ Requires-Dist: torch>=2.13.0; extra == 'ner'
22
+ Requires-Dist: transformers>=4.40; extra == 'ner'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # localscrub
26
+
27
+ Local-first PHI/PII de-identification for clinical and free-form text.
28
+
29
+ Your data never leaves your machine: a fast rule/NER pass catches the obvious
30
+ identifiers, and a **local LLM** handles the context-dependent remainder — no
31
+ cloud APIs, no data crossing your trust boundary.
32
+
33
+ > **Status:** v0.1 — usable, honest about its limits, pre-1.0 API.
34
+ > New here? Start with the **[quickstart](docs/quickstart.md)**. Roadmap: [ROADMAP.md](ROADMAP.md).
35
+
36
+ ## Why
37
+
38
+ Existing options force a bad trade:
39
+
40
+ - **Cloud de-id APIs** — accurate, but you send the sensitive data out to get it scrubbed.
41
+ - **Local rule/NER tools** — private, but miss context-dependent PHI in free text
42
+ ("the patient's sister works at the bakery on Elm Street").
43
+
44
+ localscrub runs a two-stage cascade entirely on your hardware: cheap detection for
45
+ the 90%+, a small fine-tuned local model for the ambiguous rest.
46
+
47
+ ## Usage
48
+
49
+ ```bash
50
+ localscrub scrub notes.txt # print redacted text
51
+ localscrub scrub notes.txt --json # print the JSON entity report
52
+ localscrub scrub notes.txt -o clean.txt --report report.json
53
+ localscrub scrub --report-only < notes.txt # detect without rewriting
54
+ localscrub scrub notes.txt --fail-on-detect # CI gate: exit 3 if anything found
55
+ localscrub scrub notes.txt --llm # + stage 2: local LLM via Ollama
56
+ localscrub scrub notes.txt --ner # + pretrained clinical NER (CPU)
57
+
58
+ localscrub synth -n 500 --seed 42 -o data/corpora/dev.jsonl # synthetic eval corpus
59
+ localscrub synth -n 500 --seed 42 --diversify -o dev.jsonl # + local-LLM paraphrase (Ollama)
60
+ localscrub mtsamples --fetch -n 100 --seed 42 -o mts.jsonl # injection benchmark: real prose
61
+ localscrub eval data/corpora/dev.jsonl # per-entity precision/recall
62
+ ```
63
+
64
+ Current accuracy numbers (including what stage 1 honestly cannot catch yet)
65
+ live in [docs/results.md](docs/results.md). On our benchmark of authentic
66
+ medical-transcription prose, localscrub with the `[ner]` extra fully redacts
67
+ **99.9%** of planted identifiers on CPU, vs. **75%** for Presidio, the
68
+ standard rules-only baseline — measured by the same harness, reproducible
69
+ locally: [docs/benchmark.md](docs/benchmark.md).
70
+
71
+ Deploying on real clinical text? Read the trust-boundary and residual-risk
72
+ discussion first: [docs/threat-model.md](docs/threat-model.md).
73
+
74
+ Or from Python:
75
+
76
+ ```python
77
+ from localscrub import scrub
78
+
79
+ result = scrub("Reach the patient at test@example.com.")
80
+ result.redacted # 'Reach the patient at [EMAIL_1].'
81
+ result.entities # (Entity(type=EMAIL, start=21, end=37, confidence=0.95, ...),)
82
+ result.escalations # spans stage 1 couldn't settle — stage 2's work queue
83
+ ```
84
+
85
+ Stage 1 (rules) currently detects: emails, phone/fax numbers, SSNs, credit
86
+ cards (Luhn-validated), IP addresses, URLs, dates and ages over 89, and
87
+ labeled MRN / health-plan / account identifiers. Uncertain or ambiguous spans
88
+ are redacted fail-closed *and* flagged for stage-2 adjudication. The `[ner]`
89
+ extra (`pip install 'localscrub[ner]'`, then `--ner`) adds a pretrained
90
+ clinical NER model for person/place names on CPU. Stage 2 (`--llm`, or
91
+ `scrub(text, stage2=LlmExtractor())`) runs a local Ollama model for
92
+ narrative identifiers and escalation adjudication; see
93
+ [ADR 0002](docs/decisions/0002-stage2-llm-interface.md) for its contract.
94
+
95
+ ## Entity coverage
96
+
97
+ All 18 HIPAA Safe Harbor identifier categories (45 CFR 164.514(b)(2)), plus
98
+ generic PII that matters in practice: credit cards, passports, national IDs,
99
+ and leaked credentials/secrets. See `src/localscrub/entities.py`.
100
+
101
+ ## License
102
+
103
+ Apache-2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,79 @@
1
+ # localscrub
2
+
3
+ Local-first PHI/PII de-identification for clinical and free-form text.
4
+
5
+ Your data never leaves your machine: a fast rule/NER pass catches the obvious
6
+ identifiers, and a **local LLM** handles the context-dependent remainder — no
7
+ cloud APIs, no data crossing your trust boundary.
8
+
9
+ > **Status:** v0.1 — usable, honest about its limits, pre-1.0 API.
10
+ > New here? Start with the **[quickstart](docs/quickstart.md)**. Roadmap: [ROADMAP.md](ROADMAP.md).
11
+
12
+ ## Why
13
+
14
+ Existing options force a bad trade:
15
+
16
+ - **Cloud de-id APIs** — accurate, but you send the sensitive data out to get it scrubbed.
17
+ - **Local rule/NER tools** — private, but miss context-dependent PHI in free text
18
+ ("the patient's sister works at the bakery on Elm Street").
19
+
20
+ localscrub runs a two-stage cascade entirely on your hardware: cheap detection for
21
+ the 90%+, a small fine-tuned local model for the ambiguous rest.
22
+
23
+ ## Usage
24
+
25
+ ```bash
26
+ localscrub scrub notes.txt # print redacted text
27
+ localscrub scrub notes.txt --json # print the JSON entity report
28
+ localscrub scrub notes.txt -o clean.txt --report report.json
29
+ localscrub scrub --report-only < notes.txt # detect without rewriting
30
+ localscrub scrub notes.txt --fail-on-detect # CI gate: exit 3 if anything found
31
+ localscrub scrub notes.txt --llm # + stage 2: local LLM via Ollama
32
+ localscrub scrub notes.txt --ner # + pretrained clinical NER (CPU)
33
+
34
+ localscrub synth -n 500 --seed 42 -o data/corpora/dev.jsonl # synthetic eval corpus
35
+ localscrub synth -n 500 --seed 42 --diversify -o dev.jsonl # + local-LLM paraphrase (Ollama)
36
+ localscrub mtsamples --fetch -n 100 --seed 42 -o mts.jsonl # injection benchmark: real prose
37
+ localscrub eval data/corpora/dev.jsonl # per-entity precision/recall
38
+ ```
39
+
40
+ Current accuracy numbers (including what stage 1 honestly cannot catch yet)
41
+ live in [docs/results.md](docs/results.md). On our benchmark of authentic
42
+ medical-transcription prose, localscrub with the `[ner]` extra fully redacts
43
+ **99.9%** of planted identifiers on CPU, vs. **75%** for Presidio, the
44
+ standard rules-only baseline — measured by the same harness, reproducible
45
+ locally: [docs/benchmark.md](docs/benchmark.md).
46
+
47
+ Deploying on real clinical text? Read the trust-boundary and residual-risk
48
+ discussion first: [docs/threat-model.md](docs/threat-model.md).
49
+
50
+ Or from Python:
51
+
52
+ ```python
53
+ from localscrub import scrub
54
+
55
+ result = scrub("Reach the patient at test@example.com.")
56
+ result.redacted # 'Reach the patient at [EMAIL_1].'
57
+ result.entities # (Entity(type=EMAIL, start=21, end=37, confidence=0.95, ...),)
58
+ result.escalations # spans stage 1 couldn't settle — stage 2's work queue
59
+ ```
60
+
61
+ Stage 1 (rules) currently detects: emails, phone/fax numbers, SSNs, credit
62
+ cards (Luhn-validated), IP addresses, URLs, dates and ages over 89, and
63
+ labeled MRN / health-plan / account identifiers. Uncertain or ambiguous spans
64
+ are redacted fail-closed *and* flagged for stage-2 adjudication. The `[ner]`
65
+ extra (`pip install 'localscrub[ner]'`, then `--ner`) adds a pretrained
66
+ clinical NER model for person/place names on CPU. Stage 2 (`--llm`, or
67
+ `scrub(text, stage2=LlmExtractor())`) runs a local Ollama model for
68
+ narrative identifiers and escalation adjudication; see
69
+ [ADR 0002](docs/decisions/0002-stage2-llm-interface.md) for its contract.
70
+
71
+ ## Entity coverage
72
+
73
+ All 18 HIPAA Safe Harbor identifier categories (45 CFR 164.514(b)(2)), plus
74
+ generic PII that matters in practice: credit cards, passports, national IDs,
75
+ and leaked credentials/secrets. See `src/localscrub/entities.py`.
76
+
77
+ ## License
78
+
79
+ Apache-2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,83 @@
1
+ # Roadmap
2
+
3
+ ## Architecture — the cascade
4
+
5
+ ```
6
+ text ──> Stage 1: fast & wide (CPU, ~µs/doc)
7
+ regex + dictionaries + small NER
8
+ → catches obvious 90–95%; flags ambiguous spans/docs
9
+ ──> Stage 2: narrow & smart (GPU, only ~10–20% of volume)
10
+ local LLM (fine-tuned small open-weights model)
11
+ → context-dependent PHI, unusual formats, clinical narrative
12
+ ──> Output: redacted text + entity report (type, span, confidence, stage)
13
+ + audit log (what was redacted and why)
14
+ ```
15
+
16
+ Model backend is pluggable:
17
+
18
+ - `ollama` — default: runs entirely on your machine
19
+ - `vllm` — production throughput (continuous batching, quantized weights)
20
+ - `bedrock` — optional adapter for AWS-native teams (explicitly **not** local;
21
+ see the trust-boundary notes, to be documented)
22
+
23
+ ## Non-goals (v1)
24
+
25
+ - No claim of HIPAA Safe Harbor certification — localscrub reduces the problem to
26
+ review-and-attest; residual-risk sign-off stays human.
27
+ - No cloud-hosted SaaS offering.
28
+ - No images/audio/DICOM — text only.
29
+ - English-only.
30
+ - No training or evaluation on real PHI, ever.
31
+
32
+ ## Milestones
33
+
34
+ ### M0 — skeleton ✅
35
+ - [x] Package layout, `pyproject.toml`, CI (ruff + pytest), Apache-2.0 license
36
+ - [x] Entity taxonomy: the 18 HIPAA Safe Harbor categories + generic PII set
37
+
38
+ ### M1 — stage 1: rules & NER ✅
39
+ - [x] Stage-1 engine decision → in-house recognizers, no Presidio dependency
40
+ ([ADR 0001](docs/decisions/0001-stage1-engine.md))
41
+ - [x] Regex + dictionary recognizers for structured identifiers
42
+ (SSN, MRN, phone/fax, email, dates/ages, URL, IP, credit card, accounts)
43
+ - [x] Ambiguity scoring: confidence bands + overlap adjudication; uncertain spans
44
+ are redacted fail-closed and escalated to stage 2
45
+ - [x] CLI: `localscrub scrub file.txt` → redacted text + JSON entity report
46
+ (+ `--report-only`, `--fail-on-detect`, JSONL audit log)
47
+ - [x] Optional `[ner]` extra: pretrained clinical NER recognizer for NAME/GEO
48
+ (`obi/deid_roberta_i2b2`, CPU; landed with M2 — chosen over plain spaCy because
49
+ it is trained on the i2b2 de-id task itself)
50
+
51
+ ### M2 — stage 2: local LLM + evaluation ✅ (i2b2 item pending upstream availability)
52
+ - [x] Synthetic corpus generator (fake clinical notes with planted entities, scored ground
53
+ truth): `localscrub synth` emits JSONL with exact gold spans; optional `--diversify`
54
+ paraphrases prose with a local Ollama model, fail-closed on span damage
55
+ - [x] MTSamples-injection benchmark: synthetic PHI planted at known positions in public
56
+ medical-transcription samples → authentic prose, perfect ground truth, fully
57
+ reproducible (`localscrub mtsamples --fetch`; CSV pinned by SHA-256, never
58
+ redistributed; recall is exact, precision a lower bound — see docs/results.md)
59
+ - [ ] i2b2/n2c2 2014 de-identification corpus for literature-comparable numbers
60
+ (currently unavailable upstream; evaluation-only when obtainable, never redistributed)
61
+ - [x] Ollama backend: verbatim-snippet extraction + escalation adjudication, additive
62
+ fail-closed merge ([ADR 0002](docs/decisions/0002-stage2-llm-interface.md));
63
+ `localscrub scrub --llm`, `localscrub eval --llm`
64
+ - [x] Eval harness: per-entity precision/recall on every change (regression floors in
65
+ `tests/test_evaluation.py`); results table in [docs/results.md](docs/results.md)
66
+ - [x] LoRA fine-tune recipe on synthetic data, with before/after numbers
67
+ ([docs/finetune.md](docs/finetune.md)): base 1.7B unparseable on 35/35 notes →
68
+ tuned 0/80, MTSamples redaction recall 0.61 → 0.92
69
+
70
+ ### M3 — v0.1
71
+ - [x] Quickstart docs ([docs/quickstart.md](docs/quickstart.md)), honest accuracy
72
+ table ([docs/results.md](docs/results.md)), threat-model / trust-boundary
73
+ doc ([docs/threat-model.md](docs/threat-model.md))
74
+ - [ ] PyPI release
75
+ - [ ] Published benchmark: localscrub vs. rules-only vs. cloud APIs
76
+ (accuracy, latency, cost, and where your data goes) — Presidio baseline
77
+ done ([docs/benchmark.md](docs/benchmark.md), `scripts/bench_presidio.py`,
78
+ `bench` dependency group); pending: full-cascade rerun + LLM legs at full
79
+ size (**needs the local GPU**), cloud API legs (needs provider accounts)
80
+
81
+ ### Later
82
+ - [ ] vLLM throughput mode, stream-processing consumer (log pipelines)
83
+ - [ ] Additional fine-tuning recipes and faster processing paths
@@ -0,0 +1,106 @@
1
+ # Benchmark: localscrub vs. rules-only vs. cloud
2
+
3
+ The comparison this project exists to win — and to report honestly where it
4
+ doesn't. Everything here runs on one machine, on public or synthetic data,
5
+ and is exactly reproducible.
6
+
7
+ ## Systems compared
8
+
9
+ | system | what it is | where your data goes |
10
+ |---|---|---|
11
+ | **Presidio** (`presidio-analyzer` 2.2.364, default recognizers, spaCy `en_core_web_lg`, score ≥ 0.35) | the standard open-source rules-only baseline (ADR 0001: a benchmark baseline, never a runtime dependency) | stays local |
12
+ | **localscrub stage 1** | in-house regex/dictionary/checksum recognizers, pure Python | stays local |
13
+ | **localscrub stage 1 + NER** | + `obi/deid_roberta_i2b2`, a 125M-param token classifier (`[ner]` extra), CPU | stays local |
14
+ | **localscrub cascade (+ LLM)** | + stage-2 local LLM (Ollama, qwen3:14b) for narrative PHI and escalation adjudication | stays local (your GPU) |
15
+ | **cloud de-id APIs** | commercial PHI-detection endpoints | **leaves your machine** — the text to be scrubbed is sent to the provider |
16
+
17
+ All systems are scored by the same harness (`localscrub.evaluation.score`):
18
+ identical one-to-one span matching, identical redaction-recall definition.
19
+ **Redaction recall** — the fraction of gold spans whose every character is
20
+ removed from the output — is the headline safety number; a partial detection
21
+ that leaves half an address in the text does not count.
22
+
23
+ ## Reproduce
24
+
25
+ ```bash
26
+ localscrub synth -n 500 --seed 42 -o data/corpora/eval.jsonl
27
+ localscrub mtsamples --fetch -n 100 --seed 42 -o data/corpora/mtsamples-100.jsonl
28
+
29
+ localscrub eval data/corpora/eval.jsonl # stage 1
30
+ localscrub eval data/corpora/eval.jsonl --ner # + NER extra
31
+ localscrub eval data/corpora/eval.jsonl --ner --llm # full cascade (GPU)
32
+
33
+ uv run --group bench python scripts/bench_presidio.py data/corpora/eval.jsonl
34
+ uv run --group bench python scripts/bench_presidio.py data/corpora/mtsamples-100.jsonl
35
+ ```
36
+
37
+ Presidio type mapping, and what its typed metrics can and cannot be blamed
38
+ for, is documented at the top of `scripts/bench_presidio.py` (short version:
39
+ unmapped Presidio types still get redaction credit — scoring generosity
40
+ always leans toward the baseline, never toward us).
41
+
42
+ ## Template corpus (500 synthetic notes, seed 42)
43
+
44
+ | system | relaxed F1 | strict F1 | redaction recall | latency/note |
45
+ |---|---|---|---|---|
46
+ | Presidio (rules-only) | 0.73 | 0.59 | 0.78 | 14 ms (CPU) |
47
+ | localscrub stage 1 | 0.79 | 0.74 | 0.66 | µs (CPU) |
48
+ | localscrub stage 1 + NER | **0.97** | **0.85** | **0.94** | 184 ms (CPU) |
49
+ | localscrub cascade (+ LLM) | *pending 500-note rerun (GPU)* | | | |
50
+
51
+ ## MTSamples injection benchmark (authentic prose, 100 notes, seed 42)
52
+
53
+ Precision is a lower bound on this benchmark for every system (the public
54
+ transcripts contain their own name- and date-like strings not in the injected
55
+ gold) — see [results.md](results.md).
56
+
57
+ | system | relaxed R | relaxed P† | redaction recall | latency/note |
58
+ |---|---|---|---|---|
59
+ | Presidio (rules-only) | 0.80 | 0.49 | 0.75 | 46 ms (CPU) |
60
+ | localscrub stage 1 | 0.62 | 0.94 | 0.62 | µs (CPU) |
61
+ | localscrub stage 1 + NER | **1.00** | 0.81 | **0.999** | 652 ms (CPU) |
62
+ | localscrub stage 1 + LLM* | **1.00** | 0.89 | 0.976 | 6.0 s (GPU) |
63
+ | localscrub cascade (NER + LLM)* | **1.00** | 0.80 | **1.000** | 6.8 s (GPU) |
64
+
65
+ † lower bound. \* LLM rows measured on a 30-note subset (210 gold spans);
66
+ to be rerun at 100 notes alongside the 500-note cascade rerun.
67
+
68
+ ## Reading it
69
+
70
+ - **Presidio beats bare stage 1 on redaction recall** (0.78 vs 0.66; 0.75 vs
71
+ 0.62). No surprise: spaCy gives it person/place names, which stage 1
72
+ intentionally defers to the `[ner]` extra and stage 2 (ADR 0001). Rules-only
73
+ localscrub is not the recommended configuration; it exists to be fast,
74
+ calibrated, and honest about what it cannot see.
75
+ - **With the NER extra, localscrub wins decisively on both corpora**
76
+ (0.94 vs 0.78 and 0.999 vs 0.75 redaction recall) — and the gap is
77
+ concentrated exactly where a leak hurts:
78
+ - **Clinical identifiers**: Presidio has no MRN or health-plan recognizer —
79
+ it fully redacts 6% of MRNs and 15% of plan IDs on the template corpus
80
+ (2% and 14% on MTSamples), and only by accident (its UK_NHS and date
81
+ patterns happening to overlap). localscrub holds these at 1.00 in every
82
+ configuration.
83
+ - **Addresses**: Presidio never fully covered a single gold address on
84
+ either corpus (GEO fully-redacted 0.00; strict F1 0.00) — spaCy tags
85
+ "Dayton" but drops "412 Birch Lane". Partial address redaction is the
86
+ canonical re-identification leak.
87
+ - **Presidio's strong suit is names** (NAME relaxed F1 0.94 template, strict
88
+ 0.87 — better boundaries than our NER extra's 0.73). Its structured-type
89
+ rows (EMAIL, SSN, IP, credit card) are 1.00, same as ours.
90
+ - **Latency**: Presidio 14–46 ms/note; localscrub+NER 184–652 ms/note.
91
+ Presidio is 4–14× faster than our recommended CPU configuration — if its
92
+ accuracy profile is acceptable for your data, that is a real advantage;
93
+ for clinical text the MRN/address rows above say it is not.
94
+ - **Cloud APIs**: not yet measured (requires sending the benchmark corpora to
95
+ each provider and an account with each; planned before the article). The
96
+ qualitative row stands regardless of the numbers: the input text crosses
97
+ your trust boundary — see [threat-model.md](threat-model.md).
98
+
99
+ ## Pending measurements
100
+
101
+ - [ ] Full-cascade (`--ner --llm`) rerun on the 500-note template corpus and
102
+ 100-note MTSamples benchmark — **needs the local GPU** (qwen3:14b).
103
+ - [ ] Cloud API legs (accuracy, latency, $/note) — needs provider accounts
104
+ and an explicit decision to send the (synthetic) corpora out.
105
+ - [ ] i2b2/n2c2 2014 corpus for literature-comparable numbers (blocked
106
+ upstream, request drafted).
@@ -0,0 +1,51 @@
1
+ # ADR 0001: Stage-1 engine — in-house recognizers, not Presidio
2
+
3
+ - **Status:** accepted
4
+ - **Date:** 2026-07-28
5
+
6
+ ## Context
7
+
8
+ Stage 1 of the cascade needs fast, CPU-only detection of structured identifiers
9
+ (SSNs, phone numbers, emails, dates, labeled MRNs, …) with confidence scores that
10
+ drive the escalation decision to stage 2. The candidates were:
11
+
12
+ 1. **Microsoft Presidio** (`presidio-analyzer`) as the stage-1 engine, extended
13
+ with custom recognizers;
14
+ 2. **plain spaCy** NER plus our own regex layer;
15
+ 3. **in-house recognizers** (regex + dictionaries + checksums), with NER as an
16
+ optional extra later.
17
+
18
+ ## Decision
19
+
20
+ Build the stage-1 recognizer layer in-house. Do not depend on Presidio at
21
+ runtime. Add spaCy-based NAME/GEO detection later as an optional `[ner]` extra
22
+ so the base install stays pure-Python (Typer is the only runtime dependency).
23
+
24
+ ## Rationale
25
+
26
+ - **Benchmark integrity.** The project's headline evaluation is
27
+ "localscrub vs. rules-only vs. cloud APIs", with Presidio as the natural
28
+ rules-only baseline. If stage 1 *is* Presidio, that comparison collapses into
29
+ "Presidio vs. Presidio + LLM" and localscrub reads as a Presidio plugin.
30
+ Owning stage 1 keeps the three-way comparison clean; Presidio appears as a
31
+ benchmark baseline (a `bench` dependency group), never as a runtime dependency.
32
+ - **Dependency weight.** `presidio-analyzer` hard-depends on spaCy, so even
33
+ "Presidio for the regex parts" drags a large model ecosystem into every
34
+ install. The M1 identifier set is entirely regex + checksum + context words.
35
+ - **Escalation semantics.** The cascade lives or dies on calibrated confidence
36
+ bands (see `recognizers/base.py`). Mapping Presidio's per-recognizer scores
37
+ and context enhancers onto our bands would have to be done anyway; owning the
38
+ scoring means the calibration contract is explicit and testable.
39
+ - **Licensing is not a discriminator.** Presidio and spaCy are both MIT,
40
+ compatible with Apache-2.0 either way.
41
+
42
+ ## Consequences
43
+
44
+ - We maintain our own recognizers and their false-positive/negative profiles;
45
+ the eval harness (M2) must measure us against Presidio to prove this was
46
+ worth it.
47
+ - NAME and GEO_SUBDIVISION detection is deferred to the `[ner]` extra / stage 2;
48
+ until then, stage 1 does not catch person or place names — documented in the
49
+ README's honesty table when it ships.
50
+ - The Luhn/SSA/calendar validation logic is ours to test exhaustively (see
51
+ the recognizer test tables).