2017-10-17 19:18:10 +03:00
|
|
|
|
import functools
|
2023-06-26 12:41:03 +03:00
|
|
|
|
import itertools
|
|
|
|
|
import multiprocessing as mp
|
|
|
|
|
import random
|
|
|
|
|
import traceback
|
|
|
|
|
import warnings
|
2017-10-27 22:07:59 +03:00
|
|
|
|
from contextlib import contextmanager
|
2020-08-28 16:20:14 +03:00
|
|
|
|
from copy import deepcopy
|
2023-06-26 12:41:03 +03:00
|
|
|
|
from dataclasses import dataclass
|
|
|
|
|
from itertools import chain, cycle
|
2020-02-27 20:42:27 +03:00
|
|
|
|
from pathlib import Path
|
2023-06-26 12:41:03 +03:00
|
|
|
|
from timeit import default_timer as timer
|
|
|
|
|
from typing import (
|
|
|
|
|
Any,
|
|
|
|
|
Callable,
|
|
|
|
|
Dict,
|
|
|
|
|
Iterable,
|
|
|
|
|
Iterator,
|
|
|
|
|
List,
|
|
|
|
|
Literal,
|
|
|
|
|
NoReturn,
|
|
|
|
|
Optional,
|
|
|
|
|
Pattern,
|
|
|
|
|
Sequence,
|
|
|
|
|
Set,
|
|
|
|
|
Tuple,
|
|
|
|
|
TypeVar,
|
|
|
|
|
Union,
|
|
|
|
|
cast,
|
|
|
|
|
overload,
|
|
|
|
|
)
|
2022-09-27 15:22:36 +03:00
|
|
|
|
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
|
import srsly
|
2023-06-26 12:41:03 +03:00
|
|
|
|
from thinc.api import Config, CupyOps, Optimizer, get_current_ops
|
2017-05-18 12:25:19 +03:00
|
|
|
|
|
2023-06-26 12:41:03 +03:00
|
|
|
|
from . import about, ty, util
|
2020-04-28 14:37:37 +03:00
|
|
|
|
from .errors import Errors, Warnings
|
2020-07-02 18:10:27 +03:00
|
|
|
|
from .git_info import GIT_VERSION
|
2023-06-26 12:41:03 +03:00
|
|
|
|
from .lang.punctuation import TOKENIZER_INFIXES, TOKENIZER_PREFIXES, TOKENIZER_SUFFIXES
|
|
|
|
|
from .lang.tokenizer_exceptions import BASE_EXCEPTIONS, URL_MATCH
|
2020-09-18 16:45:55 +03:00
|
|
|
|
from .lookups import load_lookups
|
2023-06-26 12:41:03 +03:00
|
|
|
|
from .pipe_analysis import analyze_pipes, print_pipe_analysis, validate_attrs
|
|
|
|
|
from .schemas import (
|
|
|
|
|
ConfigSchema,
|
|
|
|
|
ConfigSchemaInit,
|
|
|
|
|
ConfigSchemaNlp,
|
|
|
|
|
ConfigSchemaPretrain,
|
|
|
|
|
validate_init_settings,
|
|
|
|
|
)
|
|
|
|
|
from .scorer import Scorer
|
|
|
|
|
from .tokenizer import Tokenizer
|
|
|
|
|
from .tokens import Doc
|
|
|
|
|
from .tokens.underscore import Underscore
|
|
|
|
|
from .training import Example, validate_distillation_examples, validate_examples
|
|
|
|
|
from .training.initialize import init_tok2vec, init_vocab
|
|
|
|
|
from .util import (
|
|
|
|
|
_DEFAULT_EMPTY_PIPES,
|
|
|
|
|
CONFIG_SECTION_ORDER,
|
|
|
|
|
SimpleFrozenDict,
|
|
|
|
|
SimpleFrozenList,
|
|
|
|
|
_pipe,
|
|
|
|
|
combine_score_weights,
|
|
|
|
|
raise_error,
|
|
|
|
|
registry,
|
|
|
|
|
warn_if_jupyter_cupy,
|
|
|
|
|
)
|
|
|
|
|
from .vocab import Vocab, create_vocab
|
🏷 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 16:21:40 +03:00
|
|
|
|
|
2022-11-29 15:20:08 +03:00
|
|
|
|
PipeCallable = Callable[[Doc], Doc]
|
2016-10-09 13:24:24 +03:00
|
|
|
|
|
2015-08-27 10:16:11 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
# This is the base config will all settings (training etc.)
|
|
|
|
|
DEFAULT_CONFIG_PATH = Path(__file__).parent / "default_config.cfg"
|
2020-08-14 15:06:22 +03:00
|
|
|
|
DEFAULT_CONFIG = util.load_config(DEFAULT_CONFIG_PATH)
|
2023-01-31 15:06:02 +03:00
|
|
|
|
# This is the base config for the [distillation] block and currently not included
|
|
|
|
|
# in the main config and only added via the 'init fill-config' command
|
|
|
|
|
DEFAULT_CONFIG_DISTILL_PATH = Path(__file__).parent / "default_config_distillation.cfg"
|
2020-08-24 16:56:03 +03:00
|
|
|
|
# This is the base config for the [pretraining] block and currently not included
|
|
|
|
|
# in the main config and only added via the 'init fill-config' command
|
|
|
|
|
DEFAULT_CONFIG_PRETRAIN_PATH = Path(__file__).parent / "default_config_pretraining.cfg"
|
2019-10-27 15:35:49 +03: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 16:21:40 +03:00
|
|
|
|
# Type variable for contexts piped with documents
|
|
|
|
|
_AnyContext = TypeVar("_AnyContext")
|
|
|
|
|
|
2019-10-27 15:35:49 +03:00
|
|
|
|
|
2020-07-12 15:03:23 +03:00
|
|
|
|
class BaseDefaults:
|
2020-07-29 00:12:42 +03:00
|
|
|
|
"""Language data defaults, available via Language.Defaults. Can be
|
|
|
|
|
overwritten by language subclasses by defining their own subclasses of
|
|
|
|
|
Language.Defaults.
|
|
|
|
|
"""
|
2020-07-29 16:14:07 +03:00
|
|
|
|
|
2020-08-14 15:06:22 +03:00
|
|
|
|
config: Config = Config(section_order=CONFIG_SECTION_ORDER)
|
2020-07-24 15:50:26 +03:00
|
|
|
|
tokenizer_exceptions: Dict[str, List[dict]] = BASE_EXCEPTIONS
|
🏷 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 16:21:40 +03:00
|
|
|
|
prefixes: Optional[Sequence[Union[str, Pattern]]] = TOKENIZER_PREFIXES
|
|
|
|
|
suffixes: Optional[Sequence[Union[str, Pattern]]] = TOKENIZER_SUFFIXES
|
|
|
|
|
infixes: Optional[Sequence[Union[str, Pattern]]] = TOKENIZER_INFIXES
|
|
|
|
|
token_match: Optional[Callable] = None
|
|
|
|
|
url_match: Optional[Callable] = URL_MATCH
|
2020-07-24 15:50:26 +03:00
|
|
|
|
syntax_iterators: Dict[str, Callable] = {}
|
|
|
|
|
lex_attr_getters: Dict[int, Callable[[str], Any]] = {}
|
🏷 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 16:21:40 +03:00
|
|
|
|
stop_words: Set[str] = set()
|
2020-07-24 15:50:26 +03:00
|
|
|
|
writing_system = {"direction": "ltr", "has_case": True, "has_letters": True}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@registry.tokenizers("spacy.Tokenizer.v1")
|
|
|
|
|
def create_tokenizer() -> Callable[["Language"], Tokenizer]:
|
2020-07-29 00:12:42 +03:00
|
|
|
|
"""Registered function to create a tokenizer. Returns a factory that takes
|
|
|
|
|
the nlp object and returns a Tokenizer instance using the language detaults.
|
|
|
|
|
"""
|
2020-07-29 16:14:07 +03:00
|
|
|
|
|
2020-07-24 15:50:26 +03:00
|
|
|
|
def tokenizer_factory(nlp: "Language") -> Tokenizer:
|
|
|
|
|
prefixes = nlp.Defaults.prefixes
|
|
|
|
|
suffixes = nlp.Defaults.suffixes
|
|
|
|
|
infixes = nlp.Defaults.infixes
|
|
|
|
|
prefix_search = util.compile_prefix_regex(prefixes).search if prefixes else None
|
|
|
|
|
suffix_search = util.compile_suffix_regex(suffixes).search if suffixes else None
|
|
|
|
|
infix_finditer = util.compile_infix_regex(infixes).finditer if infixes else None
|
|
|
|
|
return Tokenizer(
|
|
|
|
|
nlp.vocab,
|
|
|
|
|
rules=nlp.Defaults.tokenizer_exceptions,
|
|
|
|
|
prefix_search=prefix_search,
|
|
|
|
|
suffix_search=suffix_search,
|
|
|
|
|
infix_finditer=infix_finditer,
|
|
|
|
|
token_match=nlp.Defaults.token_match,
|
|
|
|
|
url_match=nlp.Defaults.url_match,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return tokenizer_factory
|
|
|
|
|
|
|
|
|
|
|
2020-09-18 20:43:19 +03:00
|
|
|
|
@registry.misc("spacy.LookupsDataLoader.v1")
|
2020-09-18 16:45:55 +03:00
|
|
|
|
def load_lookups_data(lang, tables):
|
2023-02-02 13:15:22 +03:00
|
|
|
|
util.logger.debug("Loading lookups from spacy-lookups-data: %s", tables)
|
2020-09-18 16:45:55 +03:00
|
|
|
|
lookups = load_lookups(lang=lang, tables=tables)
|
|
|
|
|
return lookups
|
|
|
|
|
|
|
|
|
|
|
2020-07-12 15:03:23 +03:00
|
|
|
|
class Language:
|
2017-05-19 00:57:38 +03:00
|
|
|
|
"""A text-processing pipeline. Usually you'll load this once per process,
|
|
|
|
|
and pass the instance around your application.
|
2017-05-19 19:47:24 +03:00
|
|
|
|
|
|
|
|
|
Defaults (class): Settings, data and factory methods for creating the `nlp`
|
|
|
|
|
object and processing pipeline.
|
2021-10-05 10:52:22 +03:00
|
|
|
|
lang (str): IETF language code, such as 'en'.
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language
|
2019-03-08 13:42:26 +03:00
|
|
|
|
"""
|
2019-03-11 01:36:47 +03:00
|
|
|
|
|
2016-09-24 21:26:17 +03:00
|
|
|
|
Defaults = BaseDefaults
|
🏷 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 16:21:40 +03:00
|
|
|
|
lang: Optional[str] = None
|
2020-07-22 14:42:59 +03:00
|
|
|
|
default_config = DEFAULT_CONFIG
|
2015-08-25 16:37:17 +03:00
|
|
|
|
|
2020-07-24 15:50:26 +03:00
|
|
|
|
factories = SimpleFrozenDict(error=Errors.E957)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
_factory_meta: Dict[str, "FactoryMeta"] = {} # meta by factory
|
2017-10-07 01:25:54 +03:00
|
|
|
|
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
def __init__(
|
2020-02-28 13:57:41 +03:00
|
|
|
|
self,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
vocab: Union[Vocab, bool] = True,
|
2020-07-27 01:27:53 +03:00
|
|
|
|
*,
|
2022-02-06 18:30:30 +03:00
|
|
|
|
max_length: int = 10**6,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
meta: Dict[str, Any] = {},
|
|
|
|
|
create_tokenizer: Optional[Callable[["Language"], Callable[[str], Doc]]] = None,
|
2020-12-09 11:13:26 +03:00
|
|
|
|
batch_size: int = 1000,
|
2020-02-28 13:57:41 +03:00
|
|
|
|
**kwargs,
|
2020-07-29 00:12:42 +03:00
|
|
|
|
) -> None:
|
2017-05-19 00:57:38 +03:00
|
|
|
|
"""Initialise a Language object.
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
vocab (Vocab): A `Vocab` object. If `True`, a vocab is created.
|
2017-05-19 00:57:38 +03:00
|
|
|
|
meta (dict): Custom meta data for the Language class. Is written to by
|
|
|
|
|
models to add model meta data.
|
2020-07-25 13:14:28 +03:00
|
|
|
|
max_length (int): Maximum number of characters in a single text. The
|
|
|
|
|
current models may run out memory on extremely long texts, due to
|
|
|
|
|
large internal allocations. You should segment these texts into
|
|
|
|
|
meaningful units, e.g. paragraphs, subsections etc, before passing
|
|
|
|
|
them to spaCy. Default maximum length is 1,000,000 charas (1mb). As
|
|
|
|
|
a rule of thumb, if all pipeline components are enabled, spaCy's
|
|
|
|
|
default models currently requires roughly 1GB of temporary memory per
|
2018-03-29 22:45:26 +03:00
|
|
|
|
100,000 characters in one text.
|
2020-07-25 13:14:28 +03:00
|
|
|
|
create_tokenizer (Callable): Function that takes the nlp object and
|
|
|
|
|
returns a tokenizer.
|
2020-12-09 11:13:26 +03:00
|
|
|
|
batch_size (int): Default batch size for pipe and evaluate.
|
2020-07-29 00:12:42 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#init
|
2017-05-19 00:57:38 +03:00
|
|
|
|
"""
|
2020-07-22 14:42:59 +03:00
|
|
|
|
# We're only calling this to import all factories provided via entry
|
|
|
|
|
# points. The factory decorator applied to these functions takes care
|
|
|
|
|
# of the rest.
|
|
|
|
|
util.registry._entry_point_factories.get_all()
|
|
|
|
|
|
2020-08-13 18:38:30 +03:00
|
|
|
|
self._config = DEFAULT_CONFIG.merge(self.default_config)
|
2017-07-23 01:50:18 +03:00
|
|
|
|
self._meta = dict(meta)
|
2017-10-25 12:57:43 +03:00
|
|
|
|
self._path = None
|
🏷 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 16:21:40 +03:00
|
|
|
|
self._optimizer: Optional[Optimizer] = None
|
2020-07-22 14:42:59 +03:00
|
|
|
|
# Component meta and configs are only needed on the instance
|
|
|
|
|
self._pipe_meta: Dict[str, "FactoryMeta"] = {} # meta by component
|
|
|
|
|
self._pipe_configs: Dict[str, Config] = {} # config by component
|
|
|
|
|
|
2020-09-15 14:25:34 +03:00
|
|
|
|
if not isinstance(vocab, Vocab) and vocab is not True:
|
|
|
|
|
raise ValueError(Errors.E918.format(vocab=vocab, vocab_type=type(Vocab)))
|
2017-05-16 12:21:59 +03:00
|
|
|
|
if vocab is True:
|
2023-02-08 16:37:42 +03:00
|
|
|
|
vocab = create_vocab(self.lang, self.Defaults)
|
2019-08-01 18:13:01 +03:00
|
|
|
|
else:
|
|
|
|
|
if (self.lang and vocab.lang) and (self.lang != vocab.lang):
|
|
|
|
|
raise ValueError(Errors.E150.format(nlp=self.lang, vocab=vocab.lang))
|
2020-07-25 16:01:15 +03:00
|
|
|
|
self.vocab: Vocab = vocab
|
2020-07-22 14:42:59 +03:00
|
|
|
|
if self.lang is None:
|
|
|
|
|
self.lang = self.vocab.lang
|
2022-11-29 15:20:08 +03:00
|
|
|
|
self._components: List[Tuple[str, PipeCallable]] = []
|
🏷 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 16:21:40 +03:00
|
|
|
|
self._disabled: Set[str] = set()
|
2018-03-29 22:45:26 +03:00
|
|
|
|
self.max_length = max_length
|
2020-07-22 14:42:59 +03:00
|
|
|
|
# Create the default tokenizer from the default config
|
|
|
|
|
if not create_tokenizer:
|
|
|
|
|
tokenizer_cfg = {"tokenizer": self._config["nlp"]["tokenizer"]}
|
2020-09-27 23:21:31 +03:00
|
|
|
|
create_tokenizer = registry.resolve(tokenizer_cfg)["tokenizer"]
|
2020-07-22 14:42:59 +03:00
|
|
|
|
self.tokenizer = create_tokenizer(self)
|
2020-12-09 11:13:26 +03:00
|
|
|
|
self.batch_size = batch_size
|
2021-01-29 03:51:21 +03:00
|
|
|
|
self.default_error_handler = raise_error
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
|
|
def __init_subclass__(cls, **kwargs):
|
|
|
|
|
super().__init_subclass__(**kwargs)
|
2020-08-13 18:38:30 +03:00
|
|
|
|
cls.default_config = DEFAULT_CONFIG.merge(cls.Defaults.config)
|
2020-07-24 15:50:26 +03:00
|
|
|
|
cls.default_config["nlp"]["lang"] = cls.lang
|
2015-10-12 11:33:11 +03:00
|
|
|
|
|
2017-10-25 12:57:43 +03:00
|
|
|
|
@property
|
|
|
|
|
def path(self):
|
|
|
|
|
return self._path
|
|
|
|
|
|
2017-07-23 01:50:18 +03:00
|
|
|
|
@property
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def meta(self) -> Dict[str, Any]:
|
2020-07-29 00:12:42 +03:00
|
|
|
|
"""Custom meta data of the language class. If a model is loaded, this
|
|
|
|
|
includes details from the model's meta.json.
|
|
|
|
|
|
|
|
|
|
RETURNS (Dict[str, Any]): The meta.
|
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#meta
|
2020-07-29 00:12:42 +03:00
|
|
|
|
"""
|
2021-08-17 15:05:13 +03:00
|
|
|
|
spacy_version = util.get_minor_version_range(about.__version__)
|
2019-08-01 18:13:01 +03:00
|
|
|
|
if self.vocab.lang:
|
|
|
|
|
self._meta.setdefault("lang", self.vocab.lang)
|
|
|
|
|
else:
|
|
|
|
|
self._meta.setdefault("lang", self.lang)
|
2020-09-03 14:13:03 +03:00
|
|
|
|
self._meta.setdefault("name", "pipeline")
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
self._meta.setdefault("version", "0.0.0")
|
2020-05-30 16:01:58 +03:00
|
|
|
|
self._meta.setdefault("spacy_version", spacy_version)
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
self._meta.setdefault("description", "")
|
|
|
|
|
self._meta.setdefault("author", "")
|
|
|
|
|
self._meta.setdefault("email", "")
|
|
|
|
|
self._meta.setdefault("url", "")
|
|
|
|
|
self._meta.setdefault("license", "")
|
2020-07-02 18:10:27 +03:00
|
|
|
|
self._meta.setdefault("spacy_git_version", GIT_VERSION)
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
self._meta["vectors"] = {
|
|
|
|
|
"width": self.vocab.vectors_length,
|
|
|
|
|
"vectors": len(self.vocab.vectors),
|
|
|
|
|
"keys": self.vocab.vectors.n_keys,
|
2021-10-27 15:08:31 +03:00
|
|
|
|
"mode": self.vocab.vectors.mode,
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
}
|
2020-08-29 16:20:11 +03:00
|
|
|
|
self._meta["labels"] = dict(self.pipe_labels)
|
2020-07-28 17:14:23 +03:00
|
|
|
|
# TODO: Adding this back to prevent breaking people's code etc., but
|
|
|
|
|
# we should consider removing it
|
2020-08-29 16:20:11 +03:00
|
|
|
|
self._meta["pipeline"] = list(self.pipe_names)
|
2020-09-04 15:42:12 +03:00
|
|
|
|
self._meta["components"] = list(self.component_names)
|
2020-08-29 16:20:11 +03:00
|
|
|
|
self._meta["disabled"] = list(self.disabled)
|
2017-07-23 01:50:18 +03:00
|
|
|
|
return self._meta
|
|
|
|
|
|
|
|
|
|
@meta.setter
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def meta(self, value: Dict[str, Any]) -> None:
|
2017-07-23 01:50:18 +03:00
|
|
|
|
self._meta = value
|
|
|
|
|
|
2017-06-04 23:52:09 +03:00
|
|
|
|
@property
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def config(self) -> Config:
|
2020-07-29 00:12:42 +03:00
|
|
|
|
"""Trainable config for the current language instance. Includes the
|
|
|
|
|
current pipeline components, as well as default training config.
|
|
|
|
|
|
|
|
|
|
RETURNS (thinc.api.Config): The config.
|
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#config
|
2020-07-29 00:12:42 +03:00
|
|
|
|
"""
|
2020-07-22 14:42:59 +03:00
|
|
|
|
self._config.setdefault("nlp", {})
|
2020-07-26 14:18:43 +03:00
|
|
|
|
self._config.setdefault("training", {})
|
2020-07-22 14:42:59 +03:00
|
|
|
|
self._config["nlp"]["lang"] = self.lang
|
|
|
|
|
# We're storing the filled config for each pipeline component and so
|
|
|
|
|
# we can populate the config again later
|
|
|
|
|
pipeline = {}
|
2020-07-26 14:18:43 +03:00
|
|
|
|
score_weights = []
|
2020-08-28 22:04:02 +03:00
|
|
|
|
for pipe_name in self.component_names:
|
2020-07-22 14:42:59 +03:00
|
|
|
|
pipe_meta = self.get_pipe_meta(pipe_name)
|
|
|
|
|
pipe_config = self.get_pipe_config(pipe_name)
|
2020-07-22 18:29:31 +03:00
|
|
|
|
pipeline[pipe_name] = {"factory": pipe_meta.factory, **pipe_config}
|
2020-07-27 13:27:40 +03:00
|
|
|
|
if pipe_meta.default_score_weights:
|
|
|
|
|
score_weights.append(pipe_meta.default_score_weights)
|
2020-08-29 16:20:11 +03:00
|
|
|
|
self._config["nlp"]["pipeline"] = list(self.component_names)
|
|
|
|
|
self._config["nlp"]["disabled"] = list(self.disabled)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
self._config["components"] = pipeline
|
2020-09-24 11:27:33 +03:00
|
|
|
|
# We're merging the existing score weights back into the combined
|
|
|
|
|
# weights to make sure we're preserving custom settings in the config
|
|
|
|
|
# but also reflect updates (e.g. new components added)
|
2020-09-24 11:42:47 +03:00
|
|
|
|
prev_weights = self._config["training"].get("score_weights", {})
|
|
|
|
|
combined_score_weights = combine_score_weights(score_weights, prev_weights)
|
2020-09-24 11:27:33 +03:00
|
|
|
|
self._config["training"]["score_weights"] = combined_score_weights
|
2020-07-22 14:42:59 +03:00
|
|
|
|
if not srsly.is_json_serializable(self._config):
|
|
|
|
|
raise ValueError(Errors.E961.format(config=self._config))
|
2020-02-27 20:42:27 +03:00
|
|
|
|
return self._config
|
2017-10-07 01:25:54 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
@config.setter
|
|
|
|
|
def config(self, value: Config) -> None:
|
|
|
|
|
self._config = value
|
|
|
|
|
|
2020-08-29 13:08:33 +03:00
|
|
|
|
@property
|
|
|
|
|
def disabled(self) -> List[str]:
|
|
|
|
|
"""Get the names of all disabled components.
|
|
|
|
|
|
|
|
|
|
RETURNS (List[str]): The disabled components.
|
|
|
|
|
"""
|
2020-08-29 13:58:22 +03:00
|
|
|
|
# Make sure the disabled components are returned in the order they
|
|
|
|
|
# appear in the pipeline (which isn't guaranteed by the set)
|
2020-08-29 16:20:11 +03:00
|
|
|
|
names = [name for name, _ in self._components if name in self._disabled]
|
|
|
|
|
return SimpleFrozenList(names, error=Errors.E926.format(attr="disabled"))
|
2020-08-29 13:08:33 +03:00
|
|
|
|
|
2017-10-07 01:25:54 +03:00
|
|
|
|
@property
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def factory_names(self) -> List[str]:
|
|
|
|
|
"""Get names of all available factories.
|
|
|
|
|
|
|
|
|
|
RETURNS (List[str]): The factory names.
|
|
|
|
|
"""
|
2020-08-29 16:20:11 +03:00
|
|
|
|
names = list(self.factories.keys())
|
|
|
|
|
return SimpleFrozenList(names)
|
|
|
|
|
|
|
|
|
|
@property
|
2022-11-29 15:20:08 +03:00
|
|
|
|
def components(self) -> List[Tuple[str, PipeCallable]]:
|
2020-08-29 16:20:11 +03:00
|
|
|
|
"""Get all (name, component) tuples in the pipeline, including the
|
|
|
|
|
currently disabled components.
|
|
|
|
|
"""
|
|
|
|
|
return SimpleFrozenList(
|
|
|
|
|
self._components, error=Errors.E926.format(attr="components")
|
|
|
|
|
)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
2020-08-28 16:20:14 +03:00
|
|
|
|
@property
|
2020-08-28 22:04:02 +03:00
|
|
|
|
def component_names(self) -> List[str]:
|
2020-08-28 16:20:14 +03:00
|
|
|
|
"""Get the names of the available pipeline components. Includes all
|
|
|
|
|
active and inactive pipeline components.
|
|
|
|
|
|
|
|
|
|
RETURNS (List[str]): List of component name strings, in order.
|
|
|
|
|
"""
|
2020-08-29 16:20:11 +03:00
|
|
|
|
names = [pipe_name for pipe_name, _ in self._components]
|
|
|
|
|
return SimpleFrozenList(names, error=Errors.E926.format(attr="component_names"))
|
2020-08-28 16:20:14 +03:00
|
|
|
|
|
|
|
|
|
@property
|
2022-11-29 15:20:08 +03:00
|
|
|
|
def pipeline(self) -> List[Tuple[str, PipeCallable]]:
|
2020-08-28 16:20:14 +03:00
|
|
|
|
"""The processing pipeline consisting of (name, component) tuples. The
|
|
|
|
|
components are called on the Doc in order as it passes through the
|
|
|
|
|
pipeline.
|
|
|
|
|
|
2022-11-29 15:20:08 +03:00
|
|
|
|
RETURNS (List[Tuple[str, Callable[[Doc], Doc]]]): The pipeline.
|
2020-08-28 16:20:14 +03:00
|
|
|
|
"""
|
2020-08-29 16:20:11 +03:00
|
|
|
|
pipes = [(n, p) for n, p in self._components if n not in self._disabled]
|
|
|
|
|
return SimpleFrozenList(pipes, error=Errors.E926.format(attr="pipeline"))
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def pipe_names(self) -> List[str]:
|
2020-08-28 16:20:14 +03:00
|
|
|
|
"""Get names of available active pipeline components.
|
2017-10-07 01:25:54 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
RETURNS (List[str]): List of component name strings, in order.
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""
|
2020-08-29 16:20:11 +03:00
|
|
|
|
names = [pipe_name for pipe_name, _ in self.pipeline]
|
|
|
|
|
return SimpleFrozenList(names, error=Errors.E926.format(attr="pipe_names"))
|
2017-10-07 01:25:54 +03:00
|
|
|
|
|
2019-10-27 15:35:49 +03:00
|
|
|
|
@property
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def pipe_factories(self) -> Dict[str, str]:
|
2019-10-27 15:35:49 +03:00
|
|
|
|
"""Get the component factories for the available pipeline components.
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
RETURNS (Dict[str, str]): Factory names, keyed by component names.
|
2019-10-27 15:35:49 +03:00
|
|
|
|
"""
|
|
|
|
|
factories = {}
|
2020-08-29 16:20:11 +03:00
|
|
|
|
for pipe_name, pipe in self._components:
|
2020-07-22 14:42:59 +03:00
|
|
|
|
factories[pipe_name] = self.get_pipe_meta(pipe_name).factory
|
2020-08-29 16:20:11 +03:00
|
|
|
|
return SimpleFrozenDict(factories)
|
2019-10-27 15:35:49 +03:00
|
|
|
|
|
2019-09-12 11:56:28 +03:00
|
|
|
|
@property
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def pipe_labels(self) -> Dict[str, List[str]]:
|
2019-09-12 14:03:38 +03:00
|
|
|
|
"""Get the labels set by the pipeline components, if available (if
|
2022-02-05 19:59:24 +03:00
|
|
|
|
the component exposes a labels property and the labels are not
|
|
|
|
|
hidden).
|
2019-09-12 11:56:28 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
RETURNS (Dict[str, List[str]]): Labels keyed by component name.
|
2019-09-12 11:56:28 +03:00
|
|
|
|
"""
|
2019-12-22 03:53:56 +03:00
|
|
|
|
labels = {}
|
2020-08-29 16:20:11 +03:00
|
|
|
|
for name, pipe in self._components:
|
2022-02-05 19:59:24 +03:00
|
|
|
|
if hasattr(pipe, "hide_labels") and pipe.hide_labels is True:
|
|
|
|
|
continue
|
2019-09-12 11:56:28 +03:00
|
|
|
|
if hasattr(pipe, "labels"):
|
|
|
|
|
labels[name] = list(pipe.labels)
|
2020-08-29 16:20:11 +03:00
|
|
|
|
return SimpleFrozenDict(labels)
|
2019-09-12 11:56:28 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
@classmethod
|
|
|
|
|
def has_factory(cls, name: str) -> bool:
|
|
|
|
|
"""RETURNS (bool): Whether a factory of that name is registered."""
|
|
|
|
|
internal_name = cls.get_factory_name(name)
|
|
|
|
|
return name in registry.factories or internal_name in registry.factories
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_factory_name(cls, name: str) -> str:
|
|
|
|
|
"""Get the internal factory name based on the language subclass.
|
|
|
|
|
|
|
|
|
|
name (str): The factory name.
|
|
|
|
|
RETURNS (str): The internal factory name.
|
|
|
|
|
"""
|
|
|
|
|
if cls.lang is None:
|
|
|
|
|
return name
|
|
|
|
|
return f"{cls.lang}.{name}"
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_factory_meta(cls, name: str) -> "FactoryMeta":
|
|
|
|
|
"""Get the meta information for a given factory name.
|
|
|
|
|
|
|
|
|
|
name (str): The component factory name.
|
|
|
|
|
RETURNS (FactoryMeta): The meta for the given factory name.
|
|
|
|
|
"""
|
|
|
|
|
internal_name = cls.get_factory_name(name)
|
|
|
|
|
if internal_name in cls._factory_meta:
|
|
|
|
|
return cls._factory_meta[internal_name]
|
|
|
|
|
if name in cls._factory_meta:
|
|
|
|
|
return cls._factory_meta[name]
|
|
|
|
|
raise ValueError(Errors.E967.format(meta="factory", name=name))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def set_factory_meta(cls, name: str, value: "FactoryMeta") -> None:
|
|
|
|
|
"""Set the meta information for a given factory name.
|
|
|
|
|
|
|
|
|
|
name (str): The component factory name.
|
|
|
|
|
value (FactoryMeta): The meta to set.
|
|
|
|
|
"""
|
|
|
|
|
cls._factory_meta[cls.get_factory_name(name)] = value
|
|
|
|
|
|
|
|
|
|
def get_pipe_meta(self, name: str) -> "FactoryMeta":
|
|
|
|
|
"""Get the meta information for a given component name.
|
|
|
|
|
|
|
|
|
|
name (str): The component name.
|
|
|
|
|
RETURNS (FactoryMeta): The meta for the given component name.
|
|
|
|
|
"""
|
|
|
|
|
if name not in self._pipe_meta:
|
|
|
|
|
raise ValueError(Errors.E967.format(meta="component", name=name))
|
|
|
|
|
return self._pipe_meta[name]
|
|
|
|
|
|
|
|
|
|
def get_pipe_config(self, name: str) -> Config:
|
|
|
|
|
"""Get the config used to create a pipeline component.
|
|
|
|
|
|
|
|
|
|
name (str): The component name.
|
|
|
|
|
RETURNS (Config): The config used to create the pipeline component.
|
|
|
|
|
"""
|
|
|
|
|
if name not in self._pipe_configs:
|
|
|
|
|
raise ValueError(Errors.E960.format(name=name))
|
|
|
|
|
pipe_config = self._pipe_configs[name]
|
|
|
|
|
return pipe_config
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def factory(
|
|
|
|
|
cls,
|
|
|
|
|
name: str,
|
|
|
|
|
*,
|
|
|
|
|
default_config: Dict[str, Any] = SimpleFrozenDict(),
|
2020-08-29 16:20:11 +03:00
|
|
|
|
assigns: Iterable[str] = SimpleFrozenList(),
|
|
|
|
|
requires: Iterable[str] = SimpleFrozenList(),
|
2020-07-22 14:42:59 +03:00
|
|
|
|
retokenizes: bool = False,
|
🏷 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 16:21:40 +03:00
|
|
|
|
default_score_weights: Dict[str, Optional[float]] = SimpleFrozenDict(),
|
2020-07-22 14:42:59 +03:00
|
|
|
|
func: Optional[Callable] = None,
|
|
|
|
|
) -> Callable:
|
|
|
|
|
"""Register a new pipeline component factory. Can be used as a decorator
|
|
|
|
|
on a function or classmethod, or called as a function with the factory
|
|
|
|
|
provided as the func keyword argument. To create a component and add
|
|
|
|
|
it to the pipeline, you can use nlp.add_pipe(name).
|
|
|
|
|
|
|
|
|
|
name (str): The name of the component factory.
|
|
|
|
|
default_config (Dict[str, Any]): Default configuration, describing the
|
|
|
|
|
default values of the factory arguments.
|
|
|
|
|
assigns (Iterable[str]): Doc/Token attributes assigned by this component,
|
2021-05-03 15:44:09 +03:00
|
|
|
|
e.g. "token.ent_id". Used for pipeline analysis.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
requires (Iterable[str]): Doc/Token attributes required by this component,
|
2021-05-03 15:44:09 +03:00
|
|
|
|
e.g. "token.ent_id". Used for pipeline analysis.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
retokenizes (bool): Whether the component changes the tokenization.
|
|
|
|
|
Used for pipeline analysis.
|
🏷 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 16:21:40 +03:00
|
|
|
|
default_score_weights (Dict[str, Optional[float]]): The scores to report during
|
2020-07-28 12:22:24 +03:00
|
|
|
|
training, and their default weight towards the final score used to
|
|
|
|
|
select the best model. Weights should sum to 1.0 per component and
|
2020-09-24 11:27:33 +03:00
|
|
|
|
will be combined and normalized for the whole pipeline. If None,
|
|
|
|
|
the score won't be shown in the logs or be weighted.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
func (Optional[Callable]): Factory function if not used as a decorator.
|
2020-07-29 00:12:42 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#factory
|
2020-07-22 14:42:59 +03:00
|
|
|
|
"""
|
|
|
|
|
if not isinstance(name, str):
|
|
|
|
|
raise ValueError(Errors.E963.format(decorator="factory"))
|
2022-08-19 10:52:12 +03:00
|
|
|
|
if "." in name:
|
|
|
|
|
raise ValueError(Errors.E853.format(name=name))
|
2020-07-22 14:42:59 +03:00
|
|
|
|
if not isinstance(default_config, dict):
|
|
|
|
|
err = Errors.E962.format(
|
|
|
|
|
style="default config", name=name, cfg_type=type(default_config)
|
|
|
|
|
)
|
|
|
|
|
raise ValueError(err)
|
|
|
|
|
|
|
|
|
|
def add_factory(factory_func: Callable) -> Callable:
|
2020-08-28 17:27:22 +03:00
|
|
|
|
internal_name = cls.get_factory_name(name)
|
|
|
|
|
if internal_name in registry.factories:
|
|
|
|
|
# We only check for the internal name here – it's okay if it's a
|
|
|
|
|
# subclass and the base class has a factory of the same name. We
|
|
|
|
|
# also only raise if the function is different to prevent raising
|
|
|
|
|
# if module is reloaded.
|
|
|
|
|
existing_func = registry.factories.get(internal_name)
|
|
|
|
|
if not util.is_same_func(factory_func, existing_func):
|
|
|
|
|
err = Errors.E004.format(
|
|
|
|
|
name=name, func=existing_func, new_func=factory_func
|
|
|
|
|
)
|
|
|
|
|
raise ValueError(err)
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
arg_names = util.get_arg_names(factory_func)
|
|
|
|
|
if "nlp" not in arg_names or "name" not in arg_names:
|
|
|
|
|
raise ValueError(Errors.E964.format(name=name))
|
|
|
|
|
# Officially register the factory so we can later call
|
2020-09-27 23:21:31 +03:00
|
|
|
|
# registry.resolve and refer to it in the config as
|
2020-07-22 14:42:59 +03:00
|
|
|
|
# @factories = "spacy.Language.xyz". We use the class name here so
|
|
|
|
|
# different classes can have different factories.
|
|
|
|
|
registry.factories.register(internal_name, func=factory_func)
|
|
|
|
|
factory_meta = FactoryMeta(
|
|
|
|
|
factory=name,
|
|
|
|
|
default_config=default_config,
|
|
|
|
|
assigns=validate_attrs(assigns),
|
|
|
|
|
requires=validate_attrs(requires),
|
2020-09-24 11:27:33 +03:00
|
|
|
|
scores=list(default_score_weights.keys()),
|
2020-07-27 13:27:40 +03:00
|
|
|
|
default_score_weights=default_score_weights,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
retokenizes=retokenizes,
|
|
|
|
|
)
|
|
|
|
|
cls.set_factory_meta(name, factory_meta)
|
|
|
|
|
# We're overwriting the class attr with a frozen dict to handle
|
|
|
|
|
# backwards-compat (writing to Language.factories directly). This
|
|
|
|
|
# wouldn't work with an instance property and just produce a
|
|
|
|
|
# confusing error – here we can show a custom error
|
|
|
|
|
cls.factories = SimpleFrozenDict(
|
|
|
|
|
registry.factories.get_all(), error=Errors.E957
|
|
|
|
|
)
|
|
|
|
|
return factory_func
|
|
|
|
|
|
|
|
|
|
if func is not None: # Support non-decorator use cases
|
|
|
|
|
return add_factory(func)
|
|
|
|
|
return add_factory
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def component(
|
|
|
|
|
cls,
|
🏷 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 16:21:40 +03:00
|
|
|
|
name: str,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
*,
|
2020-08-29 16:20:11 +03:00
|
|
|
|
assigns: Iterable[str] = SimpleFrozenList(),
|
|
|
|
|
requires: Iterable[str] = SimpleFrozenList(),
|
2020-07-22 14:42:59 +03:00
|
|
|
|
retokenizes: bool = False,
|
2022-11-29 15:20:08 +03:00
|
|
|
|
func: Optional[PipeCallable] = None,
|
2022-01-28 18:59:54 +03:00
|
|
|
|
) -> Callable[..., Any]:
|
2020-07-22 14:42:59 +03:00
|
|
|
|
"""Register a new pipeline component. Can be used for stateless function
|
|
|
|
|
components that don't require a separate factory. Can be used as a
|
|
|
|
|
decorator on a function or classmethod, or called as a function with the
|
|
|
|
|
factory provided as the func keyword argument. To create a component and
|
|
|
|
|
add it to the pipeline, you can use nlp.add_pipe(name).
|
|
|
|
|
|
|
|
|
|
name (str): The name of the component factory.
|
|
|
|
|
assigns (Iterable[str]): Doc/Token attributes assigned by this component,
|
2021-05-03 15:44:09 +03:00
|
|
|
|
e.g. "token.ent_id". Used for pipeline analysis.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
requires (Iterable[str]): Doc/Token attributes required by this component,
|
2021-05-03 15:44:09 +03:00
|
|
|
|
e.g. "token.ent_id". Used for pipeline analysis.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
retokenizes (bool): Whether the component changes the tokenization.
|
|
|
|
|
Used for pipeline analysis.
|
2022-11-29 15:20:08 +03:00
|
|
|
|
func (Optional[Callable[[Doc], Doc]): Factory function if not used as a decorator.
|
2020-07-29 00:12:42 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#component
|
2020-07-22 14:42:59 +03:00
|
|
|
|
"""
|
2022-08-19 10:52:12 +03:00
|
|
|
|
if name is not None:
|
|
|
|
|
if not isinstance(name, str):
|
|
|
|
|
raise ValueError(Errors.E963.format(decorator="component"))
|
|
|
|
|
if "." in name:
|
|
|
|
|
raise ValueError(Errors.E853.format(name=name))
|
2020-07-22 14:42:59 +03:00
|
|
|
|
component_name = name if name is not None else util.get_object_name(func)
|
|
|
|
|
|
2022-11-29 15:20:08 +03:00
|
|
|
|
def add_component(component_func: PipeCallable) -> Callable:
|
2020-07-22 14:42:59 +03:00
|
|
|
|
if isinstance(func, type): # function is a class
|
|
|
|
|
raise ValueError(Errors.E965.format(name=component_name))
|
|
|
|
|
|
2022-11-29 15:20:08 +03:00
|
|
|
|
def factory_func(nlp, name: str) -> PipeCallable:
|
2020-07-22 14:42:59 +03:00
|
|
|
|
return component_func
|
|
|
|
|
|
2020-08-28 17:27:22 +03:00
|
|
|
|
internal_name = cls.get_factory_name(name)
|
|
|
|
|
if internal_name in registry.factories:
|
|
|
|
|
# We only check for the internal name here – it's okay if it's a
|
|
|
|
|
# subclass and the base class has a factory of the same name. We
|
|
|
|
|
# also only raise if the function is different to prevent raising
|
|
|
|
|
# if module is reloaded. It's hacky, but we need to check the
|
|
|
|
|
# existing functure for a closure and whether that's identical
|
|
|
|
|
# to the component function (because factory_func created above
|
|
|
|
|
# will always be different, even for the same function)
|
|
|
|
|
existing_func = registry.factories.get(internal_name)
|
|
|
|
|
closure = existing_func.__closure__
|
|
|
|
|
wrapped = [c.cell_contents for c in closure][0] if closure else None
|
|
|
|
|
if util.is_same_func(wrapped, component_func):
|
|
|
|
|
factory_func = existing_func # noqa: F811
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
cls.factory(
|
|
|
|
|
component_name,
|
|
|
|
|
assigns=assigns,
|
|
|
|
|
requires=requires,
|
|
|
|
|
retokenizes=retokenizes,
|
|
|
|
|
func=factory_func,
|
|
|
|
|
)
|
|
|
|
|
return component_func
|
|
|
|
|
|
|
|
|
|
if func is not None: # Support non-decorator use cases
|
|
|
|
|
return add_component(func)
|
|
|
|
|
return add_component
|
|
|
|
|
|
2020-07-31 19:34:35 +03:00
|
|
|
|
def analyze_pipes(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
keys: List[str] = ["assigns", "requires", "scores", "retokenizes"],
|
2020-08-01 14:40:06 +03:00
|
|
|
|
pretty: bool = False,
|
2020-07-31 19:34:35 +03:00
|
|
|
|
) -> Optional[Dict[str, Any]]:
|
|
|
|
|
"""Analyze the current pipeline components, print a summary of what
|
|
|
|
|
they assign or require and check that all requirements are met.
|
|
|
|
|
|
|
|
|
|
keys (List[str]): The meta values to display in the table. Corresponds
|
|
|
|
|
to values in FactoryMeta, defined by @Language.factory decorator.
|
2020-08-01 14:40:06 +03:00
|
|
|
|
pretty (bool): Pretty-print the results.
|
|
|
|
|
RETURNS (dict): The data.
|
2020-07-31 19:34:35 +03:00
|
|
|
|
"""
|
2020-08-01 14:40:06 +03:00
|
|
|
|
analysis = analyze_pipes(self, keys=keys)
|
|
|
|
|
if pretty:
|
|
|
|
|
print_pipe_analysis(analysis, keys=keys)
|
|
|
|
|
return analysis
|
2020-07-31 19:34:35 +03:00
|
|
|
|
|
2022-11-29 15:20:08 +03:00
|
|
|
|
def get_pipe(self, name: str) -> PipeCallable:
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""Get a pipeline component for a given component name.
|
|
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
|
name (str): Name of pipeline component to get.
|
2017-10-07 01:25:54 +03:00
|
|
|
|
RETURNS (callable): The pipeline component.
|
2019-03-15 18:23:17 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#get_pipe
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""
|
2020-08-29 16:20:11 +03:00
|
|
|
|
for pipe_name, component in self._components:
|
2017-10-07 01:25:54 +03:00
|
|
|
|
if pipe_name == name:
|
|
|
|
|
return component
|
2020-08-28 22:04:02 +03:00
|
|
|
|
raise KeyError(Errors.E001.format(name=name, opts=self.component_names))
|
2017-10-07 01:25:54 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def create_pipe(
|
|
|
|
|
self,
|
|
|
|
|
factory_name: str,
|
|
|
|
|
name: Optional[str] = None,
|
2020-07-29 00:12:42 +03:00
|
|
|
|
*,
|
2021-08-27 12:44:31 +03:00
|
|
|
|
config: Dict[str, Any] = SimpleFrozenDict(),
|
2020-08-13 18:38:30 +03:00
|
|
|
|
raw_config: Optional[Config] = None,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
validate: bool = True,
|
2022-11-29 15:20:08 +03:00
|
|
|
|
) -> PipeCallable:
|
2020-07-22 14:42:59 +03:00
|
|
|
|
"""Create a pipeline component. Mostly used internally. To create and
|
|
|
|
|
add a component to the pipeline, you can use nlp.add_pipe.
|
|
|
|
|
|
|
|
|
|
factory_name (str): Name of component factory.
|
|
|
|
|
name (Optional[str]): Optional name to assign to component instance.
|
|
|
|
|
Defaults to factory name if not set.
|
2021-08-27 12:44:31 +03:00
|
|
|
|
config (Dict[str, Any]): Config parameters to use for this component.
|
|
|
|
|
Will be merged with default config, if available.
|
2020-08-13 18:38:30 +03:00
|
|
|
|
raw_config (Optional[Config]): Internals: the non-interpolated config.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
validate (bool): Whether to validate the component config against the
|
|
|
|
|
arguments and types expected by the factory.
|
2022-11-29 15:20:08 +03:00
|
|
|
|
RETURNS (Callable[[Doc], Doc]): The pipeline component.
|
2020-07-29 00:12:42 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#create_pipe
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""
|
2020-07-22 14:42:59 +03:00
|
|
|
|
name = name if name is not None else factory_name
|
|
|
|
|
if not isinstance(config, dict):
|
|
|
|
|
err = Errors.E962.format(style="config", name=name, cfg_type=type(config))
|
|
|
|
|
raise ValueError(err)
|
|
|
|
|
if not srsly.is_json_serializable(config):
|
|
|
|
|
raise ValueError(Errors.E961.format(config=config))
|
|
|
|
|
if not self.has_factory(factory_name):
|
|
|
|
|
err = Errors.E002.format(
|
|
|
|
|
name=factory_name,
|
|
|
|
|
opts=", ".join(self.factory_names),
|
|
|
|
|
method="create_pipe",
|
|
|
|
|
lang=util.get_object_name(self),
|
|
|
|
|
lang_code=self.lang,
|
2020-05-21 19:39:06 +03:00
|
|
|
|
)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
raise ValueError(err)
|
|
|
|
|
pipe_meta = self.get_factory_meta(factory_name)
|
|
|
|
|
# This is unideal, but the alternative would mean you always need to
|
|
|
|
|
# specify the full config settings, which is not really viable.
|
|
|
|
|
if pipe_meta.default_config:
|
2020-08-13 18:38:30 +03:00
|
|
|
|
config = Config(pipe_meta.default_config).merge(config)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
internal_name = self.get_factory_name(factory_name)
|
|
|
|
|
# If the language-specific factory doesn't exist, try again with the
|
|
|
|
|
# not-specific name
|
|
|
|
|
if internal_name not in registry.factories:
|
|
|
|
|
internal_name = factory_name
|
2021-01-27 04:40:03 +03:00
|
|
|
|
# The name allows components to know their pipe name and use it in the
|
|
|
|
|
# losses etc. (even if multiple instances of the same factory are used)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
config = {"nlp": self, "name": name, **config, "@factories": internal_name}
|
2021-01-27 04:40:03 +03:00
|
|
|
|
# We need to create a top-level key because Thinc doesn't allow resolving
|
|
|
|
|
# top-level references to registered functions. Also gives nicer errors.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
cfg = {factory_name: config}
|
|
|
|
|
# We're calling the internal _fill here to avoid constructing the
|
|
|
|
|
# registered functions twice
|
2020-09-27 23:21:31 +03:00
|
|
|
|
resolved = registry.resolve(cfg, validate=validate)
|
|
|
|
|
filled = registry.fill({"cfg": cfg[factory_name]}, validate=validate)["cfg"]
|
|
|
|
|
filled = Config(filled)
|
2020-07-22 18:29:31 +03:00
|
|
|
|
filled["factory"] = factory_name
|
2020-07-26 16:11:24 +03:00
|
|
|
|
filled.pop("@factories", None)
|
2020-09-15 15:24:17 +03:00
|
|
|
|
# Remove the extra values we added because we don't want to keep passing
|
|
|
|
|
# them around, copying them etc.
|
|
|
|
|
filled.pop("nlp", None)
|
|
|
|
|
filled.pop("name", None)
|
2020-08-13 18:38:30 +03:00
|
|
|
|
# Merge the final filled config with the raw config (including non-
|
|
|
|
|
# interpolated variables)
|
|
|
|
|
if raw_config:
|
|
|
|
|
filled = filled.merge(raw_config)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
self._pipe_configs[name] = filled
|
|
|
|
|
return resolved[factory_name]
|
2017-10-07 01:25:54 +03:00
|
|
|
|
|
2020-08-05 00:39:19 +03:00
|
|
|
|
def create_pipe_from_source(
|
2020-09-08 23:44:25 +03:00
|
|
|
|
self, source_name: str, source: "Language", *, name: str
|
2022-11-29 15:20:08 +03:00
|
|
|
|
) -> Tuple[PipeCallable, str]:
|
2020-08-05 00:39:19 +03:00
|
|
|
|
"""Create a pipeline component by copying it from an existing model.
|
|
|
|
|
|
|
|
|
|
source_name (str): Name of the component in the source pipeline.
|
|
|
|
|
source (Language): The source nlp object to copy from.
|
|
|
|
|
name (str): Optional alternative name to use in current pipeline.
|
2022-11-29 15:20:08 +03:00
|
|
|
|
RETURNS (Tuple[Callable[[Doc], Doc], str]): The component and its factory name.
|
2020-08-05 00:39:19 +03:00
|
|
|
|
"""
|
2021-04-19 11:36:32 +03:00
|
|
|
|
# Check source type
|
|
|
|
|
if not isinstance(source, Language):
|
2020-08-05 00:39:19 +03:00
|
|
|
|
raise ValueError(Errors.E945.format(name=source_name, source=type(source)))
|
2022-11-16 11:44:42 +03:00
|
|
|
|
if self.vocab.vectors != source.vocab.vectors:
|
2021-06-04 18:44:04 +03:00
|
|
|
|
warnings.warn(Warnings.W113.format(name=source_name))
|
2021-06-28 13:03:29 +03:00
|
|
|
|
if source_name not in source.component_names:
|
2020-08-05 00:39:19 +03:00
|
|
|
|
raise KeyError(
|
|
|
|
|
Errors.E944.format(
|
|
|
|
|
name=source_name,
|
|
|
|
|
model=f"{source.meta['lang']}_{source.meta['name']}",
|
2021-02-26 15:50:56 +03:00
|
|
|
|
opts=", ".join(source.component_names),
|
2020-08-05 00:39:19 +03:00
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
pipe = source.get_pipe(source_name)
|
2023-06-27 11:47:07 +03:00
|
|
|
|
# There is no actual solution here. Either the component has the right
|
|
|
|
|
# name for the source pipeline or the component has the right name for
|
|
|
|
|
# the current pipeline. This prioritizes the current pipeline.
|
|
|
|
|
if hasattr(pipe, "name"):
|
|
|
|
|
pipe.name = name
|
2020-08-13 18:38:30 +03:00
|
|
|
|
# Make sure the source config is interpolated so we don't end up with
|
|
|
|
|
# orphaned variables in our final config
|
|
|
|
|
source_config = source.config.interpolate()
|
|
|
|
|
pipe_config = util.copy_config(source_config["components"][source_name])
|
2020-08-05 00:39:19 +03:00
|
|
|
|
self._pipe_configs[name] = pipe_config
|
2021-10-04 13:19:02 +03:00
|
|
|
|
if self.vocab.strings != source.vocab.strings:
|
|
|
|
|
for s in source.vocab.strings:
|
|
|
|
|
self.vocab.strings.add(s)
|
2020-08-05 00:39:19 +03:00
|
|
|
|
return pipe, pipe_config["factory"]
|
|
|
|
|
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
def add_pipe(
|
2020-07-22 14:42:59 +03:00
|
|
|
|
self,
|
|
|
|
|
factory_name: str,
|
|
|
|
|
name: Optional[str] = None,
|
|
|
|
|
*,
|
|
|
|
|
before: Optional[Union[str, int]] = None,
|
|
|
|
|
after: Optional[Union[str, int]] = None,
|
2023-07-06 16:20:13 +03:00
|
|
|
|
first: Optional[Literal[True]] = None,
|
|
|
|
|
last: Optional[Literal[True]] = None,
|
2020-08-05 00:39:19 +03:00
|
|
|
|
source: Optional["Language"] = None,
|
2021-08-27 12:44:31 +03:00
|
|
|
|
config: Dict[str, Any] = SimpleFrozenDict(),
|
2020-08-13 18:38:30 +03:00
|
|
|
|
raw_config: Optional[Config] = None,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
validate: bool = True,
|
2022-11-29 15:20:08 +03:00
|
|
|
|
) -> PipeCallable:
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""Add a component to the processing pipeline. Valid components are
|
2017-10-27 15:40:14 +03:00
|
|
|
|
callables that take a `Doc` object, modify it and return it. Only one
|
|
|
|
|
of before/after/first/last can be set. Default behaviour is "last".
|
2017-10-07 01:25:54 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
factory_name (str): Name of the component factory.
|
2020-05-24 18:20:58 +03:00
|
|
|
|
name (str): Name of pipeline component. Overwrites existing
|
2017-10-07 01:25:54 +03:00
|
|
|
|
component.name attribute if available. If no name is set and
|
|
|
|
|
the component exposes no name attribute, component.__name__ is
|
2017-10-27 15:40:14 +03:00
|
|
|
|
used. An error is raised if a name already exists in the pipeline.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
before (Union[str, int]): Name or index of the component to insert new
|
|
|
|
|
component directly before.
|
|
|
|
|
after (Union[str, int]): Name or index of the component to insert new
|
|
|
|
|
component directly after.
|
2023-07-06 16:20:13 +03:00
|
|
|
|
first (Optional[Literal[True]]): If True, insert component first in the pipeline.
|
|
|
|
|
last (Optional[Literal[True]]): If True, insert component last in the pipeline.
|
2020-08-05 00:39:19 +03:00
|
|
|
|
source (Language): Optional loaded nlp object to copy the pipeline
|
|
|
|
|
component from.
|
2021-08-27 12:44:31 +03:00
|
|
|
|
config (Dict[str, Any]): Config parameters to use for this component.
|
|
|
|
|
Will be merged with default config, if available.
|
2020-08-13 18:38:30 +03:00
|
|
|
|
raw_config (Optional[Config]): Internals: the non-interpolated config.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
validate (bool): Whether to validate the component config against the
|
|
|
|
|
arguments and types expected by the factory.
|
2022-11-29 15:20:08 +03:00
|
|
|
|
RETURNS (Callable[[Doc], Doc]): The pipeline component.
|
2017-10-07 01:25:54 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#add_pipe
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""
|
2020-07-22 14:42:59 +03:00
|
|
|
|
if not isinstance(factory_name, str):
|
|
|
|
|
bad_val = repr(factory_name)
|
|
|
|
|
err = Errors.E966.format(component=bad_val, name=name)
|
|
|
|
|
raise ValueError(err)
|
|
|
|
|
name = name if name is not None else factory_name
|
2020-08-28 22:04:02 +03:00
|
|
|
|
if name in self.component_names:
|
|
|
|
|
raise ValueError(Errors.E007.format(name=name, opts=self.component_names))
|
2022-05-12 12:46:08 +03:00
|
|
|
|
# Overriding pipe name in the config is not supported and will be ignored.
|
|
|
|
|
if "name" in config:
|
|
|
|
|
warnings.warn(Warnings.W119.format(name_in_config=config.pop("name")))
|
2020-08-05 00:39:19 +03:00
|
|
|
|
if source is not None:
|
|
|
|
|
# We're loading the component from a model. After loading the
|
|
|
|
|
# component, we know its real factory name
|
|
|
|
|
pipe_component, factory_name = self.create_pipe_from_source(
|
|
|
|
|
factory_name, source, name=name
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
pipe_component = self.create_pipe(
|
2020-08-13 18:38:30 +03:00
|
|
|
|
factory_name,
|
|
|
|
|
name=name,
|
|
|
|
|
config=config,
|
|
|
|
|
raw_config=raw_config,
|
|
|
|
|
validate=validate,
|
2020-08-05 00:39:19 +03:00
|
|
|
|
)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
pipe_index = self._get_pipe_index(before, after, first, last)
|
|
|
|
|
self._pipe_meta[name] = self.get_factory_meta(factory_name)
|
2020-08-29 16:20:11 +03:00
|
|
|
|
self._components.insert(pipe_index, (name, pipe_component))
|
2023-06-27 11:47:07 +03:00
|
|
|
|
self._link_components()
|
2020-07-22 14:42:59 +03:00
|
|
|
|
return pipe_component
|
2017-06-04 23:52:09 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def _get_pipe_index(
|
|
|
|
|
self,
|
|
|
|
|
before: Optional[Union[str, int]] = None,
|
|
|
|
|
after: Optional[Union[str, int]] = None,
|
2023-07-06 16:20:13 +03:00
|
|
|
|
first: Optional[Literal[True]] = None,
|
|
|
|
|
last: Optional[Literal[True]] = None,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
) -> int:
|
|
|
|
|
"""Determine where to insert a pipeline component based on the before/
|
|
|
|
|
after/first/last values.
|
|
|
|
|
|
|
|
|
|
before (str): Name or index of the component to insert directly before.
|
|
|
|
|
after (str): Name or index of component to insert directly after.
|
2023-07-06 16:20:13 +03:00
|
|
|
|
first (Optional[Literal[True]]): If True, insert component first in the pipeline.
|
|
|
|
|
last (Optional[Literal[True]]): If True, insert component last in the pipeline.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
RETURNS (int): The index of the new pipeline component.
|
|
|
|
|
"""
|
2023-07-06 16:20:13 +03:00
|
|
|
|
if first is not None and first is not True:
|
|
|
|
|
raise ValueError(Errors.E4009.format(attr="first", value=first))
|
|
|
|
|
if last is not None and last is not True:
|
|
|
|
|
raise ValueError(Errors.E4009.format(attr="last", value=last))
|
2020-07-22 14:42:59 +03:00
|
|
|
|
all_args = {"before": before, "after": after, "first": first, "last": last}
|
|
|
|
|
if sum(arg is not None for arg in [before, after, first, last]) >= 2:
|
2020-08-28 22:04:02 +03:00
|
|
|
|
raise ValueError(
|
|
|
|
|
Errors.E006.format(args=all_args, opts=self.component_names)
|
|
|
|
|
)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
if last or not any(value is not None for value in [first, before, after]):
|
2020-08-29 16:20:11 +03:00
|
|
|
|
return len(self._components)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
elif first:
|
|
|
|
|
return 0
|
|
|
|
|
elif isinstance(before, str):
|
2020-08-28 22:04:02 +03:00
|
|
|
|
if before not in self.component_names:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
Errors.E001.format(name=before, opts=self.component_names)
|
|
|
|
|
)
|
|
|
|
|
return self.component_names.index(before)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
elif isinstance(after, str):
|
2020-08-28 22:04:02 +03:00
|
|
|
|
if after not in self.component_names:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
Errors.E001.format(name=after, opts=self.component_names)
|
|
|
|
|
)
|
|
|
|
|
return self.component_names.index(after) + 1
|
2020-07-22 14:42:59 +03:00
|
|
|
|
# We're only accepting indices referring to components that exist
|
|
|
|
|
# (can't just do isinstance here because bools are instance of int, too)
|
|
|
|
|
elif type(before) == int:
|
2020-08-29 16:20:11 +03:00
|
|
|
|
if before >= len(self._components) or before < 0:
|
2020-08-28 16:20:14 +03:00
|
|
|
|
err = Errors.E959.format(
|
2020-08-28 22:04:02 +03:00
|
|
|
|
dir="before", idx=before, opts=self.component_names
|
2020-08-28 16:20:14 +03:00
|
|
|
|
)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
raise ValueError(err)
|
|
|
|
|
return before
|
|
|
|
|
elif type(after) == int:
|
2020-08-29 16:20:11 +03:00
|
|
|
|
if after >= len(self._components) or after < 0:
|
2020-08-28 22:04:02 +03:00
|
|
|
|
err = Errors.E959.format(
|
|
|
|
|
dir="after", idx=after, opts=self.component_names
|
|
|
|
|
)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
raise ValueError(err)
|
|
|
|
|
return after + 1
|
2020-08-28 22:04:02 +03:00
|
|
|
|
raise ValueError(Errors.E006.format(args=all_args, opts=self.component_names))
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
|
|
def has_pipe(self, name: str) -> bool:
|
2017-10-17 12:20:07 +03:00
|
|
|
|
"""Check if a component name is present in the pipeline. Equivalent to
|
|
|
|
|
`name in nlp.pipe_names`.
|
|
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
|
name (str): Name of the component.
|
2017-10-27 15:40:14 +03:00
|
|
|
|
RETURNS (bool): Whether a component of the name exists in the pipeline.
|
2019-03-15 18:23:17 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#has_pipe
|
2017-10-17 12:20:07 +03:00
|
|
|
|
"""
|
|
|
|
|
return name in self.pipe_names
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def replace_pipe(
|
|
|
|
|
self,
|
|
|
|
|
name: str,
|
|
|
|
|
factory_name: str,
|
2020-07-29 00:12:42 +03:00
|
|
|
|
*,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
config: Dict[str, Any] = SimpleFrozenDict(),
|
|
|
|
|
validate: bool = True,
|
2022-11-29 15:20:08 +03:00
|
|
|
|
) -> PipeCallable:
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""Replace a component in the pipeline.
|
|
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
|
name (str): Name of the component to replace.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
factory_name (str): Factory name of replacement component.
|
|
|
|
|
config (Optional[Dict[str, Any]]): Config parameters to use for this
|
|
|
|
|
component. Will be merged with default config, if available.
|
|
|
|
|
validate (bool): Whether to validate the component config against the
|
|
|
|
|
arguments and types expected by the factory.
|
2022-11-29 15:20:08 +03:00
|
|
|
|
RETURNS (Callable[[Doc], Doc]): The new pipeline component.
|
2019-03-15 18:23:17 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#replace_pipe
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""
|
2021-07-19 11:06:12 +03:00
|
|
|
|
if name not in self.component_names:
|
2018-04-03 16:50:31 +03:00
|
|
|
|
raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names))
|
2020-07-22 14:42:59 +03:00
|
|
|
|
if hasattr(factory_name, "__call__"):
|
|
|
|
|
err = Errors.E968.format(component=repr(factory_name), name=name)
|
|
|
|
|
raise ValueError(err)
|
|
|
|
|
# We need to delegate to Language.add_pipe here instead of just writing
|
|
|
|
|
# to Language.pipeline to make sure the configs are handled correctly
|
2021-07-19 11:06:12 +03:00
|
|
|
|
pipe_index = self.component_names.index(name)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
self.remove_pipe(name)
|
2020-08-29 16:20:11 +03:00
|
|
|
|
if not len(self._components) or pipe_index == len(self._components):
|
2020-08-05 10:30:58 +03:00
|
|
|
|
# we have no components to insert before/after, or we're replacing the last component
|
2020-10-08 11:34:01 +03:00
|
|
|
|
return self.add_pipe(
|
|
|
|
|
factory_name, name=name, config=config, validate=validate
|
|
|
|
|
)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
else:
|
2020-10-08 11:34:01 +03:00
|
|
|
|
return self.add_pipe(
|
2020-08-23 22:15:12 +03:00
|
|
|
|
factory_name,
|
|
|
|
|
name=name,
|
|
|
|
|
before=pipe_index,
|
|
|
|
|
config=config,
|
|
|
|
|
validate=validate,
|
|
|
|
|
)
|
2017-10-07 01:25:54 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def rename_pipe(self, old_name: str, new_name: str) -> None:
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""Rename a pipeline component.
|
|
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
|
old_name (str): Name of the component to rename.
|
|
|
|
|
new_name (str): New name of the component.
|
2019-03-15 18:23:17 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#rename_pipe
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""
|
2020-08-28 22:04:02 +03:00
|
|
|
|
if old_name not in self.component_names:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
Errors.E001.format(name=old_name, opts=self.component_names)
|
|
|
|
|
)
|
|
|
|
|
if new_name in self.component_names:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
Errors.E007.format(name=new_name, opts=self.component_names)
|
|
|
|
|
)
|
|
|
|
|
i = self.component_names.index(old_name)
|
2020-08-29 16:20:11 +03:00
|
|
|
|
self._components[i] = (new_name, self._components[i][1])
|
2020-07-22 14:42:59 +03:00
|
|
|
|
self._pipe_meta[new_name] = self._pipe_meta.pop(old_name)
|
|
|
|
|
self._pipe_configs[new_name] = self._pipe_configs.pop(old_name)
|
2020-10-04 15:43:45 +03:00
|
|
|
|
# Make sure [initialize] config is adjusted
|
|
|
|
|
if old_name in self._config["initialize"]["components"]:
|
|
|
|
|
init_cfg = self._config["initialize"]["components"].pop(old_name)
|
|
|
|
|
self._config["initialize"]["components"][new_name] = init_cfg
|
2023-06-27 11:47:07 +03:00
|
|
|
|
self._link_components()
|
2017-10-07 01:25:54 +03:00
|
|
|
|
|
2022-11-29 15:20:08 +03:00
|
|
|
|
def remove_pipe(self, name: str) -> Tuple[str, PipeCallable]:
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""Remove a component from the pipeline.
|
|
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
|
name (str): Name of the component to remove.
|
2022-11-29 15:20:08 +03:00
|
|
|
|
RETURNS (Tuple[str, Callable[[Doc], Doc]]): A `(name, component)` tuple of the removed component.
|
2019-03-15 18:23:17 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#remove_pipe
|
2017-10-07 01:25:54 +03:00
|
|
|
|
"""
|
2020-08-28 22:04:02 +03:00
|
|
|
|
if name not in self.component_names:
|
|
|
|
|
raise ValueError(Errors.E001.format(name=name, opts=self.component_names))
|
2020-08-29 16:20:11 +03:00
|
|
|
|
removed = self._components.pop(self.component_names.index(name))
|
2020-07-22 14:42:59 +03:00
|
|
|
|
# We're only removing the component itself from the metas/configs here
|
|
|
|
|
# because factory may be used for something else
|
|
|
|
|
self._pipe_meta.pop(name)
|
|
|
|
|
self._pipe_configs.pop(name)
|
2021-07-06 13:43:17 +03:00
|
|
|
|
self.meta.get("_sourced_vectors_hashes", {}).pop(name, None)
|
2020-10-04 15:43:45 +03:00
|
|
|
|
# Make sure name is removed from the [initialize] config
|
|
|
|
|
if name in self._config["initialize"]["components"]:
|
|
|
|
|
self._config["initialize"]["components"].pop(name)
|
2020-08-28 16:20:14 +03:00
|
|
|
|
# Make sure the name is also removed from the set of disabled components
|
2020-08-28 22:04:02 +03:00
|
|
|
|
if name in self.disabled:
|
2020-08-29 13:08:33 +03:00
|
|
|
|
self._disabled.remove(name)
|
2023-06-27 11:47:07 +03:00
|
|
|
|
self._link_components()
|
2019-10-30 21:04:17 +03:00
|
|
|
|
return removed
|
2017-06-04 23:52:09 +03:00
|
|
|
|
|
2020-08-28 16:20:14 +03:00
|
|
|
|
def disable_pipe(self, name: str) -> None:
|
|
|
|
|
"""Disable a pipeline component. The component will still exist on
|
2020-08-28 21:34:46 +03:00
|
|
|
|
the nlp object, but it won't be run as part of the pipeline. Does
|
|
|
|
|
nothing if the component is already disabled.
|
2020-08-28 16:20:14 +03:00
|
|
|
|
|
|
|
|
|
name (str): The name of the component to disable.
|
|
|
|
|
"""
|
2020-08-28 22:04:02 +03:00
|
|
|
|
if name not in self.component_names:
|
|
|
|
|
raise ValueError(Errors.E001.format(name=name, opts=self.component_names))
|
2020-08-29 13:08:33 +03:00
|
|
|
|
self._disabled.add(name)
|
2020-08-28 16:20:14 +03:00
|
|
|
|
|
|
|
|
|
def enable_pipe(self, name: str) -> None:
|
|
|
|
|
"""Enable a previously disabled pipeline component so it's run as part
|
2020-08-28 21:34:46 +03:00
|
|
|
|
of the pipeline. Does nothing if the component is already enabled.
|
2020-08-28 16:20:14 +03:00
|
|
|
|
|
|
|
|
|
name (str): The name of the component to enable.
|
|
|
|
|
"""
|
2020-08-28 22:04:02 +03:00
|
|
|
|
if name not in self.component_names:
|
|
|
|
|
raise ValueError(Errors.E001.format(name=name, opts=self.component_names))
|
|
|
|
|
if name in self.disabled:
|
2020-08-29 13:08:33 +03:00
|
|
|
|
self._disabled.remove(name)
|
2020-08-28 16:20:14 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def __call__(
|
|
|
|
|
self,
|
2021-09-22 10:41:05 +03:00
|
|
|
|
text: Union[str, Doc],
|
2020-07-29 00:12:42 +03:00
|
|
|
|
*,
|
2020-08-29 16:20:11 +03:00
|
|
|
|
disable: Iterable[str] = SimpleFrozenList(),
|
2020-07-22 14:42:59 +03:00
|
|
|
|
component_cfg: Optional[Dict[str, Dict[str, Any]]] = None,
|
|
|
|
|
) -> Doc:
|
2017-10-07 01:26:05 +03:00
|
|
|
|
"""Apply the pipeline to some text. The text can span multiple sentences,
|
2020-05-21 00:06:39 +03:00
|
|
|
|
and can contain arbitrary whitespace. Alignment into the original string
|
2015-08-25 16:37:17 +03:00
|
|
|
|
is preserved.
|
2016-12-18 18:54:52 +03:00
|
|
|
|
|
2021-09-22 10:41:05 +03:00
|
|
|
|
text (Union[str, Doc]): If `str`, the text to be processed. If `Doc`,
|
|
|
|
|
the doc will be passed directly to the pipeline, skipping
|
|
|
|
|
`Language.make_doc`.
|
🏷 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 16:21:40 +03:00
|
|
|
|
disable (List[str]): Names of the pipeline components to disable.
|
2020-07-29 00:12:42 +03:00
|
|
|
|
component_cfg (Dict[str, dict]): An optional dictionary with extra
|
|
|
|
|
keyword arguments for specific components.
|
2017-05-19 00:57:38 +03:00
|
|
|
|
RETURNS (Doc): A container for accessing the annotations.
|
2016-11-01 14:25:36 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#call
|
2015-08-25 16:37:17 +03:00
|
|
|
|
"""
|
2021-09-22 10:41:05 +03:00
|
|
|
|
doc = self._ensure_doc(text)
|
2019-03-11 01:36:47 +03:00
|
|
|
|
if component_cfg is None:
|
|
|
|
|
component_cfg = {}
|
2017-10-07 01:25:54 +03:00
|
|
|
|
for name, proc in self.pipeline:
|
2017-05-26 13:33:54 +03:00
|
|
|
|
if name in disable:
|
2017-05-16 12:21:59 +03:00
|
|
|
|
continue
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
if not hasattr(proc, "__call__"):
|
2018-04-03 16:50:31 +03:00
|
|
|
|
raise ValueError(Errors.E003.format(component=type(proc), name=name))
|
2021-01-29 03:51:21 +03:00
|
|
|
|
error_handler = self.default_error_handler
|
|
|
|
|
if hasattr(proc, "get_error_handler"):
|
|
|
|
|
error_handler = proc.get_error_handler()
|
2020-02-27 20:42:27 +03:00
|
|
|
|
try:
|
🏷 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 16:21:40 +03:00
|
|
|
|
doc = proc(doc, **component_cfg.get(name, {})) # type: ignore[call-arg]
|
2020-10-01 10:21:00 +03:00
|
|
|
|
except KeyError as e:
|
2020-10-03 12:43:56 +03:00
|
|
|
|
# This typically happens if a component is not initialized
|
|
|
|
|
raise ValueError(Errors.E109.format(name=name)) from e
|
2021-01-29 03:51:21 +03:00
|
|
|
|
except Exception as e:
|
|
|
|
|
error_handler(name, proc, [doc], e)
|
2022-09-01 20:37:23 +03:00
|
|
|
|
if not isinstance(doc, Doc):
|
|
|
|
|
raise ValueError(Errors.E005.format(name=name, returned_type=type(doc)))
|
2016-05-17 17:55:42 +03:00
|
|
|
|
return doc
|
2015-08-25 16:37:17 +03:00
|
|
|
|
|
2023-01-30 14:44:11 +03:00
|
|
|
|
def distill(
|
|
|
|
|
self,
|
|
|
|
|
teacher: "Language",
|
|
|
|
|
examples: Iterable[Example],
|
|
|
|
|
*,
|
|
|
|
|
drop: float = 0.0,
|
2023-04-21 14:49:40 +03:00
|
|
|
|
sgd: Union[Optimizer, None, Literal[False]] = None,
|
2023-01-30 14:44:11 +03:00
|
|
|
|
losses: Optional[Dict[str, float]] = None,
|
|
|
|
|
component_cfg: Optional[Dict[str, Dict[str, Any]]] = None,
|
|
|
|
|
exclude: Iterable[str] = SimpleFrozenList(),
|
|
|
|
|
annotates: Iterable[str] = SimpleFrozenList(),
|
|
|
|
|
student_to_teacher: Optional[Dict[str, str]] = None,
|
|
|
|
|
):
|
|
|
|
|
"""Distill the models in a student pipeline from a teacher pipeline.
|
|
|
|
|
teacher (Language): Teacher to distill from.
|
|
|
|
|
examples (Iterable[Example]): Distillation examples. The reference
|
|
|
|
|
(teacher) and predicted (student) docs must have the same number of
|
|
|
|
|
tokens and the same orthography.
|
|
|
|
|
drop (float): The dropout rate.
|
2023-04-21 14:49:40 +03:00
|
|
|
|
sgd (Union[Optimizer, None, Literal[False]]): An optimizer. Will
|
|
|
|
|
be created via create_optimizer if 'None'. No optimizer will
|
|
|
|
|
be used when set to 'False'.
|
2023-01-30 14:44:11 +03:00
|
|
|
|
losses (Optional(Dict[str, float])): Dictionary to update with the loss,
|
|
|
|
|
keyed by component.
|
|
|
|
|
component_cfg (Optional[Dict[str, Dict[str, Any]]]): Config parameters
|
|
|
|
|
for specific pipeline components, keyed by component name.
|
|
|
|
|
exclude (Iterable[str]): Names of components that shouldn't be updated.
|
|
|
|
|
annotates (Iterable[str]): Names of components that should set
|
|
|
|
|
annotations on the predicted examples after updating.
|
|
|
|
|
student_to_teacher (Optional[Dict[str, str]]): Map student pipe name to
|
|
|
|
|
teacher pipe name, only needed for pipes where the student pipe
|
|
|
|
|
name does not match the teacher pipe name.
|
|
|
|
|
RETURNS (Dict[str, float]): The updated losses dictionary
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/language#distill
|
|
|
|
|
"""
|
|
|
|
|
if student_to_teacher is None:
|
|
|
|
|
student_to_teacher = {}
|
|
|
|
|
if losses is None:
|
|
|
|
|
losses = {}
|
|
|
|
|
if isinstance(examples, list) and len(examples) == 0:
|
|
|
|
|
return losses
|
|
|
|
|
|
|
|
|
|
validate_distillation_examples(examples, "Language.distill")
|
2023-01-31 15:19:42 +03:00
|
|
|
|
examples = _copy_examples(examples, copy_x=True, copy_y=True)
|
2023-01-30 14:44:11 +03:00
|
|
|
|
|
|
|
|
|
if sgd is None:
|
|
|
|
|
if self._optimizer is None:
|
|
|
|
|
self._optimizer = self.create_optimizer()
|
|
|
|
|
sgd = self._optimizer
|
|
|
|
|
|
|
|
|
|
if component_cfg is None:
|
|
|
|
|
component_cfg = {}
|
|
|
|
|
pipe_kwargs = {}
|
|
|
|
|
for student_name, student_proc in self.pipeline:
|
|
|
|
|
component_cfg.setdefault(student_name, {})
|
|
|
|
|
pipe_kwargs[student_name] = deepcopy(component_cfg[student_name])
|
|
|
|
|
component_cfg[student_name].setdefault("drop", drop)
|
|
|
|
|
pipe_kwargs[student_name].setdefault("batch_size", self.batch_size)
|
|
|
|
|
|
|
|
|
|
teacher_pipes = dict(teacher.pipeline)
|
|
|
|
|
for student_name, student_proc in self.pipeline:
|
|
|
|
|
if student_name in annotates:
|
|
|
|
|
for doc, eg in zip(
|
|
|
|
|
_pipe(
|
|
|
|
|
(eg.predicted for eg in examples),
|
|
|
|
|
proc=student_proc,
|
|
|
|
|
name=student_name,
|
|
|
|
|
default_error_handler=self.default_error_handler,
|
|
|
|
|
kwargs=pipe_kwargs[student_name],
|
|
|
|
|
),
|
|
|
|
|
examples,
|
|
|
|
|
):
|
|
|
|
|
eg.predicted = doc
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
student_name not in exclude
|
|
|
|
|
and isinstance(student_proc, ty.DistillableComponent)
|
|
|
|
|
and student_proc.is_distillable
|
|
|
|
|
):
|
|
|
|
|
# A missing teacher pipe is not an error, some student pipes
|
|
|
|
|
# do not need a teacher, such as tok2vec layer losses.
|
|
|
|
|
teacher_name = (
|
|
|
|
|
student_to_teacher[student_name]
|
|
|
|
|
if student_name in student_to_teacher
|
|
|
|
|
else student_name
|
|
|
|
|
)
|
|
|
|
|
teacher_pipe = teacher_pipes.get(teacher_name, None)
|
|
|
|
|
student_proc.distill(
|
|
|
|
|
teacher_pipe,
|
|
|
|
|
examples,
|
2023-04-21 14:49:40 +03:00
|
|
|
|
sgd=None,
|
2023-01-30 14:44:11 +03:00
|
|
|
|
losses=losses,
|
|
|
|
|
**component_cfg[student_name],
|
|
|
|
|
)
|
|
|
|
|
|
2023-04-21 14:49:40 +03:00
|
|
|
|
# Only finish the update after all component updates are done. Some
|
|
|
|
|
# components may share weights (such as tok2vec) and we only want
|
|
|
|
|
# to apply weight updates after all gradients are accumulated.
|
|
|
|
|
for student_name, student_proc in self.pipeline:
|
|
|
|
|
if (
|
|
|
|
|
student_name not in exclude
|
|
|
|
|
and isinstance(student_proc, ty.DistillableComponent)
|
|
|
|
|
and student_proc.is_distillable
|
|
|
|
|
and sgd not in (None, False)
|
|
|
|
|
):
|
|
|
|
|
student_proc.finish_update(sgd)
|
|
|
|
|
|
2023-01-30 14:44:11 +03:00
|
|
|
|
return losses
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def disable_pipes(self, *names) -> "DisabledPipes":
|
2017-10-27 15:40:14 +03:00
|
|
|
|
"""Disable one or more pipeline components. If used as a context
|
|
|
|
|
manager, the pipeline will be restored to the initial state at the end
|
|
|
|
|
of the block. Otherwise, a DisabledPipes object is returned, that has
|
|
|
|
|
a `.restore()` method you can use to undo your changes.
|
2017-10-25 14:46:41 +03:00
|
|
|
|
|
2020-05-18 23:27:10 +03:00
|
|
|
|
This method has been deprecated since 3.0
|
2017-10-27 15:40:14 +03:00
|
|
|
|
"""
|
2020-05-18 23:27:10 +03:00
|
|
|
|
warnings.warn(Warnings.W096, DeprecationWarning)
|
2019-10-25 17:19:08 +03:00
|
|
|
|
if len(names) == 1 and isinstance(names[0], (list, tuple)):
|
🏷 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 16:21:40 +03:00
|
|
|
|
names = names[0] # type: ignore[assignment] # support list of names instead of spread
|
2020-08-29 13:08:46 +03:00
|
|
|
|
return self.select_pipes(disable=names)
|
2020-05-18 23:27:10 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def select_pipes(
|
|
|
|
|
self,
|
2020-07-29 00:12:42 +03:00
|
|
|
|
*,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
disable: Optional[Union[str, Iterable[str]]] = None,
|
|
|
|
|
enable: Optional[Union[str, Iterable[str]]] = None,
|
|
|
|
|
) -> "DisabledPipes":
|
2020-05-18 23:27:10 +03:00
|
|
|
|
"""Disable one or more pipeline components. If used as a context
|
|
|
|
|
manager, the pipeline will be restored to the initial state at the end
|
|
|
|
|
of the block. Otherwise, a DisabledPipes object is returned, that has
|
|
|
|
|
a `.restore()` method you can use to undo your changes.
|
|
|
|
|
|
|
|
|
|
disable (str or iterable): The name(s) of the pipes to disable
|
|
|
|
|
enable (str or iterable): The name(s) of the pipes to enable - all others will be disabled
|
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#select_pipes
|
2020-05-18 23:27:10 +03:00
|
|
|
|
"""
|
|
|
|
|
if enable is None and disable is None:
|
|
|
|
|
raise ValueError(Errors.E991)
|
2022-08-31 10:02:34 +03:00
|
|
|
|
if isinstance(disable, str):
|
2020-05-18 23:27:10 +03:00
|
|
|
|
disable = [disable]
|
|
|
|
|
if enable is not None:
|
|
|
|
|
if isinstance(enable, str):
|
|
|
|
|
enable = [enable]
|
|
|
|
|
to_disable = [pipe for pipe in self.pipe_names if pipe not in enable]
|
|
|
|
|
# raise an error if the enable and disable keywords are not consistent
|
|
|
|
|
if disable is not None and disable != to_disable:
|
2020-05-19 17:20:03 +03:00
|
|
|
|
raise ValueError(
|
|
|
|
|
Errors.E992.format(
|
|
|
|
|
enable=enable, disable=disable, names=self.pipe_names
|
|
|
|
|
)
|
|
|
|
|
)
|
2020-05-18 23:27:10 +03:00
|
|
|
|
disable = to_disable
|
🏷 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 16:21:40 +03:00
|
|
|
|
assert disable is not None
|
2020-10-09 13:06:20 +03:00
|
|
|
|
# DisabledPipes will restore the pipes in 'disable' when it's done, so we need to exclude
|
|
|
|
|
# those pipes that were already disabled.
|
|
|
|
|
disable = [d for d in disable if d not in self._disabled]
|
2020-05-18 23:27:10 +03:00
|
|
|
|
return DisabledPipes(self, disable)
|
2017-10-25 14:46:41 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def make_doc(self, text: str) -> Doc:
|
|
|
|
|
"""Turn a text into a Doc object.
|
|
|
|
|
|
|
|
|
|
text (str): The text to process.
|
|
|
|
|
RETURNS (Doc): The processed doc.
|
|
|
|
|
"""
|
2020-12-08 09:24:02 +03:00
|
|
|
|
if len(text) > self.max_length:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
Errors.E088.format(length=len(text), max_length=self.max_length)
|
|
|
|
|
)
|
2017-05-29 16:40:45 +03:00
|
|
|
|
return self.tokenizer(text)
|
|
|
|
|
|
2022-06-02 21:06:49 +03:00
|
|
|
|
def _ensure_doc(self, doc_like: Union[str, Doc, bytes]) -> Doc:
|
|
|
|
|
"""Create a Doc if need be, or raise an error if the input is not
|
|
|
|
|
a Doc, string, or a byte array (generated by Doc.to_bytes())."""
|
2021-09-22 10:41:05 +03:00
|
|
|
|
if isinstance(doc_like, Doc):
|
|
|
|
|
return doc_like
|
|
|
|
|
if isinstance(doc_like, str):
|
|
|
|
|
return self.make_doc(doc_like)
|
2022-06-02 21:06:49 +03:00
|
|
|
|
if isinstance(doc_like, bytes):
|
|
|
|
|
return Doc(self.vocab).from_bytes(doc_like)
|
|
|
|
|
raise ValueError(Errors.E1041.format(type=type(doc_like)))
|
2021-09-22 10:41:05 +03:00
|
|
|
|
|
2022-06-02 21:06:49 +03:00
|
|
|
|
def _ensure_doc_with_context(
|
|
|
|
|
self, doc_like: Union[str, Doc, bytes], context: _AnyContext
|
|
|
|
|
) -> Doc:
|
|
|
|
|
"""Call _ensure_doc to generate a Doc and set its context object."""
|
2021-11-02 17:08:22 +03:00
|
|
|
|
doc = self._ensure_doc(doc_like)
|
|
|
|
|
doc._context = context
|
|
|
|
|
return doc
|
|
|
|
|
|
2020-05-21 19:39:06 +03:00
|
|
|
|
def update(
|
|
|
|
|
self,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
examples: Iterable[Example],
|
2020-07-29 00:12:42 +03:00
|
|
|
|
_: Optional[Any] = None,
|
2020-05-21 19:39:06 +03:00
|
|
|
|
*,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
drop: float = 0.0,
|
2023-03-30 10:30:42 +03:00
|
|
|
|
sgd: Union[Optimizer, None, Literal[False]] = None,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
losses: Optional[Dict[str, float]] = None,
|
|
|
|
|
component_cfg: Optional[Dict[str, Dict[str, Any]]] = None,
|
2020-08-29 16:20:11 +03:00
|
|
|
|
exclude: Iterable[str] = SimpleFrozenList(),
|
2021-04-26 17:53:53 +03:00
|
|
|
|
annotates: Iterable[str] = SimpleFrozenList(),
|
2020-05-21 19:39:06 +03:00
|
|
|
|
):
|
2017-05-19 00:57:38 +03:00
|
|
|
|
"""Update the models in the pipeline.
|
|
|
|
|
|
2020-07-09 20:43:39 +03:00
|
|
|
|
examples (Iterable[Example]): A batch of examples
|
2020-07-29 00:12:42 +03:00
|
|
|
|
_: Should not be set - serves to catch backwards-incompatible scripts.
|
2019-10-14 13:28:53 +03:00
|
|
|
|
drop (float): The dropout rate.
|
2023-03-30 10:30:42 +03:00
|
|
|
|
sgd (Union[Optimizer, None, Literal[False]]): An optimizer. Will
|
|
|
|
|
be created via create_optimizer if 'None'. No optimizer will
|
|
|
|
|
be used when set to 'False'.
|
2021-04-26 17:53:53 +03:00
|
|
|
|
losses (Dict[str, float]): Dictionary to update with the loss, keyed by
|
|
|
|
|
component.
|
2020-07-09 20:43:39 +03:00
|
|
|
|
component_cfg (Dict[str, Dict]): Config parameters for specific pipeline
|
2019-05-24 15:06:26 +03:00
|
|
|
|
components, keyed by component name.
|
2020-08-05 00:39:19 +03:00
|
|
|
|
exclude (Iterable[str]): Names of components that shouldn't be updated.
|
2021-04-26 17:53:53 +03:00
|
|
|
|
annotates (Iterable[str]): Names of components that should set
|
|
|
|
|
annotations on the predicted examples after updating.
|
2020-07-09 20:43:39 +03:00
|
|
|
|
RETURNS (Dict[str, float]): The updated losses dictionary
|
2017-05-19 00:57:38 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#update
|
2017-05-19 00:57:38 +03:00
|
|
|
|
"""
|
2020-07-29 00:12:42 +03:00
|
|
|
|
if _ is not None:
|
2020-05-20 12:41:12 +03:00
|
|
|
|
raise ValueError(Errors.E989)
|
2020-07-09 20:43:39 +03:00
|
|
|
|
if losses is None:
|
|
|
|
|
losses = {}
|
🏷 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 16:21:40 +03:00
|
|
|
|
if isinstance(examples, list) and len(examples) == 0:
|
2020-07-09 20:43:39 +03:00
|
|
|
|
return losses
|
2020-08-12 00:29:31 +03:00
|
|
|
|
validate_examples(examples, "Language.update")
|
2021-01-19 18:47:44 +03:00
|
|
|
|
examples = _copy_examples(examples)
|
2017-08-20 15:42:07 +03:00
|
|
|
|
if sgd is None:
|
|
|
|
|
if self._optimizer is None:
|
2020-09-29 12:42:19 +03:00
|
|
|
|
self._optimizer = self.create_optimizer()
|
2017-08-20 15:42:07 +03:00
|
|
|
|
sgd = self._optimizer
|
2019-03-11 01:36:47 +03:00
|
|
|
|
if component_cfg is None:
|
|
|
|
|
component_cfg = {}
|
2021-04-26 17:53:53 +03:00
|
|
|
|
pipe_kwargs = {}
|
2020-05-22 16:55:45 +03:00
|
|
|
|
for i, (name, proc) in enumerate(self.pipeline):
|
2020-01-29 19:06:46 +03:00
|
|
|
|
component_cfg.setdefault(name, {})
|
2021-04-26 17:53:53 +03:00
|
|
|
|
pipe_kwargs[name] = deepcopy(component_cfg[name])
|
2020-01-29 19:06:46 +03:00
|
|
|
|
component_cfg[name].setdefault("drop", drop)
|
2021-04-26 17:53:53 +03:00
|
|
|
|
pipe_kwargs[name].setdefault("batch_size", self.batch_size)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
for name, proc in self.pipeline:
|
2023-02-03 17:22:25 +03:00
|
|
|
|
if (
|
|
|
|
|
name not in exclude
|
|
|
|
|
and isinstance(proc, ty.TrainableComponent)
|
|
|
|
|
and proc.is_trainable
|
|
|
|
|
):
|
|
|
|
|
proc.update(examples, sgd=None, losses=losses, **component_cfg[name])
|
2021-04-26 17:53:53 +03:00
|
|
|
|
if name in annotates:
|
|
|
|
|
for doc, eg in zip(
|
|
|
|
|
_pipe(
|
|
|
|
|
(eg.predicted for eg in examples),
|
|
|
|
|
proc=proc,
|
|
|
|
|
name=name,
|
|
|
|
|
default_error_handler=self.default_error_handler,
|
|
|
|
|
kwargs=pipe_kwargs[name],
|
|
|
|
|
),
|
|
|
|
|
examples,
|
|
|
|
|
):
|
|
|
|
|
eg.predicted = doc
|
2023-02-03 17:22:25 +03:00
|
|
|
|
# Only finish the update after all component updates are done. Some
|
|
|
|
|
# components may share weights (such as tok2vec) and we only want
|
|
|
|
|
# to apply weight updates after all gradients are accumulated.
|
|
|
|
|
for name, proc in self.pipeline:
|
|
|
|
|
if (
|
|
|
|
|
name not in exclude
|
|
|
|
|
and isinstance(proc, ty.TrainableComponent)
|
|
|
|
|
and proc.is_trainable
|
2023-03-30 10:30:42 +03:00
|
|
|
|
and sgd not in (None, False)
|
2023-02-03 17:22:25 +03:00
|
|
|
|
):
|
|
|
|
|
proc.finish_update(sgd)
|
|
|
|
|
|
2020-07-09 20:43:39 +03:00
|
|
|
|
return losses
|
2017-05-16 17:17:30 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def rehearse(
|
|
|
|
|
self,
|
|
|
|
|
examples: Iterable[Example],
|
2020-07-29 00:12:42 +03:00
|
|
|
|
*,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
sgd: Optional[Optimizer] = None,
|
|
|
|
|
losses: Optional[Dict[str, float]] = None,
|
|
|
|
|
component_cfg: Optional[Dict[str, Dict[str, Any]]] = None,
|
2020-08-29 16:20:11 +03:00
|
|
|
|
exclude: Iterable[str] = SimpleFrozenList(),
|
2020-07-22 14:42:59 +03:00
|
|
|
|
) -> Dict[str, float]:
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
"""Make a "rehearsal" update to the models in the pipeline, to prevent
|
|
|
|
|
forgetting. Rehearsal updates run an initial copy of the model over some
|
|
|
|
|
data, and update the model so its current predictions are more like the
|
2019-10-02 11:37:39 +03:00
|
|
|
|
initial ones. This is useful for keeping a pretrained model on-track,
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
even if you're updating it with a smaller set of examples.
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
examples (Iterable[Example]): A batch of `Example` objects.
|
|
|
|
|
sgd (Optional[Optimizer]): An optimizer.
|
|
|
|
|
component_cfg (Dict[str, Dict]): Config parameters for specific pipeline
|
|
|
|
|
components, keyed by component name.
|
2020-08-05 00:39:19 +03:00
|
|
|
|
exclude (Iterable[str]): Names of components that shouldn't be updated.
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
RETURNS (dict): Results from the update.
|
|
|
|
|
|
|
|
|
|
EXAMPLE:
|
|
|
|
|
>>> raw_text_batches = minibatch(raw_texts)
|
2020-07-06 14:02:36 +03:00
|
|
|
|
>>> for labelled_batch in minibatch(examples):
|
2019-11-11 19:35:27 +03:00
|
|
|
|
>>> nlp.update(labelled_batch)
|
2020-07-06 14:02:36 +03:00
|
|
|
|
>>> raw_batch = [Example.from_dict(nlp.make_doc(text), {}) for text in next(raw_text_batches)]
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
>>> nlp.rehearse(raw_batch)
|
2020-07-29 00:12:42 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#rehearse
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03: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 16:21:40 +03:00
|
|
|
|
if losses is None:
|
|
|
|
|
losses = {}
|
|
|
|
|
if isinstance(examples, list) and len(examples) == 0:
|
|
|
|
|
return losses
|
2020-08-12 00:29:31 +03:00
|
|
|
|
validate_examples(examples, "Language.rehearse")
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
if sgd is None:
|
|
|
|
|
if self._optimizer is None:
|
2020-09-29 12:42:19 +03:00
|
|
|
|
self._optimizer = self.create_optimizer()
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
sgd = self._optimizer
|
|
|
|
|
pipes = list(self.pipeline)
|
|
|
|
|
random.shuffle(pipes)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
if component_cfg is None:
|
|
|
|
|
component_cfg = {}
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
grads = {}
|
|
|
|
|
|
2022-02-23 18:10:05 +03:00
|
|
|
|
def get_grads(key, W, dW):
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
grads[key] = (W, dW)
|
2022-02-23 18:10:05 +03:00
|
|
|
|
return W, dW
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03: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 16:21:40 +03:00
|
|
|
|
get_grads.learn_rate = sgd.learn_rate # type: ignore[attr-defined, union-attr]
|
|
|
|
|
get_grads.b1 = sgd.b1 # type: ignore[attr-defined, union-attr]
|
|
|
|
|
get_grads.b2 = sgd.b2 # type: ignore[attr-defined, union-attr]
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
for name, proc in pipes:
|
2020-08-05 00:39:19 +03:00
|
|
|
|
if name in exclude or not hasattr(proc, "rehearse"):
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
continue
|
|
|
|
|
grads = {}
|
🏷 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 16:21:40 +03:00
|
|
|
|
proc.rehearse( # type: ignore[attr-defined]
|
2020-07-22 14:42:59 +03:00
|
|
|
|
examples, sgd=get_grads, losses=losses, **component_cfg.get(name, {})
|
2020-02-03 15:02:12 +03:00
|
|
|
|
)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
for key, (W, dW) in grads.items():
|
2022-02-23 18:10:05 +03:00
|
|
|
|
sgd(key, W, dW) # type: ignore[call-arg, misc]
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
return losses
|
|
|
|
|
|
2020-09-28 22:35:09 +03:00
|
|
|
|
def initialize(
|
|
|
|
|
self,
|
|
|
|
|
get_examples: Optional[Callable[[], Iterable[Example]]] = None,
|
|
|
|
|
*,
|
2023-01-30 14:44:11 +03:00
|
|
|
|
labels: Optional[Dict[str, Any]] = None,
|
2020-09-28 22:35:09 +03:00
|
|
|
|
sgd: Optional[Optimizer] = None,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
) -> Optimizer:
|
2020-07-29 00:12:42 +03:00
|
|
|
|
"""Initialize the pipe for training, using data examples if available.
|
2017-05-19 00:57:38 +03:00
|
|
|
|
|
2020-07-29 00:12:42 +03:00
|
|
|
|
get_examples (Callable[[], Iterable[Example]]): Optional function that
|
|
|
|
|
returns gold-standard Example objects.
|
2023-01-30 14:44:11 +03:00
|
|
|
|
labels (Optional[Dict[str, Any]]): Labels to pass to pipe initialization,
|
|
|
|
|
using the names of the pipes as keys. Overrides labels that are in
|
|
|
|
|
the model configuration.
|
2020-09-29 13:14:08 +03:00
|
|
|
|
sgd (Optional[Optimizer]): An optimizer to use for updates. If not
|
2020-09-29 12:42:19 +03:00
|
|
|
|
provided, will be created using the .create_optimizer() method.
|
2020-07-29 00:12:42 +03:00
|
|
|
|
RETURNS (thinc.api.Optimizer): The optimizer.
|
2019-03-15 18:23:17 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#initialize
|
2017-05-19 00:57:38 +03:00
|
|
|
|
"""
|
2019-11-11 19:35:27 +03:00
|
|
|
|
if get_examples is None:
|
2020-09-08 23:44:25 +03:00
|
|
|
|
util.logger.debug(
|
2020-09-28 22:35:09 +03:00
|
|
|
|
"No 'get_examples' callback provided to 'Language.initialize', creating dummy examples"
|
2020-09-08 23:44:25 +03:00
|
|
|
|
)
|
|
|
|
|
doc = Doc(self.vocab, words=["x", "y", "z"])
|
2023-06-02 15:29:52 +03:00
|
|
|
|
|
|
|
|
|
def get_examples():
|
|
|
|
|
return [Example.from_dict(doc, {})]
|
|
|
|
|
|
2020-09-08 23:44:25 +03:00
|
|
|
|
if not hasattr(get_examples, "__call__"):
|
2020-10-10 20:14:48 +03:00
|
|
|
|
err = Errors.E930.format(
|
|
|
|
|
method="Language.initialize", obj=type(get_examples)
|
|
|
|
|
)
|
2020-10-08 22:33:49 +03:00
|
|
|
|
raise TypeError(err)
|
2020-09-29 17:05:48 +03:00
|
|
|
|
# Make sure the config is interpolated so we can resolve subsections
|
|
|
|
|
config = self.config.interpolate()
|
|
|
|
|
# These are the settings provided in the [initialize] block in the config
|
|
|
|
|
I = registry.resolve(config["initialize"], schema=ConfigSchemaInit)
|
2021-01-12 13:29:31 +03:00
|
|
|
|
before_init = I["before_init"]
|
|
|
|
|
if before_init is not None:
|
|
|
|
|
before_init(self)
|
2021-03-09 15:01:31 +03:00
|
|
|
|
try:
|
|
|
|
|
init_vocab(
|
|
|
|
|
self, data=I["vocab_data"], lookups=I["lookups"], vectors=I["vectors"]
|
|
|
|
|
)
|
|
|
|
|
except IOError:
|
|
|
|
|
raise IOError(Errors.E884.format(vectors=I["vectors"]))
|
2022-01-18 19:14:35 +03:00
|
|
|
|
if self.vocab.vectors.shape[1] >= 1:
|
2020-09-29 12:42:19 +03:00
|
|
|
|
ops = get_current_ops()
|
2022-01-18 19:14:35 +03:00
|
|
|
|
self.vocab.vectors.to_ops(ops)
|
2020-09-29 12:52:45 +03:00
|
|
|
|
if hasattr(self.tokenizer, "initialize"):
|
|
|
|
|
tok_settings = validate_init_settings(
|
🏷 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 16:21:40 +03:00
|
|
|
|
self.tokenizer.initialize, # type: ignore[union-attr]
|
2020-09-29 17:05:48 +03:00
|
|
|
|
I["tokenizer"],
|
2020-09-29 12:52:45 +03:00
|
|
|
|
section="tokenizer",
|
|
|
|
|
name="tokenizer",
|
|
|
|
|
)
|
🏷 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 16:21:40 +03:00
|
|
|
|
self.tokenizer.initialize(get_examples, nlp=self, **tok_settings) # type: ignore[union-attr]
|
2017-10-07 01:25:54 +03:00
|
|
|
|
for name, proc in self.pipeline:
|
2021-10-21 16:31:06 +03:00
|
|
|
|
if isinstance(proc, ty.InitializableComponent):
|
2020-09-29 17:05:48 +03:00
|
|
|
|
p_settings = I["components"].get(name, {})
|
2023-01-30 14:44:11 +03:00
|
|
|
|
if labels is not None and name in labels:
|
|
|
|
|
p_settings["labels"] = labels[name]
|
2020-09-29 12:52:45 +03:00
|
|
|
|
p_settings = validate_init_settings(
|
|
|
|
|
proc.initialize, p_settings, section="components", name=name
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
)
|
2020-09-29 13:21:52 +03:00
|
|
|
|
proc.initialize(get_examples, nlp=self, **p_settings)
|
2021-03-09 06:01:13 +03:00
|
|
|
|
pretrain_cfg = config.get("pretraining")
|
|
|
|
|
if pretrain_cfg:
|
|
|
|
|
P = registry.resolve(pretrain_cfg, schema=ConfigSchemaPretrain)
|
|
|
|
|
init_tok2vec(self, P, I)
|
2021-02-02 05:08:40 +03:00
|
|
|
|
self._link_components()
|
2020-09-29 17:05:48 +03:00
|
|
|
|
self._optimizer = sgd
|
2020-09-29 12:42:19 +03:00
|
|
|
|
if sgd is not None:
|
|
|
|
|
self._optimizer = sgd
|
|
|
|
|
elif self._optimizer is None:
|
|
|
|
|
self._optimizer = self.create_optimizer()
|
2021-01-12 13:29:31 +03:00
|
|
|
|
after_init = I["after_init"]
|
|
|
|
|
if after_init is not None:
|
|
|
|
|
after_init(self)
|
2017-08-20 15:42:07 +03:00
|
|
|
|
return self._optimizer
|
2017-05-21 17:07:06 +03:00
|
|
|
|
|
2020-09-29 12:42:19 +03:00
|
|
|
|
def resume_training(self, *, sgd: Optional[Optimizer] = None) -> Optimizer:
|
2019-10-02 11:37:39 +03:00
|
|
|
|
"""Continue training a pretrained model.
|
2018-12-18 15:48:10 +03:00
|
|
|
|
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
Create and return an optimizer, and initialize "rehearsal" for any pipeline
|
|
|
|
|
component that has a .rehearse() method. Rehearsal is used to prevent
|
2020-07-29 00:12:42 +03:00
|
|
|
|
models from "forgetting" their initialized "knowledge". To perform
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
rehearsal, collect samples of text you want the models to retain performance
|
2020-07-06 14:02:36 +03:00
|
|
|
|
on, and call nlp.rehearse() with a batch of Example objects.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
|
|
RETURNS (Optimizer): The optimizer.
|
2020-07-29 00:12:42 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#resume_training
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
"""
|
2020-09-29 12:42:19 +03:00
|
|
|
|
ops = get_current_ops()
|
2022-01-18 19:14:35 +03:00
|
|
|
|
if self.vocab.vectors.shape[1] >= 1:
|
|
|
|
|
self.vocab.vectors.to_ops(ops)
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
for name, proc in self.pipeline:
|
|
|
|
|
if hasattr(proc, "_rehearsal_model"):
|
🏷 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 16:21:40 +03:00
|
|
|
|
proc._rehearsal_model = deepcopy(proc.model) # type: ignore[attr-defined]
|
2020-09-29 12:42:19 +03:00
|
|
|
|
if sgd is not None:
|
|
|
|
|
self._optimizer = sgd
|
|
|
|
|
elif self._optimizer is None:
|
|
|
|
|
self._optimizer = self.create_optimizer()
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
return self._optimizer
|
|
|
|
|
|
2021-01-29 03:51:21 +03:00
|
|
|
|
def set_error_handler(
|
|
|
|
|
self,
|
2022-11-29 15:20:08 +03:00
|
|
|
|
error_handler: Callable[[str, PipeCallable, List[Doc], Exception], NoReturn],
|
2021-01-29 03:51:21 +03:00
|
|
|
|
):
|
2022-11-29 15:20:08 +03:00
|
|
|
|
"""Set an error handler object for all the components in the pipeline
|
|
|
|
|
that implement a set_error_handler function.
|
2021-01-29 03:51:21 +03:00
|
|
|
|
|
2022-11-29 15:20:08 +03:00
|
|
|
|
error_handler (Callable[[str, Callable[[Doc], Doc], List[Doc], Exception], NoReturn]):
|
|
|
|
|
Function that deals with a failing batch of documents. This callable
|
|
|
|
|
function should take in the component's name, the component itself,
|
|
|
|
|
the offending batch of documents, and the exception that was thrown.
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#set_error_handler
|
2021-01-29 03:51:21 +03:00
|
|
|
|
"""
|
|
|
|
|
self.default_error_handler = error_handler
|
|
|
|
|
for name, pipe in self.pipeline:
|
|
|
|
|
if hasattr(pipe, "set_error_handler"):
|
|
|
|
|
pipe.set_error_handler(error_handler)
|
|
|
|
|
|
2019-03-11 01:36:47 +03:00
|
|
|
|
def evaluate(
|
2020-07-22 14:42:59 +03:00
|
|
|
|
self,
|
|
|
|
|
examples: Iterable[Example],
|
2020-07-29 00:12:42 +03:00
|
|
|
|
*,
|
2020-12-09 11:13:26 +03:00
|
|
|
|
batch_size: Optional[int] = None,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
scorer: Optional[Scorer] = None,
|
|
|
|
|
component_cfg: Optional[Dict[str, Dict[str, Any]]] = None,
|
2020-07-31 12:02:17 +03:00
|
|
|
|
scorer_cfg: Optional[Dict[str, Any]] = None,
|
2023-05-12 16:36:54 +03:00
|
|
|
|
per_component: bool = False,
|
🏷 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 16:21:40 +03:00
|
|
|
|
) -> Dict[str, Any]:
|
2019-05-24 15:06:36 +03:00
|
|
|
|
"""Evaluate a model's pipeline components.
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
examples (Iterable[Example]): `Example` objects.
|
2020-12-09 12:21:39 +03:00
|
|
|
|
batch_size (Optional[int]): Batch size to use.
|
2020-07-22 14:42:59 +03:00
|
|
|
|
scorer (Optional[Scorer]): Scorer to use. If not passed in, a new one
|
2019-05-24 15:06:36 +03:00
|
|
|
|
will be created.
|
|
|
|
|
component_cfg (dict): An optional dictionary with extra keyword
|
|
|
|
|
arguments for specific components.
|
2020-07-31 12:02:17 +03:00
|
|
|
|
scorer_cfg (dict): An optional dictionary with extra keyword arguments
|
|
|
|
|
for the scorer.
|
2023-05-12 16:36:54 +03:00
|
|
|
|
per_component (bool): Whether to return the scores keyed by component
|
|
|
|
|
name. Defaults to False.
|
2021-01-29 03:51:21 +03:00
|
|
|
|
|
2019-05-24 15:06:36 +03:00
|
|
|
|
RETURNS (Scorer): The scorer containing the evaluation results.
|
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#evaluate
|
2019-05-24 15:06:36 +03:00
|
|
|
|
"""
|
2020-12-31 02:45:50 +03:00
|
|
|
|
examples = list(examples)
|
2020-08-12 00:29:31 +03:00
|
|
|
|
validate_examples(examples, "Language.evaluate")
|
2021-01-19 18:47:44 +03:00
|
|
|
|
examples = _copy_examples(examples)
|
2020-12-09 11:13:26 +03:00
|
|
|
|
if batch_size is None:
|
|
|
|
|
batch_size = self.batch_size
|
2019-03-15 17:20:09 +03:00
|
|
|
|
if component_cfg is None:
|
|
|
|
|
component_cfg = {}
|
2020-07-31 12:02:17 +03:00
|
|
|
|
if scorer_cfg is None:
|
|
|
|
|
scorer_cfg = {}
|
Refactor the Scorer to improve flexibility (#5731)
* Refactor the Scorer to improve flexibility
Refactor the `Scorer` to improve flexibility for arbitrary pipeline
components.
* Individual pipeline components provide their own `evaluate` methods
that score a list of `Example`s and return a dictionary of scores
* `Scorer` is initialized either:
* with a provided pipeline containing components to be scored
* with a default pipeline containing the built-in statistical
components (senter, tagger, morphologizer, parser, ner)
* `Scorer.score` evaluates a list of `Example`s and returns a dictionary
of scores referring to the scores provided by the components in the
pipeline
Significant differences:
* `tags_acc` is renamed to `tag_acc` to be consistent with `token_acc`
and the new `morph_acc`, `pos_acc`, and `lemma_acc`
* Scoring is no longer cumulative: `Scorer.score` scores a list of
examples rather than a single example and does not retain any state
about previously scored examples
* PRF values in the returned scores are no longer multiplied by 100
* Add kwargs to Morphologizer.evaluate
* Create generalized scoring methods in Scorer
* Generalized static scoring methods are added to `Scorer`
* Methods require an attribute (either on Token or Doc) that is
used to key the returned scores
Naming differences:
* `uas`, `las`, and `las_per_type` in the scores dict are renamed to
`dep_uas`, `dep_las`, and `dep_las_per_type`
Scoring differences:
* `Doc.sents` is now scored as spans rather than on sentence-initial
token positions so that `Doc.sents` and `Doc.ents` can be scored with
the same method (this lowers scores since a single incorrect sentence
start results in two incorrect spans)
* Simplify / extend hasattr check for eval method
* Add hasattr check to tokenizer scoring
* Simplify to hasattr check for component scoring
* Reset Example alignment if docs are set
Reset the Example alignment if either doc is set in case the
tokenization has changed.
* Add PRF tokenization scoring for tokens as spans
Add PRF scores for tokens as character spans. The scores are:
* token_acc: # correct tokens / # gold tokens
* token_p/r/f: PRF for (token.idx, token.idx + len(token))
* Add docstring to Scorer.score_tokenization
* Rename component.evaluate() to component.score()
* Update Scorer API docs
* Update scoring for positive_label in textcat
* Fix TextCategorizer.score kwargs
* Update Language.evaluate docs
* Update score names in default config
2020-07-25 13:53:02 +03:00
|
|
|
|
if scorer is None:
|
2020-07-31 12:02:17 +03:00
|
|
|
|
kwargs = dict(scorer_cfg)
|
Refactor the Scorer to improve flexibility (#5731)
* Refactor the Scorer to improve flexibility
Refactor the `Scorer` to improve flexibility for arbitrary pipeline
components.
* Individual pipeline components provide their own `evaluate` methods
that score a list of `Example`s and return a dictionary of scores
* `Scorer` is initialized either:
* with a provided pipeline containing components to be scored
* with a default pipeline containing the built-in statistical
components (senter, tagger, morphologizer, parser, ner)
* `Scorer.score` evaluates a list of `Example`s and returns a dictionary
of scores referring to the scores provided by the components in the
pipeline
Significant differences:
* `tags_acc` is renamed to `tag_acc` to be consistent with `token_acc`
and the new `morph_acc`, `pos_acc`, and `lemma_acc`
* Scoring is no longer cumulative: `Scorer.score` scores a list of
examples rather than a single example and does not retain any state
about previously scored examples
* PRF values in the returned scores are no longer multiplied by 100
* Add kwargs to Morphologizer.evaluate
* Create generalized scoring methods in Scorer
* Generalized static scoring methods are added to `Scorer`
* Methods require an attribute (either on Token or Doc) that is
used to key the returned scores
Naming differences:
* `uas`, `las`, and `las_per_type` in the scores dict are renamed to
`dep_uas`, `dep_las`, and `dep_las_per_type`
Scoring differences:
* `Doc.sents` is now scored as spans rather than on sentence-initial
token positions so that `Doc.sents` and `Doc.ents` can be scored with
the same method (this lowers scores since a single incorrect sentence
start results in two incorrect spans)
* Simplify / extend hasattr check for eval method
* Add hasattr check to tokenizer scoring
* Simplify to hasattr check for component scoring
* Reset Example alignment if docs are set
Reset the Example alignment if either doc is set in case the
tokenization has changed.
* Add PRF tokenization scoring for tokens as spans
Add PRF scores for tokens as character spans. The scores are:
* token_acc: # correct tokens / # gold tokens
* token_p/r/f: PRF for (token.idx, token.idx + len(token))
* Add docstring to Scorer.score_tokenization
* Rename component.evaluate() to component.score()
* Update Scorer API docs
* Update scoring for positive_label in textcat
* Fix TextCategorizer.score kwargs
* Update Language.evaluate docs
* Update score names in default config
2020-07-25 13:53:02 +03:00
|
|
|
|
kwargs.setdefault("nlp", self)
|
|
|
|
|
scorer = Scorer(**kwargs)
|
2020-12-31 02:45:50 +03:00
|
|
|
|
# reset annotation in predicted docs and time tokenization
|
2020-07-29 12:02:31 +03:00
|
|
|
|
start_time = timer()
|
2021-09-27 21:44:14 +03:00
|
|
|
|
# this is purely for timing
|
|
|
|
|
for eg in examples:
|
|
|
|
|
self.make_doc(eg.reference.text)
|
2020-12-31 02:45:50 +03:00
|
|
|
|
# apply all pipeline components
|
2021-12-06 22:39:15 +03:00
|
|
|
|
docs = self.pipe(
|
|
|
|
|
(eg.predicted for eg in examples),
|
|
|
|
|
batch_size=batch_size,
|
|
|
|
|
component_cfg=component_cfg,
|
|
|
|
|
)
|
|
|
|
|
for eg, doc in zip(examples, docs):
|
|
|
|
|
eg.predicted = doc
|
2020-07-29 12:02:31 +03:00
|
|
|
|
end_time = timer()
|
2023-05-12 16:36:54 +03:00
|
|
|
|
results = scorer.score(examples, per_component=per_component)
|
2020-12-31 02:45:50 +03:00
|
|
|
|
n_words = sum(len(eg.predicted) for eg in examples)
|
2020-07-29 12:02:31 +03:00
|
|
|
|
results["speed"] = n_words / (end_time - start_time)
|
|
|
|
|
return results
|
2017-05-16 12:21:59 +03:00
|
|
|
|
|
2020-09-29 12:42:19 +03:00
|
|
|
|
def create_optimizer(self):
|
|
|
|
|
"""Create an optimizer, usually using the [training.optimizer] config."""
|
2020-09-29 13:00:08 +03:00
|
|
|
|
subconfig = {"optimizer": self.config["training"]["optimizer"]}
|
|
|
|
|
return registry.resolve(subconfig)["optimizer"]
|
2017-05-16 12:21:59 +03:00
|
|
|
|
|
2017-05-18 12:25:19 +03:00
|
|
|
|
@contextmanager
|
2020-09-03 13:51:04 +03:00
|
|
|
|
def use_params(self, params: Optional[dict]):
|
2017-05-19 00:57:38 +03:00
|
|
|
|
"""Replace weights of models in the pipeline with those provided in the
|
|
|
|
|
params dictionary. Can be used as a contextmanager, in which case,
|
|
|
|
|
models go back to their original weights after the block.
|
|
|
|
|
|
|
|
|
|
params (dict): A dictionary of parameters keyed by model ID.
|
|
|
|
|
|
|
|
|
|
EXAMPLE:
|
|
|
|
|
>>> with nlp.use_params(optimizer.averages):
|
2020-07-29 00:12:42 +03:00
|
|
|
|
>>> nlp.to_disk("/tmp/checkpoint")
|
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#use_params
|
2017-05-19 00:57:38 +03:00
|
|
|
|
"""
|
2020-09-03 13:51:04 +03:00
|
|
|
|
if not params:
|
|
|
|
|
yield
|
|
|
|
|
else:
|
|
|
|
|
contexts = [
|
🏷 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 16:21:40 +03:00
|
|
|
|
pipe.use_params(params) # type: ignore[attr-defined]
|
2020-09-03 13:51:04 +03:00
|
|
|
|
for name, pipe in self.pipeline
|
|
|
|
|
if hasattr(pipe, "use_params") and hasattr(pipe, "model")
|
|
|
|
|
]
|
|
|
|
|
# TODO: Having trouble with contextlib
|
|
|
|
|
# Workaround: these aren't actually context managers atm.
|
|
|
|
|
for context in contexts:
|
|
|
|
|
try:
|
|
|
|
|
next(context)
|
|
|
|
|
except StopIteration:
|
|
|
|
|
pass
|
|
|
|
|
yield
|
|
|
|
|
for context in contexts:
|
|
|
|
|
try:
|
|
|
|
|
next(context)
|
|
|
|
|
except StopIteration:
|
|
|
|
|
pass
|
2017-05-18 12:25:19 +03:00
|
|
|
|
|
2021-07-06 15:18:40 +03:00
|
|
|
|
@overload
|
|
|
|
|
def pipe(
|
|
|
|
|
self,
|
2021-10-26 12:53:50 +03:00
|
|
|
|
texts: Iterable[Union[str, Doc]],
|
2021-07-06 15:18:40 +03: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 16:21:40 +03:00
|
|
|
|
as_tuples: Literal[False] = ...,
|
|
|
|
|
batch_size: Optional[int] = ...,
|
|
|
|
|
disable: Iterable[str] = ...,
|
|
|
|
|
component_cfg: Optional[Dict[str, Dict[str, Any]]] = ...,
|
|
|
|
|
n_process: int = ...,
|
|
|
|
|
) -> Iterator[Doc]:
|
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
@overload
|
|
|
|
|
def pipe( # noqa: F811
|
2021-07-06 15:18:40 +03:00
|
|
|
|
self,
|
2021-11-02 17:08:22 +03:00
|
|
|
|
texts: Iterable[Tuple[Union[str, Doc], _AnyContext]],
|
2021-07-06 15:18:40 +03: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 16:21:40 +03:00
|
|
|
|
as_tuples: Literal[True] = ...,
|
2021-07-06 15:18:40 +03:00
|
|
|
|
batch_size: Optional[int] = ...,
|
|
|
|
|
disable: Iterable[str] = ...,
|
|
|
|
|
component_cfg: Optional[Dict[str, Dict[str, Any]]] = ...,
|
|
|
|
|
n_process: int = ...,
|
|
|
|
|
) -> Iterator[Tuple[Doc, _AnyContext]]:
|
|
|
|
|
...
|
|
|
|
|
|
2021-07-18 08:44:56 +03:00
|
|
|
|
def pipe( # noqa: F811
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
self,
|
2021-11-02 17:08:22 +03:00
|
|
|
|
texts: Union[
|
|
|
|
|
Iterable[Union[str, Doc]], Iterable[Tuple[Union[str, Doc], _AnyContext]]
|
|
|
|
|
],
|
2020-07-29 00:12:42 +03:00
|
|
|
|
*,
|
2020-07-22 14:42:59 +03:00
|
|
|
|
as_tuples: bool = False,
|
2020-12-09 11:13:26 +03:00
|
|
|
|
batch_size: Optional[int] = None,
|
2020-08-29 16:20:11 +03:00
|
|
|
|
disable: Iterable[str] = SimpleFrozenList(),
|
2020-07-22 14:42:59 +03:00
|
|
|
|
component_cfg: Optional[Dict[str, Dict[str, Any]]] = None,
|
|
|
|
|
n_process: int = 1,
|
🏷 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 16:21:40 +03:00
|
|
|
|
) -> Union[Iterator[Doc], Iterator[Tuple[Doc, _AnyContext]]]:
|
2017-10-27 15:40:14 +03:00
|
|
|
|
"""Process texts as a stream, and yield `Doc` objects in order.
|
2017-05-19 00:57:38 +03:00
|
|
|
|
|
2021-09-22 10:41:05 +03:00
|
|
|
|
texts (Iterable[Union[str, Doc]]): A sequence of texts or docs to
|
|
|
|
|
process.
|
2019-03-15 18:23:17 +03:00
|
|
|
|
as_tuples (bool): If set to True, inputs should be a sequence of
|
2017-08-19 13:21:33 +03:00
|
|
|
|
(text, context) tuples. Output will then be a sequence of
|
|
|
|
|
(doc, context) tuples. Defaults to False.
|
2020-12-09 11:13:26 +03:00
|
|
|
|
batch_size (Optional[int]): The number of texts to buffer.
|
2020-07-09 20:43:39 +03:00
|
|
|
|
disable (List[str]): Names of the pipeline components to disable.
|
|
|
|
|
component_cfg (Dict[str, Dict]): An optional dictionary with extra keyword
|
2019-03-15 18:23:17 +03:00
|
|
|
|
arguments for specific components.
|
2020-07-09 20:43:39 +03:00
|
|
|
|
n_process (int): Number of processors to process texts. If -1, set `multiprocessing.cpu_count()`.
|
2017-05-19 00:57:38 +03:00
|
|
|
|
YIELDS (Doc): Documents in the order of the original text.
|
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#pipe
|
2017-04-15 12:59:21 +03:00
|
|
|
|
"""
|
2017-08-19 13:21:33 +03:00
|
|
|
|
if as_tuples:
|
2021-11-02 17:08:22 +03:00
|
|
|
|
texts = cast(Iterable[Tuple[Union[str, Doc], _AnyContext]], texts)
|
|
|
|
|
docs_with_contexts = (
|
|
|
|
|
self._ensure_doc_with_context(text, context) for text, context in texts
|
|
|
|
|
)
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
docs = self.pipe(
|
2021-11-02 17:08:22 +03:00
|
|
|
|
docs_with_contexts,
|
2019-03-11 01:36:47 +03:00
|
|
|
|
batch_size=batch_size,
|
|
|
|
|
disable=disable,
|
2019-11-04 22:29:03 +03:00
|
|
|
|
n_process=n_process,
|
2019-03-11 01:36:47 +03:00
|
|
|
|
component_cfg=component_cfg,
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
)
|
2021-11-02 17:08:22 +03:00
|
|
|
|
for doc in docs:
|
|
|
|
|
context = doc._context
|
|
|
|
|
doc._context = None
|
2017-07-25 19:57:59 +03:00
|
|
|
|
yield (doc, context)
|
|
|
|
|
return
|
🏷 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 16:21:40 +03:00
|
|
|
|
|
2021-11-03 12:57:34 +03:00
|
|
|
|
texts = cast(Iterable[Union[str, Doc]], texts)
|
🏷 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 16:21:40 +03:00
|
|
|
|
|
|
|
|
|
# Set argument defaults
|
|
|
|
|
if n_process == -1:
|
|
|
|
|
n_process = mp.cpu_count()
|
2019-03-11 01:36:47 +03:00
|
|
|
|
if component_cfg is None:
|
|
|
|
|
component_cfg = {}
|
2020-12-09 11:13:26 +03:00
|
|
|
|
if batch_size is None:
|
|
|
|
|
batch_size = self.batch_size
|
2019-10-08 13:20:55 +03:00
|
|
|
|
|
|
|
|
|
pipes = (
|
|
|
|
|
[]
|
2020-01-06 16:57:34 +03:00
|
|
|
|
) # contains functools.partial objects to easily create multiprocess worker.
|
2017-10-07 01:25:54 +03:00
|
|
|
|
for name, proc in self.pipeline:
|
2017-05-26 13:33:54 +03:00
|
|
|
|
if name in disable:
|
2017-05-16 12:21:59 +03:00
|
|
|
|
continue
|
2019-03-11 01:36:47 +03:00
|
|
|
|
kwargs = component_cfg.get(name, {})
|
|
|
|
|
# Allow component_cfg to overwrite the top-level kwargs.
|
|
|
|
|
kwargs.setdefault("batch_size", batch_size)
|
2021-01-29 03:51:21 +03:00
|
|
|
|
f = functools.partial(
|
|
|
|
|
_pipe,
|
|
|
|
|
proc=proc,
|
|
|
|
|
name=name,
|
|
|
|
|
kwargs=kwargs,
|
|
|
|
|
default_error_handler=self.default_error_handler,
|
|
|
|
|
)
|
2019-10-08 13:20:55 +03:00
|
|
|
|
pipes.append(f)
|
|
|
|
|
|
|
|
|
|
if n_process != 1:
|
2021-10-21 17:14:23 +03:00
|
|
|
|
if self._has_gpu_model(disable):
|
|
|
|
|
warnings.warn(Warnings.W114)
|
|
|
|
|
|
2019-10-08 13:20:55 +03:00
|
|
|
|
docs = self._multiprocessing_pipe(texts, pipes, n_process, batch_size)
|
|
|
|
|
else:
|
|
|
|
|
# if n_process == 1, no processes are forked.
|
2021-09-22 10:41:05 +03:00
|
|
|
|
docs = (self._ensure_doc(text) for text in texts)
|
2019-10-08 13:20:55 +03:00
|
|
|
|
for pipe in pipes:
|
|
|
|
|
docs = pipe(docs)
|
2017-05-19 21:25:42 +03:00
|
|
|
|
for doc in docs:
|
2016-02-03 04:04:55 +03:00
|
|
|
|
yield doc
|
2016-02-01 11:01:13 +03:00
|
|
|
|
|
2021-10-21 17:14:23 +03:00
|
|
|
|
def _has_gpu_model(self, disable: Iterable[str]):
|
|
|
|
|
for name, proc in self.pipeline:
|
|
|
|
|
is_trainable = hasattr(proc, "is_trainable") and proc.is_trainable # type: ignore
|
|
|
|
|
if name in disable or not is_trainable:
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
if hasattr(proc, "model") and hasattr(proc.model, "ops") and isinstance(proc.model.ops, CupyOps): # type: ignore
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def _multiprocessing_pipe(
|
|
|
|
|
self,
|
2021-11-03 12:57:34 +03:00
|
|
|
|
texts: Iterable[Union[str, Doc]],
|
🏷 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 16:21:40 +03:00
|
|
|
|
pipes: Iterable[Callable[..., Iterator[Doc]]],
|
2020-07-22 14:42:59 +03:00
|
|
|
|
n_process: int,
|
|
|
|
|
batch_size: int,
|
🏷 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 16:21:40 +03:00
|
|
|
|
) -> Iterator[Doc]:
|
2022-06-02 21:06:49 +03:00
|
|
|
|
def prepare_input(
|
|
|
|
|
texts: Iterable[Union[str, Doc]]
|
|
|
|
|
) -> Iterable[Tuple[Union[str, bytes], _AnyContext]]:
|
|
|
|
|
# Serialize Doc inputs to bytes to avoid incurring pickling
|
|
|
|
|
# overhead when they are passed to child processes. Also yield
|
|
|
|
|
# any context objects they might have separately (as they are not serialized).
|
|
|
|
|
for doc_like in texts:
|
|
|
|
|
if isinstance(doc_like, Doc):
|
|
|
|
|
yield (doc_like.to_bytes(), cast(_AnyContext, doc_like._context))
|
|
|
|
|
else:
|
|
|
|
|
yield (doc_like, cast(_AnyContext, None))
|
|
|
|
|
|
|
|
|
|
serialized_texts_with_ctx = prepare_input(texts) # type: ignore
|
2019-10-08 13:20:55 +03:00
|
|
|
|
# raw_texts is used later to stop iteration.
|
2022-06-02 21:06:49 +03:00
|
|
|
|
texts, raw_texts = itertools.tee(serialized_texts_with_ctx) # type: ignore
|
2019-10-08 13:20:55 +03:00
|
|
|
|
# for sending texts to worker
|
🏷 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 16:21:40 +03:00
|
|
|
|
texts_q: List[mp.Queue] = [mp.Queue() for _ in range(n_process)]
|
2020-01-06 16:57:34 +03:00
|
|
|
|
# for receiving byte-encoded docs from worker
|
2019-10-08 13:20:55 +03:00
|
|
|
|
bytedocs_recv_ch, bytedocs_send_ch = zip(
|
|
|
|
|
*[mp.Pipe(False) for _ in range(n_process)]
|
|
|
|
|
)
|
|
|
|
|
|
2020-05-21 21:05:03 +03:00
|
|
|
|
batch_texts = util.minibatch(texts, batch_size)
|
2019-10-08 13:20:55 +03:00
|
|
|
|
# Sender sends texts to the workers.
|
|
|
|
|
# This is necessary to properly handle infinite length of texts.
|
|
|
|
|
# (In this case, all data cannot be sent to the workers at once)
|
|
|
|
|
sender = _Sender(batch_texts, texts_q, chunk_size=n_process)
|
2020-01-06 16:57:34 +03:00
|
|
|
|
# send twice to make process busy
|
2019-10-08 13:20:55 +03:00
|
|
|
|
sender.send()
|
|
|
|
|
sender.send()
|
|
|
|
|
|
|
|
|
|
procs = [
|
2020-02-12 13:50:42 +03:00
|
|
|
|
mp.Process(
|
|
|
|
|
target=_apply_pipes,
|
2022-06-02 21:06:49 +03:00
|
|
|
|
args=(
|
|
|
|
|
self._ensure_doc_with_context,
|
|
|
|
|
pipes,
|
|
|
|
|
rch,
|
|
|
|
|
sch,
|
|
|
|
|
Underscore.get_state(),
|
|
|
|
|
),
|
2020-02-12 13:50:42 +03:00
|
|
|
|
)
|
2019-10-08 13:20:55 +03:00
|
|
|
|
for rch, sch in zip(texts_q, bytedocs_send_ch)
|
|
|
|
|
]
|
|
|
|
|
for proc in procs:
|
|
|
|
|
proc.start()
|
|
|
|
|
|
|
|
|
|
# Cycle channels not to break the order of docs.
|
2020-01-06 16:57:34 +03:00
|
|
|
|
# The received object is a batch of byte-encoded docs, so flatten them with chain.from_iterable.
|
2021-06-28 12:48:00 +03:00
|
|
|
|
byte_tuples = chain.from_iterable(
|
|
|
|
|
recv.recv() for recv in cycle(bytedocs_recv_ch)
|
|
|
|
|
)
|
2019-10-08 13:20:55 +03:00
|
|
|
|
try:
|
2022-06-02 21:06:49 +03:00
|
|
|
|
for i, (_, (byte_doc, context, byte_error)) in enumerate(
|
2021-06-28 12:48:00 +03:00
|
|
|
|
zip(raw_texts, byte_tuples), 1
|
|
|
|
|
):
|
2021-05-17 14:28:39 +03:00
|
|
|
|
if byte_doc is not None:
|
|
|
|
|
doc = Doc(self.vocab).from_bytes(byte_doc)
|
2022-06-02 21:06:49 +03:00
|
|
|
|
doc._context = context
|
2021-05-17 14:28:39 +03:00
|
|
|
|
yield doc
|
|
|
|
|
elif byte_error is not None:
|
|
|
|
|
error = srsly.msgpack_loads(byte_error)
|
2021-06-28 12:48:00 +03:00
|
|
|
|
self.default_error_handler(
|
|
|
|
|
None, None, None, ValueError(Errors.E871.format(error=error))
|
|
|
|
|
)
|
2019-10-08 13:20:55 +03:00
|
|
|
|
if i % batch_size == 0:
|
|
|
|
|
# tell `sender` that one batch was consumed.
|
|
|
|
|
sender.step()
|
|
|
|
|
finally:
|
|
|
|
|
for proc in procs:
|
|
|
|
|
proc.terminate()
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def _link_components(self) -> None:
|
2020-01-29 19:06:46 +03:00
|
|
|
|
"""Register 'listeners' within pipeline components, to allow them to
|
|
|
|
|
effectively share weights.
|
|
|
|
|
"""
|
2021-02-01 14:19:58 +03:00
|
|
|
|
# I had thought, "Why do we do this inside the Language object? Shouldn't
|
2020-09-16 18:51:29 +03:00
|
|
|
|
# it be the tok2vec/transformer/etc's job?
|
|
|
|
|
# The problem is we need to do it during deserialization...And the
|
|
|
|
|
# components don't receive the pipeline then. So this does have to be
|
|
|
|
|
# here :(
|
2023-06-27 11:47:07 +03:00
|
|
|
|
# First, fix up all the internal component names in case they have
|
|
|
|
|
# gotten out of sync due to sourcing components from different
|
|
|
|
|
# pipelines, since find_listeners uses proc2.name for the listener
|
|
|
|
|
# map.
|
|
|
|
|
for name, proc in self.pipeline:
|
|
|
|
|
if hasattr(proc, "name"):
|
|
|
|
|
proc.name = name
|
2020-01-29 19:06:46 +03:00
|
|
|
|
for i, (name1, proc1) in enumerate(self.pipeline):
|
2021-10-21 16:31:06 +03:00
|
|
|
|
if isinstance(proc1, ty.ListenedToComponent):
|
2023-06-27 11:47:07 +03:00
|
|
|
|
proc1.listener_map = {}
|
2020-09-21 11:59:07 +03:00
|
|
|
|
for name2, proc2 in self.pipeline[i + 1 :]:
|
2021-01-20 03:12:35 +03:00
|
|
|
|
proc1.find_listeners(proc2)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
@classmethod
|
|
|
|
|
def from_config(
|
|
|
|
|
cls,
|
|
|
|
|
config: Union[Dict[str, Any], Config] = {},
|
2020-07-27 01:27:53 +03:00
|
|
|
|
*,
|
2020-08-05 00:39:19 +03:00
|
|
|
|
vocab: Union[Vocab, bool] = True,
|
2022-09-27 15:22:36 +03:00
|
|
|
|
disable: Union[str, Iterable[str]] = _DEFAULT_EMPTY_PIPES,
|
|
|
|
|
enable: Union[str, Iterable[str]] = _DEFAULT_EMPTY_PIPES,
|
|
|
|
|
exclude: Union[str, Iterable[str]] = _DEFAULT_EMPTY_PIPES,
|
2020-09-15 12:12:12 +03:00
|
|
|
|
meta: Dict[str, Any] = SimpleFrozenDict(),
|
2020-07-22 14:42:59 +03:00
|
|
|
|
auto_fill: bool = True,
|
|
|
|
|
validate: bool = True,
|
|
|
|
|
) -> "Language":
|
|
|
|
|
"""Create the nlp object from a loaded config. Will set up the tokenizer
|
|
|
|
|
and language data, add pipeline components etc. If no config is provided,
|
|
|
|
|
the default config of the given language is used.
|
2020-07-29 00:12:42 +03:00
|
|
|
|
|
|
|
|
|
config (Dict[str, Any] / Config): The loaded config.
|
2020-08-05 00:39:19 +03:00
|
|
|
|
vocab (Vocab): A Vocab object. If True, a vocab is created.
|
2022-08-31 10:02:34 +03:00
|
|
|
|
disable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to disable.
|
2020-08-28 16:20:14 +03:00
|
|
|
|
Disabled pipes will be loaded but they won't be run unless you
|
|
|
|
|
explicitly enable them by calling nlp.enable_pipe.
|
2022-08-31 10:02:34 +03:00
|
|
|
|
enable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to enable. All other
|
2022-06-17 22:24:13 +03:00
|
|
|
|
pipes will be disabled (and can be enabled using `nlp.enable_pipe`).
|
2022-08-31 10:02:34 +03:00
|
|
|
|
exclude (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to exclude.
|
2020-08-28 16:20:14 +03:00
|
|
|
|
Excluded components won't be loaded.
|
2020-09-15 12:12:12 +03:00
|
|
|
|
meta (Dict[str, Any]): Meta overrides for nlp.meta.
|
2020-07-29 00:12:42 +03:00
|
|
|
|
auto_fill (bool): Automatically fill in missing values in config based
|
|
|
|
|
on defaults and function argument annotations.
|
|
|
|
|
validate (bool): Validate the component config and arguments against
|
|
|
|
|
the types expected by the factory.
|
|
|
|
|
RETURNS (Language): The initialized Language class.
|
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#from_config
|
2020-07-22 14:42:59 +03:00
|
|
|
|
"""
|
|
|
|
|
if auto_fill:
|
2020-08-14 15:06:22 +03:00
|
|
|
|
config = Config(
|
|
|
|
|
cls.default_config, section_order=CONFIG_SECTION_ORDER
|
|
|
|
|
).merge(config)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
if "nlp" not in config:
|
|
|
|
|
raise ValueError(Errors.E985.format(config=config))
|
2020-09-29 22:08:13 +03:00
|
|
|
|
config_lang = config["nlp"].get("lang")
|
2020-09-15 15:24:06 +03:00
|
|
|
|
if config_lang is not None and config_lang != cls.lang:
|
2020-07-22 14:42:59 +03:00
|
|
|
|
raise ValueError(
|
|
|
|
|
Errors.E958.format(
|
2020-07-24 15:50:26 +03:00
|
|
|
|
bad_lang_code=config["nlp"]["lang"],
|
2020-07-22 14:42:59 +03:00
|
|
|
|
lang_code=cls.lang,
|
|
|
|
|
lang=util.get_object_name(cls),
|
|
|
|
|
)
|
|
|
|
|
)
|
2020-07-24 15:50:26 +03:00
|
|
|
|
config["nlp"]["lang"] = cls.lang
|
2020-07-22 14:42:59 +03:00
|
|
|
|
# This isn't very elegant, but we remove the [components] block here to prevent
|
|
|
|
|
# it from getting resolved (causes problems because we expect to pass in
|
|
|
|
|
# the nlp and name args for each component). If we're auto-filling, we're
|
|
|
|
|
# using the nlp.config with all defaults.
|
|
|
|
|
config = util.copy_config(config)
|
|
|
|
|
orig_pipeline = config.pop("components", {})
|
2023-04-21 14:49:40 +03:00
|
|
|
|
orig_distill = config.pop("distillation", None)
|
2021-03-09 06:01:13 +03:00
|
|
|
|
orig_pretraining = config.pop("pretraining", None)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
config["components"] = {}
|
2020-09-27 23:50:36 +03:00
|
|
|
|
if auto_fill:
|
|
|
|
|
filled = registry.fill(config, validate=validate, schema=ConfigSchema)
|
|
|
|
|
else:
|
|
|
|
|
filled = config
|
2020-07-22 14:42:59 +03:00
|
|
|
|
filled["components"] = orig_pipeline
|
|
|
|
|
config["components"] = orig_pipeline
|
2023-01-30 14:44:11 +03:00
|
|
|
|
if orig_distill is not None:
|
2023-04-21 14:49:40 +03:00
|
|
|
|
filled["distillation"] = orig_distill
|
|
|
|
|
config["distillation"] = orig_distill
|
2021-03-09 06:01:13 +03:00
|
|
|
|
if orig_pretraining is not None:
|
|
|
|
|
filled["pretraining"] = orig_pretraining
|
|
|
|
|
config["pretraining"] = orig_pretraining
|
2020-09-27 23:50:36 +03:00
|
|
|
|
resolved_nlp = registry.resolve(
|
|
|
|
|
filled["nlp"], validate=validate, schema=ConfigSchemaNlp
|
|
|
|
|
)
|
2020-09-27 23:21:31 +03:00
|
|
|
|
create_tokenizer = resolved_nlp["tokenizer"]
|
|
|
|
|
before_creation = resolved_nlp["before_creation"]
|
|
|
|
|
after_creation = resolved_nlp["after_creation"]
|
|
|
|
|
after_pipeline_creation = resolved_nlp["after_pipeline_creation"]
|
2020-08-05 20:47:54 +03:00
|
|
|
|
lang_cls = cls
|
|
|
|
|
if before_creation is not None:
|
|
|
|
|
lang_cls = before_creation(cls)
|
|
|
|
|
if (
|
|
|
|
|
not isinstance(lang_cls, type)
|
|
|
|
|
or not issubclass(lang_cls, cls)
|
|
|
|
|
or lang_cls is not cls
|
|
|
|
|
):
|
|
|
|
|
raise ValueError(Errors.E943.format(value=type(lang_cls)))
|
2021-03-09 17:35:21 +03:00
|
|
|
|
|
|
|
|
|
# Warn about require_gpu usage in jupyter notebook
|
|
|
|
|
warn_if_jupyter_cupy()
|
|
|
|
|
|
2020-08-13 18:38:30 +03:00
|
|
|
|
# Note that we don't load vectors here, instead they get loaded explicitly
|
|
|
|
|
# inside stuff like the spacy train function. If we loaded them here,
|
|
|
|
|
# then we would load them twice at runtime: once when we make from config,
|
|
|
|
|
# and then again when we load from disk.
|
2020-09-15 12:12:12 +03:00
|
|
|
|
nlp = lang_cls(vocab=vocab, create_tokenizer=create_tokenizer, meta=meta)
|
2020-08-05 20:47:54 +03:00
|
|
|
|
if after_creation is not None:
|
|
|
|
|
nlp = after_creation(nlp)
|
|
|
|
|
if not isinstance(nlp, cls):
|
|
|
|
|
raise ValueError(Errors.E942.format(name="creation", value=type(nlp)))
|
2020-08-13 18:38:30 +03:00
|
|
|
|
# To create the components we need to use the final interpolated config
|
|
|
|
|
# so all values are available (if component configs use variables).
|
|
|
|
|
# Later we replace the component config with the raw config again.
|
|
|
|
|
interpolated = filled.interpolate() if not filled.is_interpolated else filled
|
|
|
|
|
pipeline = interpolated.get("components", {})
|
2020-08-05 00:39:19 +03:00
|
|
|
|
# If components are loaded from a source (existing models), we cache
|
|
|
|
|
# them here so they're only loaded once
|
|
|
|
|
source_nlps = {}
|
2021-07-06 13:43:17 +03:00
|
|
|
|
source_nlp_vectors_hashes = {}
|
2021-10-04 13:19:02 +03:00
|
|
|
|
vocab_b = None
|
2020-07-24 15:50:26 +03:00
|
|
|
|
for pipe_name in config["nlp"]["pipeline"]:
|
2020-07-22 14:42:59 +03:00
|
|
|
|
if pipe_name not in pipeline:
|
|
|
|
|
opts = ", ".join(pipeline.keys())
|
|
|
|
|
raise ValueError(Errors.E956.format(name=pipe_name, opts=opts))
|
2020-07-22 18:29:31 +03:00
|
|
|
|
pipe_cfg = util.copy_config(pipeline[pipe_name])
|
2020-08-13 18:38:30 +03:00
|
|
|
|
raw_config = Config(filled["components"][pipe_name])
|
2020-08-28 16:20:14 +03:00
|
|
|
|
if pipe_name not in exclude:
|
2020-08-05 00:39:19 +03:00
|
|
|
|
if "factory" not in pipe_cfg and "source" not in pipe_cfg:
|
2020-07-22 14:42:59 +03:00
|
|
|
|
err = Errors.E984.format(name=pipe_name, config=pipe_cfg)
|
|
|
|
|
raise ValueError(err)
|
2020-08-05 00:39:19 +03:00
|
|
|
|
if "factory" in pipe_cfg:
|
|
|
|
|
factory = pipe_cfg.pop("factory")
|
|
|
|
|
# The pipe name (key in the config) here is the unique name
|
|
|
|
|
# of the component, not necessarily the factory
|
|
|
|
|
nlp.add_pipe(
|
2020-08-13 18:38:30 +03:00
|
|
|
|
factory,
|
|
|
|
|
name=pipe_name,
|
|
|
|
|
config=pipe_cfg,
|
|
|
|
|
validate=validate,
|
|
|
|
|
raw_config=raw_config,
|
2020-08-05 00:39:19 +03:00
|
|
|
|
)
|
|
|
|
|
else:
|
2023-06-27 11:47:07 +03:00
|
|
|
|
assert "source" in pipe_cfg
|
2021-10-04 13:19:02 +03:00
|
|
|
|
# We need the sourced components to reference the same
|
|
|
|
|
# vocab without modifying the current vocab state **AND**
|
|
|
|
|
# we still want to load the source model vectors to perform
|
|
|
|
|
# the vectors check. Since the source vectors clobber the
|
|
|
|
|
# current ones, we save the original vocab state and
|
|
|
|
|
# restore after this loop. Existing strings are preserved
|
|
|
|
|
# during deserialization, so they do not need any
|
|
|
|
|
# additional handling.
|
|
|
|
|
if vocab_b is None:
|
|
|
|
|
vocab_b = nlp.vocab.to_bytes(exclude=["lookups", "strings"])
|
2020-08-05 00:39:19 +03:00
|
|
|
|
model = pipe_cfg["source"]
|
|
|
|
|
if model not in source_nlps:
|
2021-10-04 13:19:02 +03:00
|
|
|
|
# Load with the same vocab, adding any strings
|
|
|
|
|
source_nlps[model] = util.load_model(
|
|
|
|
|
model, vocab=nlp.vocab, exclude=["lookups"]
|
|
|
|
|
)
|
2020-08-05 00:39:19 +03:00
|
|
|
|
source_name = pipe_cfg.get("component", pipe_name)
|
2021-04-08 11:21:22 +03:00
|
|
|
|
listeners_replaced = False
|
|
|
|
|
if "replace_listeners" in pipe_cfg:
|
2023-06-27 11:47:07 +03:00
|
|
|
|
# Make sure that the listened-to component has the
|
|
|
|
|
# state of the source pipeline listener map so that the
|
|
|
|
|
# replace_listeners method below works as intended.
|
|
|
|
|
source_nlps[model]._link_components()
|
2021-04-08 11:21:22 +03:00
|
|
|
|
for name, proc in source_nlps[model].pipeline:
|
|
|
|
|
if source_name in getattr(proc, "listening_components", []):
|
2021-06-28 12:48:00 +03:00
|
|
|
|
source_nlps[model].replace_listeners(
|
|
|
|
|
name, source_name, pipe_cfg["replace_listeners"]
|
|
|
|
|
)
|
2021-04-08 11:21:22 +03:00
|
|
|
|
listeners_replaced = True
|
2021-07-06 13:43:17 +03:00
|
|
|
|
with warnings.catch_warnings():
|
|
|
|
|
warnings.filterwarnings("ignore", message="\\[W113\\]")
|
2021-07-09 11:06:06 +03:00
|
|
|
|
nlp.add_pipe(
|
|
|
|
|
source_name, source=source_nlps[model], name=pipe_name
|
|
|
|
|
)
|
2023-06-27 11:47:07 +03:00
|
|
|
|
# At this point after nlp.add_pipe, the listener map
|
|
|
|
|
# corresponds to the new pipeline.
|
2021-07-06 13:43:17 +03:00
|
|
|
|
if model not in source_nlp_vectors_hashes:
|
2021-07-09 11:06:06 +03:00
|
|
|
|
source_nlp_vectors_hashes[model] = hash(
|
2021-11-19 10:51:19 +03:00
|
|
|
|
source_nlps[model].vocab.vectors.to_bytes(
|
|
|
|
|
exclude=["strings"]
|
|
|
|
|
)
|
2021-07-09 11:06:06 +03:00
|
|
|
|
)
|
2021-08-02 19:22:35 +03:00
|
|
|
|
if "_sourced_vectors_hashes" not in nlp.meta:
|
|
|
|
|
nlp.meta["_sourced_vectors_hashes"] = {}
|
2021-07-09 11:06:06 +03:00
|
|
|
|
nlp.meta["_sourced_vectors_hashes"][
|
|
|
|
|
pipe_name
|
|
|
|
|
] = source_nlp_vectors_hashes[model]
|
2021-04-08 11:21:22 +03:00
|
|
|
|
# Delete from cache if listeners were replaced
|
|
|
|
|
if listeners_replaced:
|
|
|
|
|
del source_nlps[model]
|
2021-10-04 13:19:02 +03:00
|
|
|
|
# Restore the original vocab after sourcing if necessary
|
|
|
|
|
if vocab_b is not None:
|
|
|
|
|
nlp.vocab.from_bytes(vocab_b)
|
2022-06-17 22:24:13 +03:00
|
|
|
|
|
|
|
|
|
# Resolve disabled/enabled settings.
|
2022-09-27 15:22:36 +03:00
|
|
|
|
if isinstance(disable, str):
|
|
|
|
|
disable = [disable]
|
|
|
|
|
if isinstance(enable, str):
|
|
|
|
|
enable = [enable]
|
|
|
|
|
if isinstance(exclude, str):
|
|
|
|
|
exclude = [exclude]
|
|
|
|
|
|
2022-11-08 16:58:10 +03:00
|
|
|
|
# `enable` should not be merged with `enabled` (the opposite is true for `disable`/`disabled`). If the config
|
|
|
|
|
# specifies values for `enabled` not included in `enable`, emit warning.
|
|
|
|
|
if id(enable) != id(_DEFAULT_EMPTY_PIPES):
|
|
|
|
|
enabled = config["nlp"].get("enabled", [])
|
|
|
|
|
if len(enabled) and not set(enabled).issubset(enable):
|
|
|
|
|
warnings.warn(
|
|
|
|
|
Warnings.W123.format(
|
|
|
|
|
enable=enable,
|
|
|
|
|
enabled=enabled,
|
2022-09-27 15:22:36 +03:00
|
|
|
|
)
|
2022-11-08 16:58:10 +03:00
|
|
|
|
)
|
2022-09-27 15:22:36 +03:00
|
|
|
|
|
2022-11-08 16:58:10 +03:00
|
|
|
|
# Ensure sets of disabled/enabled pipe names are not contradictory.
|
2022-06-17 22:24:13 +03:00
|
|
|
|
disabled_pipes = cls._resolve_component_status(
|
2022-11-08 16:58:10 +03:00
|
|
|
|
list({*disable, *config["nlp"].get("disabled", [])}),
|
|
|
|
|
enable,
|
2022-06-17 22:24:13 +03:00
|
|
|
|
config["nlp"]["pipeline"],
|
|
|
|
|
)
|
2020-08-29 13:08:33 +03:00
|
|
|
|
nlp._disabled = set(p for p in disabled_pipes if p not in exclude)
|
2022-06-17 22:24:13 +03:00
|
|
|
|
|
2020-12-09 11:13:26 +03:00
|
|
|
|
nlp.batch_size = config["nlp"]["batch_size"]
|
2020-07-22 14:42:59 +03:00
|
|
|
|
nlp.config = filled if auto_fill else config
|
2020-08-05 20:47:54 +03:00
|
|
|
|
if after_pipeline_creation is not None:
|
|
|
|
|
nlp = after_pipeline_creation(nlp)
|
|
|
|
|
if not isinstance(nlp, cls):
|
|
|
|
|
raise ValueError(
|
|
|
|
|
Errors.E942.format(name="pipeline_creation", value=type(nlp))
|
|
|
|
|
)
|
2020-07-22 14:42:59 +03:00
|
|
|
|
return nlp
|
|
|
|
|
|
2021-01-29 10:42:41 +03:00
|
|
|
|
def replace_listeners(
|
2021-01-30 04:52:33 +03:00
|
|
|
|
self,
|
|
|
|
|
tok2vec_name: str,
|
|
|
|
|
pipe_name: str,
|
|
|
|
|
listeners: Iterable[str],
|
2021-01-29 10:42:41 +03:00
|
|
|
|
) -> None:
|
|
|
|
|
"""Find listener layers (connecting to a token-to-vector embedding
|
|
|
|
|
component) of a given pipeline component model and replace
|
|
|
|
|
them with a standalone copy of the token-to-vector layer. This can be
|
|
|
|
|
useful when training a pipeline with components sourced from an existing
|
|
|
|
|
pipeline: if multiple components (e.g. tagger, parser, NER) listen to
|
|
|
|
|
the same tok2vec component, but some of them are frozen and not updated,
|
2023-07-14 10:45:54 +03:00
|
|
|
|
their performance may degrade significantly as the tok2vec component is
|
2021-01-29 10:42:41 +03:00
|
|
|
|
updated with new data. To prevent this, listeners can be replaced with
|
|
|
|
|
a standalone tok2vec layer that is owned by the component and doesn't
|
|
|
|
|
change if the component isn't updated.
|
|
|
|
|
|
|
|
|
|
tok2vec_name (str): Name of the token-to-vector component, typically
|
|
|
|
|
"tok2vec" or "transformer".
|
|
|
|
|
pipe_name (str): Name of pipeline component to replace listeners for.
|
|
|
|
|
listeners (Iterable[str]): The paths to the listeners, relative to the
|
|
|
|
|
component config, e.g. ["model.tok2vec"]. Typically, implementations
|
|
|
|
|
will only connect to one tok2vec component, [model.tok2vec], but in
|
|
|
|
|
theory, custom models can use multiple listeners. The value here can
|
|
|
|
|
either be an empty list to not replace any listeners, or a complete
|
|
|
|
|
(!) list of the paths to all listener layers used by the model.
|
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#replace_listeners
|
2021-01-29 10:42:41 +03:00
|
|
|
|
"""
|
|
|
|
|
if tok2vec_name not in self.pipe_names:
|
2021-01-29 15:39:23 +03:00
|
|
|
|
err = Errors.E889.format(
|
|
|
|
|
tok2vec=tok2vec_name,
|
|
|
|
|
name=pipe_name,
|
|
|
|
|
unknown=tok2vec_name,
|
|
|
|
|
opts=", ".join(self.pipe_names),
|
|
|
|
|
)
|
2021-01-29 10:42:41 +03:00
|
|
|
|
raise ValueError(err)
|
|
|
|
|
if pipe_name not in self.pipe_names:
|
2021-01-29 15:39:23 +03:00
|
|
|
|
err = Errors.E889.format(
|
|
|
|
|
tok2vec=tok2vec_name,
|
|
|
|
|
name=pipe_name,
|
|
|
|
|
unknown=pipe_name,
|
|
|
|
|
opts=", ".join(self.pipe_names),
|
|
|
|
|
)
|
2021-01-29 10:42:41 +03:00
|
|
|
|
raise ValueError(err)
|
|
|
|
|
tok2vec = self.get_pipe(tok2vec_name)
|
|
|
|
|
tok2vec_cfg = self.get_pipe_config(tok2vec_name)
|
2021-10-21 16:31:06 +03:00
|
|
|
|
if not isinstance(tok2vec, ty.ListenedToComponent):
|
2021-01-29 10:42:41 +03:00
|
|
|
|
raise ValueError(Errors.E888.format(name=tok2vec_name, pipe=type(tok2vec)))
|
2021-10-21 16:31:06 +03:00
|
|
|
|
tok2vec_model = tok2vec.model
|
2021-01-29 10:42:41 +03:00
|
|
|
|
pipe_listeners = tok2vec.listener_map.get(pipe_name, [])
|
2021-05-12 18:19:38 +03:00
|
|
|
|
pipe = self.get_pipe(pipe_name)
|
2021-01-29 10:42:41 +03:00
|
|
|
|
pipe_cfg = self._pipe_configs[pipe_name]
|
|
|
|
|
if listeners:
|
2023-02-02 13:15:22 +03:00
|
|
|
|
util.logger.debug("Replacing listeners of component '%s'", pipe_name)
|
🏷 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 16:21:40 +03:00
|
|
|
|
if len(list(listeners)) != len(pipe_listeners):
|
2021-01-29 10:42:41 +03:00
|
|
|
|
# The number of listeners defined in the component model doesn't
|
|
|
|
|
# match the listeners to replace, so we won't be able to update
|
|
|
|
|
# the nodes and generate a matching config
|
|
|
|
|
err = Errors.E887.format(
|
|
|
|
|
name=pipe_name,
|
|
|
|
|
tok2vec=tok2vec_name,
|
|
|
|
|
paths=listeners,
|
|
|
|
|
n_listeners=len(pipe_listeners),
|
|
|
|
|
)
|
|
|
|
|
raise ValueError(err)
|
2021-01-29 13:41:17 +03:00
|
|
|
|
# Update the config accordingly by copying the tok2vec model to all
|
2021-01-29 10:42:41 +03:00
|
|
|
|
# sections defined in the listener paths
|
|
|
|
|
for listener_path in listeners:
|
|
|
|
|
# Check if the path actually exists in the config
|
|
|
|
|
try:
|
|
|
|
|
util.dot_to_object(pipe_cfg, listener_path)
|
|
|
|
|
except KeyError:
|
|
|
|
|
err = Errors.E886.format(
|
|
|
|
|
name=pipe_name, tok2vec=tok2vec_name, path=listener_path
|
|
|
|
|
)
|
|
|
|
|
raise ValueError(err)
|
2021-05-12 18:19:38 +03:00
|
|
|
|
new_config = tok2vec_cfg["model"]
|
|
|
|
|
if "replace_listener_cfg" in tok2vec_model.attrs:
|
|
|
|
|
replace_func = tok2vec_model.attrs["replace_listener_cfg"]
|
2021-06-28 12:48:00 +03:00
|
|
|
|
new_config = replace_func(
|
|
|
|
|
tok2vec_cfg["model"], pipe_cfg["model"]["tok2vec"]
|
|
|
|
|
)
|
2021-05-12 18:19:38 +03:00
|
|
|
|
util.set_dot_to_object(pipe_cfg, listener_path, new_config)
|
2021-01-29 10:42:41 +03:00
|
|
|
|
# Go over the listener layers and replace them
|
|
|
|
|
for listener in pipe_listeners:
|
2021-05-12 18:19:38 +03:00
|
|
|
|
new_model = tok2vec_model.copy()
|
|
|
|
|
if "replace_listener" in tok2vec_model.attrs:
|
|
|
|
|
new_model = tok2vec_model.attrs["replace_listener"](new_model)
|
🏷 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 16:21:40 +03:00
|
|
|
|
util.replace_model_node(pipe.model, listener, new_model) # type: ignore[attr-defined]
|
2021-01-29 11:37:04 +03:00
|
|
|
|
tok2vec.remove_listener(listener, pipe_name)
|
2021-01-29 10:42:41 +03:00
|
|
|
|
|
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:
|
2017-05-26 13:33:54 +03:00
|
|
|
|
"""Save the current state to a directory. If a model is loaded, this
|
|
|
|
|
will include the model.
|
2017-04-17 02:40:26 +03:00
|
|
|
|
|
2020-05-24 19:51:10 +03:00
|
|
|
|
path (str / Path): Path to a directory, which will be created if
|
2019-03-10 21:16:45 +03:00
|
|
|
|
it doesn't exist.
|
🏷 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 16:21:40 +03:00
|
|
|
|
exclude (Iterable[str]): Names of components or serialization fields to exclude.
|
2017-05-19 00:57:38 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#to_disk
|
2017-05-17 13:04:50 +03:00
|
|
|
|
"""
|
|
|
|
|
path = util.ensure_path(path)
|
2019-12-22 03:53:56 +03:00
|
|
|
|
serializers = {}
|
🏷 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 16:21:40 +03:00
|
|
|
|
serializers["tokenizer"] = lambda p: self.tokenizer.to_disk( # type: ignore[union-attr]
|
2019-08-01 18:13:01 +03:00
|
|
|
|
p, exclude=["vocab"]
|
|
|
|
|
)
|
2020-04-06 19:54:32 +03:00
|
|
|
|
serializers["meta.json"] = lambda p: srsly.write_json(p, self.meta)
|
2020-02-27 20:42:27 +03:00
|
|
|
|
serializers["config.cfg"] = lambda p: self.config.to_disk(p)
|
2020-08-29 16:20:11 +03:00
|
|
|
|
for name, proc in self._components:
|
2019-03-10 21:16:45 +03:00
|
|
|
|
if name in exclude:
|
2017-05-31 14:42:39 +03:00
|
|
|
|
continue
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
if not hasattr(proc, "to_disk"):
|
2017-05-31 14:42:39 +03:00
|
|
|
|
continue
|
🏷 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 16:21:40 +03:00
|
|
|
|
serializers[name] = lambda p, proc=proc: proc.to_disk(p, exclude=["vocab"]) # type: ignore[misc]
|
2021-08-03 15:42:44 +03:00
|
|
|
|
serializers["vocab"] = lambda p: self.vocab.to_disk(p, exclude=exclude)
|
2019-03-10 21:16:45 +03:00
|
|
|
|
util.to_disk(path, serializers, exclude)
|
2017-05-31 14:42:39 +03:00
|
|
|
|
|
2022-06-17 22:24:13 +03:00
|
|
|
|
@staticmethod
|
|
|
|
|
def _resolve_component_status(
|
2022-08-31 10:02:34 +03:00
|
|
|
|
disable: Union[str, Iterable[str]],
|
|
|
|
|
enable: Union[str, Iterable[str]],
|
|
|
|
|
pipe_names: Iterable[str],
|
2022-06-17 22:24:13 +03:00
|
|
|
|
) -> Tuple[str, ...]:
|
|
|
|
|
"""Derives whether (1) `disable` and `enable` values are consistent and (2)
|
|
|
|
|
resolves those to a single set of disabled components. Raises an error in
|
|
|
|
|
case of inconsistency.
|
|
|
|
|
|
2022-08-31 10:02:34 +03:00
|
|
|
|
disable (Union[str, Iterable[str]]): Name(s) of component(s) or serialization fields to disable.
|
|
|
|
|
enable (Union[str, Iterable[str]]): Name(s) of pipeline component(s) to enable.
|
2022-06-17 22:24:13 +03:00
|
|
|
|
pipe_names (Iterable[str]): Names of all pipeline components.
|
|
|
|
|
|
|
|
|
|
RETURNS (Tuple[str, ...]): Names of components to exclude from pipeline w.r.t.
|
|
|
|
|
specified includes and excludes.
|
|
|
|
|
"""
|
|
|
|
|
|
2022-08-31 10:02:34 +03:00
|
|
|
|
if isinstance(disable, str):
|
2022-06-17 22:24:13 +03:00
|
|
|
|
disable = [disable]
|
|
|
|
|
to_disable = disable
|
|
|
|
|
|
|
|
|
|
if enable:
|
2022-08-31 10:02:34 +03:00
|
|
|
|
if isinstance(enable, str):
|
|
|
|
|
enable = [enable]
|
2022-11-08 16:58:10 +03:00
|
|
|
|
to_disable = {
|
|
|
|
|
*[pipe_name for pipe_name in pipe_names if pipe_name not in enable],
|
|
|
|
|
*disable,
|
|
|
|
|
}
|
|
|
|
|
# If any pipe to be enabled is in to_disable, the specification is inconsistent.
|
|
|
|
|
if len(set(enable) & to_disable):
|
2022-09-27 15:22:36 +03:00
|
|
|
|
raise ValueError(Errors.E1042.format(enable=enable, disable=disable))
|
2022-06-17 22:24:13 +03:00
|
|
|
|
|
|
|
|
|
return tuple(to_disable)
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def from_disk(
|
2021-06-28 12:48:00 +03:00
|
|
|
|
self,
|
|
|
|
|
path: Union[str, Path],
|
|
|
|
|
*,
|
|
|
|
|
exclude: Iterable[str] = SimpleFrozenList(),
|
|
|
|
|
overrides: Dict[str, Any] = SimpleFrozenDict(),
|
2020-07-22 14:42:59 +03:00
|
|
|
|
) -> "Language":
|
2017-05-19 00:57:38 +03:00
|
|
|
|
"""Loads state from a directory. Modifies the object in place and
|
2017-05-26 13:33:54 +03:00
|
|
|
|
returns it. If the saved `Language` object contains a model, the
|
|
|
|
|
model will be loaded.
|
2017-05-17 13:04:50 +03:00
|
|
|
|
|
2020-05-24 19:51:10 +03:00
|
|
|
|
path (str / Path): A path to a directory.
|
🏷 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 16:21:40 +03:00
|
|
|
|
exclude (Iterable[str]): Names of components or serialization fields to exclude.
|
2017-05-19 00:57:38 +03:00
|
|
|
|
RETURNS (Language): The modified `Language` object.
|
2017-05-17 13:04:50 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#from_disk
|
2017-05-17 13:04:50 +03:00
|
|
|
|
"""
|
2020-06-20 16:52:00 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def deserialize_meta(path: Path) -> None:
|
2020-05-27 15:48:54 +03:00
|
|
|
|
if path.exists():
|
|
|
|
|
data = srsly.read_json(path)
|
|
|
|
|
self.meta.update(data)
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def deserialize_vocab(path: Path) -> None:
|
2020-05-27 15:48:54 +03:00
|
|
|
|
if path.exists():
|
2021-08-03 15:42:44 +03:00
|
|
|
|
self.vocab.from_disk(path, exclude=exclude)
|
2020-05-27 15:48:54 +03:00
|
|
|
|
|
2017-05-17 13:04:50 +03:00
|
|
|
|
path = util.ensure_path(path)
|
2019-12-22 03:53:56 +03:00
|
|
|
|
deserializers = {}
|
🏷 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 16:21:40 +03:00
|
|
|
|
if Path(path / "config.cfg").exists(): # type: ignore[operator]
|
2020-08-27 17:44:36 +03:00
|
|
|
|
deserializers["config.cfg"] = lambda p: self.config.from_disk(
|
2021-05-31 11:36:52 +03:00
|
|
|
|
p, interpolate=False, overrides=overrides
|
2020-08-27 17:44:36 +03: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 16:21:40 +03:00
|
|
|
|
deserializers["meta.json"] = deserialize_meta # type: ignore[assignment]
|
|
|
|
|
deserializers["vocab"] = deserialize_vocab # type: ignore[assignment]
|
|
|
|
|
deserializers["tokenizer"] = lambda p: self.tokenizer.from_disk( # type: ignore[union-attr]
|
2019-08-01 18:13:01 +03:00
|
|
|
|
p, exclude=["vocab"]
|
|
|
|
|
)
|
2020-08-29 16:20:11 +03:00
|
|
|
|
for name, proc in self._components:
|
2019-03-10 21:16:45 +03:00
|
|
|
|
if name in exclude:
|
2017-05-31 14:42:39 +03:00
|
|
|
|
continue
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
if not hasattr(proc, "from_disk"):
|
2017-05-31 14:42:39 +03:00
|
|
|
|
continue
|
🏷 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 16:21:40 +03:00
|
|
|
|
deserializers[name] = lambda p, proc=proc: proc.from_disk( # type: ignore[misc]
|
2019-08-01 18:13:01 +03:00
|
|
|
|
p, exclude=["vocab"]
|
|
|
|
|
)
|
🏷 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 16:21:40 +03:00
|
|
|
|
if not (path / "vocab").exists() and "vocab" not in exclude: # type: ignore[operator]
|
2019-03-10 21:16:45 +03:00
|
|
|
|
# Convert to list here in case exclude is (default) tuple
|
|
|
|
|
exclude = list(exclude) + ["vocab"]
|
🏷 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 16:21:40 +03:00
|
|
|
|
util.from_disk(path, deserializers, exclude) # type: ignore[arg-type]
|
|
|
|
|
self._path = path # type: ignore[assignment]
|
2020-01-29 19:06:46 +03:00
|
|
|
|
self._link_components()
|
2017-05-31 14:42:39 +03:00
|
|
|
|
return self
|
2017-05-17 13:04:50 +03:00
|
|
|
|
|
2020-08-29 16:20:11 +03:00
|
|
|
|
def to_bytes(self, *, exclude: Iterable[str] = SimpleFrozenList()) -> bytes:
|
2017-05-17 13:04:50 +03:00
|
|
|
|
"""Serialize the current state to a binary string.
|
2016-12-18 18:54:52 +03: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 16:21:40 +03:00
|
|
|
|
exclude (Iterable[str]): Names of components or serialization fields to exclude.
|
2017-05-19 00:57:38 +03:00
|
|
|
|
RETURNS (bytes): The serialized form of the `Language` object.
|
2019-03-10 21:16:45 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#to_bytes
|
2017-05-17 13:04:50 +03: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 16:21:40 +03:00
|
|
|
|
serializers: Dict[str, Callable[[], bytes]] = {}
|
2021-08-03 15:42:44 +03:00
|
|
|
|
serializers["vocab"] = lambda: self.vocab.to_bytes(exclude=exclude)
|
🏷 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 16:21:40 +03:00
|
|
|
|
serializers["tokenizer"] = lambda: self.tokenizer.to_bytes(exclude=["vocab"]) # type: ignore[union-attr]
|
2019-03-10 21:16:45 +03:00
|
|
|
|
serializers["meta.json"] = lambda: srsly.json_dumps(self.meta)
|
2020-02-27 20:42:27 +03:00
|
|
|
|
serializers["config.cfg"] = lambda: self.config.to_bytes()
|
2020-08-29 16:20:11 +03:00
|
|
|
|
for name, proc in self._components:
|
2019-03-10 21:16:45 +03:00
|
|
|
|
if name in exclude:
|
2017-05-29 12:45:45 +03:00
|
|
|
|
continue
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
if not hasattr(proc, "to_bytes"):
|
2017-05-29 12:45:45 +03:00
|
|
|
|
continue
|
🏷 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 16:21:40 +03:00
|
|
|
|
serializers[name] = lambda proc=proc: proc.to_bytes(exclude=["vocab"]) # type: ignore[misc]
|
2017-10-17 19:18:10 +03:00
|
|
|
|
return util.to_bytes(serializers, exclude)
|
2017-04-15 13:05:47 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def from_bytes(
|
2020-08-29 16:20:11 +03:00
|
|
|
|
self, bytes_data: bytes, *, exclude: Iterable[str] = SimpleFrozenList()
|
2020-07-22 14:42:59 +03:00
|
|
|
|
) -> "Language":
|
2017-05-17 13:04:50 +03:00
|
|
|
|
"""Load state from a binary string.
|
|
|
|
|
|
2017-05-19 00:57:38 +03:00
|
|
|
|
bytes_data (bytes): The data to load from.
|
🏷 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 16:21:40 +03:00
|
|
|
|
exclude (Iterable[str]): Names of components or serialization fields to exclude.
|
2017-05-19 00:57:38 +03:00
|
|
|
|
RETURNS (Language): The `Language` object.
|
2019-03-10 21:16:45 +03:00
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
|
DOCS: https://spacy.io/api/language#from_bytes
|
2017-05-17 13:04:50 +03:00
|
|
|
|
"""
|
2020-06-20 16:52:00 +03:00
|
|
|
|
|
2020-05-27 15:48:54 +03:00
|
|
|
|
def deserialize_meta(b):
|
|
|
|
|
data = srsly.json_loads(b)
|
|
|
|
|
self.meta.update(data)
|
|
|
|
|
|
🏷 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 16:21:40 +03:00
|
|
|
|
deserializers: Dict[str, Callable[[bytes], Any]] = {}
|
2020-08-27 17:44:36 +03:00
|
|
|
|
deserializers["config.cfg"] = lambda b: self.config.from_bytes(
|
|
|
|
|
b, interpolate=False
|
|
|
|
|
)
|
2020-05-27 15:48:54 +03:00
|
|
|
|
deserializers["meta.json"] = deserialize_meta
|
2021-08-03 15:42:44 +03:00
|
|
|
|
deserializers["vocab"] = lambda b: self.vocab.from_bytes(b, exclude=exclude)
|
🏷 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 16:21:40 +03:00
|
|
|
|
deserializers["tokenizer"] = lambda b: self.tokenizer.from_bytes( # type: ignore[union-attr]
|
2019-08-01 18:13:01 +03:00
|
|
|
|
b, exclude=["vocab"]
|
|
|
|
|
)
|
2020-08-29 16:20:11 +03:00
|
|
|
|
for name, proc in self._components:
|
2019-03-10 21:16:45 +03:00
|
|
|
|
if name in exclude:
|
2017-05-29 12:45:45 +03:00
|
|
|
|
continue
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
if not hasattr(proc, "from_bytes"):
|
2017-05-29 12:45:45 +03:00
|
|
|
|
continue
|
🏷 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 16:21:40 +03:00
|
|
|
|
deserializers[name] = lambda b, proc=proc: proc.from_bytes( # type: ignore[misc]
|
2019-08-01 18:13:01 +03:00
|
|
|
|
b, exclude=["vocab"]
|
|
|
|
|
)
|
2019-03-10 21:16:45 +03:00
|
|
|
|
util.from_bytes(bytes_data, deserializers, exclude)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
self._link_components()
|
2017-05-17 13:04:50 +03:00
|
|
|
|
return self
|
2017-05-22 02:43:31 +03:00
|
|
|
|
|
2017-05-29 12:45:45 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
@dataclass
|
|
|
|
|
class FactoryMeta:
|
2020-07-29 00:12:42 +03:00
|
|
|
|
"""Dataclass containing information about a component and its defaults
|
|
|
|
|
provided by the @Language.component or @Language.factory decorator. It's
|
|
|
|
|
created whenever a component is defined and stored on the Language class for
|
|
|
|
|
each component instance and factory instance.
|
|
|
|
|
"""
|
2020-07-29 16:14:07 +03:00
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
factory: str
|
|
|
|
|
default_config: Optional[Dict[str, Any]] = None # noqa: E704
|
|
|
|
|
assigns: Iterable[str] = tuple()
|
|
|
|
|
requires: Iterable[str] = tuple()
|
|
|
|
|
retokenizes: bool = False
|
2020-07-26 14:18:43 +03:00
|
|
|
|
scores: Iterable[str] = tuple()
|
🏷 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 16:21:40 +03:00
|
|
|
|
default_score_weights: Optional[Dict[str, Optional[float]]] = None # noqa: E704
|
2019-10-27 15:35:49 +03:00
|
|
|
|
|
|
|
|
|
|
2017-10-25 14:46:41 +03:00
|
|
|
|
class DisabledPipes(list):
|
2017-10-27 15:40:14 +03:00
|
|
|
|
"""Manager for temporary pipeline disabling."""
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
|
2020-07-29 00:12:42 +03:00
|
|
|
|
def __init__(self, nlp: Language, names: List[str]) -> None:
|
2017-10-25 14:46:41 +03:00
|
|
|
|
self.nlp = nlp
|
|
|
|
|
self.names = names
|
2020-08-28 16:20:14 +03:00
|
|
|
|
for name in self.names:
|
|
|
|
|
self.nlp.disable_pipe(name)
|
2017-10-25 14:46:41 +03:00
|
|
|
|
list.__init__(self)
|
2020-08-28 16:20:14 +03:00
|
|
|
|
self.extend(self.names)
|
2017-10-25 14:46:41 +03:00
|
|
|
|
|
|
|
|
|
def __enter__(self):
|
2017-10-25 15:56:16 +03:00
|
|
|
|
return self
|
2017-10-25 14:46:41 +03:00
|
|
|
|
|
|
|
|
|
def __exit__(self, *args):
|
|
|
|
|
self.restore()
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def restore(self) -> None:
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
"""Restore the pipeline to its state when DisabledPipes was created."""
|
2020-08-28 16:20:14 +03:00
|
|
|
|
for name in self.names:
|
2020-08-28 22:04:02 +03:00
|
|
|
|
if name not in self.nlp.component_names:
|
2020-08-28 21:35:26 +03:00
|
|
|
|
raise ValueError(Errors.E008.format(name=name))
|
2020-08-28 16:20:14 +03:00
|
|
|
|
self.nlp.enable_pipe(name)
|
2017-10-25 14:46:41 +03:00
|
|
|
|
self[:] = []
|
|
|
|
|
|
|
|
|
|
|
2023-01-31 15:19:42 +03:00
|
|
|
|
def _copy_examples(
|
|
|
|
|
examples: Iterable[Example], *, copy_x: bool = True, copy_y: bool = False
|
|
|
|
|
) -> List[Example]:
|
2021-01-19 18:47:44 +03:00
|
|
|
|
"""Make a copy of a batch of examples, copying the predicted Doc as well.
|
|
|
|
|
This is used in contexts where we need to take ownership of the examples
|
2021-01-27 04:40:03 +03:00
|
|
|
|
so that they can be mutated, for instance during Language.evaluate and
|
2021-01-19 18:47:44 +03:00
|
|
|
|
Language.update.
|
|
|
|
|
"""
|
2023-01-31 15:19:42 +03:00
|
|
|
|
return [
|
|
|
|
|
Example(eg.x.copy() if copy_x else eg.x, eg.y.copy() if copy_y else eg.y)
|
|
|
|
|
for eg in examples
|
|
|
|
|
]
|
2021-01-19 18:47:44 +03:00
|
|
|
|
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def _apply_pipes(
|
2022-06-02 21:06:49 +03:00
|
|
|
|
ensure_doc: Callable[[Union[str, Doc, bytes], _AnyContext], Doc],
|
🏷 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 16:21:40 +03:00
|
|
|
|
pipes: Iterable[Callable[..., Iterator[Doc]]],
|
2020-07-22 14:42:59 +03:00
|
|
|
|
receiver,
|
|
|
|
|
sender,
|
|
|
|
|
underscore_state: Tuple[dict, dict, dict],
|
|
|
|
|
) -> None:
|
2019-10-08 13:20:55 +03:00
|
|
|
|
"""Worker for Language.pipe
|
|
|
|
|
|
2021-09-22 10:41:05 +03:00
|
|
|
|
ensure_doc (Callable[[Union[str, Doc]], Doc]): Function to create Doc from text
|
|
|
|
|
or raise an error if the input is neither a Doc nor a string.
|
🏷 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 16:21:40 +03:00
|
|
|
|
pipes (Iterable[Pipe]): The components to apply.
|
2019-10-18 12:33:38 +03:00
|
|
|
|
receiver (multiprocessing.Connection): Pipe to receive text. Usually
|
|
|
|
|
created by `multiprocessing.Pipe()`
|
|
|
|
|
sender (multiprocessing.Connection): Pipe to send doc. Usually created by
|
|
|
|
|
`multiprocessing.Pipe()`
|
2020-07-22 14:42:59 +03:00
|
|
|
|
underscore_state (Tuple[dict, dict, dict]): The data in the Underscore class
|
|
|
|
|
of the parent.
|
2019-10-08 13:20:55 +03:00
|
|
|
|
"""
|
2020-02-12 13:50:42 +03:00
|
|
|
|
Underscore.load_state(underscore_state)
|
2019-10-08 13:20:55 +03:00
|
|
|
|
while True:
|
2021-05-17 14:28:39 +03:00
|
|
|
|
try:
|
2022-06-02 21:06:49 +03:00
|
|
|
|
texts_with_ctx = receiver.get()
|
|
|
|
|
docs = (
|
|
|
|
|
ensure_doc(doc_like, context) for doc_like, context in texts_with_ctx
|
|
|
|
|
)
|
2021-05-17 14:28:39 +03:00
|
|
|
|
for pipe in pipes:
|
🏷 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 16:21:40 +03:00
|
|
|
|
docs = pipe(docs) # type: ignore[arg-type, assignment]
|
2021-05-17 14:28:39 +03:00
|
|
|
|
# Connection does not accept unpickable objects, so send list.
|
2021-11-03 09:51:53 +03:00
|
|
|
|
byte_docs = [(doc.to_bytes(), doc._context, None) for doc in docs]
|
2022-06-02 21:06:49 +03:00
|
|
|
|
padding = [(None, None, None)] * (len(texts_with_ctx) - len(byte_docs))
|
🏷 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 16:21:40 +03:00
|
|
|
|
sender.send(byte_docs + padding) # type: ignore[operator]
|
2021-05-17 14:28:39 +03:00
|
|
|
|
except Exception:
|
2021-11-03 09:51:53 +03:00
|
|
|
|
error_msg = [(None, None, srsly.msgpack_dumps(traceback.format_exc()))]
|
2022-06-02 21:06:49 +03:00
|
|
|
|
padding = [(None, None, None)] * (len(texts_with_ctx) - 1)
|
2021-05-17 14:28:39 +03:00
|
|
|
|
sender.send(error_msg + padding)
|
2019-10-08 13:20:55 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class _Sender:
|
|
|
|
|
"""Util for sending data to multiprocessing workers in Language.pipe"""
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def __init__(
|
|
|
|
|
self, data: Iterable[Any], queues: List[mp.Queue], chunk_size: int
|
|
|
|
|
) -> None:
|
2019-10-08 13:20:55 +03:00
|
|
|
|
self.data = iter(data)
|
|
|
|
|
self.queues = iter(cycle(queues))
|
|
|
|
|
self.chunk_size = chunk_size
|
|
|
|
|
self.count = 0
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def send(self) -> None:
|
2019-10-08 13:20:55 +03:00
|
|
|
|
"""Send chunk_size items from self.data to channels."""
|
|
|
|
|
for item, q in itertools.islice(
|
|
|
|
|
zip(self.data, cycle(self.queues)), self.chunk_size
|
|
|
|
|
):
|
|
|
|
|
# cycle channels so that distribute the texts evenly
|
|
|
|
|
q.put(item)
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
def step(self) -> None:
|
|
|
|
|
"""Tell sender that comsumed one item. Data is sent to the workers after
|
|
|
|
|
every chunk_size calls.
|
|
|
|
|
"""
|
2019-10-08 13:20:55 +03:00
|
|
|
|
self.count += 1
|
|
|
|
|
if self.count >= self.chunk_size:
|
|
|
|
|
self.count = 0
|
|
|
|
|
self.send()
|