mirror of
https://github.com/explosion/spaCy.git
synced 2024-11-11 04:08:09 +03:00
657af5f91f
* 🚨 Ignore all existing Mypy errors * 🏗 Add Mypy check to CI * Add types-mock and types-requests as dev requirements * Add additional type ignore directives * Add types packages to dev-only list in reqs test * Add types-dataclasses for python 3.6 * Add ignore to pretrain * 🏷 Improve type annotation on `run_command` helper The `run_command` helper previously declared that it returned an `Optional[subprocess.CompletedProcess]`, but it isn't actually possible for the function to return `None`. These changes modify the type annotation of the `run_command` helper and remove all now-unnecessary `# type: ignore` directives. * 🔧 Allow variable type redefinition in limited contexts These changes modify how Mypy is configured to allow variables to have their type automatically redefined under certain conditions. The Mypy documentation contains the following example: ```python def process(items: List[str]) -> None: # 'items' has type List[str] items = [item.split() for item in items] # 'items' now has type List[List[str]] ... ``` This configuration change is especially helpful in reducing the number of `# type: ignore` directives needed to handle the common pattern of: * Accepting a filepath as a string * Overwriting the variable using `filepath = ensure_path(filepath)` These changes enable redefinition and remove all `# type: ignore` directives rendered redundant by this change. * 🏷 Add type annotation to converters mapping * 🚨 Fix Mypy error in convert CLI argument verification * 🏷 Improve type annotation on `resolve_dot_names` helper * 🏷 Add type annotations for `Vocab` attributes `strings` and `vectors` * 🏷 Add type annotations for more `Vocab` attributes * 🏷 Add loose type annotation for gold data compilation * 🏷 Improve `_format_labels` type annotation * 🏷 Fix `get_lang_class` type annotation * 🏷 Loosen return type of `Language.evaluate` * 🏷 Don't accept `Scorer` in `handle_scores_per_type` * 🏷 Add `string_to_list` overloads * 🏷 Fix non-Optional command-line options * 🙈 Ignore redefinition of `wandb_logger` in `loggers.py` * ➕ Install `typing_extensions` in Python 3.8+ The `typing_extensions` package states that it should be used when "writing code that must be compatible with multiple Python versions". Since SpaCy needs to support multiple Python versions, it should be used when newer `typing` module members are required. One example of this is `Literal`, which is available starting with Python 3.8. Previously SpaCy tried to import `Literal` from `typing`, falling back to `typing_extensions` if the import failed. However, Mypy doesn't seem to be able to understand what `Literal` means when the initial import means. Therefore, these changes modify how `compat` imports `Literal` by always importing it from `typing_extensions`. These changes also modify how `typing_extensions` is installed, so that it is a requirement for all Python versions, including those greater than or equal to 3.8. * 🏷 Improve type annotation for `Language.pipe` These changes add a missing overload variant to the type signature of `Language.pipe`. Additionally, the type signature is enhanced to allow type checkers to differentiate between the two overload variants based on the `as_tuple` parameter. Fixes #8772 * ➖ Don't install `typing-extensions` in Python 3.8+ After more detailed analysis of how to implement Python version-specific type annotations using SpaCy, it has been determined that by branching on a comparison against `sys.version_info` can be statically analyzed by Mypy well enough to enable us to conditionally use `typing_extensions.Literal`. This means that we no longer need to install `typing_extensions` for Python versions greater than or equal to 3.8! 🎉 These changes revert previous changes installing `typing-extensions` regardless of Python version and modify how we import the `Literal` type to ensure that Mypy treats it properly. * resolve mypy errors for Strict pydantic types * refactor code to avoid missing return statement * fix types of convert CLI command * avoid list-set confustion in debug_data * fix typo and formatting * small fixes to avoid type ignores * fix types in profile CLI command and make it more efficient * type fixes in projects CLI * put one ignore back * type fixes for render * fix render types - the sequel * fix BaseDefault in language definitions * fix type of noun_chunks iterator - yields tuple instead of span * fix types in language-specific modules * 🏷 Expand accepted inputs of `get_string_id` `get_string_id` accepts either a string (in which case it returns its ID) or an ID (in which case it immediately returns the ID). These changes extend the type annotation of `get_string_id` to indicate that it can accept either strings or IDs. * 🏷 Handle override types in `combine_score_weights` The `combine_score_weights` function allows users to pass an `overrides` mapping to override data extracted from the `weights` argument. Since it allows `Optional` dictionary values, the return value may also include `Optional` dictionary values. These changes update the type annotations for `combine_score_weights` to reflect this fact. * 🏷 Fix tokenizer serialization method signatures in `DummyTokenizer` * 🏷 Fix redefinition of `wandb_logger` These changes fix the redefinition of `wandb_logger` by giving a separate name to each `WandbLogger` version. For backwards-compatibility, `spacy.train` still exports `wandb_logger_v3` as `wandb_logger` for now. * more fixes for typing in language * type fixes in model definitions * 🏷 Annotate `_RandomWords.probs` as `NDArray` * 🏷 Annotate `tok2vec` layers to help Mypy * 🐛 Fix `_RandomWords.probs` type annotations for Python 3.6 Also remove an import that I forgot to move to the top of the module 😅 * more fixes for matchers and other pipeline components * quick fix for entity linker * fixing types for spancat, textcat, etc * bugfix for tok2vec * type annotations for scorer * add runtime_checkable for Protocol * type and import fixes in tests * mypy fixes for training utilities * few fixes in util * fix import * 🐵 Remove unused `# type: ignore` directives * 🏷 Annotate `Language._components` * 🏷 Annotate `spacy.pipeline.Pipe` * add doc as property to span.pyi * small fixes and cleanup * explicit type annotations instead of via comment Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com> Co-authored-by: svlandeg <svlandeg@github.com>
356 lines
14 KiB
Python
356 lines
14 KiB
Python
from typing import List, Dict, Union, Iterable, Any, Optional, Callable
|
|
from typing import Tuple
|
|
import srsly
|
|
from pathlib import Path
|
|
|
|
from .pipe import Pipe
|
|
from ..errors import Errors
|
|
from ..training import validate_examples, Example
|
|
from ..language import Language
|
|
from ..matcher import Matcher
|
|
from ..scorer import Scorer
|
|
from ..symbols import IDS, TAG, POS, MORPH, LEMMA
|
|
from ..tokens import Doc, Span
|
|
from ..tokens._retokenize import normalize_token_attrs, set_token_attrs
|
|
from ..vocab import Vocab
|
|
from ..util import SimpleFrozenList
|
|
from .. import util
|
|
|
|
|
|
MatcherPatternType = List[Dict[Union[int, str], Any]]
|
|
AttributeRulerPatternType = Dict[str, Union[MatcherPatternType, Dict, int]]
|
|
TagMapType = Dict[str, Dict[Union[int, str], Union[int, str]]]
|
|
MorphRulesType = Dict[str, Dict[str, Dict[Union[int, str], Union[int, str]]]]
|
|
|
|
|
|
@Language.factory("attribute_ruler", default_config={"validate": False})
|
|
def make_attribute_ruler(nlp: Language, name: str, validate: bool):
|
|
return AttributeRuler(nlp.vocab, name, validate=validate)
|
|
|
|
|
|
class AttributeRuler(Pipe):
|
|
"""Set token-level attributes for tokens matched by Matcher patterns.
|
|
Additionally supports importing patterns from tag maps and morph rules.
|
|
|
|
DOCS: https://spacy.io/api/attributeruler
|
|
"""
|
|
|
|
def __init__(
|
|
self, vocab: Vocab, name: str = "attribute_ruler", *, validate: bool = False
|
|
) -> None:
|
|
"""Create the AttributeRuler. After creation, you can add patterns
|
|
with the `.initialize()` or `.add_patterns()` methods, or load patterns
|
|
with `.from_bytes()` or `.from_disk()`. Loading patterns will remove
|
|
any patterns you've added previously.
|
|
|
|
vocab (Vocab): The vocab.
|
|
name (str): The pipe name. Defaults to "attribute_ruler".
|
|
|
|
RETURNS (AttributeRuler): The AttributeRuler component.
|
|
|
|
DOCS: https://spacy.io/api/attributeruler#init
|
|
"""
|
|
self.name = name
|
|
self.vocab = vocab
|
|
self.matcher = Matcher(self.vocab, validate=validate)
|
|
self.validate = validate
|
|
self.attrs: List[Dict] = []
|
|
self._attrs_unnormed: List[Dict] = [] # store for reference
|
|
self.indices: List[int] = []
|
|
|
|
def clear(self) -> None:
|
|
"""Reset all patterns."""
|
|
self.matcher = Matcher(self.vocab, validate=self.validate)
|
|
self.attrs = []
|
|
self._attrs_unnormed = []
|
|
self.indices = []
|
|
|
|
def initialize(
|
|
self,
|
|
get_examples: Optional[Callable[[], Iterable[Example]]],
|
|
*,
|
|
nlp: Optional[Language] = None,
|
|
patterns: Optional[Iterable[AttributeRulerPatternType]] = None,
|
|
tag_map: Optional[TagMapType] = None,
|
|
morph_rules: Optional[MorphRulesType] = None,
|
|
) -> None:
|
|
"""Initialize the attribute ruler by adding zero or more patterns.
|
|
|
|
Rules can be specified as a sequence of dicts using the `patterns`
|
|
keyword argument. You can also provide rules using the "tag map" or
|
|
"morph rules" formats supported by spaCy prior to v3.
|
|
"""
|
|
self.clear()
|
|
if patterns:
|
|
self.add_patterns(patterns)
|
|
if tag_map:
|
|
self.load_from_tag_map(tag_map)
|
|
if morph_rules:
|
|
self.load_from_morph_rules(morph_rules)
|
|
|
|
def __call__(self, doc: Doc) -> Doc:
|
|
"""Apply the AttributeRuler to a Doc and set all attribute exceptions.
|
|
|
|
doc (Doc): The document to process.
|
|
RETURNS (Doc): The processed Doc.
|
|
|
|
DOCS: https://spacy.io/api/attributeruler#call
|
|
"""
|
|
error_handler = self.get_error_handler()
|
|
try:
|
|
matches = self.match(doc)
|
|
self.set_annotations(doc, matches)
|
|
return doc
|
|
except Exception as e:
|
|
return error_handler(self.name, self, [doc], e)
|
|
|
|
def match(self, doc: Doc):
|
|
matches = self.matcher(doc, allow_missing=True, as_spans=False)
|
|
# Sort by the attribute ID, so that later rules have precedence
|
|
matches = [
|
|
(int(self.vocab.strings[m_id]), m_id, s, e) for m_id, s, e in matches # type: ignore
|
|
]
|
|
matches.sort()
|
|
return matches
|
|
|
|
def set_annotations(self, doc, matches):
|
|
"""Modify the document in place"""
|
|
for attr_id, match_id, start, end in matches:
|
|
span = Span(doc, start, end, label=match_id)
|
|
attrs = self.attrs[attr_id]
|
|
index = self.indices[attr_id]
|
|
try:
|
|
# The index can be negative, which makes it annoying to do
|
|
# the boundscheck. Let Span do it instead.
|
|
token = span[index] # noqa: F841
|
|
except IndexError:
|
|
# The original exception is just our conditional logic, so we
|
|
# raise from.
|
|
raise ValueError(
|
|
Errors.E1001.format(
|
|
patterns=self.matcher.get(span.label),
|
|
span=[t.text for t in span],
|
|
index=index,
|
|
)
|
|
) from None
|
|
set_token_attrs(span[index], attrs)
|
|
|
|
def load_from_tag_map(
|
|
self, tag_map: Dict[str, Dict[Union[int, str], Union[int, str]]]
|
|
) -> None:
|
|
"""Load attribute ruler patterns from a tag map.
|
|
|
|
tag_map (dict): The tag map that maps fine-grained tags to
|
|
coarse-grained tags and morphological features.
|
|
|
|
DOCS: https://spacy.io/api/attributeruler#load_from_morph_rules
|
|
"""
|
|
for tag, attrs in tag_map.items():
|
|
pattern = [{"TAG": tag}]
|
|
attrs, morph_attrs = _split_morph_attrs(attrs)
|
|
if "MORPH" not in attrs:
|
|
morph = self.vocab.morphology.add(morph_attrs)
|
|
attrs["MORPH"] = self.vocab.strings[morph]
|
|
else:
|
|
morph = self.vocab.morphology.add(attrs["MORPH"])
|
|
attrs["MORPH"] = self.vocab.strings[morph]
|
|
self.add([pattern], attrs) # type: ignore[list-item]
|
|
|
|
def load_from_morph_rules(
|
|
self, morph_rules: Dict[str, Dict[str, Dict[Union[int, str], Union[int, str]]]]
|
|
) -> None:
|
|
"""Load attribute ruler patterns from morph rules.
|
|
|
|
morph_rules (dict): The morph rules that map token text and
|
|
fine-grained tags to coarse-grained tags, lemmas and morphological
|
|
features.
|
|
|
|
DOCS: https://spacy.io/api/attributeruler#load_from_morph_rules
|
|
"""
|
|
for tag in morph_rules:
|
|
for word in morph_rules[tag]:
|
|
pattern = [{"ORTH": word, "TAG": tag}]
|
|
attrs = morph_rules[tag][word]
|
|
attrs, morph_attrs = _split_morph_attrs(attrs)
|
|
if "MORPH" in attrs:
|
|
morph = self.vocab.morphology.add(attrs["MORPH"])
|
|
attrs["MORPH"] = self.vocab.strings[morph]
|
|
elif morph_attrs:
|
|
morph = self.vocab.morphology.add(morph_attrs)
|
|
attrs["MORPH"] = self.vocab.strings[morph]
|
|
self.add([pattern], attrs) # type: ignore[list-item]
|
|
|
|
def add(
|
|
self, patterns: Iterable[MatcherPatternType], attrs: Dict, index: int = 0
|
|
) -> None:
|
|
"""Add Matcher patterns for tokens that should be modified with the
|
|
provided attributes. The token at the specified index within the
|
|
matched span will be assigned the attributes.
|
|
|
|
patterns (Iterable[List[Dict]]): A list of Matcher patterns.
|
|
attrs (Dict): The attributes to assign to the target token in the
|
|
matched span.
|
|
index (int): The index of the token in the matched span to modify. May
|
|
be negative to index from the end of the span. Defaults to 0.
|
|
|
|
DOCS: https://spacy.io/api/attributeruler#add
|
|
"""
|
|
# We need to make a string here, because otherwise the ID we pass back
|
|
# will be interpreted as the hash of a string, rather than an ordinal.
|
|
key = str(len(self.attrs))
|
|
self.matcher.add(self.vocab.strings.add(key), patterns) # type: ignore[arg-type]
|
|
self._attrs_unnormed.append(attrs)
|
|
attrs = normalize_token_attrs(self.vocab, attrs)
|
|
self.attrs.append(attrs)
|
|
self.indices.append(index)
|
|
|
|
def add_patterns(self, patterns: Iterable[AttributeRulerPatternType]) -> None:
|
|
"""Add patterns from a list of pattern dicts with the keys as the
|
|
arguments to AttributeRuler.add.
|
|
patterns (Iterable[dict]): A list of pattern dicts with the keys
|
|
as the arguments to AttributeRuler.add (patterns/attrs/index) to
|
|
add as patterns.
|
|
|
|
DOCS: https://spacy.io/api/attributeruler#add_patterns
|
|
"""
|
|
for p in patterns:
|
|
self.add(**p) # type: ignore[arg-type]
|
|
|
|
@property
|
|
def patterns(self) -> List[AttributeRulerPatternType]:
|
|
"""All the added patterns."""
|
|
all_patterns = []
|
|
for i in range(len(self.attrs)):
|
|
p = {}
|
|
p["patterns"] = self.matcher.get(str(i))[1]
|
|
p["attrs"] = self._attrs_unnormed[i] # type: ignore
|
|
p["index"] = self.indices[i] # type: ignore
|
|
all_patterns.append(p)
|
|
return all_patterns # type: ignore[return-value]
|
|
|
|
def score(self, examples: Iterable[Example], **kwargs) -> Dict[str, Any]:
|
|
"""Score a batch of examples.
|
|
|
|
examples (Iterable[Example]): The examples to score.
|
|
RETURNS (Dict[str, Any]): The scores, produced by
|
|
Scorer.score_token_attr for the attributes "tag", "pos", "morph"
|
|
and "lemma" for the target token attributes.
|
|
|
|
DOCS: https://spacy.io/api/tagger#score
|
|
"""
|
|
|
|
def morph_key_getter(token, attr):
|
|
return getattr(token, attr).key
|
|
|
|
validate_examples(examples, "AttributeRuler.score")
|
|
results = {}
|
|
attrs = set() # type: ignore
|
|
for token_attrs in self.attrs:
|
|
attrs.update(token_attrs)
|
|
for attr in attrs:
|
|
if attr == TAG:
|
|
results.update(Scorer.score_token_attr(examples, "tag", **kwargs))
|
|
elif attr == POS:
|
|
results.update(Scorer.score_token_attr(examples, "pos", **kwargs))
|
|
elif attr == MORPH:
|
|
results.update(
|
|
Scorer.score_token_attr(
|
|
examples, "morph", getter=morph_key_getter, **kwargs
|
|
)
|
|
)
|
|
results.update(
|
|
Scorer.score_token_attr_per_feat(
|
|
examples, "morph", getter=morph_key_getter, **kwargs
|
|
)
|
|
)
|
|
elif attr == LEMMA:
|
|
results.update(Scorer.score_token_attr(examples, "lemma", **kwargs))
|
|
return results
|
|
|
|
def to_bytes(self, exclude: Iterable[str] = SimpleFrozenList()) -> bytes:
|
|
"""Serialize the AttributeRuler to a bytestring.
|
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
RETURNS (bytes): The serialized object.
|
|
|
|
DOCS: https://spacy.io/api/attributeruler#to_bytes
|
|
"""
|
|
serialize = {}
|
|
serialize["vocab"] = lambda: self.vocab.to_bytes(exclude=exclude)
|
|
serialize["patterns"] = lambda: srsly.msgpack_dumps(self.patterns)
|
|
return util.to_bytes(serialize, exclude)
|
|
|
|
def from_bytes(
|
|
self, bytes_data: bytes, exclude: Iterable[str] = SimpleFrozenList()
|
|
) -> "AttributeRuler":
|
|
"""Load the AttributeRuler from a bytestring.
|
|
|
|
bytes_data (bytes): The data to load.
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
returns (AttributeRuler): The loaded object.
|
|
|
|
DOCS: https://spacy.io/api/attributeruler#from_bytes
|
|
"""
|
|
|
|
def load_patterns(b):
|
|
self.add_patterns(srsly.msgpack_loads(b))
|
|
|
|
deserialize = {
|
|
"vocab": lambda b: self.vocab.from_bytes(b, exclude=exclude),
|
|
"patterns": load_patterns,
|
|
}
|
|
util.from_bytes(bytes_data, deserialize, exclude)
|
|
return self
|
|
|
|
def to_disk(
|
|
self, path: Union[Path, str], exclude: Iterable[str] = SimpleFrozenList()
|
|
) -> None:
|
|
"""Serialize the AttributeRuler to disk.
|
|
|
|
path (Union[Path, str]): A path to a directory.
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
|
|
DOCS: https://spacy.io/api/attributeruler#to_disk
|
|
"""
|
|
serialize = {
|
|
"vocab": lambda p: self.vocab.to_disk(p, exclude=exclude),
|
|
"patterns": lambda p: srsly.write_msgpack(p, self.patterns),
|
|
}
|
|
util.to_disk(path, serialize, exclude)
|
|
|
|
def from_disk(
|
|
self, path: Union[Path, str], exclude: Iterable[str] = SimpleFrozenList()
|
|
) -> "AttributeRuler":
|
|
"""Load the AttributeRuler from disk.
|
|
|
|
path (Union[Path, str]): A path to a directory.
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
RETURNS (AttributeRuler): The loaded object.
|
|
|
|
DOCS: https://spacy.io/api/attributeruler#from_disk
|
|
"""
|
|
|
|
def load_patterns(p):
|
|
self.add_patterns(srsly.read_msgpack(p))
|
|
|
|
deserialize = {
|
|
"vocab": lambda p: self.vocab.from_disk(p, exclude=exclude),
|
|
"patterns": load_patterns,
|
|
}
|
|
util.from_disk(path, deserialize, exclude)
|
|
return self
|
|
|
|
|
|
def _split_morph_attrs(attrs: dict) -> Tuple[dict, dict]:
|
|
"""Split entries from a tag map or morph rules dict into to two dicts, one
|
|
with the token-level features (POS, LEMMA) and one with the remaining
|
|
features, which are presumed to be individual MORPH features."""
|
|
other_attrs = {}
|
|
morph_attrs = {}
|
|
for k, v in attrs.items():
|
|
if k in "_" or k in IDS.keys() or k in IDS.values():
|
|
other_attrs[k] = v
|
|
else:
|
|
morph_attrs[k] = v
|
|
return other_attrs, morph_attrs
|