2020-07-22 14:42:59 +03:00
|
|
|
from typing import Optional, Union, List, Dict, Tuple, Iterable, Any
|
2019-12-22 03:53:56 +03:00
|
|
|
from collections import defaultdict
|
2020-07-22 14:42:59 +03:00
|
|
|
from pathlib import Path
|
2019-02-10 14:14:51 +03:00
|
|
|
import srsly
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
from ..language import Language
|
2019-02-10 14:14:51 +03:00
|
|
|
from ..errors import Errors
|
2020-08-29 16:20:11 +03:00
|
|
|
from ..util import ensure_path, to_disk, from_disk, SimpleFrozenList
|
2020-02-16 20:17:47 +03:00
|
|
|
from ..tokens import Doc, Span
|
2019-02-10 14:14:51 +03:00
|
|
|
from ..matcher import Matcher, PhraseMatcher
|
2020-07-27 16:08:51 +03:00
|
|
|
from ..scorer import Scorer
|
2020-09-09 11:31:03 +03:00
|
|
|
from ..training import validate_examples
|
2019-07-08 18:28:28 +03:00
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
|
2019-07-10 13:03:05 +03:00
|
|
|
DEFAULT_ENT_ID_SEP = "||"
|
2020-07-22 14:42:59 +03:00
|
|
|
PatternType = Dict[str, Union[str, List[Dict[str, Any]]]]
|
|
|
|
|
|
|
|
|
|
|
|
@Language.factory(
|
|
|
|
"entity_ruler",
|
|
|
|
assigns=["doc.ents", "token.ent_type", "token.ent_iob"],
|
|
|
|
default_config={
|
|
|
|
"phrase_matcher_attr": None,
|
2020-08-07 15:43:47 +03:00
|
|
|
"validate": False,
|
2020-07-22 14:42:59 +03:00
|
|
|
"overwrite_ents": False,
|
|
|
|
"ent_id_sep": DEFAULT_ENT_ID_SEP,
|
|
|
|
},
|
2020-07-27 13:27:40 +03:00
|
|
|
scores=["ents_p", "ents_r", "ents_f", "ents_per_type"],
|
|
|
|
default_score_weights={"ents_f": 1.0, "ents_p": 0.0, "ents_r": 0.0},
|
2020-07-22 14:42:59 +03:00
|
|
|
)
|
|
|
|
def make_entity_ruler(
|
|
|
|
nlp: Language,
|
|
|
|
name: str,
|
|
|
|
phrase_matcher_attr: Optional[Union[int, str]],
|
2020-08-07 15:43:47 +03:00
|
|
|
validate: bool,
|
2020-07-22 14:42:59 +03:00
|
|
|
overwrite_ents: bool,
|
|
|
|
ent_id_sep: str,
|
|
|
|
):
|
|
|
|
return EntityRuler(
|
|
|
|
nlp,
|
|
|
|
name,
|
|
|
|
phrase_matcher_attr=phrase_matcher_attr,
|
2020-08-07 15:43:47 +03:00
|
|
|
validate=validate,
|
2020-07-22 14:42:59 +03:00
|
|
|
overwrite_ents=overwrite_ents,
|
|
|
|
ent_id_sep=ent_id_sep,
|
|
|
|
)
|
2019-07-08 18:28:28 +03:00
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
|
2020-07-12 15:03:23 +03:00
|
|
|
class EntityRuler:
|
2019-03-08 13:42:26 +03:00
|
|
|
"""The EntityRuler lets you add spans to the `Doc.ents` using token-based
|
|
|
|
rules or exact phrase matches. It can be combined with the statistical
|
|
|
|
`EntityRecognizer` to boost accuracy, or used on its own to implement a
|
|
|
|
purely rule-based entity recognition system. After initialization, the
|
|
|
|
component is typically added to the pipeline using `nlp.add_pipe`.
|
|
|
|
|
2020-09-04 13:58:50 +03:00
|
|
|
DOCS: https://nightly.spacy.io/api/entityruler
|
|
|
|
USAGE: https://nightly.spacy.io/usage/rule-based-matching#entityruler
|
2019-03-08 13:42:26 +03:00
|
|
|
"""
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
nlp: Language,
|
|
|
|
name: str = "entity_ruler",
|
|
|
|
*,
|
|
|
|
phrase_matcher_attr: Optional[Union[int, str]] = None,
|
|
|
|
validate: bool = False,
|
|
|
|
overwrite_ents: bool = False,
|
|
|
|
ent_id_sep: str = DEFAULT_ENT_ID_SEP,
|
|
|
|
patterns: Optional[List[PatternType]] = None,
|
2020-07-25 16:01:15 +03:00
|
|
|
) -> None:
|
2020-08-26 16:24:33 +03:00
|
|
|
"""Initialize the entity ruler. If patterns are supplied here, they
|
2019-02-10 14:14:51 +03:00
|
|
|
need to be a list of dictionaries with a `"label"` and `"pattern"`
|
|
|
|
key. A pattern can either be a token pattern (list) or a phrase pattern
|
|
|
|
(string). For example: `{'label': 'ORG', 'pattern': 'Apple'}`.
|
|
|
|
|
|
|
|
nlp (Language): The shared nlp object to pass the vocab to the matchers
|
|
|
|
and process phrase patterns.
|
2020-07-27 19:11:45 +03:00
|
|
|
name (str): Instance name of the current pipeline component. Typically
|
|
|
|
passed in automatically from the factory when the component is
|
|
|
|
added. Used to disable the current entity ruler while creating
|
|
|
|
phrase patterns with the nlp object.
|
2020-05-24 19:51:10 +03:00
|
|
|
phrase_matcher_attr (int / str): Token attribute to match on, passed
|
2019-07-09 21:09:17 +03:00
|
|
|
to the internal PhraseMatcher as `attr`
|
2019-08-07 01:40:53 +03:00
|
|
|
validate (bool): Whether patterns should be validated, passed to
|
|
|
|
Matcher and PhraseMatcher as `validate`
|
2019-02-10 14:14:51 +03:00
|
|
|
patterns (iterable): Optional patterns to load in.
|
|
|
|
overwrite_ents (bool): If existing entities are present, e.g. entities
|
|
|
|
added by the model, overwrite them by matches if necessary.
|
2020-07-22 14:42:59 +03:00
|
|
|
ent_id_sep (str): Separator used internally for entity IDs.
|
2019-10-25 12:19:46 +03:00
|
|
|
|
2020-09-04 13:58:50 +03:00
|
|
|
DOCS: https://nightly.spacy.io/api/entityruler#init
|
2019-02-10 14:14:51 +03:00
|
|
|
"""
|
|
|
|
self.nlp = nlp
|
2020-07-22 14:42:59 +03:00
|
|
|
self.name = name
|
|
|
|
self.overwrite = overwrite_ents
|
2019-02-10 14:14:51 +03:00
|
|
|
self.token_patterns = defaultdict(list)
|
|
|
|
self.phrase_patterns = defaultdict(list)
|
2019-08-07 01:40:53 +03:00
|
|
|
self.matcher = Matcher(nlp.vocab, validate=validate)
|
2019-07-09 21:09:17 +03:00
|
|
|
if phrase_matcher_attr is not None:
|
2019-08-21 15:00:37 +03:00
|
|
|
if phrase_matcher_attr.upper() == "TEXT":
|
|
|
|
phrase_matcher_attr = "ORTH"
|
2019-07-09 21:09:17 +03:00
|
|
|
self.phrase_matcher_attr = phrase_matcher_attr
|
2019-07-10 13:03:05 +03:00
|
|
|
self.phrase_matcher = PhraseMatcher(
|
2019-08-07 01:40:53 +03:00
|
|
|
nlp.vocab, attr=self.phrase_matcher_attr, validate=validate
|
2019-07-10 13:03:05 +03:00
|
|
|
)
|
2019-07-09 21:09:17 +03:00
|
|
|
else:
|
|
|
|
self.phrase_matcher_attr = None
|
2019-08-07 01:40:53 +03:00
|
|
|
self.phrase_matcher = PhraseMatcher(nlp.vocab, validate=validate)
|
2020-07-22 14:42:59 +03:00
|
|
|
self.ent_id_sep = ent_id_sep
|
2019-10-25 12:16:42 +03:00
|
|
|
self._ent_ids = defaultdict(dict)
|
2019-02-10 14:14:51 +03:00
|
|
|
if patterns is not None:
|
|
|
|
self.add_patterns(patterns)
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def __len__(self) -> int:
|
2019-02-10 14:14:51 +03:00
|
|
|
"""The number of all patterns added to the entity ruler."""
|
|
|
|
n_token_patterns = sum(len(p) for p in self.token_patterns.values())
|
|
|
|
n_phrase_patterns = sum(len(p) for p in self.phrase_patterns.values())
|
|
|
|
return n_token_patterns + n_phrase_patterns
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def __contains__(self, label: str) -> bool:
|
2019-02-10 14:14:51 +03:00
|
|
|
"""Whether a label is present in the patterns."""
|
|
|
|
return label in self.token_patterns or label in self.phrase_patterns
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def __call__(self, doc: Doc) -> Doc:
|
2019-02-10 14:14:51 +03:00
|
|
|
"""Find matches in document and add them as entities.
|
|
|
|
|
|
|
|
doc (Doc): The Doc object in the pipeline.
|
2019-10-25 12:16:42 +03:00
|
|
|
RETURNS (Doc): The Doc with added entities, if available.
|
2019-10-25 12:19:46 +03:00
|
|
|
|
2020-09-04 13:58:50 +03:00
|
|
|
DOCS: https://nightly.spacy.io/api/entityruler#call
|
2019-02-10 14:14:51 +03:00
|
|
|
"""
|
|
|
|
matches = list(self.matcher(doc)) + list(self.phrase_matcher(doc))
|
|
|
|
matches = set(
|
|
|
|
[(m_id, start, end) for m_id, start, end in matches if start != end]
|
|
|
|
)
|
2020-07-31 17:09:32 +03:00
|
|
|
get_sort_key = lambda m: (m[2] - m[1], -m[1])
|
2019-02-10 14:14:51 +03:00
|
|
|
matches = sorted(matches, key=get_sort_key, reverse=True)
|
|
|
|
entities = list(doc.ents)
|
|
|
|
new_entities = []
|
|
|
|
seen_tokens = set()
|
|
|
|
for match_id, start, end in matches:
|
|
|
|
if any(t.ent_type for t in doc[start:end]) and not self.overwrite:
|
|
|
|
continue
|
|
|
|
# check for end - 1 here because boundaries are inclusive
|
|
|
|
if start not in seen_tokens and end - 1 not in seen_tokens:
|
2019-10-25 12:16:42 +03:00
|
|
|
if match_id in self._ent_ids:
|
|
|
|
label, ent_id = self._ent_ids[match_id]
|
|
|
|
span = Span(doc, start, end, label=label)
|
2019-06-16 14:29:04 +03:00
|
|
|
if ent_id:
|
|
|
|
for token in span:
|
|
|
|
token.ent_id_ = ent_id
|
|
|
|
else:
|
|
|
|
span = Span(doc, start, end, label=match_id)
|
|
|
|
new_entities.append(span)
|
2019-02-10 14:14:51 +03:00
|
|
|
entities = [
|
|
|
|
e for e in entities if not (e.start < end and e.end > start)
|
|
|
|
]
|
|
|
|
seen_tokens.update(range(start, end))
|
|
|
|
doc.ents = entities + new_entities
|
|
|
|
return doc
|
|
|
|
|
|
|
|
@property
|
2020-07-22 14:42:59 +03:00
|
|
|
def labels(self) -> Tuple[str, ...]:
|
2019-02-10 14:14:51 +03:00
|
|
|
"""All labels present in the match patterns.
|
2019-10-25 12:25:44 +03:00
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
RETURNS (set): The string labels.
|
2019-10-25 12:19:46 +03:00
|
|
|
|
2020-09-04 13:58:50 +03:00
|
|
|
DOCS: https://nightly.spacy.io/api/entityruler#labels
|
2019-02-10 14:14:51 +03:00
|
|
|
"""
|
2020-01-16 04:01:31 +03:00
|
|
|
keys = set(self.token_patterns.keys())
|
|
|
|
keys.update(self.phrase_patterns.keys())
|
|
|
|
all_labels = set()
|
|
|
|
|
|
|
|
for l in keys:
|
|
|
|
if self.ent_id_sep in l:
|
|
|
|
label, _ = self._split_label(l)
|
|
|
|
all_labels.add(label)
|
|
|
|
else:
|
|
|
|
all_labels.add(l)
|
2019-02-14 22:03:19 +03:00
|
|
|
return tuple(all_labels)
|
2019-02-10 14:14:51 +03:00
|
|
|
|
2019-06-16 14:29:04 +03:00
|
|
|
@property
|
2020-07-22 14:42:59 +03:00
|
|
|
def ent_ids(self) -> Tuple[str, ...]:
|
2020-01-16 04:01:31 +03:00
|
|
|
"""All entity ids present in the match patterns `id` properties
|
2019-10-25 12:25:44 +03:00
|
|
|
|
2019-06-16 14:29:04 +03:00
|
|
|
RETURNS (set): The string entity ids.
|
2019-10-25 12:19:46 +03:00
|
|
|
|
2020-09-04 13:58:50 +03:00
|
|
|
DOCS: https://nightly.spacy.io/api/entityruler#ent_ids
|
2019-06-16 14:29:04 +03:00
|
|
|
"""
|
2020-01-16 04:01:31 +03:00
|
|
|
keys = set(self.token_patterns.keys())
|
|
|
|
keys.update(self.phrase_patterns.keys())
|
2019-06-16 14:29:04 +03:00
|
|
|
all_ent_ids = set()
|
2020-01-16 04:01:31 +03:00
|
|
|
|
|
|
|
for l in keys:
|
2019-06-16 14:29:04 +03:00
|
|
|
if self.ent_id_sep in l:
|
|
|
|
_, ent_id = self._split_label(l)
|
|
|
|
all_ent_ids.add(ent_id)
|
|
|
|
return tuple(all_ent_ids)
|
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
@property
|
2020-07-22 14:42:59 +03:00
|
|
|
def patterns(self) -> List[PatternType]:
|
2019-02-10 14:14:51 +03:00
|
|
|
"""Get all patterns that were added to the entity ruler.
|
2020-02-16 20:17:47 +03:00
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
RETURNS (list): The original patterns, one dictionary per pattern.
|
2019-10-25 12:19:46 +03:00
|
|
|
|
2020-09-04 13:58:50 +03:00
|
|
|
DOCS: https://nightly.spacy.io/api/entityruler#patterns
|
2019-02-10 14:14:51 +03:00
|
|
|
"""
|
|
|
|
all_patterns = []
|
|
|
|
for label, patterns in self.token_patterns.items():
|
|
|
|
for pattern in patterns:
|
2019-06-16 14:29:04 +03:00
|
|
|
ent_label, ent_id = self._split_label(label)
|
|
|
|
p = {"label": ent_label, "pattern": pattern}
|
|
|
|
if ent_id:
|
|
|
|
p["id"] = ent_id
|
|
|
|
all_patterns.append(p)
|
2019-02-10 14:14:51 +03:00
|
|
|
for label, patterns in self.phrase_patterns.items():
|
|
|
|
for pattern in patterns:
|
2019-06-16 14:29:04 +03:00
|
|
|
ent_label, ent_id = self._split_label(label)
|
|
|
|
p = {"label": ent_label, "pattern": pattern.text}
|
|
|
|
if ent_id:
|
|
|
|
p["id"] = ent_id
|
|
|
|
all_patterns.append(p)
|
2019-02-10 14:14:51 +03:00
|
|
|
return all_patterns
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def add_patterns(self, patterns: List[PatternType]) -> None:
|
2020-08-26 16:24:33 +03:00
|
|
|
"""Add patterns to the entity ruler. A pattern can either be a token
|
2019-02-10 14:14:51 +03:00
|
|
|
pattern (list of dicts) or a phrase pattern (string). For example:
|
|
|
|
{'label': 'ORG', 'pattern': 'Apple'}
|
|
|
|
{'label': 'GPE', 'pattern': [{'lower': 'san'}, {'lower': 'francisco'}]}
|
2019-10-25 12:19:46 +03:00
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
patterns (list): The patterns to add.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2020-09-04 13:58:50 +03:00
|
|
|
DOCS: https://nightly.spacy.io/api/entityruler#add_patterns
|
2019-02-10 14:14:51 +03:00
|
|
|
"""
|
2020-02-16 20:17:47 +03:00
|
|
|
|
2019-09-27 21:57:13 +03:00
|
|
|
# disable the nlp components after this one in case they hadn't been initialized / deserialised yet
|
|
|
|
try:
|
|
|
|
current_index = self.nlp.pipe_names.index(self.name)
|
2019-10-18 12:27:38 +03:00
|
|
|
subsequent_pipes = [
|
|
|
|
pipe for pipe in self.nlp.pipe_names[current_index + 1 :]
|
|
|
|
]
|
2019-09-27 21:57:13 +03:00
|
|
|
except ValueError:
|
|
|
|
subsequent_pipes = []
|
2020-05-18 23:27:10 +03:00
|
|
|
with self.nlp.select_pipes(disable=subsequent_pipes):
|
2020-02-16 20:17:47 +03:00
|
|
|
token_patterns = []
|
|
|
|
phrase_pattern_labels = []
|
|
|
|
phrase_pattern_texts = []
|
|
|
|
phrase_pattern_ids = []
|
2019-09-27 21:57:13 +03:00
|
|
|
for entry in patterns:
|
2020-02-18 16:47:23 +03:00
|
|
|
if isinstance(entry["pattern"], str):
|
2020-02-16 20:17:47 +03:00
|
|
|
phrase_pattern_labels.append(entry["label"])
|
|
|
|
phrase_pattern_texts.append(entry["pattern"])
|
|
|
|
phrase_pattern_ids.append(entry.get("id"))
|
|
|
|
elif isinstance(entry["pattern"], list):
|
|
|
|
token_patterns.append(entry)
|
|
|
|
phrase_patterns = []
|
|
|
|
for label, pattern, ent_id in zip(
|
|
|
|
phrase_pattern_labels,
|
|
|
|
self.nlp.pipe(phrase_pattern_texts),
|
2020-03-25 14:28:12 +03:00
|
|
|
phrase_pattern_ids,
|
2020-02-16 20:17:47 +03:00
|
|
|
):
|
2020-03-25 14:28:12 +03:00
|
|
|
phrase_pattern = {"label": label, "pattern": pattern, "id": ent_id}
|
2020-02-16 20:17:47 +03:00
|
|
|
if ent_id:
|
|
|
|
phrase_pattern["id"] = ent_id
|
|
|
|
phrase_patterns.append(phrase_pattern)
|
|
|
|
for entry in token_patterns + phrase_patterns:
|
2019-09-27 21:57:13 +03:00
|
|
|
label = entry["label"]
|
|
|
|
if "id" in entry:
|
2019-10-25 12:16:42 +03:00
|
|
|
ent_label = label
|
2019-09-27 21:57:13 +03:00
|
|
|
label = self._create_label(label, entry["id"])
|
2019-10-25 12:16:42 +03:00
|
|
|
key = self.matcher._normalize_key(label)
|
|
|
|
self._ent_ids[key] = (ent_label, entry["id"])
|
2019-09-27 21:57:13 +03:00
|
|
|
pattern = entry["pattern"]
|
2020-02-16 20:17:47 +03:00
|
|
|
if isinstance(pattern, Doc):
|
|
|
|
self.phrase_patterns[label].append(pattern)
|
2019-09-27 21:57:13 +03:00
|
|
|
elif isinstance(pattern, list):
|
|
|
|
self.token_patterns[label].append(pattern)
|
|
|
|
else:
|
|
|
|
raise ValueError(Errors.E097.format(pattern=pattern))
|
|
|
|
for label, patterns in self.token_patterns.items():
|
2019-10-25 23:21:08 +03:00
|
|
|
self.matcher.add(label, patterns)
|
2019-09-27 21:57:13 +03:00
|
|
|
for label, patterns in self.phrase_patterns.items():
|
2019-10-25 23:21:08 +03:00
|
|
|
self.phrase_matcher.add(label, patterns)
|
2019-02-10 14:14:51 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def clear(self) -> None:
|
|
|
|
"""Reset all patterns."""
|
|
|
|
self.token_patterns = defaultdict(list)
|
|
|
|
self.phrase_patterns = defaultdict(list)
|
|
|
|
self._ent_ids = defaultdict(dict)
|
|
|
|
|
|
|
|
def _split_label(self, label: str) -> Tuple[str, str]:
|
2019-06-16 14:29:04 +03:00
|
|
|
"""Split Entity label into ent_label and ent_id if it contains self.ent_id_sep
|
|
|
|
|
2020-02-16 20:17:47 +03:00
|
|
|
label (str): The value of label in a pattern entry
|
2019-06-16 14:29:04 +03:00
|
|
|
RETURNS (tuple): ent_label, ent_id
|
|
|
|
"""
|
|
|
|
if self.ent_id_sep in label:
|
|
|
|
ent_label, ent_id = label.rsplit(self.ent_id_sep, 1)
|
|
|
|
else:
|
|
|
|
ent_label = label
|
|
|
|
ent_id = None
|
|
|
|
return ent_label, ent_id
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def _create_label(self, label: str, ent_id: str) -> str:
|
2019-06-16 14:29:04 +03:00
|
|
|
"""Join Entity label with ent_id if the pattern has an `id` attribute
|
2019-07-08 18:28:28 +03:00
|
|
|
|
2020-02-16 20:17:47 +03:00
|
|
|
label (str): The label to set for ent.label_
|
|
|
|
ent_id (str): The label
|
2019-06-16 14:29:04 +03:00
|
|
|
RETURNS (str): The ent_label joined with configured `ent_id_sep`
|
|
|
|
"""
|
2019-12-22 03:53:56 +03:00
|
|
|
if isinstance(ent_id, str):
|
|
|
|
label = f"{label}{self.ent_id_sep}{ent_id}"
|
2019-06-16 14:29:04 +03:00
|
|
|
return label
|
|
|
|
|
2020-07-27 13:27:40 +03:00
|
|
|
def score(self, examples, **kwargs):
|
2020-08-12 00:29:31 +03:00
|
|
|
validate_examples(examples, "EntityRuler.score")
|
2020-07-27 13:27:40 +03:00
|
|
|
return Scorer.score_spans(examples, "ents", **kwargs)
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def from_bytes(
|
2020-08-29 16:20:11 +03:00
|
|
|
self, patterns_bytes: bytes, *, exclude: Iterable[str] = SimpleFrozenList()
|
2020-07-22 14:42:59 +03:00
|
|
|
) -> "EntityRuler":
|
2019-02-10 14:14:51 +03:00
|
|
|
"""Load the entity ruler from a bytestring.
|
|
|
|
|
|
|
|
patterns_bytes (bytes): The bytestring to load.
|
2019-10-25 12:16:42 +03:00
|
|
|
RETURNS (EntityRuler): The loaded entity ruler.
|
2019-10-25 12:19:46 +03:00
|
|
|
|
2020-09-04 13:58:50 +03:00
|
|
|
DOCS: https://nightly.spacy.io/api/entityruler#from_bytes
|
2019-02-10 14:14:51 +03:00
|
|
|
"""
|
2019-07-08 18:28:28 +03:00
|
|
|
cfg = srsly.msgpack_loads(patterns_bytes)
|
2020-07-22 14:42:59 +03:00
|
|
|
self.clear()
|
2019-07-08 18:28:28 +03:00
|
|
|
if isinstance(cfg, dict):
|
2019-07-10 13:03:05 +03:00
|
|
|
self.add_patterns(cfg.get("patterns", cfg))
|
|
|
|
self.overwrite = cfg.get("overwrite", False)
|
|
|
|
self.phrase_matcher_attr = cfg.get("phrase_matcher_attr", None)
|
2019-07-09 21:09:17 +03:00
|
|
|
if self.phrase_matcher_attr is not None:
|
2019-07-10 13:03:05 +03:00
|
|
|
self.phrase_matcher = PhraseMatcher(
|
|
|
|
self.nlp.vocab, attr=self.phrase_matcher_attr
|
|
|
|
)
|
|
|
|
self.ent_id_sep = cfg.get("ent_id_sep", DEFAULT_ENT_ID_SEP)
|
2019-07-08 18:28:28 +03:00
|
|
|
else:
|
|
|
|
self.add_patterns(cfg)
|
2019-02-10 14:14:51 +03:00
|
|
|
return self
|
|
|
|
|
2020-08-29 16:20:11 +03:00
|
|
|
def to_bytes(self, *, exclude: Iterable[str] = SimpleFrozenList()) -> bytes:
|
2019-02-10 14:14:51 +03:00
|
|
|
"""Serialize the entity ruler patterns to a bytestring.
|
|
|
|
|
|
|
|
RETURNS (bytes): The serialized patterns.
|
2019-10-25 12:19:46 +03:00
|
|
|
|
2020-09-04 13:58:50 +03:00
|
|
|
DOCS: https://nightly.spacy.io/api/entityruler#to_bytes
|
2019-02-10 14:14:51 +03:00
|
|
|
"""
|
2019-12-22 03:53:56 +03:00
|
|
|
serial = {
|
|
|
|
"overwrite": self.overwrite,
|
|
|
|
"ent_id_sep": self.ent_id_sep,
|
|
|
|
"phrase_matcher_attr": self.phrase_matcher_attr,
|
|
|
|
"patterns": self.patterns,
|
|
|
|
}
|
2019-07-08 18:28:28 +03:00
|
|
|
return srsly.msgpack_dumps(serial)
|
2019-02-10 14:14:51 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def from_disk(
|
2020-08-29 16:20:11 +03:00
|
|
|
self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList()
|
2020-07-22 14:42:59 +03:00
|
|
|
) -> "EntityRuler":
|
2019-02-10 14:14:51 +03:00
|
|
|
"""Load the entity ruler from a file. Expects a file containing
|
|
|
|
newline-delimited JSON (JSONL) with one entry per line.
|
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
path (str / Path): The JSONL file to load.
|
2019-10-25 12:16:42 +03:00
|
|
|
RETURNS (EntityRuler): The loaded entity ruler.
|
2019-10-25 12:19:46 +03:00
|
|
|
|
2020-09-04 13:58:50 +03:00
|
|
|
DOCS: https://nightly.spacy.io/api/entityruler#from_disk
|
2019-02-10 14:14:51 +03:00
|
|
|
"""
|
|
|
|
path = ensure_path(path)
|
2020-07-22 14:42:59 +03:00
|
|
|
self.clear()
|
2019-07-10 13:14:12 +03:00
|
|
|
depr_patterns_path = path.with_suffix(".jsonl")
|
|
|
|
if depr_patterns_path.is_file():
|
|
|
|
patterns = srsly.read_jsonl(depr_patterns_path)
|
2019-07-08 18:28:28 +03:00
|
|
|
self.add_patterns(patterns)
|
|
|
|
else:
|
|
|
|
cfg = {}
|
2019-11-21 18:26:37 +03:00
|
|
|
deserializers_patterns = {
|
2019-07-10 13:03:05 +03:00
|
|
|
"patterns": lambda p: self.add_patterns(
|
|
|
|
srsly.read_jsonl(p.with_suffix(".jsonl"))
|
2019-12-21 21:04:17 +03:00
|
|
|
)
|
2019-07-08 18:28:28 +03:00
|
|
|
}
|
2019-12-21 21:04:17 +03:00
|
|
|
deserializers_cfg = {"cfg": lambda p: cfg.update(srsly.read_json(p))}
|
2019-11-21 18:26:37 +03:00
|
|
|
from_disk(path, deserializers_cfg, {})
|
2019-07-10 13:03:05 +03:00
|
|
|
self.overwrite = cfg.get("overwrite", False)
|
|
|
|
self.phrase_matcher_attr = cfg.get("phrase_matcher_attr")
|
|
|
|
self.ent_id_sep = cfg.get("ent_id_sep", DEFAULT_ENT_ID_SEP)
|
2019-07-09 21:09:17 +03:00
|
|
|
|
|
|
|
if self.phrase_matcher_attr is not None:
|
2019-07-10 13:03:05 +03:00
|
|
|
self.phrase_matcher = PhraseMatcher(
|
|
|
|
self.nlp.vocab, attr=self.phrase_matcher_attr
|
|
|
|
)
|
2019-11-21 18:26:37 +03:00
|
|
|
from_disk(path, deserializers_patterns, {})
|
2019-02-10 14:14:51 +03:00
|
|
|
return self
|
|
|
|
|
2020-07-29 16:14:07 +03:00
|
|
|
def to_disk(
|
2020-08-29 16:20:11 +03:00
|
|
|
self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList()
|
2020-07-29 16:14:07 +03:00
|
|
|
) -> None:
|
2019-02-10 14:14:51 +03:00
|
|
|
"""Save the entity ruler patterns to a directory. The patterns will be
|
|
|
|
saved as newline-delimited JSON (JSONL).
|
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
path (str / Path): The JSONL file to save.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2020-09-04 13:58:50 +03:00
|
|
|
DOCS: https://nightly.spacy.io/api/entityruler#to_disk
|
2019-02-10 14:14:51 +03:00
|
|
|
"""
|
2019-07-10 13:25:45 +03:00
|
|
|
path = ensure_path(path)
|
2019-07-10 13:03:05 +03:00
|
|
|
cfg = {
|
|
|
|
"overwrite": self.overwrite,
|
|
|
|
"phrase_matcher_attr": self.phrase_matcher_attr,
|
|
|
|
"ent_id_sep": self.ent_id_sep,
|
|
|
|
}
|
2019-07-08 18:28:28 +03:00
|
|
|
serializers = {
|
2019-07-10 13:03:05 +03:00
|
|
|
"patterns": lambda p: srsly.write_jsonl(
|
|
|
|
p.with_suffix(".jsonl"), self.patterns
|
|
|
|
),
|
|
|
|
"cfg": lambda p: srsly.write_json(p, cfg),
|
2019-07-08 18:28:28 +03:00
|
|
|
}
|
2019-07-10 13:25:45 +03:00
|
|
|
if path.suffix == ".jsonl": # user wants to save only JSONL
|
|
|
|
srsly.write_jsonl(path, self.patterns)
|
|
|
|
else:
|
|
|
|
to_disk(path, serializers, {})
|