spacy-redefiner 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.
- spacy_redefiner-0.1.0/LICENSE +202 -0
- spacy_redefiner-0.1.0/PKG-INFO +147 -0
- spacy_redefiner-0.1.0/README.md +119 -0
- spacy_redefiner-0.1.0/pyproject.toml +51 -0
- spacy_redefiner-0.1.0/setup.cfg +4 -0
- spacy_redefiner-0.1.0/src/spacy_redefiner/__init__.py +13 -0
- spacy_redefiner-0.1.0/src/spacy_redefiner/component.py +161 -0
- spacy_redefiner-0.1.0/src/spacy_redefiner.egg-info/PKG-INFO +147 -0
- spacy_redefiner-0.1.0/src/spacy_redefiner.egg-info/SOURCES.txt +13 -0
- spacy_redefiner-0.1.0/src/spacy_redefiner.egg-info/dependency_links.txt +1 -0
- spacy_redefiner-0.1.0/src/spacy_redefiner.egg-info/entry_points.txt +2 -0
- spacy_redefiner-0.1.0/src/spacy_redefiner.egg-info/requires.txt +6 -0
- spacy_redefiner-0.1.0/src/spacy_redefiner.egg-info/top_level.txt +1 -0
- spacy_redefiner-0.1.0/tests/test_component.py +117 -0
- spacy_redefiner-0.1.0/tests/test_slow.py +22 -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,147 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: spacy-redefiner
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A spaCy component that finds the entities you define in a plain-English rulebook, using ReDefiNER.
|
|
5
|
+
Author: Sethuraman T A, Jungroo AI Labs
|
|
6
|
+
Author-email: Cibe Hariharan K <cibe@jungroo.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: Homepage, https://github.com/Jungroo-AI/spacy-redefiner
|
|
9
|
+
Project-URL: Repository, https://github.com/Jungroo-AI/spacy-redefiner
|
|
10
|
+
Project-URL: Issues, https://github.com/Jungroo-AI/spacy-redefiner/issues
|
|
11
|
+
Project-URL: ReDefiNER, https://github.com/jungroo-ai/redefiner
|
|
12
|
+
Keywords: spacy,spacy-extension,named-entity-recognition,ner,entity-extraction,rulebook,pii,redefiner
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
18
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: spacy<4,>=3.7
|
|
23
|
+
Requires-Dist: redefiner>=1.0.9
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest; extra == "dev"
|
|
26
|
+
Requires-Dist: ruff; extra == "dev"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# spacy-redefiner
|
|
30
|
+
|
|
31
|
+
A [spaCy](https://spacy.io) pipeline component that finds the entities you define in a plain-English rulebook, using
|
|
32
|
+
[ReDefiNER](https://github.com/jungroo-ai/redefiner).
|
|
33
|
+
|
|
34
|
+
ReDefiNER is an open model (0.8B parameters, Apache 2.0) that marks the spans of text a rulebook defines: entity
|
|
35
|
+
types, a one-line description each, and optional rules. To change what is found, edit the rulebook; no training data
|
|
36
|
+
and no retraining. It is non-generative, runs on CPU or GPU, and supports English only.
|
|
37
|
+
|
|
38
|
+
## Install
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install spacy-redefiner
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The first document downloads the model weights (about 0.8 GB) from Hugging Face.
|
|
45
|
+
|
|
46
|
+
## Quickstart
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import spacy
|
|
50
|
+
|
|
51
|
+
RULEBOOK = """[TYPE] PERSON
|
|
52
|
+
[DESCRIPTION] A person's name.
|
|
53
|
+
|
|
54
|
+
[TYPE] ORGANIZATION
|
|
55
|
+
[DESCRIPTION] A company, institution or society.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
nlp = spacy.blank("en")
|
|
59
|
+
nlp.add_pipe("redefiner", config={"rulebook": RULEBOOK})
|
|
60
|
+
doc = nlp("Ada Lovelace corresponded with the Royal Society.")
|
|
61
|
+
print([(ent.text, ent.label_, ent._.redefiner_confidence) for ent in doc.ents])
|
|
62
|
+
# [('Ada Lovelace', 'PERSON', 0.99), ('Royal Society', 'ORGANIZATION', 0.891)]
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The component also works after a trained spaCy pipeline, for example `spacy.load("en_core_web_sm")`. By default it
|
|
66
|
+
replaces the pipeline's entities; set `overwrite_ents` to `false` to keep them and add only new, non-overlapping ones.
|
|
67
|
+
|
|
68
|
+
## Personal data
|
|
69
|
+
|
|
70
|
+
[`jungroo-ai/redefiner-pii`](https://huggingface.co/jungroo-ai/redefiner-pii) holds a ready-made PII rulebook (20
|
|
71
|
+
types) and its settings. With it, no rulebook is needed:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
nlp = spacy.blank("en")
|
|
75
|
+
nlp.add_pipe("redefiner", config={"model": "jungroo-ai/redefiner-pii"})
|
|
76
|
+
doc = nlp("Call Meera Nair on 020 7946 0155 or write to meera.nair@example.org.")
|
|
77
|
+
print([(ent.text, ent.label_) for ent in doc.ents])
|
|
78
|
+
# [('Meera Nair', 'PERSON'), ('020 7946 0155', 'PHONE'), ('meera.nair@example.org', 'EMAIL')]
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The model can miss personal data and can mark text that is not personal. Check its output on your own documents
|
|
82
|
+
before relying on it, and don't use it as the only safeguard.
|
|
83
|
+
|
|
84
|
+
## Writing a rulebook
|
|
85
|
+
|
|
86
|
+
A rulebook has one `[TYPE]` section per entity type with a `[DESCRIPTION]` line, and can add rule lines, a `[RULES]`
|
|
87
|
+
section for rules that apply to every type, and a `[TYPE] NOT_AN_ENTITY` section for what must never be found.
|
|
88
|
+
Descriptions matter: one line per type does much better than type names alone. See the
|
|
89
|
+
[rulebook guide](https://github.com/jungroo-ai/redefiner/blob/main/docs/writing-rules.md) and the
|
|
90
|
+
[templates](https://github.com/jungroo-ai/redefiner/tree/main/docs/templates).
|
|
91
|
+
|
|
92
|
+
`rulebook` takes the rulebook text or the path of a rulebook file.
|
|
93
|
+
|
|
94
|
+
## Settings
|
|
95
|
+
|
|
96
|
+
| Setting | Default | Meaning |
|
|
97
|
+
|---|---|---|
|
|
98
|
+
| `model` | `"jungroo-ai/redefiner-0.8b"` | A Hugging Face repo or local folder. A page such as `jungroo-ai/redefiner-pii` brings its own rulebook and settings |
|
|
99
|
+
| `rulebook` | `null` | Rulebook text or a file path. Needed unless the model page has a default rulebook |
|
|
100
|
+
| `spans_key` | `null` | Write the spans to `doc.spans[spans_key]` instead of `doc.ents` |
|
|
101
|
+
| `overwrite_ents` | `true` | With `doc.ents`: replace existing entities, or (`false`) keep them and add non-overlapping spans |
|
|
102
|
+
| `min_confidence` | `0.0` | Drop spans below this confidence |
|
|
103
|
+
| `threshold` | model default (0.5) | Span score needed before a span gets a type |
|
|
104
|
+
| `none_bias` | model default (2) | Higher finds more borderline spans |
|
|
105
|
+
| `max_span_tokens` | model default | Longest span in model tokens (16 by default; 64 on the PII page). Raise it for long IDs or URLs |
|
|
106
|
+
| `device` | `null` | `"cpu"`, `"cuda"` or `"cuda:N"`; default: a GPU when PyTorch can use one |
|
|
107
|
+
| `revision` | `null` | Hugging Face revision of the model |
|
|
108
|
+
| `batch_size` | `16` | Texts per model forward pass |
|
|
109
|
+
| `alignment_mode` | `"expand"` | How model spans snap to spaCy tokens: `"strict"`, `"contract"` or `"expand"` |
|
|
110
|
+
|
|
111
|
+
In a spaCy config file:
|
|
112
|
+
|
|
113
|
+
```ini
|
|
114
|
+
[components.redefiner]
|
|
115
|
+
factory = "redefiner"
|
|
116
|
+
rulebook = "rules/contracts.txt"
|
|
117
|
+
spans_key = "redefiner"
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Output
|
|
121
|
+
|
|
122
|
+
- `doc.ents`, or `doc.spans[spans_key]` when a key is set.
|
|
123
|
+
- Each span's confidence is in `span._.redefiner_confidence`. A span group also keeps the confidences in
|
|
124
|
+
`group.attrs["scores"]`, as spaCy's span categorizer does.
|
|
125
|
+
- `nlp.to_disk()` saves the rulebook text with the pipeline, so a saved pipeline does not depend on the rulebook file.
|
|
126
|
+
- Components with the same model and settings share one loaded model.
|
|
127
|
+
|
|
128
|
+
## Speed and limits
|
|
129
|
+
|
|
130
|
+
- On an Apple M2 CPU, the first document with a new rulebook took about 7 seconds while the rulebook was read; it is
|
|
131
|
+
then cached, and later short texts take under a second. A GPU is much faster for large batches.
|
|
132
|
+
- English only.
|
|
133
|
+
- Long texts are read in parts of 256 tokens, so the same name can get different labels in different parts.
|
|
134
|
+
- Rules that go against what the model already knows, such as calling a person's name something other than a person,
|
|
135
|
+
are mostly ignored. Try a rulebook on a few dozen of your own texts first.
|
|
136
|
+
|
|
137
|
+
## Development
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
pip install -e ".[dev]"
|
|
141
|
+
pytest # fast tests with a fake model
|
|
142
|
+
pytest -m slow # the real model on CPU
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Licence
|
|
146
|
+
|
|
147
|
+
Apache License 2.0. See [LICENSE](LICENSE). Made by [Jungroo AI Labs](https://jungroo.com).
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# spacy-redefiner
|
|
2
|
+
|
|
3
|
+
A [spaCy](https://spacy.io) pipeline component that finds the entities you define in a plain-English rulebook, using
|
|
4
|
+
[ReDefiNER](https://github.com/jungroo-ai/redefiner).
|
|
5
|
+
|
|
6
|
+
ReDefiNER is an open model (0.8B parameters, Apache 2.0) that marks the spans of text a rulebook defines: entity
|
|
7
|
+
types, a one-line description each, and optional rules. To change what is found, edit the rulebook; no training data
|
|
8
|
+
and no retraining. It is non-generative, runs on CPU or GPU, and supports English only.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pip install spacy-redefiner
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
The first document downloads the model weights (about 0.8 GB) from Hugging Face.
|
|
17
|
+
|
|
18
|
+
## Quickstart
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import spacy
|
|
22
|
+
|
|
23
|
+
RULEBOOK = """[TYPE] PERSON
|
|
24
|
+
[DESCRIPTION] A person's name.
|
|
25
|
+
|
|
26
|
+
[TYPE] ORGANIZATION
|
|
27
|
+
[DESCRIPTION] A company, institution or society.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
nlp = spacy.blank("en")
|
|
31
|
+
nlp.add_pipe("redefiner", config={"rulebook": RULEBOOK})
|
|
32
|
+
doc = nlp("Ada Lovelace corresponded with the Royal Society.")
|
|
33
|
+
print([(ent.text, ent.label_, ent._.redefiner_confidence) for ent in doc.ents])
|
|
34
|
+
# [('Ada Lovelace', 'PERSON', 0.99), ('Royal Society', 'ORGANIZATION', 0.891)]
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The component also works after a trained spaCy pipeline, for example `spacy.load("en_core_web_sm")`. By default it
|
|
38
|
+
replaces the pipeline's entities; set `overwrite_ents` to `false` to keep them and add only new, non-overlapping ones.
|
|
39
|
+
|
|
40
|
+
## Personal data
|
|
41
|
+
|
|
42
|
+
[`jungroo-ai/redefiner-pii`](https://huggingface.co/jungroo-ai/redefiner-pii) holds a ready-made PII rulebook (20
|
|
43
|
+
types) and its settings. With it, no rulebook is needed:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
nlp = spacy.blank("en")
|
|
47
|
+
nlp.add_pipe("redefiner", config={"model": "jungroo-ai/redefiner-pii"})
|
|
48
|
+
doc = nlp("Call Meera Nair on 020 7946 0155 or write to meera.nair@example.org.")
|
|
49
|
+
print([(ent.text, ent.label_) for ent in doc.ents])
|
|
50
|
+
# [('Meera Nair', 'PERSON'), ('020 7946 0155', 'PHONE'), ('meera.nair@example.org', 'EMAIL')]
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The model can miss personal data and can mark text that is not personal. Check its output on your own documents
|
|
54
|
+
before relying on it, and don't use it as the only safeguard.
|
|
55
|
+
|
|
56
|
+
## Writing a rulebook
|
|
57
|
+
|
|
58
|
+
A rulebook has one `[TYPE]` section per entity type with a `[DESCRIPTION]` line, and can add rule lines, a `[RULES]`
|
|
59
|
+
section for rules that apply to every type, and a `[TYPE] NOT_AN_ENTITY` section for what must never be found.
|
|
60
|
+
Descriptions matter: one line per type does much better than type names alone. See the
|
|
61
|
+
[rulebook guide](https://github.com/jungroo-ai/redefiner/blob/main/docs/writing-rules.md) and the
|
|
62
|
+
[templates](https://github.com/jungroo-ai/redefiner/tree/main/docs/templates).
|
|
63
|
+
|
|
64
|
+
`rulebook` takes the rulebook text or the path of a rulebook file.
|
|
65
|
+
|
|
66
|
+
## Settings
|
|
67
|
+
|
|
68
|
+
| Setting | Default | Meaning |
|
|
69
|
+
|---|---|---|
|
|
70
|
+
| `model` | `"jungroo-ai/redefiner-0.8b"` | A Hugging Face repo or local folder. A page such as `jungroo-ai/redefiner-pii` brings its own rulebook and settings |
|
|
71
|
+
| `rulebook` | `null` | Rulebook text or a file path. Needed unless the model page has a default rulebook |
|
|
72
|
+
| `spans_key` | `null` | Write the spans to `doc.spans[spans_key]` instead of `doc.ents` |
|
|
73
|
+
| `overwrite_ents` | `true` | With `doc.ents`: replace existing entities, or (`false`) keep them and add non-overlapping spans |
|
|
74
|
+
| `min_confidence` | `0.0` | Drop spans below this confidence |
|
|
75
|
+
| `threshold` | model default (0.5) | Span score needed before a span gets a type |
|
|
76
|
+
| `none_bias` | model default (2) | Higher finds more borderline spans |
|
|
77
|
+
| `max_span_tokens` | model default | Longest span in model tokens (16 by default; 64 on the PII page). Raise it for long IDs or URLs |
|
|
78
|
+
| `device` | `null` | `"cpu"`, `"cuda"` or `"cuda:N"`; default: a GPU when PyTorch can use one |
|
|
79
|
+
| `revision` | `null` | Hugging Face revision of the model |
|
|
80
|
+
| `batch_size` | `16` | Texts per model forward pass |
|
|
81
|
+
| `alignment_mode` | `"expand"` | How model spans snap to spaCy tokens: `"strict"`, `"contract"` or `"expand"` |
|
|
82
|
+
|
|
83
|
+
In a spaCy config file:
|
|
84
|
+
|
|
85
|
+
```ini
|
|
86
|
+
[components.redefiner]
|
|
87
|
+
factory = "redefiner"
|
|
88
|
+
rulebook = "rules/contracts.txt"
|
|
89
|
+
spans_key = "redefiner"
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Output
|
|
93
|
+
|
|
94
|
+
- `doc.ents`, or `doc.spans[spans_key]` when a key is set.
|
|
95
|
+
- Each span's confidence is in `span._.redefiner_confidence`. A span group also keeps the confidences in
|
|
96
|
+
`group.attrs["scores"]`, as spaCy's span categorizer does.
|
|
97
|
+
- `nlp.to_disk()` saves the rulebook text with the pipeline, so a saved pipeline does not depend on the rulebook file.
|
|
98
|
+
- Components with the same model and settings share one loaded model.
|
|
99
|
+
|
|
100
|
+
## Speed and limits
|
|
101
|
+
|
|
102
|
+
- On an Apple M2 CPU, the first document with a new rulebook took about 7 seconds while the rulebook was read; it is
|
|
103
|
+
then cached, and later short texts take under a second. A GPU is much faster for large batches.
|
|
104
|
+
- English only.
|
|
105
|
+
- Long texts are read in parts of 256 tokens, so the same name can get different labels in different parts.
|
|
106
|
+
- Rules that go against what the model already knows, such as calling a person's name something other than a person,
|
|
107
|
+
are mostly ignored. Try a rulebook on a few dozen of your own texts first.
|
|
108
|
+
|
|
109
|
+
## Development
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
pip install -e ".[dev]"
|
|
113
|
+
pytest # fast tests with a fake model
|
|
114
|
+
pytest -m slow # the real model on CPU
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Licence
|
|
118
|
+
|
|
119
|
+
Apache License 2.0. See [LICENSE](LICENSE). Made by [Jungroo AI Labs](https://jungroo.com).
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "spacy-redefiner"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "A spaCy component that finds the entities you define in a plain-English rulebook, using ReDefiNER."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Cibe Hariharan K", email = "cibe@jungroo.com" }, { name = "Sethuraman T A" }, { name = "Jungroo AI Labs" }]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
keywords = ["spacy", "spacy-extension", "named-entity-recognition", "ner", "entity-extraction", "rulebook", "pii", "redefiner"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Intended Audience :: Science/Research",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
21
|
+
"Topic :: Text Processing :: Linguistic",
|
|
22
|
+
]
|
|
23
|
+
dependencies = [
|
|
24
|
+
"spacy>=3.7,<4",
|
|
25
|
+
"redefiner>=1.0.9",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://github.com/Jungroo-AI/spacy-redefiner"
|
|
30
|
+
Repository = "https://github.com/Jungroo-AI/spacy-redefiner"
|
|
31
|
+
Issues = "https://github.com/Jungroo-AI/spacy-redefiner/issues"
|
|
32
|
+
ReDefiNER = "https://github.com/jungroo-ai/redefiner"
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
dev = ["pytest", "ruff"]
|
|
36
|
+
|
|
37
|
+
[project.entry-points.spacy_factories]
|
|
38
|
+
redefiner = "spacy_redefiner.component:make_redefiner"
|
|
39
|
+
|
|
40
|
+
[tool.setuptools.dynamic]
|
|
41
|
+
version = { attr = "spacy_redefiner.__version__" }
|
|
42
|
+
|
|
43
|
+
[tool.setuptools.packages.find]
|
|
44
|
+
where = ["src"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
markers = ["slow: loads the real model (about 0.8 GB, downloaded once)"]
|
|
48
|
+
addopts = "-m 'not slow'"
|
|
49
|
+
|
|
50
|
+
[tool.ruff]
|
|
51
|
+
line-length = 120
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""ReDefiNER as a spaCy pipeline component: entities defined by a plain-English rulebook.
|
|
2
|
+
|
|
3
|
+
import spacy
|
|
4
|
+
nlp = spacy.blank("en")
|
|
5
|
+
nlp.add_pipe("redefiner", config={"rulebook": RULEBOOK})
|
|
6
|
+
doc = nlp("Ada Lovelace corresponded with the Royal Society.")
|
|
7
|
+
[(ent.text, ent.label_, ent._.redefiner_confidence) for ent in doc.ents]
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .component import DEFAULT_MODEL, ReDefiNERComponent, make_redefiner, shared_tagger
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
__all__ = ["DEFAULT_MODEL", "ReDefiNERComponent", "__version__", "make_redefiner", "shared_tagger"]
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""The `redefiner` spaCy component: entities defined by a plain-English rulebook, found by ReDefiNER."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
from collections.abc import Iterable, Iterator
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from spacy.language import Language
|
|
10
|
+
from spacy.tokens import Doc, Span, SpanGroup
|
|
11
|
+
from spacy.util import filter_spans, minibatch
|
|
12
|
+
|
|
13
|
+
DEFAULT_MODEL = "jungroo-ai/redefiner-0.8b"
|
|
14
|
+
CONFIDENCE = "redefiner_confidence"
|
|
15
|
+
ALIGNMENT_MODES = ("strict", "contract", "expand")
|
|
16
|
+
RULEBOOK_FILE = "rulebook.txt"
|
|
17
|
+
|
|
18
|
+
if not Span.has_extension(CONFIDENCE):
|
|
19
|
+
Span.set_extension(CONFIDENCE, default=None)
|
|
20
|
+
|
|
21
|
+
_TAGGERS: dict = {}
|
|
22
|
+
_LOCK = threading.Lock()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def shared_tagger(model: str, device: str | None = None, max_span_tokens: int | None = None,
|
|
26
|
+
revision: str | None = None):
|
|
27
|
+
"""One loaded model per (model, device, span limit, revision) in a process, shared by every component."""
|
|
28
|
+
key = (str(model), device, max_span_tokens, revision)
|
|
29
|
+
with _LOCK:
|
|
30
|
+
if key not in _TAGGERS:
|
|
31
|
+
from redefiner import Tagger
|
|
32
|
+
_TAGGERS[key] = Tagger.from_pretrained(model, device=device, revision=revision,
|
|
33
|
+
max_span_tokens=max_span_tokens)
|
|
34
|
+
return _TAGGERS[key]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _read_rulebook(value: str | None) -> str | None:
|
|
38
|
+
"""Rulebook text from the config value: the text itself, or the path of a rulebook file."""
|
|
39
|
+
if value is None:
|
|
40
|
+
return None
|
|
41
|
+
text = str(value)
|
|
42
|
+
if "\n" in text or "[TYPE]" in text:
|
|
43
|
+
return text
|
|
44
|
+
path = Path(text).expanduser()
|
|
45
|
+
if path.is_file():
|
|
46
|
+
return path.read_text(encoding="utf-8")
|
|
47
|
+
raise ValueError(f"rulebook {text!r} is neither rulebook text (it has no [TYPE] section) nor an existing file")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ReDefiNERComponent:
|
|
51
|
+
"""Writes the spans ReDefiNER finds to `doc.ents`, or to `doc.spans[spans_key]` when a key is given.
|
|
52
|
+
|
|
53
|
+
Each span's confidence is in `span._.redefiner_confidence`; a span group also keeps them in `group.attrs["scores"]`.
|
|
54
|
+
The model loads on the first document, not when the component is added.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(self, nlp: Language, name: str, model: str, rulebook: str | None, spans_key: str | None,
|
|
58
|
+
threshold: float | None, none_bias: float | None, min_confidence: float,
|
|
59
|
+
max_span_tokens: int | None, device: str | None, revision: str | None, batch_size: int,
|
|
60
|
+
alignment_mode: str, overwrite_ents: bool):
|
|
61
|
+
if alignment_mode not in ALIGNMENT_MODES:
|
|
62
|
+
raise ValueError(f"alignment_mode must be one of {ALIGNMENT_MODES}, not {alignment_mode!r}")
|
|
63
|
+
if batch_size < 1:
|
|
64
|
+
raise ValueError("batch_size must be at least 1")
|
|
65
|
+
self.name = name
|
|
66
|
+
self.model = model
|
|
67
|
+
self.rulebook_config = rulebook
|
|
68
|
+
self._rulebook: str | None = None
|
|
69
|
+
self.spans_key = spans_key
|
|
70
|
+
self.threshold = threshold
|
|
71
|
+
self.none_bias = none_bias
|
|
72
|
+
self.min_confidence = min_confidence
|
|
73
|
+
self.max_span_tokens = max_span_tokens
|
|
74
|
+
self.device = device
|
|
75
|
+
self.revision = revision
|
|
76
|
+
self.batch_size = batch_size
|
|
77
|
+
self.alignment_mode = alignment_mode
|
|
78
|
+
self.overwrite_ents = overwrite_ents
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def rulebook(self) -> str | None:
|
|
82
|
+
"""The rulebook text, or None to use the model's default rulebook (pages such as jungroo-ai/redefiner-pii)."""
|
|
83
|
+
if self._rulebook is None and self.rulebook_config is not None:
|
|
84
|
+
self._rulebook = _read_rulebook(self.rulebook_config)
|
|
85
|
+
return self._rulebook
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def tagger(self):
|
|
89
|
+
return shared_tagger(self.model, self.device, self.max_span_tokens, self.revision)
|
|
90
|
+
|
|
91
|
+
def __call__(self, doc: Doc) -> Doc:
|
|
92
|
+
return self._apply([doc])[0]
|
|
93
|
+
|
|
94
|
+
def pipe(self, stream: Iterable[Doc], batch_size: int | None = None) -> Iterator[Doc]:
|
|
95
|
+
for batch in minibatch(stream, size=batch_size or self.batch_size):
|
|
96
|
+
yield from self._apply(list(batch))
|
|
97
|
+
|
|
98
|
+
def _apply(self, docs: list[Doc]) -> list[Doc]:
|
|
99
|
+
tagger = self.tagger
|
|
100
|
+
rulebook = self.rulebook
|
|
101
|
+
if rulebook is None and getattr(tagger, "default_rulebook", None) is None:
|
|
102
|
+
raise ValueError(f"the redefiner component needs a rulebook: {self.model} has no default rulebook. Pass "
|
|
103
|
+
'"rulebook" in the config, or use a model page that has one, such as '
|
|
104
|
+
'"jungroo-ai/redefiner-pii"')
|
|
105
|
+
found = tagger.extract([doc.text for doc in docs], rulebook, threshold=self.threshold,
|
|
106
|
+
none_bias=self.none_bias, batch_size=self.batch_size)
|
|
107
|
+
for doc, spans in zip(docs, found):
|
|
108
|
+
self._set(doc, spans)
|
|
109
|
+
return docs
|
|
110
|
+
|
|
111
|
+
def _set(self, doc: Doc, spans) -> None:
|
|
112
|
+
new: list[Span] = []
|
|
113
|
+
for s in spans:
|
|
114
|
+
if s["confidence"] < self.min_confidence:
|
|
115
|
+
continue
|
|
116
|
+
span = doc.char_span(s["start"], s["end"], label=s["label"], alignment_mode=self.alignment_mode)
|
|
117
|
+
if span is None: # only with alignment_mode="strict", when the span does not match token boundaries
|
|
118
|
+
continue
|
|
119
|
+
span._.set(CONFIDENCE, s["confidence"])
|
|
120
|
+
new.append(span)
|
|
121
|
+
if self.spans_key:
|
|
122
|
+
doc.spans[self.spans_key] = SpanGroup(doc, name=self.spans_key, spans=new,
|
|
123
|
+
attrs={"scores": [span._.get(CONFIDENCE) for span in new]})
|
|
124
|
+
return
|
|
125
|
+
new = filter_spans(new)
|
|
126
|
+
if self.overwrite_ents or not doc.ents:
|
|
127
|
+
doc.ents = new
|
|
128
|
+
return
|
|
129
|
+
taken = {i for ent in doc.ents for i in range(ent.start, ent.end)}
|
|
130
|
+
added = [span for span in new if not any(i in taken for i in range(span.start, span.end))]
|
|
131
|
+
doc.ents = sorted(list(doc.ents) + added, key=lambda span: span.start)
|
|
132
|
+
|
|
133
|
+
def to_disk(self, path, exclude=()) -> None:
|
|
134
|
+
"""Save the rulebook text with the pipeline, so a saved pipeline does not depend on a rulebook file path."""
|
|
135
|
+
path = Path(path)
|
|
136
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
137
|
+
if self.rulebook is not None:
|
|
138
|
+
(path / RULEBOOK_FILE).write_text(self.rulebook, encoding="utf-8")
|
|
139
|
+
|
|
140
|
+
def from_disk(self, path, exclude=()) -> ReDefiNERComponent:
|
|
141
|
+
file = Path(path) / RULEBOOK_FILE
|
|
142
|
+
if file.is_file():
|
|
143
|
+
self._rulebook = file.read_text(encoding="utf-8")
|
|
144
|
+
return self
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@Language.factory(
|
|
148
|
+
"redefiner",
|
|
149
|
+
default_config={"model": DEFAULT_MODEL, "rulebook": None, "spans_key": None, "threshold": None,
|
|
150
|
+
"none_bias": None, "min_confidence": 0.0, "max_span_tokens": None, "device": None,
|
|
151
|
+
"revision": None, "batch_size": 16, "alignment_mode": "expand", "overwrite_ents": True},
|
|
152
|
+
assigns=["doc.ents", "doc.spans"],
|
|
153
|
+
)
|
|
154
|
+
def make_redefiner(nlp: Language, name: str, model: str, rulebook: str | None, spans_key: str | None,
|
|
155
|
+
threshold: float | None, none_bias: float | None, min_confidence: float,
|
|
156
|
+
max_span_tokens: int | None, device: str | None, revision: str | None, batch_size: int,
|
|
157
|
+
alignment_mode: str, overwrite_ents: bool) -> ReDefiNERComponent:
|
|
158
|
+
return ReDefiNERComponent(nlp, name, model=model, rulebook=rulebook, spans_key=spans_key, threshold=threshold,
|
|
159
|
+
none_bias=none_bias, min_confidence=min_confidence, max_span_tokens=max_span_tokens,
|
|
160
|
+
device=device, revision=revision, batch_size=batch_size, alignment_mode=alignment_mode,
|
|
161
|
+
overwrite_ents=overwrite_ents)
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: spacy-redefiner
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A spaCy component that finds the entities you define in a plain-English rulebook, using ReDefiNER.
|
|
5
|
+
Author: Sethuraman T A, Jungroo AI Labs
|
|
6
|
+
Author-email: Cibe Hariharan K <cibe@jungroo.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: Homepage, https://github.com/Jungroo-AI/spacy-redefiner
|
|
9
|
+
Project-URL: Repository, https://github.com/Jungroo-AI/spacy-redefiner
|
|
10
|
+
Project-URL: Issues, https://github.com/Jungroo-AI/spacy-redefiner/issues
|
|
11
|
+
Project-URL: ReDefiNER, https://github.com/jungroo-ai/redefiner
|
|
12
|
+
Keywords: spacy,spacy-extension,named-entity-recognition,ner,entity-extraction,rulebook,pii,redefiner
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
18
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: spacy<4,>=3.7
|
|
23
|
+
Requires-Dist: redefiner>=1.0.9
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest; extra == "dev"
|
|
26
|
+
Requires-Dist: ruff; extra == "dev"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# spacy-redefiner
|
|
30
|
+
|
|
31
|
+
A [spaCy](https://spacy.io) pipeline component that finds the entities you define in a plain-English rulebook, using
|
|
32
|
+
[ReDefiNER](https://github.com/jungroo-ai/redefiner).
|
|
33
|
+
|
|
34
|
+
ReDefiNER is an open model (0.8B parameters, Apache 2.0) that marks the spans of text a rulebook defines: entity
|
|
35
|
+
types, a one-line description each, and optional rules. To change what is found, edit the rulebook; no training data
|
|
36
|
+
and no retraining. It is non-generative, runs on CPU or GPU, and supports English only.
|
|
37
|
+
|
|
38
|
+
## Install
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install spacy-redefiner
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The first document downloads the model weights (about 0.8 GB) from Hugging Face.
|
|
45
|
+
|
|
46
|
+
## Quickstart
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import spacy
|
|
50
|
+
|
|
51
|
+
RULEBOOK = """[TYPE] PERSON
|
|
52
|
+
[DESCRIPTION] A person's name.
|
|
53
|
+
|
|
54
|
+
[TYPE] ORGANIZATION
|
|
55
|
+
[DESCRIPTION] A company, institution or society.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
nlp = spacy.blank("en")
|
|
59
|
+
nlp.add_pipe("redefiner", config={"rulebook": RULEBOOK})
|
|
60
|
+
doc = nlp("Ada Lovelace corresponded with the Royal Society.")
|
|
61
|
+
print([(ent.text, ent.label_, ent._.redefiner_confidence) for ent in doc.ents])
|
|
62
|
+
# [('Ada Lovelace', 'PERSON', 0.99), ('Royal Society', 'ORGANIZATION', 0.891)]
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The component also works after a trained spaCy pipeline, for example `spacy.load("en_core_web_sm")`. By default it
|
|
66
|
+
replaces the pipeline's entities; set `overwrite_ents` to `false` to keep them and add only new, non-overlapping ones.
|
|
67
|
+
|
|
68
|
+
## Personal data
|
|
69
|
+
|
|
70
|
+
[`jungroo-ai/redefiner-pii`](https://huggingface.co/jungroo-ai/redefiner-pii) holds a ready-made PII rulebook (20
|
|
71
|
+
types) and its settings. With it, no rulebook is needed:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
nlp = spacy.blank("en")
|
|
75
|
+
nlp.add_pipe("redefiner", config={"model": "jungroo-ai/redefiner-pii"})
|
|
76
|
+
doc = nlp("Call Meera Nair on 020 7946 0155 or write to meera.nair@example.org.")
|
|
77
|
+
print([(ent.text, ent.label_) for ent in doc.ents])
|
|
78
|
+
# [('Meera Nair', 'PERSON'), ('020 7946 0155', 'PHONE'), ('meera.nair@example.org', 'EMAIL')]
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The model can miss personal data and can mark text that is not personal. Check its output on your own documents
|
|
82
|
+
before relying on it, and don't use it as the only safeguard.
|
|
83
|
+
|
|
84
|
+
## Writing a rulebook
|
|
85
|
+
|
|
86
|
+
A rulebook has one `[TYPE]` section per entity type with a `[DESCRIPTION]` line, and can add rule lines, a `[RULES]`
|
|
87
|
+
section for rules that apply to every type, and a `[TYPE] NOT_AN_ENTITY` section for what must never be found.
|
|
88
|
+
Descriptions matter: one line per type does much better than type names alone. See the
|
|
89
|
+
[rulebook guide](https://github.com/jungroo-ai/redefiner/blob/main/docs/writing-rules.md) and the
|
|
90
|
+
[templates](https://github.com/jungroo-ai/redefiner/tree/main/docs/templates).
|
|
91
|
+
|
|
92
|
+
`rulebook` takes the rulebook text or the path of a rulebook file.
|
|
93
|
+
|
|
94
|
+
## Settings
|
|
95
|
+
|
|
96
|
+
| Setting | Default | Meaning |
|
|
97
|
+
|---|---|---|
|
|
98
|
+
| `model` | `"jungroo-ai/redefiner-0.8b"` | A Hugging Face repo or local folder. A page such as `jungroo-ai/redefiner-pii` brings its own rulebook and settings |
|
|
99
|
+
| `rulebook` | `null` | Rulebook text or a file path. Needed unless the model page has a default rulebook |
|
|
100
|
+
| `spans_key` | `null` | Write the spans to `doc.spans[spans_key]` instead of `doc.ents` |
|
|
101
|
+
| `overwrite_ents` | `true` | With `doc.ents`: replace existing entities, or (`false`) keep them and add non-overlapping spans |
|
|
102
|
+
| `min_confidence` | `0.0` | Drop spans below this confidence |
|
|
103
|
+
| `threshold` | model default (0.5) | Span score needed before a span gets a type |
|
|
104
|
+
| `none_bias` | model default (2) | Higher finds more borderline spans |
|
|
105
|
+
| `max_span_tokens` | model default | Longest span in model tokens (16 by default; 64 on the PII page). Raise it for long IDs or URLs |
|
|
106
|
+
| `device` | `null` | `"cpu"`, `"cuda"` or `"cuda:N"`; default: a GPU when PyTorch can use one |
|
|
107
|
+
| `revision` | `null` | Hugging Face revision of the model |
|
|
108
|
+
| `batch_size` | `16` | Texts per model forward pass |
|
|
109
|
+
| `alignment_mode` | `"expand"` | How model spans snap to spaCy tokens: `"strict"`, `"contract"` or `"expand"` |
|
|
110
|
+
|
|
111
|
+
In a spaCy config file:
|
|
112
|
+
|
|
113
|
+
```ini
|
|
114
|
+
[components.redefiner]
|
|
115
|
+
factory = "redefiner"
|
|
116
|
+
rulebook = "rules/contracts.txt"
|
|
117
|
+
spans_key = "redefiner"
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Output
|
|
121
|
+
|
|
122
|
+
- `doc.ents`, or `doc.spans[spans_key]` when a key is set.
|
|
123
|
+
- Each span's confidence is in `span._.redefiner_confidence`. A span group also keeps the confidences in
|
|
124
|
+
`group.attrs["scores"]`, as spaCy's span categorizer does.
|
|
125
|
+
- `nlp.to_disk()` saves the rulebook text with the pipeline, so a saved pipeline does not depend on the rulebook file.
|
|
126
|
+
- Components with the same model and settings share one loaded model.
|
|
127
|
+
|
|
128
|
+
## Speed and limits
|
|
129
|
+
|
|
130
|
+
- On an Apple M2 CPU, the first document with a new rulebook took about 7 seconds while the rulebook was read; it is
|
|
131
|
+
then cached, and later short texts take under a second. A GPU is much faster for large batches.
|
|
132
|
+
- English only.
|
|
133
|
+
- Long texts are read in parts of 256 tokens, so the same name can get different labels in different parts.
|
|
134
|
+
- Rules that go against what the model already knows, such as calling a person's name something other than a person,
|
|
135
|
+
are mostly ignored. Try a rulebook on a few dozen of your own texts first.
|
|
136
|
+
|
|
137
|
+
## Development
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
pip install -e ".[dev]"
|
|
141
|
+
pytest # fast tests with a fake model
|
|
142
|
+
pytest -m slow # the real model on CPU
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Licence
|
|
146
|
+
|
|
147
|
+
Apache License 2.0. See [LICENSE](LICENSE). Made by [Jungroo AI Labs](https://jungroo.com).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/spacy_redefiner/__init__.py
|
|
5
|
+
src/spacy_redefiner/component.py
|
|
6
|
+
src/spacy_redefiner.egg-info/PKG-INFO
|
|
7
|
+
src/spacy_redefiner.egg-info/SOURCES.txt
|
|
8
|
+
src/spacy_redefiner.egg-info/dependency_links.txt
|
|
9
|
+
src/spacy_redefiner.egg-info/entry_points.txt
|
|
10
|
+
src/spacy_redefiner.egg-info/requires.txt
|
|
11
|
+
src/spacy_redefiner.egg-info/top_level.txt
|
|
12
|
+
tests/test_component.py
|
|
13
|
+
tests/test_slow.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
spacy_redefiner
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import spacy
|
|
3
|
+
from conftest import RULEBOOK, TEXT, FakeTagger, span
|
|
4
|
+
|
|
5
|
+
from spacy_redefiner import component
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def make(**config):
|
|
9
|
+
nlp = spacy.blank("en")
|
|
10
|
+
nlp.add_pipe("redefiner", config={"rulebook": RULEBOOK, **config})
|
|
11
|
+
return nlp
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_spans_go_to_doc_ents_with_their_confidence(fake):
|
|
15
|
+
doc = make()(TEXT)
|
|
16
|
+
assert [(e.text, e.label_, e._.redefiner_confidence) for e in doc.ents] == [
|
|
17
|
+
("Ada Lovelace", "PERSON", 0.99), ("Royal Society", "ORGANIZATION", 0.42)]
|
|
18
|
+
assert fake.calls[0]["rulebook"] == RULEBOOK
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_settings_are_passed_to_the_model(fake):
|
|
22
|
+
make(threshold=0.4, none_bias=3.0)(TEXT)
|
|
23
|
+
assert fake.calls[0]["threshold"] == 0.4 and fake.calls[0]["none_bias"] == 3.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_min_confidence_drops_low_confidence_spans(fake):
|
|
27
|
+
doc = make(min_confidence=0.5)(TEXT)
|
|
28
|
+
assert [e.text for e in doc.ents] == ["Ada Lovelace"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_spans_key_writes_a_span_group_and_leaves_ents_alone(fake):
|
|
32
|
+
doc = make(spans_key="rd")(TEXT)
|
|
33
|
+
assert [(s.text, s.label_) for s in doc.spans["rd"]] == [("Ada Lovelace", "PERSON"), ("Royal Society", "ORGANIZATION")]
|
|
34
|
+
assert doc.spans["rd"].attrs["scores"] == [0.99, 0.42]
|
|
35
|
+
assert doc.ents == ()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_keeping_existing_ents_adds_only_non_overlapping_spans(fake):
|
|
39
|
+
nlp = spacy.blank("en")
|
|
40
|
+
ruler = nlp.add_pipe("entity_ruler")
|
|
41
|
+
ruler.add_patterns([{"label": "SOCIETY", "pattern": "Royal Society"}])
|
|
42
|
+
nlp.add_pipe("redefiner", config={"rulebook": RULEBOOK, "overwrite_ents": False})
|
|
43
|
+
doc = nlp(TEXT)
|
|
44
|
+
assert [(e.text, e.label_) for e in doc.ents] == [("Ada Lovelace", "PERSON"), ("Royal Society", "SOCIETY")]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_overwriting_replaces_existing_ents(fake):
|
|
48
|
+
nlp = spacy.blank("en")
|
|
49
|
+
ruler = nlp.add_pipe("entity_ruler")
|
|
50
|
+
ruler.add_patterns([{"label": "SOCIETY", "pattern": "Royal Society"}])
|
|
51
|
+
nlp.add_pipe("redefiner", config={"rulebook": RULEBOOK})
|
|
52
|
+
assert [e.label_ for e in nlp(TEXT).ents] == ["PERSON", "ORGANIZATION"]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_alignment_strict_drops_spans_off_token_boundaries_and_expand_widens_them(monkeypatch):
|
|
56
|
+
text = "Mail ada@example.org now."
|
|
57
|
+
tagger = FakeTagger({text: [{"start": 5, "end": 8, "text": "ada", "label": "EMAIL", "confidence": 0.9}]})
|
|
58
|
+
monkeypatch.setattr(component, "shared_tagger", lambda *a, **k: tagger)
|
|
59
|
+
assert make(alignment_mode="strict")(text).ents == ()
|
|
60
|
+
assert [e.text for e in make(alignment_mode="expand")(text).ents] == ["ada@example.org"]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_pipe_sends_one_model_call_per_spacy_batch(fake):
|
|
64
|
+
texts = [TEXT, "Nothing here.", TEXT]
|
|
65
|
+
docs = list(make().pipe(texts, batch_size=2))
|
|
66
|
+
assert [len(c["texts"]) for c in fake.calls] == [2, 1]
|
|
67
|
+
assert [len(d.ents) for d in docs] == [2, 0, 2]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_rulebook_can_be_a_file_path(fake, tmp_path):
|
|
71
|
+
path = tmp_path / "rules.txt"
|
|
72
|
+
path.write_text(RULEBOOK, encoding="utf-8")
|
|
73
|
+
make(rulebook=str(path))(TEXT)
|
|
74
|
+
assert fake.calls[0]["rulebook"] == RULEBOOK
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_a_missing_rulebook_file_is_an_error(fake, tmp_path):
|
|
78
|
+
with pytest.raises(ValueError, match="neither rulebook text"):
|
|
79
|
+
make(rulebook=str(tmp_path / "missing.txt"))(TEXT)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_a_model_without_a_default_rulebook_needs_one(fake):
|
|
83
|
+
nlp = spacy.blank("en")
|
|
84
|
+
nlp.add_pipe("redefiner")
|
|
85
|
+
with pytest.raises(ValueError, match="needs a rulebook"):
|
|
86
|
+
nlp(TEXT)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_a_pointer_page_default_rulebook_is_used_when_none_is_given(monkeypatch):
|
|
90
|
+
tagger = FakeTagger({TEXT: [span(TEXT, "Ada Lovelace", "PERSON", 0.99)]}, default_rulebook="[TYPE] PERSON")
|
|
91
|
+
monkeypatch.setattr(component, "shared_tagger", lambda *a, **k: tagger)
|
|
92
|
+
nlp = spacy.blank("en")
|
|
93
|
+
nlp.add_pipe("redefiner", config={"model": "jungroo-ai/redefiner-pii"})
|
|
94
|
+
assert [e.text for e in nlp(TEXT).ents] == ["Ada Lovelace"]
|
|
95
|
+
assert tagger.calls[0]["rulebook"] is None
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_a_saved_pipeline_keeps_its_rulebook_without_the_file(fake, tmp_path):
|
|
99
|
+
path = tmp_path / "rules.txt"
|
|
100
|
+
path.write_text(RULEBOOK, encoding="utf-8")
|
|
101
|
+
make(rulebook=str(path)).to_disk(tmp_path / "pipeline")
|
|
102
|
+
path.unlink()
|
|
103
|
+
reloaded = spacy.load(tmp_path / "pipeline")
|
|
104
|
+
reloaded(TEXT)
|
|
105
|
+
assert fake.calls[-1]["rulebook"] == RULEBOOK
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@pytest.mark.parametrize("config", [{"alignment_mode": "loose"}, {"batch_size": 0}])
|
|
109
|
+
def test_bad_settings_are_rejected(config):
|
|
110
|
+
with pytest.raises(ValueError):
|
|
111
|
+
make(**config)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_empty_text_gives_no_entities(monkeypatch):
|
|
115
|
+
tagger = FakeTagger({})
|
|
116
|
+
monkeypatch.setattr(component, "shared_tagger", lambda *a, **k: tagger)
|
|
117
|
+
assert make()("").ents == ()
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Slow tests: the real model on CPU (about 0.8 GB of weights, downloaded once). Run with `pytest -m slow`."""
|
|
2
|
+
import pytest
|
|
3
|
+
import spacy
|
|
4
|
+
from conftest import RULEBOOK, TEXT
|
|
5
|
+
|
|
6
|
+
pytestmark = pytest.mark.slow
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_real_model_with_a_rulebook():
|
|
10
|
+
nlp = spacy.blank("en")
|
|
11
|
+
nlp.add_pipe("redefiner", config={"rulebook": RULEBOOK, "device": "cpu"})
|
|
12
|
+
doc = nlp(TEXT)
|
|
13
|
+
assert [(e.text, e.label_) for e in doc.ents] == [("Ada Lovelace", "PERSON"), ("Royal Society", "ORGANIZATION")]
|
|
14
|
+
assert all(0 < e._.redefiner_confidence <= 1 for e in doc.ents)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_real_model_with_the_pii_page():
|
|
18
|
+
nlp = spacy.blank("en")
|
|
19
|
+
nlp.add_pipe("redefiner", config={"model": "jungroo-ai/redefiner-pii", "device": "cpu"})
|
|
20
|
+
doc = nlp("Call Meera Nair on 020 7946 0155 or write to meera.nair@example.org.")
|
|
21
|
+
assert [(e.text, e.label_) for e in doc.ents] == [
|
|
22
|
+
("Meera Nair", "PERSON"), ("020 7946 0155", "PHONE"), ("meera.nair@example.org", "EMAIL")]
|