newmean-pii 1.0.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 (41) hide show
  1. newmean_pii-1.0.0/LICENSE +202 -0
  2. newmean_pii-1.0.0/MANIFEST.in +4 -0
  3. newmean_pii-1.0.0/NOTICE +71 -0
  4. newmean_pii-1.0.0/PKG-INFO +162 -0
  5. newmean_pii-1.0.0/README.ko.md +133 -0
  6. newmean_pii-1.0.0/README.md +137 -0
  7. newmean_pii-1.0.0/native-core/LICENSE +202 -0
  8. newmean_pii-1.0.0/native-core/NOTICE +71 -0
  9. newmean_pii-1.0.0/native-core/pii.h +180 -0
  10. newmean_pii-1.0.0/native-core/src/api.c +432 -0
  11. newmean_pii-1.0.0/native-core/src/engine.c +505 -0
  12. newmean_pii-1.0.0/native-core/src/internal.h +128 -0
  13. newmean_pii-1.0.0/native-core/src/models.c +27 -0
  14. newmean_pii-1.0.0/native-core/src/onnx.c +742 -0
  15. newmean_pii-1.0.0/native-core/src/sha256.c +83 -0
  16. newmean_pii-1.0.0/native-core/src/simd.h +132 -0
  17. newmean_pii-1.0.0/native-core/src/tokenizer.c +603 -0
  18. newmean_pii-1.0.0/native-core/src/unicode_tables.h +338 -0
  19. newmean_pii-1.0.0/native-core/src/util.c +381 -0
  20. newmean_pii-1.0.0/pyproject.toml +65 -0
  21. newmean_pii-1.0.0/setup.cfg +4 -0
  22. newmean_pii-1.0.0/setup.py +63 -0
  23. newmean_pii-1.0.0/src/newmean_pii/__init__.py +50 -0
  24. newmean_pii-1.0.0/src/newmean_pii/__main__.py +37 -0
  25. newmean_pii-1.0.0/src/newmean_pii/_core.c +276 -0
  26. newmean_pii-1.0.0/src/newmean_pii/_core.pyi +22 -0
  27. newmean_pii-1.0.0/src/newmean_pii/_models.py +155 -0
  28. newmean_pii-1.0.0/src/newmean_pii/_redactor.py +173 -0
  29. newmean_pii-1.0.0/src/newmean_pii/_regex.py +31 -0
  30. newmean_pii-1.0.0/src/newmean_pii/_types.py +24 -0
  31. newmean_pii-1.0.0/src/newmean_pii/py.typed +0 -0
  32. newmean_pii-1.0.0/src/newmean_pii.egg-info/PKG-INFO +162 -0
  33. newmean_pii-1.0.0/src/newmean_pii.egg-info/SOURCES.txt +33 -0
  34. newmean_pii-1.0.0/src/newmean_pii.egg-info/dependency_links.txt +1 -0
  35. newmean_pii-1.0.0/src/newmean_pii.egg-info/top_level.txt +1 -0
  36. newmean_pii-1.0.0/tests/conftest.py +38 -0
  37. newmean_pii-1.0.0/tests/test_api.py +105 -0
  38. newmean_pii-1.0.0/tests/test_download.py +159 -0
  39. newmean_pii-1.0.0/tests/test_model.py +136 -0
  40. newmean_pii-1.0.0/tests/test_parity.py +57 -0
  41. newmean_pii-1.0.0/tests/test_regex.py +58 -0
