2017-11-15 15:58:03 +03:00
|
|
|
# cython: profile=True
|
2019-03-10 19:21:19 +03:00
|
|
|
from libc.string cimport memcpy
|
2015-07-23 14:24:20 +03:00
|
|
|
|
2022-03-30 09:54:23 +03:00
|
|
|
import numpy
|
2018-12-06 20:53:16 +03:00
|
|
|
import srsly
|
2021-04-19 11:30:03 +03:00
|
|
|
from thinc.api import get_array_module, get_current_ops
|
2020-07-22 14:42:59 +03:00
|
|
|
import functools
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2020-04-15 14:49:47 +03:00
|
|
|
from .lexeme cimport EMPTY_LEXEME, OOV_RANK
|
2015-01-17 08:21:17 +03:00
|
|
|
from .lexeme cimport Lexeme
|
2015-01-31 08:38:58 +03:00
|
|
|
from .typedefs cimport attr_t
|
2016-11-25 14:43:24 +03:00
|
|
|
from .tokens.token cimport Token
|
2020-08-07 16:27:13 +03:00
|
|
|
from .attrs cimport LANG, ORTH
|
2016-09-24 16:42:01 +03:00
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
from .compat import copy_reg
|
2018-04-03 16:50:31 +03:00
|
|
|
from .errors import Errors
|
2020-07-22 14:42:59 +03:00
|
|
|
from .attrs import intify_attrs, NORM, IS_STOP
|
2021-10-27 15:08:31 +03:00
|
|
|
from .vectors import Vectors, Mode as VectorsMode
|
2020-07-28 23:17:47 +03:00
|
|
|
from .util import registry
|
2020-10-03 18:20:18 +03:00
|
|
|
from .lookups import Lookups
|
2017-10-27 22:07:59 +03:00
|
|
|
from . import util
|
2020-05-19 16:59:14 +03:00
|
|
|
from .lang.norm_exceptions import BASE_NORMS
|
2020-07-22 14:42:59 +03:00
|
|
|
from .lang.lex_attrs import LEX_ATTRS, is_stop, get_lang
|
2015-10-13 12:04:40 +03:00
|
|
|
|
2014-12-24 09:42:00 +03:00
|
|
|
|
2020-09-18 16:45:55 +03:00
|
|
|
def create_vocab(lang, defaults, vectors_name=None):
|
2020-07-25 12:51:30 +03:00
|
|
|
# If the spacy-lookups-data package is installed, we pre-populate the lookups
|
|
|
|
# with lexeme data, if available
|
2020-07-24 15:50:26 +03:00
|
|
|
lex_attrs = {**LEX_ATTRS, **defaults.lex_attr_getters}
|
|
|
|
# This is messy, but it's the minimal working fix to Issue #639.
|
|
|
|
lex_attrs[IS_STOP] = functools.partial(is_stop, stops=defaults.stop_words)
|
|
|
|
# Ensure that getter can be pickled
|
|
|
|
lex_attrs[LANG] = functools.partial(get_lang, lang=lang)
|
|
|
|
lex_attrs[NORM] = util.add_lookups(
|
|
|
|
lex_attrs.get(NORM, LEX_ATTRS[NORM]),
|
|
|
|
BASE_NORMS,
|
|
|
|
)
|
|
|
|
return Vocab(
|
|
|
|
lex_attr_getters=lex_attrs,
|
|
|
|
writing_system=defaults.writing_system,
|
|
|
|
get_noun_chunks=defaults.syntax_iterators.get("noun_chunks"),
|
|
|
|
vectors_name=vectors_name,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2014-12-19 22:54:03 +03:00
|
|
|
cdef class Vocab:
|
2017-05-20 14:59:31 +03:00
|
|
|
"""A look-up table that allows you to access `Lexeme` objects. The `Vocab`
|
|
|
|
instance also provides access to the `StringStore`, and owns underlying
|
|
|
|
C-data that is shared between `Doc` objects.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab
|
2017-04-15 12:59:21 +03:00
|
|
|
"""
|
2020-08-07 16:27:13 +03:00
|
|
|
def __init__(self, lex_attr_getters=None, strings=tuple(), lookups=None,
|
2020-07-22 14:42:59 +03:00
|
|
|
oov_prob=-20., vectors_name=None, writing_system={},
|
2020-07-22 23:18:46 +03:00
|
|
|
get_noun_chunks=None, **deprecated_kwargs):
|
2017-05-20 14:59:31 +03:00
|
|
|
"""Create the vocabulary.
|
|
|
|
|
2017-10-27 20:45:19 +03:00
|
|
|
lex_attr_getters (dict): A dictionary mapping attribute IDs to
|
|
|
|
functions to compute them. Defaults to `None`.
|
2017-05-20 14:59:31 +03:00
|
|
|
strings (StringStore): StringStore that maps strings to integers, and
|
|
|
|
vice versa.
|
2019-09-09 20:17:55 +03:00
|
|
|
lookups (Lookups): Container for large lookup tables and dictionaries.
|
2020-06-15 15:56:51 +03:00
|
|
|
oov_prob (float): Default OOV probability.
|
2021-09-13 18:02:17 +03:00
|
|
|
vectors_name (str): Optional name to identify the vectors table.
|
🏷 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_noun_chunks (Optional[Callable[[Union[Doc, Span], Iterator[Tuple[int, int, int]]]]]):
|
2021-02-25 18:38:21 +03:00
|
|
|
A function that yields base noun phrases used for Doc.noun_chunks.
|
2017-04-15 12:59:21 +03:00
|
|
|
"""
|
2016-09-25 15:49:53 +03:00
|
|
|
lex_attr_getters = lex_attr_getters if lex_attr_getters is not None else {}
|
2019-08-22 15:21:32 +03:00
|
|
|
if lookups in (None, True, False):
|
|
|
|
lookups = Lookups()
|
2017-10-30 18:08:50 +03:00
|
|
|
self.cfg = {'oov_prob': oov_prob}
|
2015-09-10 15:49:10 +03:00
|
|
|
self.mem = Pool()
|
|
|
|
self._by_orth = PreshMap()
|
|
|
|
self.strings = StringStore()
|
2017-06-02 11:57:25 +03:00
|
|
|
self.length = 0
|
2017-03-17 20:29:04 +03:00
|
|
|
if strings:
|
|
|
|
for string in strings:
|
2017-06-02 11:57:06 +03:00
|
|
|
_ = self[string]
|
2016-09-25 15:49:53 +03:00
|
|
|
self.lex_attr_getters = lex_attr_getters
|
2020-08-07 16:27:13 +03:00
|
|
|
self.morphology = Morphology(self.strings)
|
2021-10-27 15:08:31 +03:00
|
|
|
self.vectors = Vectors(strings=self.strings, name=vectors_name)
|
2019-08-22 15:21:32 +03:00
|
|
|
self.lookups = lookups
|
2020-07-22 14:42:59 +03:00
|
|
|
self.writing_system = writing_system
|
2020-07-22 23:18:46 +03:00
|
|
|
self.get_noun_chunks = get_noun_chunks
|
2016-12-21 20:04:41 +03:00
|
|
|
|
2021-10-27 15:08:31 +03:00
|
|
|
property vectors:
|
|
|
|
def __get__(self):
|
|
|
|
return self._vectors
|
|
|
|
|
|
|
|
def __set__(self, vectors):
|
|
|
|
for s in vectors.strings:
|
|
|
|
self.strings.add(s)
|
|
|
|
self._vectors = vectors
|
|
|
|
self._vectors.strings = self.strings
|
|
|
|
|
2019-03-11 17:59:09 +03:00
|
|
|
@property
|
|
|
|
def lang(self):
|
|
|
|
langfunc = None
|
|
|
|
if self.lex_attr_getters:
|
|
|
|
langfunc = self.lex_attr_getters.get(LANG, None)
|
|
|
|
return langfunc("_") if langfunc else ""
|
2016-03-16 17:53:35 +03:00
|
|
|
|
2014-12-19 22:54:03 +03:00
|
|
|
def __len__(self):
|
2017-05-20 14:59:31 +03:00
|
|
|
"""The current number of lexemes stored.
|
|
|
|
|
|
|
|
RETURNS (int): The current number of lexemes stored.
|
2017-04-15 12:59:21 +03:00
|
|
|
"""
|
2015-07-18 23:42:15 +03:00
|
|
|
return self.length
|
2017-05-20 14:59:31 +03:00
|
|
|
|
2016-10-14 13:15:38 +03:00
|
|
|
def add_flag(self, flag_getter, int flag_id=-1):
|
2017-05-20 14:59:31 +03:00
|
|
|
"""Set a new boolean flag to words in the vocabulary.
|
2016-12-21 20:04:41 +03:00
|
|
|
|
2017-05-20 14:59:31 +03:00
|
|
|
The flag_getter function will be called over the words currently in the
|
2016-11-01 14:25:36 +03:00
|
|
|
vocab, and then applied to new words as they occur. You'll then be able
|
2017-10-27 20:45:19 +03:00
|
|
|
to access the flag value on each token using token.check_flag(flag_id).
|
2017-05-20 14:59:31 +03:00
|
|
|
See also: `Lexeme.set_flag`, `Lexeme.check_flag`, `Token.set_flag`,
|
|
|
|
`Token.check_flag`.
|
|
|
|
|
2021-09-13 18:02:17 +03:00
|
|
|
flag_getter (callable): A function `f(str) -> bool`, to get the
|
2017-10-27 20:45:19 +03:00
|
|
|
flag value.
|
2017-05-20 14:59:31 +03:00
|
|
|
flag_id (int): An integer between 1 and 63 (inclusive), specifying
|
|
|
|
the bit at which the flag will be stored. If -1, the lowest
|
|
|
|
available bit will be chosen.
|
|
|
|
RETURNS (int): The integer ID by which the flag value can be checked.
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#add_flag
|
2017-04-15 12:59:21 +03:00
|
|
|
"""
|
2016-10-14 13:15:38 +03:00
|
|
|
if flag_id == -1:
|
|
|
|
for bit in range(1, 64):
|
|
|
|
if bit not in self.lex_attr_getters:
|
|
|
|
flag_id = bit
|
|
|
|
break
|
|
|
|
else:
|
2018-04-03 16:50:31 +03:00
|
|
|
raise ValueError(Errors.E062)
|
2016-10-14 13:15:38 +03:00
|
|
|
elif flag_id >= 64 or flag_id < 1:
|
2018-04-03 16:50:31 +03:00
|
|
|
raise ValueError(Errors.E063.format(value=flag_id))
|
2016-10-14 13:15:38 +03:00
|
|
|
for lex in self:
|
|
|
|
lex.set_flag(flag_id, flag_getter(lex.orth_))
|
|
|
|
self.lex_attr_getters[flag_id] = flag_getter
|
|
|
|
return flag_id
|
|
|
|
|
2021-09-13 18:02:17 +03:00
|
|
|
cdef const LexemeC* get(self, Pool mem, str string) except NULL:
|
2017-10-27 20:45:19 +03:00
|
|
|
"""Get a pointer to a `LexemeC` from the lexicon, creating a new
|
|
|
|
`Lexeme` if necessary using memory acquired from the given pool. If the
|
|
|
|
pool is the lexicon's own memory, the lexeme is saved in the lexicon.
|
2017-04-15 12:59:21 +03:00
|
|
|
"""
|
2019-03-08 13:42:26 +03:00
|
|
|
if string == "":
|
2015-07-26 01:18:30 +03:00
|
|
|
return &EMPTY_LEXEME
|
2015-01-12 02:26:22 +03:00
|
|
|
cdef LexemeC* lex
|
2018-08-16 00:43:34 +03:00
|
|
|
cdef hash_t key = self.strings[string]
|
💫 Small efficiency fixes to tokenizer (#2587)
This patch improves tokenizer speed by about 10%, and reduces memory usage in the `Vocab` by removing a redundant index. The `vocab._by_orth` and `vocab._by_hash` indexed on different data in v1, but in v2 the orth and the hash are identical.
The patch also fixes an uninitialized variable in the tokenizer, the `has_special` flag. This checks whether a chunk we're tokenizing triggers a special-case rule. If it does, then we avoid caching within the chunk. This check led to incorrectly rejecting some chunks from the cache.
With the `en_core_web_md` model, we now tokenize the IMDB train data at 503,104k words per second. Prior to this patch, we had 465,764k words per second.
Before switching to the regex library and supporting more languages, we had 1.3m words per second for the tokenizer. In order to recover the missing speed, we need to:
* Fix the variable-length lookarounds in the suffix, infix and `token_match` rules
* Improve the performance of the `token_match` regex
* Switch back from the `regex` library to the `re` library.
## 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-07-25 00:35:54 +03:00
|
|
|
lex = <LexemeC*>self._by_orth.get(key)
|
2015-08-23 21:49:18 +03:00
|
|
|
cdef size_t addr
|
2014-12-19 22:54:03 +03:00
|
|
|
if lex != NULL:
|
2018-08-16 00:43:34 +03:00
|
|
|
assert lex.orth in self.strings
|
💫 Small efficiency fixes to tokenizer (#2587)
This patch improves tokenizer speed by about 10%, and reduces memory usage in the `Vocab` by removing a redundant index. The `vocab._by_orth` and `vocab._by_hash` indexed on different data in v1, but in v2 the orth and the hash are identical.
The patch also fixes an uninitialized variable in the tokenizer, the `has_special` flag. This checks whether a chunk we're tokenizing triggers a special-case rule. If it does, then we avoid caching within the chunk. This check led to incorrectly rejecting some chunks from the cache.
With the `en_core_web_md` model, we now tokenize the IMDB train data at 503,104k words per second. Prior to this patch, we had 465,764k words per second.
Before switching to the regex library and supporting more languages, we had 1.3m words per second for the tokenizer. In order to recover the missing speed, we need to:
* Fix the variable-length lookarounds in the suffix, infix and `token_match` rules
* Improve the performance of the `token_match` regex
* Switch back from the `regex` library to the `re` library.
## 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-07-25 00:35:54 +03:00
|
|
|
if lex.orth != key:
|
2018-04-03 16:50:31 +03:00
|
|
|
raise KeyError(Errors.E064.format(string=lex.orth,
|
💫 Small efficiency fixes to tokenizer (#2587)
This patch improves tokenizer speed by about 10%, and reduces memory usage in the `Vocab` by removing a redundant index. The `vocab._by_orth` and `vocab._by_hash` indexed on different data in v1, but in v2 the orth and the hash are identical.
The patch also fixes an uninitialized variable in the tokenizer, the `has_special` flag. This checks whether a chunk we're tokenizing triggers a special-case rule. If it does, then we avoid caching within the chunk. This check led to incorrectly rejecting some chunks from the cache.
With the `en_core_web_md` model, we now tokenize the IMDB train data at 503,104k words per second. Prior to this patch, we had 465,764k words per second.
Before switching to the regex library and supporting more languages, we had 1.3m words per second for the tokenizer. In order to recover the missing speed, we need to:
* Fix the variable-length lookarounds in the suffix, infix and `token_match` rules
* Improve the performance of the `token_match` regex
* Switch back from the `regex` library to the `re` library.
## 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-07-25 00:35:54 +03:00
|
|
|
orth=key, orth_id=string))
|
2014-12-19 22:54:03 +03:00
|
|
|
return lex
|
2015-07-20 02:37:34 +03:00
|
|
|
else:
|
2015-08-22 23:04:34 +03:00
|
|
|
return self._new_lexeme(mem, string)
|
2014-12-19 22:54:03 +03:00
|
|
|
|
2015-07-23 02:18:19 +03:00
|
|
|
cdef const LexemeC* get_by_orth(self, Pool mem, attr_t orth) except NULL:
|
2017-10-27 20:45:19 +03:00
|
|
|
"""Get a pointer to a `LexemeC` from the lexicon, creating a new
|
|
|
|
`Lexeme` if necessary using memory acquired from the given pool. If the
|
|
|
|
pool is the lexicon's own memory, the lexeme is saved in the lexicon.
|
2017-04-15 12:59:21 +03:00
|
|
|
"""
|
2015-07-26 20:26:41 +03:00
|
|
|
if orth == 0:
|
2015-07-26 19:39:27 +03:00
|
|
|
return &EMPTY_LEXEME
|
2015-07-23 02:18:19 +03:00
|
|
|
cdef LexemeC* lex
|
|
|
|
lex = <LexemeC*>self._by_orth.get(orth)
|
|
|
|
if lex != NULL:
|
|
|
|
return lex
|
2015-08-22 23:04:34 +03:00
|
|
|
else:
|
2016-09-30 21:10:30 +03:00
|
|
|
return self._new_lexeme(mem, self.strings[orth])
|
2015-08-22 23:04:34 +03:00
|
|
|
|
2021-09-13 18:02:17 +03:00
|
|
|
cdef const LexemeC* _new_lexeme(self, Pool mem, str string) except NULL:
|
2021-01-25 16:40:18 +03:00
|
|
|
# I think this heuristic is bad, and the Vocab should always
|
|
|
|
# own the lexemes. It avoids weird bugs this way, as it's how the thing
|
|
|
|
# was originally supposed to work. The best solution to the growing
|
|
|
|
# memory use is to periodically reset the vocab, which is an action
|
|
|
|
# that should be up to the user to do (so we don't need to keep track
|
|
|
|
# of the doc ownership).
|
|
|
|
# TODO: Change the C API so that the mem isn't passed in here.
|
|
|
|
mem = self.mem
|
|
|
|
#if len(string) < 3 or self.length < 10000:
|
|
|
|
# mem = self.mem
|
2016-12-27 23:03:45 +03:00
|
|
|
cdef bint is_oov = mem is not self.mem
|
2021-01-06 04:50:17 +03:00
|
|
|
lex = <LexemeC*>mem.alloc(1, sizeof(LexemeC))
|
2017-05-28 16:10:22 +03:00
|
|
|
lex.orth = self.strings.add(string)
|
2015-08-26 20:21:46 +03:00
|
|
|
lex.length = len(string)
|
2017-11-15 16:23:58 +03:00
|
|
|
if self.vectors is not None:
|
2020-04-15 14:49:47 +03:00
|
|
|
lex.id = self.vectors.key2row.get(lex.orth, OOV_RANK)
|
2017-11-15 16:23:58 +03:00
|
|
|
else:
|
2020-04-15 14:49:47 +03:00
|
|
|
lex.id = OOV_RANK
|
2016-09-25 15:49:53 +03:00
|
|
|
if self.lex_attr_getters is not None:
|
|
|
|
for attr, func in self.lex_attr_getters.items():
|
2015-08-23 21:49:18 +03:00
|
|
|
value = func(string)
|
2021-09-13 18:02:17 +03:00
|
|
|
if isinstance(value, str):
|
2017-05-28 13:36:27 +03:00
|
|
|
value = self.strings.add(value)
|
2020-05-19 16:59:14 +03:00
|
|
|
if value is not None:
|
2015-08-26 20:21:46 +03:00
|
|
|
Lexeme.set_struct_attr(lex, attr, value)
|
2017-11-15 15:58:03 +03:00
|
|
|
if not is_oov:
|
💫 Small efficiency fixes to tokenizer (#2587)
This patch improves tokenizer speed by about 10%, and reduces memory usage in the `Vocab` by removing a redundant index. The `vocab._by_orth` and `vocab._by_hash` indexed on different data in v1, but in v2 the orth and the hash are identical.
The patch also fixes an uninitialized variable in the tokenizer, the `has_special` flag. This checks whether a chunk we're tokenizing triggers a special-case rule. If it does, then we avoid caching within the chunk. This check led to incorrectly rejecting some chunks from the cache.
With the `en_core_web_md` model, we now tokenize the IMDB train data at 503,104k words per second. Prior to this patch, we had 465,764k words per second.
Before switching to the regex library and supporting more languages, we had 1.3m words per second for the tokenizer. In order to recover the missing speed, we need to:
* Fix the variable-length lookarounds in the suffix, infix and `token_match` rules
* Improve the performance of the `token_match` regex
* Switch back from the `regex` library to the `re` library.
## 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-07-25 00:35:54 +03:00
|
|
|
self._add_lex_to_vocab(lex.orth, lex)
|
2018-04-03 16:50:31 +03:00
|
|
|
if lex == NULL:
|
|
|
|
raise ValueError(Errors.E085.format(string=string))
|
2015-07-23 02:18:19 +03:00
|
|
|
return lex
|
|
|
|
|
2015-01-13 16:03:48 +03:00
|
|
|
cdef int _add_lex_to_vocab(self, hash_t key, const LexemeC* lex) except -1:
|
2015-07-18 23:42:15 +03:00
|
|
|
self._by_orth.set(lex.orth, <void*>lex)
|
|
|
|
self.length += 1
|
|
|
|
|
2018-01-24 01:26:47 +03:00
|
|
|
def __contains__(self, key):
|
|
|
|
"""Check whether the string or int key has an entry in the vocabulary.
|
2016-11-01 14:25:36 +03:00
|
|
|
|
2021-09-13 18:02:17 +03:00
|
|
|
string (str): The ID string.
|
2017-05-20 14:59:31 +03:00
|
|
|
RETURNS (bool) Whether the string has an entry in the vocabulary.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#contains
|
2017-04-15 12:59:21 +03:00
|
|
|
"""
|
2018-01-24 01:26:47 +03:00
|
|
|
cdef hash_t int_key
|
|
|
|
if isinstance(key, bytes):
|
2019-03-08 13:42:26 +03:00
|
|
|
int_key = self.strings[key.decode("utf8")]
|
2021-09-13 18:02:17 +03:00
|
|
|
elif isinstance(key, str):
|
2018-08-16 00:43:34 +03:00
|
|
|
int_key = self.strings[key]
|
2018-01-24 01:26:47 +03:00
|
|
|
else:
|
|
|
|
int_key = key
|
💫 Small efficiency fixes to tokenizer (#2587)
This patch improves tokenizer speed by about 10%, and reduces memory usage in the `Vocab` by removing a redundant index. The `vocab._by_orth` and `vocab._by_hash` indexed on different data in v1, but in v2 the orth and the hash are identical.
The patch also fixes an uninitialized variable in the tokenizer, the `has_special` flag. This checks whether a chunk we're tokenizing triggers a special-case rule. If it does, then we avoid caching within the chunk. This check led to incorrectly rejecting some chunks from the cache.
With the `en_core_web_md` model, we now tokenize the IMDB train data at 503,104k words per second. Prior to this patch, we had 465,764k words per second.
Before switching to the regex library and supporting more languages, we had 1.3m words per second for the tokenizer. In order to recover the missing speed, we need to:
* Fix the variable-length lookarounds in the suffix, infix and `token_match` rules
* Improve the performance of the `token_match` regex
* Switch back from the `regex` library to the `re` library.
## 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-07-25 00:35:54 +03:00
|
|
|
lex = self._by_orth.get(int_key)
|
2017-01-11 12:18:22 +03:00
|
|
|
return lex is not NULL
|
2016-03-08 18:49:10 +03:00
|
|
|
|
2015-07-18 23:42:15 +03:00
|
|
|
def __iter__(self):
|
2017-05-20 14:59:31 +03:00
|
|
|
"""Iterate over the lexemes in the vocabulary.
|
2016-11-01 14:25:36 +03:00
|
|
|
|
2017-05-20 14:59:31 +03:00
|
|
|
YIELDS (Lexeme): An entry in the vocabulary.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#iter
|
2017-04-15 12:59:21 +03:00
|
|
|
"""
|
2017-10-31 04:00:26 +03:00
|
|
|
cdef attr_t key
|
2015-07-18 23:42:15 +03:00
|
|
|
cdef size_t addr
|
2017-10-31 04:00:26 +03:00
|
|
|
for key, addr in self._by_orth.items():
|
|
|
|
lex = Lexeme(self, key)
|
|
|
|
yield lex
|
2015-01-13 16:03:48 +03:00
|
|
|
|
2017-10-27 20:45:19 +03:00
|
|
|
def __getitem__(self, id_or_string):
|
|
|
|
"""Retrieve a lexeme, given an int ID or a unicode string. If a
|
2017-05-20 14:59:31 +03:00
|
|
|
previously unseen unicode string is given, a new lexeme is created and
|
|
|
|
stored.
|
|
|
|
|
2021-09-13 18:02:17 +03:00
|
|
|
id_or_string (int or str): The integer ID of a word, or its unicode
|
2017-05-20 14:59:31 +03:00
|
|
|
string. If `int >= Lexicon.size`, `IndexError` is raised. If
|
|
|
|
`id_or_string` is neither an int nor a unicode string, `ValueError`
|
|
|
|
is raised.
|
|
|
|
RETURNS (Lexeme): The lexeme indicated by the given ID.
|
|
|
|
|
|
|
|
EXAMPLE:
|
2019-03-08 13:42:26 +03:00
|
|
|
>>> apple = nlp.vocab.strings["apple"]
|
|
|
|
>>> assert nlp.vocab[apple] == nlp.vocab[u"apple"]
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#getitem
|
2017-04-15 12:59:21 +03:00
|
|
|
"""
|
2015-07-18 23:42:15 +03:00
|
|
|
cdef attr_t orth
|
2021-09-13 18:02:17 +03:00
|
|
|
if isinstance(id_or_string, str):
|
2017-05-28 13:36:27 +03:00
|
|
|
orth = self.strings.add(id_or_string)
|
2015-01-14 16:33:16 +03:00
|
|
|
else:
|
2015-08-23 21:49:18 +03:00
|
|
|
orth = id_or_string
|
|
|
|
return Lexeme(self, orth)
|
2014-12-19 22:54:03 +03:00
|
|
|
|
2015-08-28 03:02:33 +03:00
|
|
|
cdef const TokenC* make_fused_token(self, substrings) except NULL:
|
|
|
|
cdef int i
|
|
|
|
tokens = <TokenC*>self.mem.alloc(len(substrings) + 1, sizeof(TokenC))
|
|
|
|
for i, props in enumerate(substrings):
|
2022-08-17 13:13:54 +03:00
|
|
|
props = intify_attrs(props, strings_map=self.strings)
|
2015-08-28 03:02:33 +03:00
|
|
|
token = &tokens[i]
|
2016-11-25 14:43:24 +03:00
|
|
|
# Set the special tokens up to have arbitrary attributes
|
2017-10-27 20:45:19 +03:00
|
|
|
lex = <LexemeC*>self.get_by_orth(self.mem, props[ORTH])
|
2017-06-03 20:44:39 +03:00
|
|
|
token.lex = lex
|
2016-11-25 14:43:24 +03:00
|
|
|
for attr_id, value in props.items():
|
|
|
|
Token.set_struct_attr(token, attr_id, value)
|
2018-12-08 12:49:10 +03:00
|
|
|
# NORM is the only one that overlaps between the two
|
|
|
|
# (which is maybe not great?)
|
|
|
|
if attr_id != NORM:
|
|
|
|
Lexeme.set_struct_attr(lex, attr_id, value)
|
2015-08-28 03:02:33 +03:00
|
|
|
return tokens
|
2016-12-21 20:04:41 +03:00
|
|
|
|
2017-05-31 00:34:50 +03:00
|
|
|
@property
|
|
|
|
def vectors_length(self):
|
2022-01-18 19:14:35 +03:00
|
|
|
return self.vectors.shape[1]
|
2017-05-31 00:34:50 +03:00
|
|
|
|
2017-10-31 20:25:08 +03:00
|
|
|
def reset_vectors(self, *, width=None, shape=None):
|
2017-05-31 00:34:50 +03:00
|
|
|
"""Drop the current vector table. Because all vectors must be the same
|
|
|
|
width, you have to call this to change the size of the vectors.
|
|
|
|
"""
|
2017-10-31 20:25:08 +03:00
|
|
|
if width is not None and shape is not None:
|
2018-04-03 16:50:31 +03:00
|
|
|
raise ValueError(Errors.E065.format(width=width, shape=shape))
|
2017-10-31 20:25:08 +03:00
|
|
|
elif shape is not None:
|
2021-10-27 15:08:31 +03:00
|
|
|
self.vectors = Vectors(strings=self.strings, shape=shape)
|
2017-10-31 20:25:08 +03:00
|
|
|
else:
|
2022-01-18 19:14:35 +03:00
|
|
|
width = width if width is not None else self.vectors.shape[1]
|
2021-10-27 15:08:31 +03:00
|
|
|
self.vectors = Vectors(strings=self.strings, shape=(self.vectors.shape[0], width))
|
2017-10-31 04:00:26 +03:00
|
|
|
|
2022-03-30 09:54:23 +03:00
|
|
|
def deduplicate_vectors(self):
|
|
|
|
if self.vectors.mode != VectorsMode.default:
|
|
|
|
raise ValueError(Errors.E858.format(
|
|
|
|
mode=self.vectors.mode,
|
|
|
|
alternative=""
|
|
|
|
))
|
|
|
|
ops = get_current_ops()
|
|
|
|
xp = get_array_module(self.vectors.data)
|
|
|
|
filled = xp.asarray(
|
|
|
|
sorted(list({row for row in self.vectors.key2row.values()}))
|
|
|
|
)
|
|
|
|
# deduplicate data and remap keys
|
|
|
|
data = numpy.unique(ops.to_numpy(self.vectors.data[filled]), axis=0)
|
|
|
|
data = ops.asarray(data)
|
|
|
|
if data.shape == self.vectors.data.shape:
|
|
|
|
# nothing to deduplicate
|
|
|
|
return
|
|
|
|
row_by_bytes = {row.tobytes(): i for i, row in enumerate(data)}
|
|
|
|
key2row = {
|
|
|
|
key: row_by_bytes[self.vectors.data[row].tobytes()]
|
|
|
|
for key, row in self.vectors.key2row.items()
|
|
|
|
}
|
|
|
|
# replace vectors with deduplicated version
|
|
|
|
self.vectors = Vectors(strings=self.strings, data=data, name=self.vectors.name)
|
|
|
|
for key, row in key2row.items():
|
|
|
|
self.vectors.add(key, row=row)
|
|
|
|
|
2017-10-31 20:25:08 +03:00
|
|
|
def prune_vectors(self, nr_row, batch_size=1024):
|
2017-10-31 04:00:26 +03:00
|
|
|
"""Reduce the current vector table to `nr_row` unique entries. Words
|
|
|
|
mapped to the discarded vectors will be remapped to the closest vector
|
|
|
|
among those remaining.
|
|
|
|
|
|
|
|
For example, suppose the original table had vectors for the words:
|
2021-04-19 11:30:03 +03:00
|
|
|
['sat', 'cat', 'feline', 'reclined']. If we prune the vector table to
|
2017-10-31 04:00:26 +03:00
|
|
|
two rows, we would discard the vectors for 'feline' and 'reclined'.
|
|
|
|
These words would then be remapped to the closest remaining vector
|
|
|
|
-- so "feline" would have the same vector as "cat", and "reclined"
|
|
|
|
would have the same vector as "sat".
|
|
|
|
|
|
|
|
The similarities are judged by cosine. The original vectors may
|
|
|
|
be large, so the cosines are calculated in minibatches, to reduce
|
|
|
|
memory usage.
|
|
|
|
|
|
|
|
nr_row (int): The number of rows to keep in the vector table.
|
|
|
|
batch_size (int): Batch of vectors for calculating the similarities.
|
|
|
|
Larger batch sizes might be faster, while temporarily requiring
|
|
|
|
more memory.
|
|
|
|
RETURNS (dict): A dictionary keyed by removed words mapped to
|
|
|
|
`(string, score)` tuples, where `string` is the entry the removed
|
|
|
|
word was mapped to, and `score` the similarity score between the
|
|
|
|
two words.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#prune_vectors
|
2017-10-31 04:00:26 +03:00
|
|
|
"""
|
2021-10-27 15:08:31 +03:00
|
|
|
if self.vectors.mode != VectorsMode.default:
|
2022-03-30 09:54:23 +03:00
|
|
|
raise ValueError(Errors.E858.format(
|
|
|
|
mode=self.vectors.mode,
|
|
|
|
alternative=""
|
|
|
|
))
|
2021-04-19 11:30:03 +03:00
|
|
|
ops = get_current_ops()
|
2017-10-31 04:00:26 +03:00
|
|
|
xp = get_array_module(self.vectors.data)
|
2020-11-23 12:00:59 +03:00
|
|
|
# Make sure all vectors are in the vocab
|
|
|
|
for orth in self.vectors:
|
|
|
|
self[orth]
|
2017-10-31 20:25:08 +03:00
|
|
|
# Make prob negative so it sorts by rank ascending
|
|
|
|
# (key2row contains the rank)
|
|
|
|
priority = [(-lex.prob, self.vectors.key2row[lex.orth], lex.orth)
|
|
|
|
for lex in self if lex.orth in self.vectors.key2row]
|
|
|
|
priority.sort()
|
2020-05-13 11:25:05 +03:00
|
|
|
indices = xp.asarray([i for (prob, i, key) in priority], dtype="uint64")
|
2019-03-08 13:42:26 +03:00
|
|
|
keys = xp.asarray([key for (prob, i, key) in priority], dtype="uint64")
|
2017-10-31 20:25:08 +03:00
|
|
|
keep = xp.ascontiguousarray(self.vectors.data[indices[:nr_row]])
|
|
|
|
toss = xp.ascontiguousarray(self.vectors.data[indices[nr_row:]])
|
2021-10-27 15:08:31 +03:00
|
|
|
self.vectors = Vectors(strings=self.strings, data=keep, keys=keys[:nr_row], name=self.vectors.name)
|
💫 Port master changes over to develop (#2979)
* Create aryaprabhudesai.md (#2681)
* Update _install.jade (#2688)
Typo fix: "models" -> "model"
* Add FAC to spacy.explain (resolves #2706)
* Remove docstrings for deprecated arguments (see #2703)
* When calling getoption() in conftest.py, pass a default option (#2709)
* When calling getoption() in conftest.py, pass a default option
This is necessary to allow testing an installed spacy by running:
pytest --pyargs spacy
* Add contributor agreement
* update bengali token rules for hyphen and digits (#2731)
* Less norm computations in token similarity (#2730)
* Less norm computations in token similarity
* Contributor agreement
* Remove ')' for clarity (#2737)
Sorry, don't mean to be nitpicky, I just noticed this when going through the CLI and thought it was a quick fix. That said, if this was intention than please let me know.
* added contributor agreement for mbkupfer (#2738)
* Basic support for Telugu language (#2751)
* Lex _attrs for polish language (#2750)
* Signed spaCy contributor agreement
* Added polish version of english lex_attrs
* Introduces a bulk merge function, in order to solve issue #653 (#2696)
* Fix comment
* Introduce bulk merge to increase performance on many span merges
* Sign contributor agreement
* Implement pull request suggestions
* Describe converters more explicitly (see #2643)
* Add multi-threading note to Language.pipe (resolves #2582) [ci skip]
* Fix formatting
* Fix dependency scheme docs (closes #2705) [ci skip]
* Don't set stop word in example (closes #2657) [ci skip]
* Add words to portuguese language _num_words (#2759)
* Add words to portuguese language _num_words
* Add words to portuguese language _num_words
* Update Indonesian model (#2752)
* adding e-KTP in tokenizer exceptions list
* add exception token
* removing lines with containing space as it won't matter since we use .split() method in the end, added new tokens in exception
* add tokenizer exceptions list
* combining base_norms with norm_exceptions
* adding norm_exception
* fix double key in lemmatizer
* remove unused import on punctuation.py
* reformat stop_words to reduce number of lines, improve readibility
* updating tokenizer exception
* implement is_currency for lang/id
* adding orth_first_upper in tokenizer_exceptions
* update the norm_exception list
* remove bunch of abbreviations
* adding contributors file
* Fixed spaCy+Keras example (#2763)
* bug fixes in keras example
* created contributor agreement
* Adding French hyphenated first name (#2786)
* Fix typo (closes #2784)
* Fix typo (#2795) [ci skip]
Fixed typo on line 6 "regcognizer --> recognizer"
* Adding basic support for Sinhala language. (#2788)
* adding Sinhala language package, stop words, examples and lex_attrs.
* Adding contributor agreement
* Updating contributor agreement
* Also include lowercase norm exceptions
* Fix error (#2802)
* Fix error
ValueError: cannot resize an array that references or is referenced
by another array in this way. Use the resize function
* added spaCy Contributor Agreement
* Add charlax's contributor agreement (#2805)
* agreement of contributor, may I introduce a tiny pl languge contribution (#2799)
* Contributors agreement
* Contributors agreement
* Contributors agreement
* Add jupyter=True to displacy.render in documentation (#2806)
* Revert "Also include lowercase norm exceptions"
This reverts commit 70f4e8adf37cfcfab60be2b97d6deae949b30e9e.
* Remove deprecated encoding argument to msgpack
* Set up dependency tree pattern matching skeleton (#2732)
* Fix bug when too many entity types. Fixes #2800
* Fix Python 2 test failure
* Require older msgpack-numpy
* Restore encoding arg on msgpack-numpy
* Try to fix version pin for msgpack-numpy
* Update Portuguese Language (#2790)
* Add words to portuguese language _num_words
* Add words to portuguese language _num_words
* Portuguese - Add/remove stopwords, fix tokenizer, add currency symbols
* Extended punctuation and norm_exceptions in the Portuguese language
* Correct error in spacy universe docs concerning spacy-lookup (#2814)
* Update Keras Example for (Parikh et al, 2016) implementation (#2803)
* bug fixes in keras example
* created contributor agreement
* baseline for Parikh model
* initial version of parikh 2016 implemented
* tested asymmetric models
* fixed grevious error in normalization
* use standard SNLI test file
* begin to rework parikh example
* initial version of running example
* start to document the new version
* start to document the new version
* Update Decompositional Attention.ipynb
* fixed calls to similarity
* updated the README
* import sys package duh
* simplified indexing on mapping word to IDs
* stupid python indent error
* added code from https://github.com/tensorflow/tensorflow/issues/3388 for tf bug workaround
* Fix typo (closes #2815) [ci skip]
* Update regex version dependency
* Set version to 2.0.13.dev3
* Skip seemingly problematic test
* Remove problematic test
* Try previous version of regex
* Revert "Remove problematic test"
This reverts commit bdebbef45552d698d390aa430b527ee27830f11b.
* Unskip test
* Try older version of regex
* 💫 Update training examples and use minibatching (#2830)
<!--- Provide a general summary of your changes in the title. -->
## Description
Update the training examples in `/examples/training` to show usage of spaCy's `minibatch` and `compounding` helpers ([see here](https://spacy.io/usage/training#tips-batch-size) for details). The lack of batching in the examples has caused some confusion in the past, especially for beginners who would copy-paste the examples, update them with large training sets and experienced slow and unsatisfying results.
### Types of change
enhancements
## 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.
* Visual C++ link updated (#2842) (closes #2841) [ci skip]
* New landing page
* Add contribution agreement
* Correcting lang/ru/examples.py (#2845)
* Correct some grammatical inaccuracies in lang\ru\examples.py; filled Contributor Agreement
* Correct some grammatical inaccuracies in lang\ru\examples.py
* Move contributor agreement to separate file
* Set version to 2.0.13.dev4
* Add Persian(Farsi) language support (#2797)
* Also include lowercase norm exceptions
* Remove in favour of https://github.com/explosion/spaCy/graphs/contributors
* Rule-based French Lemmatizer (#2818)
<!--- Provide a general summary of your changes in the title. -->
## Description
<!--- Use this section to describe your changes. If your changes required
testing, include information about the testing environment and the tests you
ran. If your test fixes a bug reported in an issue, don't forget to include the
issue number. If your PR is still a work in progress, that's totally fine – just
include a note to let us know. -->
Add a rule-based French Lemmatizer following the english one and the excellent PR for [greek language optimizations](https://github.com/explosion/spaCy/pull/2558) to adapt the Lemmatizer class.
### Types of change
<!-- What type of change does your PR cover? Is it a bug fix, an enhancement
or new feature, or a change to the documentation? -->
- Lemma dictionary used can be found [here](http://infolingu.univ-mlv.fr/DonneesLinguistiques/Dictionnaires/telechargement.html), I used the XML version.
- Add several files containing exhaustive list of words for each part of speech
- Add some lemma rules
- Add POS that are not checked in the standard Lemmatizer, i.e PRON, DET, ADV and AUX
- Modify the Lemmatizer class to check in lookup table as a last resort if POS not mentionned
- Modify the lemmatize function to check in lookup table as a last resort
- Init files are updated so the model can support all the functionalities mentioned above
- Add words to tokenizer_exceptions_list.py in respect to regex used in tokenizer_exceptions.py
## 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.
* Set version to 2.0.13
* Fix formatting and consistency
* Update docs for new version [ci skip]
* Increment version [ci skip]
* Add info on wheels [ci skip]
* Adding "This is a sentence" example to Sinhala (#2846)
* Add wheels badge
* Update badge [ci skip]
* Update README.rst [ci skip]
* Update murmurhash pin
* Increment version to 2.0.14.dev0
* Update GPU docs for v2.0.14
* Add wheel to setup_requires
* Import prefer_gpu and require_gpu functions from Thinc
* Add tests for prefer_gpu() and require_gpu()
* Update requirements and setup.py
* Workaround bug in thinc require_gpu
* Set version to v2.0.14
* Update push-tag script
* Unhack prefer_gpu
* Require thinc 6.10.6
* Update prefer_gpu and require_gpu docs [ci skip]
* Fix specifiers for GPU
* Set version to 2.0.14.dev1
* Set version to 2.0.14
* Update Thinc version pin
* Increment version
* Fix msgpack-numpy version pin
* Increment version
* Update version to 2.0.16
* Update version [ci skip]
* Redundant ')' in the Stop words' example (#2856)
<!--- Provide a general summary of your changes in the title. -->
## Description
<!--- Use this section to describe your changes. If your changes required
testing, include information about the testing environment and the tests you
ran. If your test fixes a bug reported in an issue, don't forget to include the
issue number. If your PR is still a work in progress, that's totally fine – just
include a note to let us know. -->
### Types of change
<!-- What type of change does your PR cover? Is it a bug fix, an enhancement
or new feature, or a change to the documentation? -->
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [ ] I have submitted the spaCy Contributor Agreement.
- [ ] I ran the tests, and all new and existing tests passed.
- [ ] My changes don't require a change to the documentation, or if they do, I've added all required information.
* Documentation improvement regarding joblib and SO (#2867)
Some documentation improvements
## Description
1. Fixed the dead URL to joblib
2. Fixed Stack Overflow brand name (with space)
### Types of change
Documentation
## 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.
* raise error when setting overlapping entities as doc.ents (#2880)
* Fix out-of-bounds access in NER training
The helper method state.B(1) gets the index of the first token of the
buffer, or -1 if no such token exists. Normally this is safe because we
pass this to functions like state.safe_get(), which returns an empty
token. Here we used it directly as an array index, which is not okay!
This error may have been the cause of out-of-bounds access errors during
training. Similar errors may still be around, so much be hunted down.
Hunting this one down took a long time...I printed out values across
training runs and diffed, looking for points of divergence between
runs, when no randomness should be allowed.
* Change PyThaiNLP Url (#2876)
* Fix missing comma
* Add example showing a fix-up rule for space entities
* Set version to 2.0.17.dev0
* Update regex version
* Revert "Update regex version"
This reverts commit 62358dd867d15bc6a475942dff34effba69dd70a.
* Try setting older regex version, to align with conda
* Set version to 2.0.17
* Add spacy-js to universe [ci-skip]
* Add spacy-raspberry to universe (closes #2889)
* Add script to validate universe json [ci skip]
* Removed space in docs + added contributor indo (#2909)
* - removed unneeded space in documentation
* - added contributor info
* Allow input text of length up to max_length, inclusive (#2922)
* Include universe spec for spacy-wordnet component (#2919)
* feat: include universe spec for spacy-wordnet component
* chore: include spaCy contributor agreement
* Minor formatting changes [ci skip]
* Fix image [ci skip]
Twitter URL doesn't work on live site
* Check if the word is in one of the regular lists specific to each POS (#2886)
* 💫 Create random IDs for SVGs to prevent ID clashes (#2927)
Resolves #2924.
## Description
Fixes problem where multiple visualizations in Jupyter notebooks would have clashing arc IDs, resulting in weirdly positioned arc labels. Generating a random ID prefix so even identical parses won't receive the same IDs for consistency (even if effect of ID clash isn't noticable here.)
### Types of change
bug fix
## 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.
* Fix typo [ci skip]
* fixes symbolic link on py3 and windows (#2949)
* fixes symbolic link on py3 and windows
during setup of spacy using command
python -m spacy link en_core_web_sm en
closes #2948
* Update spacy/compat.py
Co-Authored-By: cicorias <cicorias@users.noreply.github.com>
* Fix formatting
* Update universe [ci skip]
* Catalan Language Support (#2940)
* Catalan language Support
* Ddding Catalan to documentation
* Sort languages alphabetically [ci skip]
* Update tests for pytest 4.x (#2965)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Replace marks in params for pytest 4.0 compat ([see here](https://docs.pytest.org/en/latest/deprecations.html#marks-in-pytest-mark-parametrize))
- [x] Un-xfail passing tests (some fixes in a recent update resolved a bunch of issues, but tests were apparently never updated here)
### Types of change
<!-- What type of change does your PR cover? Is it a bug fix, an enhancement
or new feature, or a change to the documentation? -->
## 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.
* Fix regex pin to harmonize with conda (#2964)
* Update README.rst
* Fix bug where Vocab.prune_vector did not use 'batch_size' (#2977)
Fixes #2976
* Fix typo
* Fix typo
* Remove duplicate file
* Require thinc 7.0.0.dev2
Fixes bug in gpu_ops that would use cupy instead of numpy on CPU
* Add missing import
* Fix error IDs
* Fix tests
2018-11-29 18:30:29 +03:00
|
|
|
syn_keys, syn_rows, scores = self.vectors.most_similar(toss, batch_size=batch_size)
|
2021-04-19 11:30:03 +03:00
|
|
|
syn_keys = ops.to_numpy(syn_keys)
|
2017-10-31 13:40:46 +03:00
|
|
|
remap = {}
|
2021-04-19 11:30:03 +03:00
|
|
|
for i, key in enumerate(ops.to_numpy(keys[nr_row:])):
|
2019-10-03 15:09:44 +03:00
|
|
|
self.vectors.add(key, row=syn_rows[i][0])
|
2017-10-31 20:25:08 +03:00
|
|
|
word = self.strings[key]
|
2019-10-03 15:09:44 +03:00
|
|
|
synonym = self.strings[syn_keys[i][0]]
|
|
|
|
score = scores[i][0]
|
2017-10-31 20:25:08 +03:00
|
|
|
remap[word] = (synonym, score)
|
2017-10-31 04:00:26 +03:00
|
|
|
return remap
|
2017-05-31 00:34:50 +03:00
|
|
|
|
2021-10-27 15:08:31 +03:00
|
|
|
def get_vector(self, orth):
|
2017-10-27 20:45:19 +03:00
|
|
|
"""Retrieve a vector for a word in the vocabulary. Words can be looked
|
2022-03-15 11:10:47 +03:00
|
|
|
up by string or int ID. If the current vectors do not contain an entry
|
|
|
|
for the word, a 0-vector with the same number of dimensions as the
|
|
|
|
current vectors is returned.
|
2019-12-22 03:53:56 +03:00
|
|
|
|
2021-10-27 15:08:31 +03:00
|
|
|
orth (int / unicode): The hash value of a word, or its unicode string.
|
2021-04-19 11:30:03 +03:00
|
|
|
RETURNS (numpy.ndarray or cupy.ndarray): A word vector. Size
|
2017-10-27 20:45:19 +03:00
|
|
|
and shape determined by the `vocab.vectors` instance. Usually, a
|
|
|
|
numpy ndarray of shape (300,) and dtype float32.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#get_vector
|
2017-05-28 12:45:32 +03:00
|
|
|
"""
|
2019-12-22 03:53:56 +03:00
|
|
|
if isinstance(orth, str):
|
2017-08-19 20:52:25 +03:00
|
|
|
orth = self.strings.add(orth)
|
2021-10-27 15:08:31 +03:00
|
|
|
if self.has_vector(orth):
|
2017-08-22 20:46:35 +03:00
|
|
|
return self.vectors[orth]
|
2019-11-23 16:59:52 +03:00
|
|
|
xp = get_array_module(self.vectors.data)
|
|
|
|
vectors = xp.zeros((self.vectors_length,), dtype="f")
|
2018-04-20 23:04:14 +03:00
|
|
|
return vectors
|
2017-05-28 12:45:32 +03:00
|
|
|
|
2017-05-31 00:34:50 +03:00
|
|
|
def set_vector(self, orth, vector):
|
2017-10-27 20:45:19 +03:00
|
|
|
"""Set a vector for a word in the vocabulary. Words can be referenced
|
|
|
|
by string or int ID.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2021-09-13 18:02:17 +03:00
|
|
|
orth (int / str): The word.
|
2021-04-19 11:30:03 +03:00
|
|
|
vector (numpy.ndarray or cupy.nadarry[ndim=1, dtype='float32']): The vector to set.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#set_vector
|
2017-05-31 00:34:50 +03:00
|
|
|
"""
|
2019-12-22 03:53:56 +03:00
|
|
|
if isinstance(orth, str):
|
2017-10-31 20:25:08 +03:00
|
|
|
orth = self.strings.add(orth)
|
|
|
|
if self.vectors.is_full and orth not in self.vectors:
|
|
|
|
new_rows = max(100, int(self.vectors.shape[0]*1.3))
|
|
|
|
if self.vectors.shape[1] == 0:
|
|
|
|
width = vector.size
|
|
|
|
else:
|
|
|
|
width = self.vectors.shape[1]
|
|
|
|
self.vectors.resize((new_rows, width))
|
2020-04-07 13:04:51 +03:00
|
|
|
lex = self[orth] # Add word to vocab if necessary
|
|
|
|
row = self.vectors.add(orth, vector=vector)
|
2021-10-27 15:08:31 +03:00
|
|
|
if row >= 0:
|
|
|
|
lex.rank = row
|
2017-05-31 00:34:50 +03:00
|
|
|
|
2017-05-28 12:45:32 +03:00
|
|
|
def has_vector(self, orth):
|
2017-10-27 20:45:19 +03:00
|
|
|
"""Check whether a word has a vector. Returns False if no vectors have
|
2019-03-08 13:42:26 +03:00
|
|
|
been loaded. Words can be looked up by string or int ID.
|
|
|
|
|
2021-09-13 18:02:17 +03:00
|
|
|
orth (int / str): The word.
|
2019-03-08 13:42:26 +03:00
|
|
|
RETURNS (bool): Whether the word has a vector.
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#has_vector
|
2019-03-08 13:42:26 +03:00
|
|
|
"""
|
2019-12-22 03:53:56 +03:00
|
|
|
if isinstance(orth, str):
|
2017-08-19 20:52:25 +03:00
|
|
|
orth = self.strings.add(orth)
|
|
|
|
return orth in self.vectors
|
2017-05-28 12:45:32 +03:00
|
|
|
|
2020-09-18 20:43:19 +03:00
|
|
|
property lookups:
|
|
|
|
def __get__(self):
|
|
|
|
return self._lookups
|
|
|
|
|
|
|
|
def __set__(self, lookups):
|
|
|
|
self._lookups = lookups
|
|
|
|
if lookups.has_table("lexeme_norm"):
|
|
|
|
self.lex_attr_getters[NORM] = util.add_lookups(
|
|
|
|
self.lex_attr_getters.get(NORM, LEX_ATTRS[NORM]),
|
|
|
|
self.lookups.get_table("lexeme_norm"),
|
|
|
|
)
|
|
|
|
|
2020-09-18 16:45:55 +03:00
|
|
|
|
2020-07-29 16:14:07 +03:00
|
|
|
def to_disk(self, path, *, exclude=tuple()):
|
2017-05-20 14:59:31 +03:00
|
|
|
"""Save the current state to a directory.
|
|
|
|
|
2021-09-13 18:02:17 +03:00
|
|
|
path (str or Path): A 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]): String names of serialization fields to exclude.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#to_disk
|
2017-05-20 14:59:31 +03:00
|
|
|
"""
|
2017-05-17 13:04:50 +03:00
|
|
|
path = util.ensure_path(path)
|
|
|
|
if not path.exists():
|
|
|
|
path.mkdir()
|
2020-05-19 16:59:14 +03:00
|
|
|
setters = ["strings", "vectors"]
|
2019-03-10 21:16:45 +03:00
|
|
|
if "strings" not in exclude:
|
|
|
|
self.strings.to_disk(path / "strings.json")
|
2020-10-05 10:33:05 +03:00
|
|
|
if "vectors" not in "exclude":
|
2021-10-27 15:08:31 +03:00
|
|
|
self.vectors.to_disk(path, exclude=["strings"])
|
2020-10-05 10:33:05 +03:00
|
|
|
if "lookups" not in "exclude":
|
2019-09-09 20:17:55 +03:00
|
|
|
self.lookups.to_disk(path)
|
2017-05-20 14:59:31 +03:00
|
|
|
|
2020-07-29 16:14:07 +03:00
|
|
|
def from_disk(self, path, *, exclude=tuple()):
|
2017-05-20 14:59:31 +03:00
|
|
|
"""Loads state from a directory. Modifies the object in place and
|
|
|
|
returns it.
|
|
|
|
|
2021-09-13 18:02:17 +03:00
|
|
|
path (str or 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]): String names of serialization fields to exclude.
|
2017-05-20 14:59:31 +03:00
|
|
|
RETURNS (Vocab): The modified `Vocab` object.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#to_disk
|
2017-05-20 14:59:31 +03:00
|
|
|
"""
|
2017-05-17 13:04:50 +03:00
|
|
|
path = util.ensure_path(path)
|
2020-05-19 16:59:14 +03:00
|
|
|
getters = ["strings", "vectors"]
|
2019-03-10 21:16:45 +03:00
|
|
|
if "strings" not in exclude:
|
|
|
|
self.strings.from_disk(path / "strings.json") # TODO: add exclude?
|
|
|
|
if "vectors" not in exclude:
|
|
|
|
if self.vectors is not None:
|
|
|
|
self.vectors.from_disk(path, exclude=["strings"])
|
2019-09-09 20:17:55 +03:00
|
|
|
if "lookups" not in exclude:
|
|
|
|
self.lookups.from_disk(path)
|
2020-05-19 16:59:14 +03:00
|
|
|
if "lexeme_norm" in self.lookups:
|
|
|
|
self.lex_attr_getters[NORM] = util.add_lookups(
|
|
|
|
self.lex_attr_getters.get(NORM, LEX_ATTRS[NORM]), self.lookups.get_table("lexeme_norm")
|
|
|
|
)
|
|
|
|
self.length = 0
|
|
|
|
self._by_orth = PreshMap()
|
2017-05-29 00:34:12 +03:00
|
|
|
return self
|
2016-11-01 14:25:36 +03:00
|
|
|
|
2020-07-29 16:14:07 +03:00
|
|
|
def to_bytes(self, *, exclude=tuple()):
|
2017-05-20 14:59:31 +03:00
|
|
|
"""Serialize the current state to a binary 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
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
2017-05-20 14:59:31 +03:00
|
|
|
RETURNS (bytes): The serialized form of the `Vocab` object.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#to_bytes
|
2017-05-20 14:59:31 +03:00
|
|
|
"""
|
2017-08-18 21:46:56 +03:00
|
|
|
def deserialize_vectors():
|
|
|
|
if self.vectors is None:
|
|
|
|
return None
|
|
|
|
else:
|
2021-10-27 15:08:31 +03:00
|
|
|
return self.vectors.to_bytes(exclude=["strings"])
|
2017-09-17 20:29:39 +03:00
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
getters = {
|
|
|
|
"strings": lambda: self.strings.to_bytes(),
|
|
|
|
"vectors": deserialize_vectors,
|
2020-05-21 19:39:06 +03:00
|
|
|
"lookups": lambda: self.lookups.to_bytes(),
|
2019-12-22 03:53:56 +03:00
|
|
|
}
|
2017-05-29 11:14:20 +03:00
|
|
|
return util.to_bytes(getters, exclude)
|
2017-05-20 14:59:31 +03:00
|
|
|
|
2020-07-29 16:14:07 +03:00
|
|
|
def from_bytes(self, bytes_data, *, exclude=tuple()):
|
2017-05-20 14:59:31 +03:00
|
|
|
"""Load state from a binary string.
|
|
|
|
|
|
|
|
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]): String names of serialization fields to exclude.
|
2017-05-20 14:59:31 +03:00
|
|
|
RETURNS (Vocab): The `Vocab` object.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/vocab#from_bytes
|
2017-05-20 14:59:31 +03:00
|
|
|
"""
|
2017-08-18 21:46:56 +03:00
|
|
|
def serialize_vectors(b):
|
|
|
|
if self.vectors is None:
|
|
|
|
return None
|
|
|
|
else:
|
2021-10-27 15:08:31 +03:00
|
|
|
return self.vectors.from_bytes(b, exclude=["strings"])
|
2019-03-10 21:16:45 +03:00
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
setters = {
|
|
|
|
"strings": lambda b: self.strings.from_bytes(b),
|
|
|
|
"vectors": lambda b: serialize_vectors(b),
|
2020-05-21 19:39:06 +03:00
|
|
|
"lookups": lambda b: self.lookups.from_bytes(b),
|
2019-12-22 03:53:56 +03:00
|
|
|
}
|
2017-06-02 11:56:40 +03:00
|
|
|
util.from_bytes(bytes_data, setters, exclude)
|
2020-05-19 16:59:14 +03:00
|
|
|
if "lexeme_norm" in self.lookups:
|
|
|
|
self.lex_attr_getters[NORM] = util.add_lookups(
|
|
|
|
self.lex_attr_getters.get(NORM, LEX_ATTRS[NORM]), self.lookups.get_table("lexeme_norm")
|
|
|
|
)
|
|
|
|
self.length = 0
|
|
|
|
self._by_orth = PreshMap()
|
2017-06-02 11:56:40 +03:00
|
|
|
return self
|
2017-05-29 00:34:12 +03:00
|
|
|
|
2017-11-14 21:15:04 +03:00
|
|
|
def _reset_cache(self, keys, strings):
|
💫 Small efficiency fixes to tokenizer (#2587)
This patch improves tokenizer speed by about 10%, and reduces memory usage in the `Vocab` by removing a redundant index. The `vocab._by_orth` and `vocab._by_hash` indexed on different data in v1, but in v2 the orth and the hash are identical.
The patch also fixes an uninitialized variable in the tokenizer, the `has_special` flag. This checks whether a chunk we're tokenizing triggers a special-case rule. If it does, then we avoid caching within the chunk. This check led to incorrectly rejecting some chunks from the cache.
With the `en_core_web_md` model, we now tokenize the IMDB train data at 503,104k words per second. Prior to this patch, we had 465,764k words per second.
Before switching to the regex library and supporting more languages, we had 1.3m words per second for the tokenizer. In order to recover the missing speed, we need to:
* Fix the variable-length lookarounds in the suffix, infix and `token_match` rules
* Improve the performance of the `token_match` regex
* Switch back from the `regex` library to the `re` library.
## 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-07-25 00:35:54 +03:00
|
|
|
# I'm not sure this made sense. Disable it for now.
|
|
|
|
raise NotImplementedError
|
2017-11-14 21:15:04 +03:00
|
|
|
|
2017-05-17 13:04:50 +03:00
|
|
|
|
2017-03-07 22:25:12 +03:00
|
|
|
def pickle_vocab(vocab):
|
|
|
|
sstore = vocab.strings
|
2017-11-23 19:19:50 +03:00
|
|
|
vectors = vocab.vectors
|
2017-03-07 22:25:12 +03:00
|
|
|
morph = vocab.morphology
|
2018-12-06 20:53:16 +03:00
|
|
|
lex_attr_getters = srsly.pickle_dumps(vocab.lex_attr_getters)
|
2020-05-19 16:59:14 +03:00
|
|
|
lookups = vocab.lookups
|
2021-02-12 15:27:46 +03:00
|
|
|
get_noun_chunks = vocab.get_noun_chunks
|
2017-03-07 22:25:12 +03:00
|
|
|
return (unpickle_vocab,
|
2022-08-22 16:52:24 +03:00
|
|
|
(sstore, vectors, morph, lex_attr_getters, lookups, get_noun_chunks))
|
2017-03-07 22:25:12 +03:00
|
|
|
|
|
|
|
|
2022-08-22 16:52:24 +03:00
|
|
|
def unpickle_vocab(sstore, vectors, morphology, lex_attr_getters, lookups, get_noun_chunks):
|
2017-03-07 22:25:12 +03:00
|
|
|
cdef Vocab vocab = Vocab()
|
2017-11-23 19:19:50 +03:00
|
|
|
vocab.vectors = vectors
|
2017-03-07 22:25:12 +03:00
|
|
|
vocab.strings = sstore
|
|
|
|
vocab.morphology = morphology
|
2018-12-06 20:53:16 +03:00
|
|
|
vocab.lex_attr_getters = srsly.pickle_loads(lex_attr_getters)
|
2020-05-19 16:59:14 +03:00
|
|
|
vocab.lookups = lookups
|
2021-02-12 15:27:46 +03:00
|
|
|
vocab.get_noun_chunks = get_noun_chunks
|
2017-03-07 22:25:12 +03:00
|
|
|
return vocab
|
|
|
|
|
|
|
|
|
|
|
|
copy_reg.pickle(Vocab, pickle_vocab, unpickle_vocab)
|