2023-06-14 15:48:41 +00:00
|
|
|
import warnings
|
2020-10-02 13:42:36 +00:00
|
|
|
from pathlib import Path
|
2023-06-14 15:48:41 +00:00
|
|
|
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2023-06-14 15:48:41 +00:00
|
|
|
from thinc.api import Model
|
2021-06-04 15:44:04 +00:00
|
|
|
|
2023-06-14 15:48:41 +00:00
|
|
|
from .. import util
|
2020-12-04 10:46:15 +00:00
|
|
|
from ..errors import Errors, Warnings
|
2020-08-07 13:27:13 +00:00
|
|
|
from ..language import Language
|
|
|
|
from ..lookups import Lookups, load_lookups
|
|
|
|
from ..scorer import Scorer
|
|
|
|
from ..tokens import Doc, Token
|
2023-06-14 15:48:41 +00:00
|
|
|
from ..training import Example
|
|
|
|
from ..util import SimpleFrozenList, logger, registry
|
2020-08-07 13:27:13 +00:00
|
|
|
from ..vocab import Vocab
|
2023-06-14 15:48:41 +00:00
|
|
|
from .pipe import Pipe
|
2020-08-07 13:27:13 +00:00
|
|
|
|
|
|
|
|
|
|
|
@Language.factory(
|
|
|
|
"lemmatizer",
|
|
|
|
assigns=["token.lemma"],
|
2021-08-10 13:13:39 +00:00
|
|
|
default_config={
|
|
|
|
"model": None,
|
|
|
|
"mode": "lookup",
|
|
|
|
"overwrite": False,
|
|
|
|
"scorer": {"@scorers": "spacy.lemmatizer_scorer.v1"},
|
|
|
|
},
|
2020-08-07 13:27:13 +00:00
|
|
|
default_score_weights={"lemma_acc": 1.0},
|
|
|
|
)
|
|
|
|
def make_lemmatizer(
|
2021-08-10 13:13:39 +00:00
|
|
|
nlp: Language,
|
|
|
|
model: Optional[Model],
|
|
|
|
name: str,
|
|
|
|
mode: str,
|
|
|
|
overwrite: bool,
|
|
|
|
scorer: Optional[Callable],
|
2020-08-07 13:27:13 +00:00
|
|
|
):
|
2021-08-10 13:13:39 +00:00
|
|
|
return Lemmatizer(
|
|
|
|
nlp.vocab, model, name, mode=mode, overwrite=overwrite, scorer=scorer
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def lemmatizer_score(examples: Iterable[Example], **kwargs) -> Dict[str, Any]:
|
|
|
|
return Scorer.score_token_attr(examples, "lemma", **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
@registry.scorers("spacy.lemmatizer_scorer.v1")
|
|
|
|
def make_lemmatizer_scorer():
|
|
|
|
return lemmatizer_score
|
2020-08-07 13:27:13 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Lemmatizer(Pipe):
|
|
|
|
"""
|
|
|
|
The Lemmatizer supports simple part-of-speech-sensitive suffix rules and
|
|
|
|
lookup tables.
|
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/lemmatizer
|
2020-08-07 13:27:13 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
@classmethod
|
2020-10-02 13:42:36 +00:00
|
|
|
def get_lookups_config(cls, mode: str) -> Tuple[List[str], List[str]]:
|
2020-08-07 13:27:13 +00:00
|
|
|
"""Returns the lookups configuration settings for a given mode for use
|
|
|
|
in Lemmatizer.load_lookups.
|
|
|
|
|
|
|
|
mode (str): The lemmatizer mode.
|
2020-10-02 13:42:36 +00:00
|
|
|
RETURNS (Tuple[List[str], List[str]]): The required and optional
|
|
|
|
lookup tables for this mode.
|
2020-08-07 13:27:13 +00:00
|
|
|
"""
|
|
|
|
if mode == "lookup":
|
2020-10-02 13:42:36 +00:00
|
|
|
return (["lemma_lookup"], [])
|
2020-08-07 13:27:13 +00:00
|
|
|
elif mode == "rule":
|
2020-10-02 13:42:36 +00:00
|
|
|
return (["lemma_rules"], ["lemma_exc", "lemma_index"])
|
|
|
|
return ([], [])
|
2020-08-07 13:27:13 +00:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
vocab: Vocab,
|
|
|
|
model: Optional[Model],
|
|
|
|
name: str = "lemmatizer",
|
|
|
|
*,
|
|
|
|
mode: str = "lookup",
|
|
|
|
overwrite: bool = False,
|
2021-08-10 13:13:39 +00:00
|
|
|
scorer: Optional[Callable] = lemmatizer_score,
|
2020-08-07 13:27:13 +00:00
|
|
|
) -> None:
|
|
|
|
"""Initialize a Lemmatizer.
|
|
|
|
|
|
|
|
vocab (Vocab): The vocab.
|
|
|
|
model (Model): A model (not yet implemented).
|
|
|
|
name (str): The component name. Defaults to "lemmatizer".
|
|
|
|
mode (str): The lemmatizer mode: "lookup", "rule". Defaults to "lookup".
|
|
|
|
overwrite (bool): Whether to overwrite existing lemmas. Defaults to
|
|
|
|
`False`.
|
2021-08-12 10:50:03 +00:00
|
|
|
scorer (Optional[Callable]): The scoring method. Defaults to
|
|
|
|
Scorer.score_token_attr for the attribute "lemma".
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/lemmatizer#init
|
2020-08-07 13:27:13 +00:00
|
|
|
"""
|
|
|
|
self.vocab = vocab
|
|
|
|
self.model = model
|
2020-08-11 21:41:58 +00:00
|
|
|
self.name = name
|
2020-08-07 13:27:13 +00:00
|
|
|
self._mode = mode
|
2020-10-02 13:42:36 +00:00
|
|
|
self.lookups = Lookups()
|
2020-08-07 13:27:13 +00:00
|
|
|
self.overwrite = overwrite
|
2020-10-02 13:42:36 +00:00
|
|
|
self._validated = False
|
2020-08-07 13:27:13 +00:00
|
|
|
if self.mode == "lookup":
|
|
|
|
self.lemmatize = self.lookup_lemmatize
|
|
|
|
elif self.mode == "rule":
|
|
|
|
self.lemmatize = self.rule_lemmatize
|
|
|
|
else:
|
2020-08-11 21:29:31 +00:00
|
|
|
mode_attr = f"{self.mode}_lemmatize"
|
|
|
|
if not hasattr(self, mode_attr):
|
2020-08-07 13:27:13 +00:00
|
|
|
raise ValueError(Errors.E1003.format(mode=mode))
|
2020-08-11 21:29:31 +00:00
|
|
|
self.lemmatize = getattr(self, mode_attr)
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 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>
2021-10-14 13:21:40 +00:00
|
|
|
self.cache = {} # type: ignore[var-annotated]
|
2021-08-10 13:13:39 +00:00
|
|
|
self.scorer = scorer
|
2020-08-07 13:27:13 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def mode(self):
|
|
|
|
return self._mode
|
|
|
|
|
|
|
|
def __call__(self, doc: Doc) -> Doc:
|
|
|
|
"""Apply the lemmatizer to one document.
|
|
|
|
|
|
|
|
doc (Doc): The Doc to process.
|
|
|
|
RETURNS (Doc): The processed Doc.
|
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/lemmatizer#call
|
2020-08-07 13:27:13 +00:00
|
|
|
"""
|
2020-10-02 13:42:36 +00:00
|
|
|
if not self._validated:
|
|
|
|
self._validate_tables(Errors.E1004)
|
2021-01-29 00:51:21 +00:00
|
|
|
error_handler = self.get_error_handler()
|
|
|
|
try:
|
|
|
|
for token in doc:
|
|
|
|
if self.overwrite or token.lemma == 0:
|
|
|
|
token.lemma_ = self.lemmatize(token)[0]
|
|
|
|
return doc
|
|
|
|
except Exception as e:
|
|
|
|
error_handler(self.name, self, [doc], e)
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2020-10-02 13:42:36 +00:00
|
|
|
def initialize(
|
|
|
|
self,
|
|
|
|
get_examples: Optional[Callable[[], Iterable[Example]]] = None,
|
|
|
|
*,
|
|
|
|
nlp: Optional[Language] = None,
|
|
|
|
lookups: Optional[Lookups] = None,
|
|
|
|
):
|
|
|
|
"""Initialize the lemmatizer and load in data.
|
|
|
|
|
|
|
|
get_examples (Callable[[], Iterable[Example]]): Function that
|
|
|
|
returns a representative sample of gold-standard Example objects.
|
|
|
|
nlp (Language): The current nlp object the component is part of.
|
|
|
|
lookups (Lookups): The lookups object containing the (optional) tables
|
|
|
|
such as "lemma_rules", "lemma_index", "lemma_exc" and
|
|
|
|
"lemma_lookup". Defaults to None.
|
|
|
|
"""
|
|
|
|
required_tables, optional_tables = self.get_lookups_config(self.mode)
|
|
|
|
if lookups is None:
|
|
|
|
logger.debug("Lemmatizer: loading tables from spacy-lookups-data")
|
|
|
|
lookups = load_lookups(lang=self.vocab.lang, tables=required_tables)
|
|
|
|
optional_lookups = load_lookups(
|
|
|
|
lang=self.vocab.lang, tables=optional_tables, strict=False
|
|
|
|
)
|
|
|
|
for table in optional_lookups.tables:
|
|
|
|
lookups.set_table(table, optional_lookups.get_table(table))
|
|
|
|
self.lookups = lookups
|
|
|
|
self._validate_tables(Errors.E1004)
|
|
|
|
|
|
|
|
def _validate_tables(self, error_message: str = Errors.E912) -> None:
|
|
|
|
"""Check that the lookups are correct for the current mode."""
|
|
|
|
required_tables, optional_tables = self.get_lookups_config(self.mode)
|
|
|
|
for table in required_tables:
|
|
|
|
if table not in self.lookups:
|
|
|
|
raise ValueError(
|
|
|
|
error_message.format(
|
|
|
|
mode=self.mode,
|
|
|
|
tables=required_tables,
|
|
|
|
found=self.lookups.tables,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
self._validated = True
|
|
|
|
|
2020-08-07 13:27:13 +00:00
|
|
|
def lookup_lemmatize(self, token: Token) -> List[str]:
|
|
|
|
"""Lemmatize using a lookup-based approach.
|
|
|
|
|
|
|
|
token (Token): The token to lemmatize.
|
|
|
|
RETURNS (list): The available lemmas for the string.
|
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/lemmatizer#lookup_lemmatize
|
2020-08-07 13:27:13 +00:00
|
|
|
"""
|
|
|
|
lookup_table = self.lookups.get_table("lemma_lookup", {})
|
|
|
|
result = lookup_table.get(token.text, token.text)
|
|
|
|
if isinstance(result, str):
|
|
|
|
result = [result]
|
|
|
|
return result
|
|
|
|
|
|
|
|
def rule_lemmatize(self, token: Token) -> List[str]:
|
|
|
|
"""Lemmatize using a rule-based approach.
|
|
|
|
|
|
|
|
token (Token): The token to lemmatize.
|
|
|
|
RETURNS (list): The available lemmas for the string.
|
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/lemmatizer#rule_lemmatize
|
2020-08-07 13:27:13 +00:00
|
|
|
"""
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 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>
2021-10-14 13:21:40 +00:00
|
|
|
cache_key = (token.orth, token.pos, token.morph.key) # type: ignore[attr-defined]
|
2020-08-07 13:27:13 +00:00
|
|
|
if cache_key in self.cache:
|
|
|
|
return self.cache[cache_key]
|
|
|
|
string = token.text
|
|
|
|
univ_pos = token.pos_.lower()
|
|
|
|
if univ_pos in ("", "eol", "space"):
|
2020-12-04 10:46:15 +00:00
|
|
|
if univ_pos == "":
|
2021-10-12 17:56:44 +00:00
|
|
|
warnings.warn(Warnings.W108)
|
2020-08-07 13:27:13 +00:00
|
|
|
return [string.lower()]
|
|
|
|
# See Issue #435 for example of where this logic is requied.
|
|
|
|
if self.is_base_form(token):
|
|
|
|
return [string.lower()]
|
|
|
|
index_table = self.lookups.get_table("lemma_index", {})
|
|
|
|
exc_table = self.lookups.get_table("lemma_exc", {})
|
|
|
|
rules_table = self.lookups.get_table("lemma_rules", {})
|
|
|
|
if not any(
|
|
|
|
(
|
|
|
|
index_table.get(univ_pos),
|
|
|
|
exc_table.get(univ_pos),
|
|
|
|
rules_table.get(univ_pos),
|
|
|
|
)
|
|
|
|
):
|
|
|
|
if univ_pos == "propn":
|
|
|
|
return [string]
|
|
|
|
else:
|
|
|
|
return [string.lower()]
|
|
|
|
|
|
|
|
index = index_table.get(univ_pos, {})
|
|
|
|
exceptions = exc_table.get(univ_pos, {})
|
|
|
|
rules = rules_table.get(univ_pos, {})
|
|
|
|
orig = string
|
|
|
|
string = string.lower()
|
|
|
|
forms = []
|
|
|
|
oov_forms = []
|
|
|
|
for old, new in rules:
|
|
|
|
if string.endswith(old):
|
|
|
|
form = string[: len(string) - len(old)] + new
|
|
|
|
if not form:
|
|
|
|
pass
|
|
|
|
elif form in index or not form.isalpha():
|
|
|
|
forms.append(form)
|
|
|
|
else:
|
|
|
|
oov_forms.append(form)
|
|
|
|
# Remove duplicates but preserve the ordering of applied "rules"
|
|
|
|
forms = list(dict.fromkeys(forms))
|
|
|
|
# Put exceptions at the front of the list, so they get priority.
|
|
|
|
# This is a dodgy heuristic -- but it's the best we can do until we get
|
|
|
|
# frequencies on this. We can at least prune out problematic exceptions,
|
|
|
|
# if they shadow more frequent analyses.
|
|
|
|
for form in exceptions.get(string, []):
|
|
|
|
if form not in forms:
|
|
|
|
forms.insert(0, form)
|
|
|
|
if not forms:
|
|
|
|
forms.extend(oov_forms)
|
|
|
|
if not forms:
|
|
|
|
forms.append(orig)
|
|
|
|
self.cache[cache_key] = forms
|
|
|
|
return forms
|
|
|
|
|
|
|
|
def is_base_form(self, token: Token) -> bool:
|
|
|
|
"""Check whether the token is a base form that does not need further
|
|
|
|
analysis for lemmatization.
|
|
|
|
|
|
|
|
token (Token): The token.
|
|
|
|
RETURNS (bool): Whether the token is a base form.
|
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/lemmatizer#is_base_form
|
2020-08-07 13:27:13 +00:00
|
|
|
"""
|
|
|
|
return False
|
|
|
|
|
2020-10-02 13:42:36 +00:00
|
|
|
def to_disk(
|
|
|
|
self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList()
|
|
|
|
):
|
|
|
|
"""Serialize the pipe to disk.
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2020-10-02 13:42:36 +00:00
|
|
|
path (str / Path): Path to a directory.
|
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/lemmatizer#to_disk
|
2020-08-07 13:27:13 +00:00
|
|
|
"""
|
|
|
|
serialize = {}
|
2021-08-03 12:42:44 +00:00
|
|
|
serialize["vocab"] = lambda p: self.vocab.to_disk(p, exclude=exclude)
|
2020-08-07 13:27:13 +00:00
|
|
|
serialize["lookups"] = lambda p: self.lookups.to_disk(p)
|
|
|
|
util.to_disk(path, serialize, exclude)
|
|
|
|
|
2020-10-02 13:42:36 +00:00
|
|
|
def from_disk(
|
|
|
|
self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList()
|
|
|
|
) -> "Lemmatizer":
|
|
|
|
"""Load the pipe from disk. Modifies the object in place and returns it.
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2020-10-02 13:42:36 +00:00
|
|
|
path (str / Path): Path to a directory.
|
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
|
|
RETURNS (Lemmatizer): The modified Lemmatizer object.
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/lemmatizer#from_disk
|
2020-08-07 13:27:13 +00:00
|
|
|
"""
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 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>
2021-10-14 13:21:40 +00:00
|
|
|
deserialize: Dict[str, Callable[[Any], Any]] = {}
|
2021-08-03 12:42:44 +00:00
|
|
|
deserialize["vocab"] = lambda p: self.vocab.from_disk(p, exclude=exclude)
|
2020-08-07 13:27:13 +00:00
|
|
|
deserialize["lookups"] = lambda p: self.lookups.from_disk(p)
|
|
|
|
util.from_disk(path, deserialize, exclude)
|
2020-10-02 13:42:36 +00:00
|
|
|
self._validate_tables()
|
|
|
|
return self
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2020-10-02 13:42:36 +00:00
|
|
|
def to_bytes(self, *, exclude: Iterable[str] = SimpleFrozenList()) -> bytes:
|
|
|
|
"""Serialize the pipe to a bytestring.
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2020-10-02 13:42:36 +00:00
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
|
|
RETURNS (bytes): The serialized object.
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/lemmatizer#to_bytes
|
2020-08-07 13:27:13 +00:00
|
|
|
"""
|
|
|
|
serialize = {}
|
2021-08-03 12:42:44 +00:00
|
|
|
serialize["vocab"] = lambda: self.vocab.to_bytes(exclude=exclude)
|
2020-08-07 13:27:13 +00:00
|
|
|
serialize["lookups"] = self.lookups.to_bytes
|
|
|
|
return util.to_bytes(serialize, exclude)
|
|
|
|
|
2020-10-02 13:42:36 +00:00
|
|
|
def from_bytes(
|
|
|
|
self, bytes_data: bytes, *, exclude: Iterable[str] = SimpleFrozenList()
|
|
|
|
) -> "Lemmatizer":
|
|
|
|
"""Load the pipe from a bytestring.
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2020-10-02 13:42:36 +00:00
|
|
|
bytes_data (bytes): The serialized pipe.
|
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
|
|
RETURNS (Lemmatizer): The loaded Lemmatizer.
|
2020-08-07 13:27:13 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/lemmatizer#from_bytes
|
2020-08-07 13:27:13 +00:00
|
|
|
"""
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 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>
2021-10-14 13:21:40 +00:00
|
|
|
deserialize: Dict[str, Callable[[Any], Any]] = {}
|
2021-08-03 12:42:44 +00:00
|
|
|
deserialize["vocab"] = lambda b: self.vocab.from_bytes(b, exclude=exclude)
|
2020-08-07 13:27:13 +00:00
|
|
|
deserialize["lookups"] = lambda b: self.lookups.from_bytes(b)
|
|
|
|
util.from_bytes(bytes_data, deserialize, exclude)
|
2020-10-02 13:42:36 +00:00
|
|
|
self._validate_tables()
|
|
|
|
return self
|