@@ -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,4 @@
1
+ include README.md README.ko.md LICENSE NOTICE
2
+ include src/newmean_pii/_core.c src/newmean_pii/_core.pyi src/newmean_pii/py.typed
3
+ recursive-include tests *.py
4
+ prune native-core
@@ -0,0 +1,71 @@
1
+ @newmean-ai/pii (https://github.com/newmean-ai/pii)
2
+ Copyright 2026 newmean.ai
3
+
4
+ The SDK code and the model weights (newmean-pii-nano, -small, -medium, -large; Hugging Face repositories newmean-ai/pii-nano,
5
+ -small, -medium, -large) are licensed under the Apache License 2.0 (LICENSE).
6
+
7
+ Attribution request (not a license condition): if you use the SDK or the models in a product, we would appreciate a
8
+ "Powered by newmean.ai" mention (linking to https://newmean.ai) in your documentation or an about, licenses or settings screen.
9
+
10
+ The models include or were derived from the following third-party material.
11
+
12
+ - mMiniLMv2 (Multilingual-MiniLM), Microsoft — https://github.com/microsoft/unilm/tree/master/minilm
13
+ The four models start from mMiniLMv2-L6-H384; the vocabulary is pruned and the layers are compressed per size.
14
+ - XLM-R SentencePiece tokenizer, Facebook AI — https://github.com/facebookresearch/fairseq/tree/main/examples/xlmr
15
+ The tokenizer files are the XLM-R tokenizer with its vocabulary pruned to the pieces used in training.
16
+ - Teacher models used only to produce training targets (not distributed): mDeBERTa-v3-base (Microsoft, MIT License) and
17
+ XLM-RoBERTa-large (Facebook AI, MIT License), fine-tuned by newmean.ai.
18
+
19
+ Training data: synthetic text generated by newmean.ai with Claude models; no third-party dataset was used for training.
20
+ Evaluation only (not distributed): KDPII (CC BY 4.0), OpenPII 1.5M (Ai4Privacy / Ai Suisse SA, CC BY 4.0), NVIDIA
21
+ Nemotron-PII (CC BY 4.0), Gretel synthetic_pii_finance_multilingual (Apache-2.0).
22
+
23
+ --------------------------------------------------------------------------------
24
+ mMiniLMv2 — https://github.com/microsoft/unilm
25
+
26
+ The MIT License (MIT)
27
+
28
+ Copyright (c) Microsoft Corporation
29
+
30
+ Permission is hereby granted, free of charge, to any person obtaining a copy
31
+ of this software and associated documentation files (the "Software"), to deal
32
+ in the Software without restriction, including without limitation the rights
33
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
34
+ copies of the Software, and to permit persons to whom the Software is
35
+ furnished to do so, subject to the following conditions:
36
+
37
+ The above copyright notice and this permission notice shall be included in all
38
+ copies or substantial portions of the Software.
39
+
40
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
45
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
46
+ SOFTWARE.
47
+
48
+ --------------------------------------------------------------------------------
49
+ XLM-R tokenizer (fairseq) — https://github.com/facebookresearch/fairseq
50
+
51
+ MIT License
52
+
53
+ Copyright (c) Facebook, Inc. and its affiliates.
54
+
55
+ Permission is hereby granted, free of charge, to any person obtaining a copy
56
+ of this software and associated documentation files (the "Software"), to deal
57
+ in the Software without restriction, including without limitation the rights
58
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
59
+ copies of the Software, and to permit persons to whom the Software is
60
+ furnished to do so, subject to the following conditions:
61
+
62
+ The above copyright notice and this permission notice shall be included in all
63
+ copies or substantial portions of the Software.
64
+
65
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
66
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
67
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
68
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
69
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
70
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
71
+ SOFTWARE.
@@ -0,0 +1,162 @@
1
+ Metadata-Version: 2.4
2
+ Name: newmean-pii
3
+ Version: 1.0.0
4
+ Summary: On-device multilingual PII detection and masking with small models (newmean-pii-nano/small/medium/large)
5
+ Author: newmean.ai
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://newmean.ai
8
+ Project-URL: Repository, https://github.com/newmean-ai/pii
9
+ Project-URL: Models, https://huggingface.co/newmean-ai
10
+ Keywords: pii,privacy,redaction,anonymization,ner,multilingual,on-device
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: C
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Security
18
+ Classifier: Topic :: Text Processing :: Linguistic
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ License-File: NOTICE
24
+ Dynamic: license-file
25
+
26
+ English | [한국어](https://github.com/newmean-ai/pii/blob/main/python/README.ko.md)
27
+
28
+ # newmean-pii
29
+
30
+ Detect and mask personal information in text **on your own machine**, before it is stored, logged or sent to an LLM. A
31
+ small multilingual token-classification model (54 languages) runs in a C extension; no network after the first
32
+ download, no dependencies. Python package of the npm package [`@newmean-ai/pii`](https://www.npmjs.com/package/@newmean-ai/pii):
33
+ same models, same spans.
34
+
35
+ ```bash
36
+ pip install newmean-pii
37
+ ```
38
+
39
+ ```python
40
+ from newmean_pii import create_redactor
41
+
42
+ redactor = create_redactor(size="medium")
43
+ redactor.redact("제 메일은 kim@example.com, 전화는 010-1234-5678입니다").text
44
+ # '제 메일은 [EMAIL], 전화는 [PHONE]입니다'
45
+ ```
46
+
47
+ Python 3.9+. Wheels for Linux (x86-64, arm64), macOS (arm64, x86-64) and Windows (x86-64); other platforms build
48
+ from the sdist with a C11 compiler.
49
+
50
+ ## Models
51
+
52
+ | size | file | notes |
53
+ |---|---|---|
54
+ | `nano` | 2.6 MB | one shared layer applied 4 times, rank-32 embeddings |
55
+ | `small` | 7.1 MB | 4 layers, rank-64 embeddings |
56
+ | `medium` (default) | 11.3 MB | 6 layers, rank-192 embeddings |
57
+ | `large` | 15.5 MB | 6 layers, full (pruned-vocabulary) embeddings |
58
+
59
+ Plus a 0.8 MB tokenizer. On first use the files are downloaded from Hugging Face (`newmean-ai/pii-<size>`, tag `v1.0.0`)
60
+ into `~/.cache/newmean-pii` and checked against SHA-256 values pinned in this package; every later load checks them again.
61
+
62
+ No model finds every piece of personal information. The technical report lists miss and over-masking rates per language
63
+ and dataset; treat the output as a strong first pass, not a guarantee. On newmean-pii-dataset (public test, 54 languages)
64
+ the models miss 1.6% (large) to 3.3% (nano) of PII characters; the full comparison is in the
65
+ [repository README](https://github.com/newmean-ai/pii#results).
66
+
67
+ ## Labels
68
+
69
+ `PERSON`, `EMAIL`, `PHONE`, `ADDRESS`, `ID_NUMBER`, `FINANCIAL`, `ORG`, `USERNAME`, `URL`, `DATE_OF_BIRTH`, `SECRET`, and two
70
+ level 2 labels for indirect identifiers: `PERSON_L2` (a surname with a title, a nickname, initials) and `URL_L2` (public
71
+ profile or page URLs). Pass `labels=LEVEL1_LABELS` to leave level 2 visible.
72
+
73
+ ## API
74
+
75
+ ```python
76
+ create_redactor( # or Redactor(...), same arguments
77
+ size="medium", # "nano" | "small" | "medium" | "large"
78
+ variant=None, # "q4" | "q4e"; default q4e for large/medium, q4 for small/nano
79
+ *,
80
+ sensitivity=0.0, # > 0 masks more, < 0 masks less (about -1..1)
81
+ labels=None, # labels to mask; default all (LABELS); unknown names raise ValueError
82
+ regex=False, # also mask a few patterns (email, URL, card/account, phone, Korean resident number);
83
+ # off by default: almost no extra coverage, double the over-masking
84
+ model_dir=None, # folder with tokenizer.web.json and onnx/model_<variant>.onnx; never downloads
85
+ cache_dir=None, # default: $NEWMEAN_PII_CACHE, $XDG_CACHE_HOME/newmean-pii or ~/.cache/newmean-pii
86
+ model_url=None, # base URL of a mirror of newmean-ai/pii-<size> (https://, http:// or file://)
87
+ on_progress=None, # callback(file, loaded_bytes, total_bytes)
88
+ ) -> Redactor
89
+
90
+ redactor.detect(text) # -> [Span(start, end, label, source)], sorted, non-overlapping
91
+ redactor.redact(text, mode="tag") # -> RedactResult(text, spans); "tag" -> [EMAIL], "mask" -> *****, "blank" -> removed
92
+ redactor.redact(text, mask_char="#", replace=None) # replace(span, original) -> str overrides mode
93
+ redactor.set_sensitivity(value) # no reload
94
+ redactor.tokenize(text) # -> [Token(id, start, end)]
95
+ redactor.close() # also: with create_redactor() as r: ...
96
+
97
+ apply_redaction(text, spans, mode="tag", mask_char="*", replace=None)
98
+ regex_spans(text) # the pattern layer alone
99
+ fetch_model(size, variant=None, cache_dir=None) # download and verify ahead of time; returns the folder
100
+ ```
101
+
102
+ - **Offsets** are Python `str` indices (code points): `text[span.start:span.end]` is the masked text, emoji included. The
103
+ npm package uses UTF-16 indices for the same spans. `source` is `"model"`, `"regex"` or `"model+regex"`.
104
+ - **`tag` mode** writes the label family: `PERSON_L2` becomes `[PERSON]`, `URL_L2` becomes `[URL]`. `mask` writes one
105
+ `mask_char` per code point.
106
+ - **Threads**: a redactor can be shared. The model is immutable and the GIL is released while it runs, so a thread
107
+ pool detects in parallel (one core per call):
108
+
109
+ ```python
110
+ from concurrent.futures import ThreadPoolExecutor
111
+ with ThreadPoolExecutor(4) as pool:
112
+ results = list(pool.map(redactor.redact, texts))
113
+ ```
114
+
115
+ - **Speed**: one thread on Apple M5 Pro, about 10 ms for a short text with nano and 15 ms with medium; a 1,000-token text
116
+ takes 0.4 s (nano) to 0.55 s (medium). Long texts are split into overlapping 256-token windows.
117
+ - Errors: `ValueError` for bad options, `ModelFileError` when a file is missing, cannot be downloaded or does not match
118
+ its pin.
119
+
120
+ ## Offline use
121
+
122
+ Download once, then run without network:
123
+
124
+ ```bash
125
+ python -m newmean_pii download --size medium # into the cache; prints the folder
126
+ NEWMEAN_PII_OFFLINE=1 python app.py # never download; fail if a file is not cached
127
+ ```
128
+
129
+ Or copy the files of the Hugging Face repo yourself (`tokenizer.web.json` and `onnx/model_<variant>.onnx`) and pass the
130
+ folder:
131
+
132
+ ```python
133
+ redactor = create_redactor(size="medium", model_dir="/opt/models/pii-medium")
134
+ ```
135
+
136
+ The files are checked against the pinned SHA-256 there too. For containers, run `python -m newmean_pii download` at
137
+ build time with `NEWMEAN_PII_CACHE` set to a folder inside the image.
138
+
139
+ There is also a small command line: `python -m newmean_pii redact --size nano --mode mask < input.txt`.
140
+
141
+ ## Development
142
+
143
+ ```bash
144
+ cd python
145
+ uv build # sdist (with native/core copied in) and a wheel built from it
146
+ pip install dist/*.whl pytest
147
+ pytest -q # fixture parity tests skip without fixtures and model copies
148
+ ```
149
+
150
+ The C extension compiles `native/core` (the shared core of every native package) with the same flags as its Makefile,
151
+ so logits are bit-identical to the npm package's baseline WebAssembly engine. Tests: regex parity with the Python
152
+ baseline, redaction modes, offsets on emoji text, threads, downloads against a local HTTP server and `file://` (no
153
+ network), and, when the private fixtures and model copies exist (`PII_FIXTURES`, default `js/test/fixtures`;
154
+ `PII_MODELS`, default `js/test/models`), tokenizer parity with Hugging Face and span parity with the Python evaluator for
155
+ every run of the npm test (`PII_SIZES=nano,medium` limits them). `NEWMEAN_PII_NETWORK_TESTS=1` adds one download from
156
+ Hugging Face. Wheels: `cibuildwheel` (configured in `pyproject.toml`, workflow `.github/workflows/python-wheels.yml`).
157
+
158
+ ## License
159
+
160
+ [Apache-2.0](LICENSE), for the package code and the model weights; third-party notices in [NOTICE](NOTICE). If you use
161
+ them in a product, we would appreciate a "Powered by newmean.ai" mention in your docs or an about or licenses screen (a
162
+ request, not a license condition). Made by [newmean.ai](https://newmean.ai).
@@ -0,0 +1,133 @@
1
+ [English](https://github.com/newmean-ai/pii/blob/main/python/README.md) | 한국어
2
+
3
+ # newmean-pii
4
+
5
+ 텍스트를 저장·로그 기록·LLM 전송하기 전에 **내 컴퓨터 안에서** 개인정보를 찾아 가립니다. 작은 다국어 토큰 분류
6
+ 모델(54개 언어)이 C 확장 모듈에서 돌고, 첫 다운로드 뒤에는 네트워크를 쓰지 않으며 의존 패키지도 없습니다. npm 패키지
7
+ [`@newmean-ai/pii`](https://www.npmjs.com/package/@newmean-ai/pii)의 Python 판으로, 같은 모델에서 같은 구간을 냅니다.
8
+
9
+ ```bash
10
+ pip install newmean-pii
11
+ ```
12
+
13
+ ```python
14
+ from newmean_pii import create_redactor
15
+
16
+ redactor = create_redactor(size="medium")
17
+ redactor.redact("제 메일은 kim@example.com, 전화는 010-1234-5678입니다").text
18
+ # '제 메일은 [EMAIL], 전화는 [PHONE]입니다'
19
+ ```
20
+
21
+ Python 3.9 이상. Linux(x86-64, arm64), macOS(arm64, x86-64), Windows(x86-64) 휠을 제공하고, 그 밖의 플랫폼은 C11
22
+ 컴파일러로 sdist에서 빌드합니다.
23
+
24
+ ## 모델
25
+
26
+ | size | 파일 | 비고 |
27
+ |---|---|---|
28
+ | `nano` | 2.6 MB | 공유 레이어 하나를 4번 적용, rank-32 임베딩 |
29
+ | `small` | 7.1 MB | 4 레이어, rank-64 임베딩 |
30
+ | `medium` (기본) | 11.3 MB | 6 레이어, rank-192 임베딩 |
31
+ | `large` | 15.5 MB | 6 레이어, 전체(어휘 가지치기) 임베딩 |
32
+
33
+ 여기에 0.8 MB 토크나이저가 더해집니다. 처음 쓸 때 Hugging Face(`newmean-ai/pii-<size>`, 태그 `v1.0.0`)에서
34
+ `~/.cache/newmean-pii`로 내려받고, 이 패키지에 고정된 SHA-256 값과 대조합니다. 이후 불러올 때마다 다시 대조합니다.
35
+
36
+ 모든 개인정보를 찾는 모델은 없습니다. 언어·데이터셋별 놓침률과 과잉 마스킹률은 기술 보고서에 있습니다. 결과는 보장이
37
+ 아니라 강력한 1차 처리로 다뤄 주세요. newmean-pii-dataset(공개 테스트, 54개 언어)에서 개인정보 글자 중 놓치는 비율은
38
+ 1.6%(large)~3.3%(nano)이며, 전체 비교는 [저장소 README](https://github.com/newmean-ai/pii#results)에 있습니다.
39
+
40
+ ## 레이블
41
+
42
+ `PERSON`, `EMAIL`, `PHONE`, `ADDRESS`, `ID_NUMBER`, `FINANCIAL`, `ORG`, `USERNAME`, `URL`, `DATE_OF_BIRTH`, `SECRET`, 그리고
43
+ 간접 식별자용 2단계 레이블 두 개: `PERSON_L2`(호칭이 붙은 성, 별명, 이니셜)와 `URL_L2`(공개 프로필·페이지 URL).
44
+ 2단계를 가리지 않으려면 `labels=LEVEL1_LABELS`를 넘기세요.
45
+
46
+ ## API
47
+
48
+ ```python
49
+ create_redactor( # 또는 Redactor(...), 인자 동일
50
+ size="medium", # "nano" | "small" | "medium" | "large"
51
+ variant=None, # "q4" | "q4e"; 기본은 large/medium q4e, small/nano q4
52
+ *,
53
+ sensitivity=0.0, # > 0 더 많이 가림, < 0 덜 가림 (대략 -1..1)
54
+ labels=None, # 가릴 레이블; 기본 전체(LABELS); 모르는 이름은 ValueError
55
+ regex=False, # 몇 가지 패턴(이메일, URL, 카드/계좌, 전화, 주민등록번호)도 가림;
56
+ # 기본 꺼짐: 추가 탐지는 거의 없고 과잉 마스킹이 두 배
57
+ model_dir=None, # tokenizer.web.json과 onnx/model_<variant>.onnx가 있는 폴더; 다운로드하지 않음
58
+ cache_dir=None, # 기본: $NEWMEAN_PII_CACHE, $XDG_CACHE_HOME/newmean-pii 또는 ~/.cache/newmean-pii
59
+ model_url=None, # newmean-ai/pii-<size> 미러의 기준 URL (https://, http://, file://)
60
+ on_progress=None, # callback(file, loaded_bytes, total_bytes)
61
+ ) -> Redactor
62
+
63
+ redactor.detect(text) # -> [Span(start, end, label, source)], 정렬, 겹침 없음
64
+ redactor.redact(text, mode="tag") # -> RedactResult(text, spans); "tag" -> [EMAIL], "mask" -> *****, "blank" -> 삭제
65
+ redactor.redact(text, mask_char="#", replace=None) # replace(span, original) -> str 가 mode보다 우선
66
+ redactor.set_sensitivity(value) # 다시 불러오지 않음
67
+ redactor.tokenize(text) # -> [Token(id, start, end)]
68
+ redactor.close() # 또는: with create_redactor() as r: ...
69
+
70
+ apply_redaction(text, spans, mode="tag", mask_char="*", replace=None)
71
+ regex_spans(text) # 패턴 레이어만
72
+ fetch_model(size, variant=None, cache_dir=None) # 미리 내려받고 검증; 폴더를 돌려줌
73
+ ```
74
+
75
+ - **오프셋**은 Python `str` 인덱스(코드 포인트)입니다. 이모지가 있어도 `text[span.start:span.end]`가 가릴 텍스트입니다.
76
+ npm 패키지는 같은 구간을 UTF-16 인덱스로 냅니다. `source`는 `"model"`, `"regex"`, `"model+regex"` 중 하나입니다.
77
+ - **`tag` 모드**는 레이블 계열을 씁니다. `PERSON_L2`는 `[PERSON]`, `URL_L2`는 `[URL]`이 됩니다. `mask`는 코드 포인트마다
78
+ `mask_char` 하나를 씁니다.
79
+ - **스레드**: redactor 하나를 함께 써도 됩니다. 모델은 불변이고 실행 중에는 GIL을 풀기 때문에 스레드 풀로 병렬
80
+ 처리됩니다(호출 하나당 코어 하나).
81
+
82
+ ```python
83
+ from concurrent.futures import ThreadPoolExecutor
84
+ with ThreadPoolExecutor(4) as pool:
85
+ results = list(pool.map(redactor.redact, texts))
86
+ ```
87
+
88
+ - **속도**: Apple M5 Pro 한 스레드에서 짧은 텍스트 하나에 nano 약 10 ms, medium 약 15 ms, 1,000토큰 텍스트는 0.4초(nano)
89
+ ~0.55초(medium). 긴 텍스트는 256토큰 창으로 겹쳐 나눠 처리합니다.
90
+ - 오류: 잘못된 옵션은 `ValueError`, 파일이 없거나 내려받지 못하거나 고정값과 다르면 `ModelFileError`.
91
+
92
+ ## 오프라인 사용
93
+
94
+ 한 번 내려받은 뒤 네트워크 없이 실행합니다.
95
+
96
+ ```bash
97
+ python -m newmean_pii download --size medium # 캐시에 저장; 폴더를 출력
98
+ NEWMEAN_PII_OFFLINE=1 python app.py # 다운로드하지 않음; 캐시에 없으면 실패
99
+ ```
100
+
101
+ 또는 Hugging Face 저장소의 파일(`tokenizer.web.json`, `onnx/model_<variant>.onnx`)을 직접 복사해 폴더를 넘깁니다.
102
+
103
+ ```python
104
+ redactor = create_redactor(size="medium", model_dir="/opt/models/pii-medium")
105
+ ```
106
+
107
+ 이 경우에도 고정된 SHA-256과 대조합니다. 컨테이너에서는 이미지 빌드 때 `NEWMEAN_PII_CACHE`를 이미지 안 폴더로 두고
108
+ `python -m newmean_pii download`를 실행하세요.
109
+
110
+ 간단한 명령줄도 있습니다: `python -m newmean_pii redact --size nano --mode mask < input.txt`.
111
+
112
+ ## 개발
113
+
114
+ ```bash
115
+ cd python
116
+ uv build # sdist(native/core 복사 포함)와 그 sdist에서 빌드한 휠
117
+ pip install dist/*.whl pytest
118
+ pytest -q # 픽스처 패리티 테스트는 픽스처와 모델 사본이 없으면 건너뜀
119
+ ```
120
+
121
+ C 확장은 `native/core`(모든 네이티브 패키지가 공유하는 코어)를 그 Makefile과 같은 플래그로 컴파일하므로, 로짓이 npm
122
+ 패키지의 기본 WebAssembly 엔진과 비트 단위로 같습니다. 테스트: Python 기준 구현과의 정규식 패리티, 마스킹 모드,
123
+ 이모지 텍스트의 오프셋, 스레드, 로컬 HTTP 서버와 `file://`를 쓰는 다운로드(네트워크 불필요), 그리고 비공개 픽스처와
124
+ 모델 사본이 있으면(`PII_FIXTURES`, 기본 `js/test/fixtures`; `PII_MODELS`, 기본 `js/test/models`) Hugging Face와의
125
+ 토크나이저 패리티, npm 테스트의 모든 실행에 대한 Python 평가기와의 구간 패리티(`PII_SIZES=nano,medium`으로 제한).
126
+ `NEWMEAN_PII_NETWORK_TESTS=1`이면 Hugging Face 다운로드 테스트 하나가 더 돕니다. 휠: `cibuildwheel`(설정은
127
+ `pyproject.toml`, 워크플로는 `.github/workflows/python-wheels.yml`).
128
+
129
+ ## 라이선스
130
+
131
+ 패키지 코드와 모델 가중치 모두 [Apache-2.0](LICENSE)이며, 제3자 고지는 [NOTICE](NOTICE)에 있습니다. 제품에 쓰신다면 문서나
132
+ 정보·라이선스 화면에 "Powered by newmean.ai"를 표기해 주시면 감사하겠습니다(라이선스 조건이 아닌 요청). 만든 곳:
133
+ [newmean.ai](https://newmean.ai).