2023-06-14 18:48:41 +03:00
|
|
|
from collections import OrderedDict
|
2020-07-22 14:42:59 +03:00
|
|
|
from pathlib import Path
|
2023-06-14 18:48:41 +03:00
|
|
|
from typing import Any, Dict, List, Optional, Union
|
|
|
|
|
2019-09-09 20:17:55 +03:00
|
|
|
import srsly
|
2019-09-15 23:08:13 +03:00
|
|
|
from preshed.bloom import BloomFilter
|
2019-09-09 20:17:55 +03:00
|
|
|
|
|
|
|
from .errors import Errors
|
2019-09-15 23:08:13 +03:00
|
|
|
from .strings import get_string_id
|
2023-06-14 18:48:41 +03:00
|
|
|
from .util import SimpleFrozenDict, ensure_path, load_language_data, registry
|
Bloom-filter backed Lookup Tables (#4268)
* Improve load_language_data helper
* WIP: Add Lookups implementation
* Start moving lemma data over to JSON
* WIP: move data over for more languages
* Convert more languages
* Fix lemmatizer fixtures in tests
* Finish conversion
* Auto-format JSON files
* Fix test for now
* Make sure tables are stored on instance
* Update docstrings
* Update docstrings and errors
* Update test
* Add Lookups.__len__
* Add serialization methods
* Add Lookups.remove_table
* Use msgpack for serialization to disk
* Fix file exists check
* Try using OrderedDict for everything
* Update .flake8 [ci skip]
* Try fixing serialization
* Update test_lookups.py
* Update test_serialize_vocab_strings.py
* Lookups / Tables now work
This implements the stubs in the Lookups/Table classes. Currently this
is in Cython but with no type declarations, so that could be improved.
* Add lookups to setup.py
* Actually add lookups pyx
The previous commit added the old py file...
* Lookups work-in-progress
* Move from pyx back to py
* Add string based lookups, fix serialization
* Update tests, language/lemmatizer to work with string lookups
There are some outstanding issues here:
- a pickling-related test fails due to the bloom filter
- some custom lemmatizers (fr/nl at least) have issues
More generally, there's a question of how to deal with the case where
you have a string but want to use the lookup table. Currently the table
allows access by string or id, but that's getting pretty awkward.
* Change lemmatizer lookup method to pass (orth, string)
* Fix token lookup
* Fix French lookup
* Fix lt lemmatizer test
* Fix Dutch lemmatizer
* Fix lemmatizer lookup test
This was using a normal dict instead of a Table, so checks for the
string instead of an integer key failed.
* Make uk/nl/ru lemmatizer lookup methods consistent
The mentioned tokenizers all have their own implementation of the
`lookup` method, which accesses a `Lookups` table. The way that was
called in `token.pyx` was changed so this should be updated to have the
same arguments as `lookup` in `lemmatizer.py` (specificially (orth/id,
string)).
Prior to this change tests weren't failing, but there would probably be
issues with normal use of a model. More tests should proably be added.
Additionally, the language-specific `lookup` implementations seem like
they might not be needed, since they handle things like lower-casing
that aren't actually language specific.
* Make recently added Greek method compatible
* Remove redundant class/method
Leftovers from a merge not cleaned up adequately.
2019-09-12 18:26:11 +03:00
|
|
|
|
2019-10-01 22:36:04 +03:00
|
|
|
UNSET = object()
|
|
|
|
|
|
|
|
|
2021-06-28 12:48:00 +03:00
|
|
|
def load_lookups(lang: str, tables: List[str], strict: bool = True) -> "Lookups":
|
2020-07-22 14:42:59 +03:00
|
|
|
"""Load the data from the spacy-lookups-data package for a given language,
|
2021-04-27 10:13:39 +03:00
|
|
|
if available. Returns an empty `Lookups` container if there's no data or if the package
|
2020-07-22 14:42:59 +03:00
|
|
|
is not installed.
|
|
|
|
|
|
|
|
lang (str): The language code (corresponds to entry point exposed by
|
|
|
|
the spacy-lookups-data package).
|
2020-07-22 16:59:37 +03:00
|
|
|
tables (List[str]): Name of tables to load, e.g. ["lemma_lookup", "lemma_exc"]
|
2020-07-25 13:21:37 +03:00
|
|
|
strict (bool): Whether to raise an error if a table doesn't exist.
|
2021-04-27 10:13:39 +03:00
|
|
|
RETURNS (Lookups): The lookups container containing the loaded tables.
|
2020-07-22 14:42:59 +03:00
|
|
|
"""
|
2020-07-22 16:59:37 +03:00
|
|
|
# TODO: import spacy_lookups_data instead of going via entry points here?
|
2020-07-24 15:50:26 +03:00
|
|
|
lookups = Lookups()
|
2020-07-22 16:59:37 +03:00
|
|
|
if lang not in registry.lookups:
|
2020-08-07 16:27:13 +03:00
|
|
|
if strict and len(tables) > 0:
|
|
|
|
raise ValueError(Errors.E955.format(table=", ".join(tables), lang=lang))
|
2020-07-24 15:50:26 +03:00
|
|
|
return lookups
|
2020-07-22 16:59:37 +03:00
|
|
|
data = registry.lookups.get(lang)
|
|
|
|
for table in tables:
|
|
|
|
if table not in data:
|
2020-07-24 15:50:26 +03:00
|
|
|
if strict:
|
2020-07-25 13:21:37 +03:00
|
|
|
raise ValueError(Errors.E955.format(table=table, lang=lang))
|
🏷 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
|
|
|
language_data = {} # type: ignore[var-annotated]
|
2020-07-24 15:50:26 +03:00
|
|
|
else:
|
🏷 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
|
|
|
language_data = load_language_data(data[table]) # type: ignore[assignment]
|
2020-07-24 15:50:26 +03:00
|
|
|
lookups.add_table(table, language_data)
|
|
|
|
return lookups
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
|
2020-08-07 16:27:13 +03:00
|
|
|
class Table(OrderedDict):
|
|
|
|
"""A table in the lookups. Subclass of builtin dict that implements a
|
|
|
|
slightly more consistent and unified API.
|
|
|
|
|
|
|
|
Includes a Bloom filter to speed up missed lookups.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_dict(cls, data: dict, name: Optional[str] = None) -> "Table":
|
|
|
|
"""Initialize a new table from a dict.
|
|
|
|
|
|
|
|
data (dict): The dictionary.
|
|
|
|
name (str): Optional table name for reference.
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#table.from_dict
|
2020-08-07 16:27:13 +03:00
|
|
|
"""
|
|
|
|
self = cls(name=name)
|
|
|
|
self.update(data)
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __init__(self, name: Optional[str] = None, data: Optional[dict] = None) -> None:
|
|
|
|
"""Initialize a new table.
|
|
|
|
|
|
|
|
name (str): Optional table name for reference.
|
|
|
|
data (dict): Initial data, used to hint Bloom Filter.
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#table.init
|
2020-08-07 16:27:13 +03:00
|
|
|
"""
|
|
|
|
OrderedDict.__init__(self)
|
|
|
|
self.name = name
|
|
|
|
# Assume a default size of 1M items
|
|
|
|
self.default_size = 1e6
|
|
|
|
size = max(len(data), 1) if data is not None else self.default_size
|
|
|
|
self.bloom = BloomFilter.from_error_rate(size)
|
|
|
|
if data:
|
|
|
|
self.update(data)
|
|
|
|
|
|
|
|
def __setitem__(self, key: Union[str, int], value: Any) -> None:
|
|
|
|
"""Set new key/value pair. String keys will be hashed.
|
|
|
|
|
|
|
|
key (str / int): The key to set.
|
|
|
|
value: The value to set.
|
|
|
|
"""
|
|
|
|
key = get_string_id(key)
|
2022-05-25 10:33:54 +03:00
|
|
|
OrderedDict.__setitem__(self, key, value) # type:ignore[assignment]
|
2020-08-07 16:27:13 +03:00
|
|
|
self.bloom.add(key)
|
|
|
|
|
|
|
|
def set(self, key: Union[str, int], value: Any) -> None:
|
|
|
|
"""Set new key/value pair. String keys will be hashed.
|
|
|
|
Same as table[key] = value.
|
|
|
|
|
|
|
|
key (str / int): The key to set.
|
|
|
|
value: The value to set.
|
|
|
|
"""
|
|
|
|
self[key] = value
|
|
|
|
|
|
|
|
def __getitem__(self, key: Union[str, int]) -> Any:
|
|
|
|
"""Get the value for a given key. String keys will be hashed.
|
|
|
|
|
|
|
|
key (str / int): The key to get.
|
|
|
|
RETURNS: The value.
|
|
|
|
"""
|
|
|
|
key = get_string_id(key)
|
2022-05-25 10:33:54 +03:00
|
|
|
return OrderedDict.__getitem__(self, key) # type:ignore[index]
|
2020-08-07 16:27:13 +03:00
|
|
|
|
|
|
|
def get(self, key: Union[str, int], default: Optional[Any] = None) -> Any:
|
|
|
|
"""Get the value for a given key. String keys will be hashed.
|
|
|
|
|
|
|
|
key (str / int): The key to get.
|
|
|
|
default: The default value to return.
|
|
|
|
RETURNS: The value.
|
|
|
|
"""
|
|
|
|
key = get_string_id(key)
|
2022-05-25 10:33:54 +03:00
|
|
|
return OrderedDict.get(self, key, default) # type:ignore[arg-type]
|
2020-08-07 16:27:13 +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
|
|
|
def __contains__(self, key: Union[str, int]) -> bool: # type: ignore[override]
|
2020-08-07 16:27:13 +03:00
|
|
|
"""Check whether a key is in the table. String keys will be hashed.
|
|
|
|
|
|
|
|
key (str / int): The key to check.
|
|
|
|
RETURNS (bool): Whether the key is in the table.
|
|
|
|
"""
|
|
|
|
key = get_string_id(key)
|
|
|
|
# This can give a false positive, so we need to check it after
|
|
|
|
if key not in self.bloom:
|
|
|
|
return False
|
|
|
|
return OrderedDict.__contains__(self, key)
|
|
|
|
|
|
|
|
def to_bytes(self) -> bytes:
|
|
|
|
"""Serialize table to a bytestring.
|
|
|
|
|
|
|
|
RETURNS (bytes): The serialized table.
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#table.to_bytes
|
2020-08-07 16:27:13 +03:00
|
|
|
"""
|
|
|
|
data = {
|
|
|
|
"name": self.name,
|
|
|
|
"dict": dict(self.items()),
|
|
|
|
"bloom": self.bloom.to_bytes(),
|
|
|
|
}
|
|
|
|
return srsly.msgpack_dumps(data)
|
|
|
|
|
|
|
|
def from_bytes(self, bytes_data: bytes) -> "Table":
|
|
|
|
"""Load a table from a bytestring.
|
|
|
|
|
|
|
|
bytes_data (bytes): The data to load.
|
|
|
|
RETURNS (Table): The loaded table.
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#table.from_bytes
|
2020-08-07 16:27:13 +03:00
|
|
|
"""
|
|
|
|
loaded = srsly.msgpack_loads(bytes_data)
|
|
|
|
data = loaded.get("dict", {})
|
|
|
|
self.name = loaded["name"]
|
|
|
|
self.bloom = BloomFilter().from_bytes(loaded["bloom"])
|
|
|
|
self.clear()
|
|
|
|
self.update(data)
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
2020-07-12 15:03:23 +03:00
|
|
|
class Lookups:
|
2019-09-09 20:17:55 +03:00
|
|
|
"""Container for large lookup tables and dictionaries, e.g. lemmatization
|
|
|
|
data or tokenizer exception lists. Lookups are available via vocab.lookups,
|
|
|
|
so they can be accessed before the pipeline components are applied (e.g.
|
|
|
|
in the tokenizer and lemmatizer), as well as within the pipeline components
|
|
|
|
via doc.vocab.lookups.
|
|
|
|
"""
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def __init__(self) -> None:
|
2019-09-09 20:17:55 +03:00
|
|
|
"""Initialize the Lookups object.
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#init
|
2019-09-09 20:17:55 +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
|
|
|
self._tables: Dict[str, Table] = {}
|
2019-08-22 15:21:32 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def __contains__(self, name: str) -> bool:
|
2019-09-09 20:17:55 +03:00
|
|
|
"""Check if the lookups contain a table of a given name. Delegates to
|
|
|
|
Lookups.has_table.
|
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
name (str): Name of the table.
|
2019-09-12 15:00:14 +03:00
|
|
|
RETURNS (bool): Whether a table of that name is in the lookups.
|
2019-09-09 20:17:55 +03:00
|
|
|
"""
|
2019-08-22 15:21:32 +03:00
|
|
|
return self.has_table(name)
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def __len__(self) -> int:
|
2019-09-09 20:17:55 +03:00
|
|
|
"""RETURNS (int): The number of tables in the lookups."""
|
|
|
|
return len(self._tables)
|
|
|
|
|
2019-08-22 15:21:32 +03:00
|
|
|
@property
|
2020-07-22 14:42:59 +03:00
|
|
|
def tables(self) -> List[str]:
|
|
|
|
"""RETURNS (List[str]): Names of all tables in the lookups."""
|
2019-08-22 15:21:32 +03:00
|
|
|
return list(self._tables.keys())
|
|
|
|
|
2020-08-07 16:27:13 +03:00
|
|
|
def add_table(self, name: str, data: dict = SimpleFrozenDict()) -> Table:
|
2019-09-09 20:17:55 +03:00
|
|
|
"""Add a new table to the lookups. Raises an error if the table exists.
|
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
name (str): Unique name of table.
|
2019-09-09 20:17:55 +03:00
|
|
|
data (dict): Optional data to add to the table.
|
|
|
|
RETURNS (Table): The newly added table.
|
2019-09-18 20:57:21 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#add_table
|
2019-09-09 20:17:55 +03:00
|
|
|
"""
|
2019-08-22 15:21:32 +03:00
|
|
|
if name in self.tables:
|
2019-09-09 20:17:55 +03:00
|
|
|
raise ValueError(Errors.E158.format(name=name))
|
Bloom-filter backed Lookup Tables (#4268)
* Improve load_language_data helper
* WIP: Add Lookups implementation
* Start moving lemma data over to JSON
* WIP: move data over for more languages
* Convert more languages
* Fix lemmatizer fixtures in tests
* Finish conversion
* Auto-format JSON files
* Fix test for now
* Make sure tables are stored on instance
* Update docstrings
* Update docstrings and errors
* Update test
* Add Lookups.__len__
* Add serialization methods
* Add Lookups.remove_table
* Use msgpack for serialization to disk
* Fix file exists check
* Try using OrderedDict for everything
* Update .flake8 [ci skip]
* Try fixing serialization
* Update test_lookups.py
* Update test_serialize_vocab_strings.py
* Lookups / Tables now work
This implements the stubs in the Lookups/Table classes. Currently this
is in Cython but with no type declarations, so that could be improved.
* Add lookups to setup.py
* Actually add lookups pyx
The previous commit added the old py file...
* Lookups work-in-progress
* Move from pyx back to py
* Add string based lookups, fix serialization
* Update tests, language/lemmatizer to work with string lookups
There are some outstanding issues here:
- a pickling-related test fails due to the bloom filter
- some custom lemmatizers (fr/nl at least) have issues
More generally, there's a question of how to deal with the case where
you have a string but want to use the lookup table. Currently the table
allows access by string or id, but that's getting pretty awkward.
* Change lemmatizer lookup method to pass (orth, string)
* Fix token lookup
* Fix French lookup
* Fix lt lemmatizer test
* Fix Dutch lemmatizer
* Fix lemmatizer lookup test
This was using a normal dict instead of a Table, so checks for the
string instead of an integer key failed.
* Make uk/nl/ru lemmatizer lookup methods consistent
The mentioned tokenizers all have their own implementation of the
`lookup` method, which accesses a `Lookups` table. The way that was
called in `token.pyx` was changed so this should be updated to have the
same arguments as `lookup` in `lemmatizer.py` (specificially (orth/id,
string)).
Prior to this change tests weren't failing, but there would probably be
issues with normal use of a model. More tests should proably be added.
Additionally, the language-specific `lookup` implementations seem like
they might not be needed, since they handle things like lower-casing
that aren't actually language specific.
* Make recently added Greek method compatible
* Remove redundant class/method
Leftovers from a merge not cleaned up adequately.
2019-09-12 18:26:11 +03:00
|
|
|
table = Table(name=name, data=data)
|
2019-08-22 15:21:32 +03:00
|
|
|
self._tables[name] = table
|
|
|
|
return table
|
|
|
|
|
2020-08-07 16:27:13 +03:00
|
|
|
def set_table(self, name: str, table: Table) -> None:
|
|
|
|
"""Set a table.
|
|
|
|
|
|
|
|
name (str): Name of the table to set.
|
|
|
|
table (Table): The Table to set.
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#set_table
|
2020-08-07 16:27:13 +03:00
|
|
|
"""
|
|
|
|
self._tables[name] = table
|
|
|
|
|
|
|
|
def get_table(self, name: str, default: Any = UNSET) -> Table:
|
2019-10-01 22:36:04 +03:00
|
|
|
"""Get a table. Raises an error if the table doesn't exist and no
|
|
|
|
default value is provided.
|
2019-09-09 20:17:55 +03:00
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
name (str): Name of the table.
|
2020-07-22 14:42:59 +03:00
|
|
|
default (Any): Optional default value to return if table doesn't exist.
|
2019-09-09 20:17:55 +03:00
|
|
|
RETURNS (Table): The table.
|
2019-09-18 20:57:21 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#get_table
|
2019-09-09 20:17:55 +03:00
|
|
|
"""
|
2019-08-22 15:21:32 +03:00
|
|
|
if name not in self._tables:
|
2019-10-01 22:36:04 +03:00
|
|
|
if default == UNSET:
|
|
|
|
raise KeyError(Errors.E159.format(name=name, tables=self.tables))
|
|
|
|
return default
|
2019-08-22 15:21:32 +03:00
|
|
|
return self._tables[name]
|
|
|
|
|
2020-08-07 16:27:13 +03:00
|
|
|
def remove_table(self, name: str) -> Table:
|
2019-09-09 20:17:55 +03:00
|
|
|
"""Remove a table. Raises an error if the table doesn't exist.
|
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
name (str): Name of the table to remove.
|
2019-09-09 20:17:55 +03:00
|
|
|
RETURNS (Table): The removed table.
|
2019-09-18 20:57:21 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#remove_table
|
2019-09-09 20:17:55 +03:00
|
|
|
"""
|
|
|
|
if name not in self._tables:
|
|
|
|
raise KeyError(Errors.E159.format(name=name, tables=self.tables))
|
|
|
|
return self._tables.pop(name)
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def has_table(self, name: str) -> bool:
|
2019-09-09 20:17:55 +03:00
|
|
|
"""Check if the lookups contain a table of a given name.
|
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
name (str): Name of the table.
|
2019-09-09 20:17:55 +03:00
|
|
|
RETURNS (bool): Whether a table of that name exists.
|
2019-09-18 20:57:21 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#has_table
|
2019-09-09 20:17:55 +03:00
|
|
|
"""
|
2019-08-22 15:21:32 +03:00
|
|
|
return name in self._tables
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def to_bytes(self, **kwargs) -> bytes:
|
2019-09-09 20:17:55 +03:00
|
|
|
"""Serialize the lookups to a bytestring.
|
|
|
|
|
|
|
|
RETURNS (bytes): The serialized Lookups.
|
2019-09-18 20:57:21 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#to_bytes
|
2019-09-09 20:17:55 +03:00
|
|
|
"""
|
|
|
|
return srsly.msgpack_dumps(self._tables)
|
2019-08-22 15:21:32 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def from_bytes(self, bytes_data: bytes, **kwargs) -> "Lookups":
|
2019-09-09 20:17:55 +03:00
|
|
|
"""Load the lookups from a bytestring.
|
|
|
|
|
2019-09-12 15:00:14 +03:00
|
|
|
bytes_data (bytes): The data to load.
|
|
|
|
RETURNS (Lookups): The loaded Lookups.
|
2019-09-18 20:57:21 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#from_bytes
|
2019-09-09 20:17:55 +03:00
|
|
|
"""
|
2019-12-22 03:53:56 +03:00
|
|
|
self._tables = {}
|
Bloom-filter backed Lookup Tables (#4268)
* Improve load_language_data helper
* WIP: Add Lookups implementation
* Start moving lemma data over to JSON
* WIP: move data over for more languages
* Convert more languages
* Fix lemmatizer fixtures in tests
* Finish conversion
* Auto-format JSON files
* Fix test for now
* Make sure tables are stored on instance
* Update docstrings
* Update docstrings and errors
* Update test
* Add Lookups.__len__
* Add serialization methods
* Add Lookups.remove_table
* Use msgpack for serialization to disk
* Fix file exists check
* Try using OrderedDict for everything
* Update .flake8 [ci skip]
* Try fixing serialization
* Update test_lookups.py
* Update test_serialize_vocab_strings.py
* Lookups / Tables now work
This implements the stubs in the Lookups/Table classes. Currently this
is in Cython but with no type declarations, so that could be improved.
* Add lookups to setup.py
* Actually add lookups pyx
The previous commit added the old py file...
* Lookups work-in-progress
* Move from pyx back to py
* Add string based lookups, fix serialization
* Update tests, language/lemmatizer to work with string lookups
There are some outstanding issues here:
- a pickling-related test fails due to the bloom filter
- some custom lemmatizers (fr/nl at least) have issues
More generally, there's a question of how to deal with the case where
you have a string but want to use the lookup table. Currently the table
allows access by string or id, but that's getting pretty awkward.
* Change lemmatizer lookup method to pass (orth, string)
* Fix token lookup
* Fix French lookup
* Fix lt lemmatizer test
* Fix Dutch lemmatizer
* Fix lemmatizer lookup test
This was using a normal dict instead of a Table, so checks for the
string instead of an integer key failed.
* Make uk/nl/ru lemmatizer lookup methods consistent
The mentioned tokenizers all have their own implementation of the
`lookup` method, which accesses a `Lookups` table. The way that was
called in `token.pyx` was changed so this should be updated to have the
same arguments as `lookup` in `lemmatizer.py` (specificially (orth/id,
string)).
Prior to this change tests weren't failing, but there would probably be
issues with normal use of a model. More tests should proably be added.
Additionally, the language-specific `lookup` implementations seem like
they might not be needed, since they handle things like lower-casing
that aren't actually language specific.
* Make recently added Greek method compatible
* Remove redundant class/method
Leftovers from a merge not cleaned up adequately.
2019-09-12 18:26:11 +03:00
|
|
|
for key, value in srsly.msgpack_loads(bytes_data).items():
|
2020-06-26 15:09:10 +03:00
|
|
|
self._tables[key] = Table(key, value)
|
2019-09-09 20:17:55 +03:00
|
|
|
return self
|
2019-08-22 15:21:32 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def to_disk(
|
|
|
|
self, path: Union[str, Path], filename: str = "lookups.bin", **kwargs
|
|
|
|
) -> None:
|
2019-09-12 15:00:14 +03:00
|
|
|
"""Save the lookups to a directory as lookups.bin. Expects a path to a
|
|
|
|
directory, which will be created if it doesn't exist.
|
2019-08-22 15:21:32 +03:00
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
path (str / Path): The file path.
|
2019-09-18 20:57:21 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#to_disk
|
2019-09-09 20:17:55 +03:00
|
|
|
"""
|
2020-10-05 10:33:05 +03:00
|
|
|
path = ensure_path(path)
|
|
|
|
if not path.exists():
|
|
|
|
path.mkdir()
|
|
|
|
filepath = path / filename
|
|
|
|
with filepath.open("wb") as file_:
|
|
|
|
file_.write(self.to_bytes())
|
2019-08-22 15:21:32 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def from_disk(
|
|
|
|
self, path: Union[str, Path], filename: str = "lookups.bin", **kwargs
|
|
|
|
) -> "Lookups":
|
2019-09-12 15:00:14 +03:00
|
|
|
"""Load lookups from a directory containing a lookups.bin. Will skip
|
|
|
|
loading if the file doesn't exist.
|
2019-09-09 20:17:55 +03:00
|
|
|
|
2020-05-24 18:20:58 +03:00
|
|
|
path (str / Path): The directory path.
|
2019-09-09 20:17:55 +03:00
|
|
|
RETURNS (Lookups): The loaded lookups.
|
2019-09-18 20:57:21 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/lookups#from_disk
|
2019-09-09 20:17:55 +03:00
|
|
|
"""
|
|
|
|
path = ensure_path(path)
|
2020-05-19 16:59:14 +03:00
|
|
|
filepath = path / filename
|
2019-09-09 20:17:55 +03:00
|
|
|
if filepath.exists():
|
|
|
|
with filepath.open("rb") as file_:
|
|
|
|
data = file_.read()
|
|
|
|
return self.from_bytes(data)
|
|
|
|
return self
|