Metadata-Version: 2.4
Name: spacy-redefiner
Version: 0.1.0
Summary: A spaCy component that finds the entities you define in a plain-English rulebook, using ReDefiNER.
Author: Sethuraman T A, Jungroo AI Labs
Author-email: Cibe Hariharan K <cibe@jungroo.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/Jungroo-AI/spacy-redefiner
Project-URL: Repository, https://github.com/Jungroo-AI/spacy-redefiner
Project-URL: Issues, https://github.com/Jungroo-AI/spacy-redefiner/issues
Project-URL: ReDefiNER, https://github.com/jungroo-ai/redefiner
Keywords: spacy,spacy-extension,named-entity-recognition,ner,entity-extraction,rulebook,pii,redefiner
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing :: Linguistic
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: spacy<4,>=3.7
Requires-Dist: redefiner>=1.0.9
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Dynamic: license-file

# spacy-redefiner

A [spaCy](https://spacy.io) pipeline component that finds the entities you define in a plain-English rulebook, using
[ReDefiNER](https://github.com/jungroo-ai/redefiner).

ReDefiNER is an open model (0.8B parameters, Apache 2.0) that marks the spans of text a rulebook defines: entity
types, a one-line description each, and optional rules. To change what is found, edit the rulebook; no training data
and no retraining. It is non-generative, runs on CPU or GPU, and supports English only.

## Install

```bash
pip install spacy-redefiner
```

The first document downloads the model weights (about 0.8 GB) from Hugging Face.

## Quickstart

```python
import spacy

RULEBOOK = """[TYPE] PERSON
[DESCRIPTION] A person's name.

[TYPE] ORGANIZATION
[DESCRIPTION] A company, institution or society.
"""

nlp = spacy.blank("en")
nlp.add_pipe("redefiner", config={"rulebook": RULEBOOK})
doc = nlp("Ada Lovelace corresponded with the Royal Society.")
print([(ent.text, ent.label_, ent._.redefiner_confidence) for ent in doc.ents])
# [('Ada Lovelace', 'PERSON', 0.99), ('Royal Society', 'ORGANIZATION', 0.891)]
```

The component also works after a trained spaCy pipeline, for example `spacy.load("en_core_web_sm")`. By default it
replaces the pipeline's entities; set `overwrite_ents` to `false` to keep them and add only new, non-overlapping ones.

## Personal data

[`jungroo-ai/redefiner-pii`](https://huggingface.co/jungroo-ai/redefiner-pii) holds a ready-made PII rulebook (20
types) and its settings. With it, no rulebook is needed:

```python
nlp = spacy.blank("en")
nlp.add_pipe("redefiner", config={"model": "jungroo-ai/redefiner-pii"})
doc = nlp("Call Meera Nair on 020 7946 0155 or write to meera.nair@example.org.")
print([(ent.text, ent.label_) for ent in doc.ents])
# [('Meera Nair', 'PERSON'), ('020 7946 0155', 'PHONE'), ('meera.nair@example.org', 'EMAIL')]
```

The model can miss personal data and can mark text that is not personal. Check its output on your own documents
before relying on it, and don't use it as the only safeguard.

## Writing a rulebook

A rulebook has one `[TYPE]` section per entity type with a `[DESCRIPTION]` line, and can add rule lines, a `[RULES]`
section for rules that apply to every type, and a `[TYPE] NOT_AN_ENTITY` section for what must never be found.
Descriptions matter: one line per type does much better than type names alone. See the
[rulebook guide](https://github.com/jungroo-ai/redefiner/blob/main/docs/writing-rules.md) and the
[templates](https://github.com/jungroo-ai/redefiner/tree/main/docs/templates).

`rulebook` takes the rulebook text or the path of a rulebook file.

## Settings

| Setting | Default | Meaning |
|---|---|---|
| `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 |
| `rulebook` | `null` | Rulebook text or a file path. Needed unless the model page has a default rulebook |
| `spans_key` | `null` | Write the spans to `doc.spans[spans_key]` instead of `doc.ents` |
| `overwrite_ents` | `true` | With `doc.ents`: replace existing entities, or (`false`) keep them and add non-overlapping spans |
| `min_confidence` | `0.0` | Drop spans below this confidence |
| `threshold` | model default (0.5) | Span score needed before a span gets a type |
| `none_bias` | model default (2) | Higher finds more borderline spans |
| `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 |
| `device` | `null` | `"cpu"`, `"cuda"` or `"cuda:N"`; default: a GPU when PyTorch can use one |
| `revision` | `null` | Hugging Face revision of the model |
| `batch_size` | `16` | Texts per model forward pass |
| `alignment_mode` | `"expand"` | How model spans snap to spaCy tokens: `"strict"`, `"contract"` or `"expand"` |

In a spaCy config file:

```ini
[components.redefiner]
factory = "redefiner"
rulebook = "rules/contracts.txt"
spans_key = "redefiner"
```

## Output

- `doc.ents`, or `doc.spans[spans_key]` when a key is set.
- Each span's confidence is in `span._.redefiner_confidence`. A span group also keeps the confidences in
  `group.attrs["scores"]`, as spaCy's span categorizer does.
- `nlp.to_disk()` saves the rulebook text with the pipeline, so a saved pipeline does not depend on the rulebook file.
- Components with the same model and settings share one loaded model.

## Speed and limits

- On an Apple M2 CPU, the first document with a new rulebook took about 7 seconds while the rulebook was read; it is
  then cached, and later short texts take under a second. A GPU is much faster for large batches.
- English only.
- Long texts are read in parts of 256 tokens, so the same name can get different labels in different parts.
- Rules that go against what the model already knows, such as calling a person's name something other than a person,
  are mostly ignored. Try a rulebook on a few dozen of your own texts first.

## Development

```bash
pip install -e ".[dev]"
pytest              # fast tests with a fake model
pytest -m slow      # the real model on CPU
```

## Licence

Apache License 2.0. See [LICENSE](LICENSE). Made by [Jungroo AI Labs](https://jungroo.com).
