2023-06-14 15:48:41 +00:00
|
|
|
import random
|
2020-08-18 14:06:37 +00:00
|
|
|
import warnings
|
2020-07-29 09:36:42 +00:00
|
|
|
from pathlib import Path
|
2023-06-14 15:48:41 +00:00
|
|
|
from typing import TYPE_CHECKING, Callable, Iterable, Iterator, List, Optional, Union
|
|
|
|
|
2020-09-13 12:05:05 +00:00
|
|
|
import srsly
|
2020-07-29 09:36:42 +00:00
|
|
|
|
2020-06-26 17:34:12 +00:00
|
|
|
from .. import util
|
2023-06-14 15:48:41 +00:00
|
|
|
from ..errors import Errors, Warnings
|
|
|
|
from ..tokens import Doc, DocBin
|
|
|
|
from ..vocab import Vocab
|
2020-09-28 01:03:27 +00:00
|
|
|
from .augment import dont_augment
|
2020-06-26 17:34:12 +00:00
|
|
|
from .example import Example
|
2020-07-29 09:36:42 +00:00
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
# This lets us add type hints for mypy etc. without causing circular imports
|
|
|
|
from ..language import Language # noqa: F401
|
2020-06-26 17:34:12 +00:00
|
|
|
|
2020-08-18 14:06:37 +00:00
|
|
|
FILE_TYPE = ".spacy"
|
|
|
|
|
2020-06-26 17:34:12 +00:00
|
|
|
|
2020-08-04 13:09:37 +00:00
|
|
|
@util.registry.readers("spacy.Corpus.v1")
|
|
|
|
def create_docbin_reader(
|
2020-09-29 20:33:46 +00:00
|
|
|
path: Optional[Path],
|
2020-09-28 01:03:27 +00:00
|
|
|
gold_preproc: bool,
|
|
|
|
max_length: int = 0,
|
|
|
|
limit: int = 0,
|
|
|
|
augmenter: Optional[Callable] = None,
|
2020-08-04 13:09:37 +00:00
|
|
|
) -> Callable[["Language"], Iterable[Example]]:
|
2020-09-29 20:33:46 +00:00
|
|
|
if path is None:
|
|
|
|
raise ValueError(Errors.E913)
|
2023-02-02 10:15:22 +00:00
|
|
|
util.logger.debug("Loading corpus from path: %s", path)
|
2020-09-28 01:03:27 +00:00
|
|
|
return Corpus(
|
|
|
|
path,
|
|
|
|
gold_preproc=gold_preproc,
|
|
|
|
max_length=max_length,
|
|
|
|
limit=limit,
|
|
|
|
augmenter=augmenter,
|
|
|
|
)
|
2020-08-04 13:09:37 +00:00
|
|
|
|
2020-09-14 22:32:49 +00:00
|
|
|
|
2020-10-01 23:36:06 +00:00
|
|
|
@util.registry.readers("spacy.JsonlCorpus.v1")
|
2020-09-13 12:05:05 +00:00
|
|
|
def create_jsonl_reader(
|
2021-11-12 09:00:03 +00:00
|
|
|
path: Optional[Union[str, Path]],
|
|
|
|
min_length: int = 0,
|
|
|
|
max_length: int = 0,
|
|
|
|
limit: int = 0,
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 Ignore all existing Mypy errors
* 🏗 Add Mypy check to CI
* Add types-mock and types-requests as dev requirements
* Add additional type ignore directives
* Add types packages to dev-only list in reqs test
* Add types-dataclasses for python 3.6
* Add ignore to pretrain
* 🏷 Improve type annotation on `run_command` helper
The `run_command` helper previously declared that it returned an
`Optional[subprocess.CompletedProcess]`, but it isn't actually possible
for the function to return `None`. These changes modify the type
annotation of the `run_command` helper and remove all now-unnecessary
`# type: ignore` directives.
* 🔧 Allow variable type redefinition in limited contexts
These changes modify how Mypy is configured to allow variables to have
their type automatically redefined under certain conditions. The Mypy
documentation contains the following example:
```python
def process(items: List[str]) -> None:
# 'items' has type List[str]
items = [item.split() for item in items]
# 'items' now has type List[List[str]]
...
```
This configuration change is especially helpful in reducing the number
of `# type: ignore` directives needed to handle the common pattern of:
* Accepting a filepath as a string
* Overwriting the variable using `filepath = ensure_path(filepath)`
These changes enable redefinition and remove all `# type: ignore`
directives rendered redundant by this change.
* 🏷 Add type annotation to converters mapping
* 🚨 Fix Mypy error in convert CLI argument verification
* 🏷 Improve type annotation on `resolve_dot_names` helper
* 🏷 Add type annotations for `Vocab` attributes `strings` and `vectors`
* 🏷 Add type annotations for more `Vocab` attributes
* 🏷 Add loose type annotation for gold data compilation
* 🏷 Improve `_format_labels` type annotation
* 🏷 Fix `get_lang_class` type annotation
* 🏷 Loosen return type of `Language.evaluate`
* 🏷 Don't accept `Scorer` in `handle_scores_per_type`
* 🏷 Add `string_to_list` overloads
* 🏷 Fix non-Optional command-line options
* 🙈 Ignore redefinition of `wandb_logger` in `loggers.py`
* ➕ Install `typing_extensions` in Python 3.8+
The `typing_extensions` package states that it should be used when
"writing code that must be compatible with multiple Python versions".
Since SpaCy needs to support multiple Python versions, it should be used
when newer `typing` module members are required. One example of this is
`Literal`, which is available starting with Python 3.8.
Previously SpaCy tried to import `Literal` from `typing`, falling back
to `typing_extensions` if the import failed. However, Mypy doesn't seem
to be able to understand what `Literal` means when the initial import
means. Therefore, these changes modify how `compat` imports `Literal` by
always importing it from `typing_extensions`.
These changes also modify how `typing_extensions` is installed, so that
it is a requirement for all Python versions, including those greater
than or equal to 3.8.
* 🏷 Improve type annotation for `Language.pipe`
These changes add a missing overload variant to the type signature of
`Language.pipe`. Additionally, the type signature is enhanced to allow
type checkers to differentiate between the two overload variants based
on the `as_tuple` parameter.
Fixes #8772
* ➖ Don't install `typing-extensions` in Python 3.8+
After more detailed analysis of how to implement Python version-specific
type annotations using SpaCy, it has been determined that by branching
on a comparison against `sys.version_info` can be statically analyzed by
Mypy well enough to enable us to conditionally use
`typing_extensions.Literal`. This means that we no longer need to
install `typing_extensions` for Python versions greater than or equal to
3.8! 🎉
These changes revert previous changes installing `typing-extensions`
regardless of Python version and modify how we import the `Literal` type
to ensure that Mypy treats it properly.
* resolve mypy errors for Strict pydantic types
* refactor code to avoid missing return statement
* fix types of convert CLI command
* avoid list-set confustion in debug_data
* fix typo and formatting
* small fixes to avoid type ignores
* fix types in profile CLI command and make it more efficient
* type fixes in projects CLI
* put one ignore back
* type fixes for render
* fix render types - the sequel
* fix BaseDefault in language definitions
* fix type of noun_chunks iterator - yields tuple instead of span
* fix types in language-specific modules
* 🏷 Expand accepted inputs of `get_string_id`
`get_string_id` accepts either a string (in which case it returns its
ID) or an ID (in which case it immediately returns the ID). These
changes extend the type annotation of `get_string_id` to indicate that
it can accept either strings or IDs.
* 🏷 Handle override types in `combine_score_weights`
The `combine_score_weights` function allows users to pass an `overrides`
mapping to override data extracted from the `weights` argument. Since it
allows `Optional` dictionary values, the return value may also include
`Optional` dictionary values.
These changes update the type annotations for `combine_score_weights` to
reflect this fact.
* 🏷 Fix tokenizer serialization method signatures in `DummyTokenizer`
* 🏷 Fix redefinition of `wandb_logger`
These changes fix the redefinition of `wandb_logger` by giving a
separate name to each `WandbLogger` version. For
backwards-compatibility, `spacy.train` still exports `wandb_logger_v3`
as `wandb_logger` for now.
* more fixes for typing in language
* type fixes in model definitions
* 🏷 Annotate `_RandomWords.probs` as `NDArray`
* 🏷 Annotate `tok2vec` layers to help Mypy
* 🐛 Fix `_RandomWords.probs` type annotations for Python 3.6
Also remove an import that I forgot to move to the top of the module 😅
* more fixes for matchers and other pipeline components
* quick fix for entity linker
* fixing types for spancat, textcat, etc
* bugfix for tok2vec
* type annotations for scorer
* add runtime_checkable for Protocol
* type and import fixes in tests
* mypy fixes for training utilities
* few fixes in util
* fix import
* 🐵 Remove unused `# type: ignore` directives
* 🏷 Annotate `Language._components`
* 🏷 Annotate `spacy.pipeline.Pipe`
* add doc as property to span.pyi
* small fixes and cleanup
* explicit type annotations instead of via comment
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
2021-10-14 13:21:40 +00:00
|
|
|
) -> Callable[["Language"], Iterable[Example]]:
|
2020-10-01 23:36:06 +00:00
|
|
|
return JsonlCorpus(path, min_length=min_length, max_length=max_length, limit=limit)
|
2020-09-13 12:05:05 +00:00
|
|
|
|
|
|
|
|
2020-09-30 14:52:27 +00:00
|
|
|
@util.registry.readers("spacy.read_labels.v1")
|
2020-10-01 15:38:17 +00:00
|
|
|
def read_labels(path: Path, *, require: bool = False):
|
2020-09-30 14:52:27 +00:00
|
|
|
# I decided not to give this a generic name, because I don't want people to
|
|
|
|
# use it for arbitrary stuff, as I want this require arg with default False.
|
|
|
|
if not require and not path.exists():
|
|
|
|
return None
|
|
|
|
return srsly.read_json(path)
|
|
|
|
|
|
|
|
|
2023-01-26 10:33:22 +00:00
|
|
|
@util.registry.readers("spacy.PlainTextCorpus.v1")
|
|
|
|
def create_plain_text_reader(
|
|
|
|
path: Optional[Path],
|
|
|
|
min_length: int = 0,
|
|
|
|
max_length: int = 0,
|
|
|
|
) -> Callable[["Language"], Iterable[Doc]]:
|
|
|
|
"""Iterate Example objects from a file or directory of plain text
|
|
|
|
UTF-8 files with one line per doc.
|
|
|
|
|
|
|
|
path (Path): The directory or filename to read from.
|
|
|
|
min_length (int): Minimum document length (in tokens). Shorter documents
|
|
|
|
will be skipped. Defaults to 0, which indicates no limit.
|
|
|
|
max_length (int): Maximum document length (in tokens). Longer documents will
|
|
|
|
be skipped. Defaults to 0, which indicates no limit.
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/corpus#plaintextcorpus
|
|
|
|
"""
|
|
|
|
if path is None:
|
|
|
|
raise ValueError(Errors.E913)
|
|
|
|
return PlainTextCorpus(path, min_length=min_length, max_length=max_length)
|
|
|
|
|
|
|
|
|
2020-09-13 12:05:05 +00:00
|
|
|
def walk_corpus(path: Union[str, Path], file_type) -> List[Path]:
|
|
|
|
path = util.ensure_path(path)
|
|
|
|
if not path.is_dir() and path.parts[-1].endswith(file_type):
|
|
|
|
return [path]
|
|
|
|
orig_path = path
|
|
|
|
paths = [path]
|
|
|
|
locs = []
|
|
|
|
seen = set()
|
|
|
|
for path in paths:
|
|
|
|
if str(path) in seen:
|
|
|
|
continue
|
|
|
|
seen.add(str(path))
|
|
|
|
if path.parts and path.parts[-1].startswith("."):
|
|
|
|
continue
|
|
|
|
elif path.is_dir():
|
|
|
|
paths.extend(path.iterdir())
|
|
|
|
elif path.parts[-1].endswith(file_type):
|
|
|
|
locs.append(path)
|
|
|
|
if len(locs) == 0:
|
2020-09-25 13:47:10 +00:00
|
|
|
warnings.warn(Warnings.W090.format(path=orig_path, format=file_type))
|
2020-09-25 17:07:26 +00:00
|
|
|
# It's good to sort these, in case the ordering messes up a cache.
|
|
|
|
locs.sort()
|
2020-09-13 12:05:05 +00:00
|
|
|
return locs
|
|
|
|
|
|
|
|
|
2020-06-26 17:34:12 +00:00
|
|
|
class Corpus:
|
2020-08-04 13:09:37 +00:00
|
|
|
"""Iterate Example objects from a file or directory of DocBin (.spacy)
|
2020-08-06 13:29:44 +00:00
|
|
|
formatted data files.
|
2020-08-04 13:09:37 +00:00
|
|
|
|
|
|
|
path (Path): The directory or filename to read from.
|
|
|
|
gold_preproc (bool): Whether to set up the Example object with gold-standard
|
2020-08-05 14:00:59 +00:00
|
|
|
sentences and tokens for the predictions. Gold preprocessing helps
|
2020-08-04 13:09:37 +00:00
|
|
|
the annotations align to the tokenization, and may result in sequences
|
|
|
|
of more consistent length. However, it may reduce run-time accuracy due
|
|
|
|
to train/test skew. Defaults to False.
|
|
|
|
max_length (int): Maximum document length. Longer documents will be
|
|
|
|
split into sentences, if sentence boundaries are available. Defaults to
|
|
|
|
0, which indicates no limit.
|
|
|
|
limit (int): Limit corpus to a subset of examples, e.g. for debugging.
|
|
|
|
Defaults to 0, which indicates no limit.
|
2020-09-28 01:03:27 +00:00
|
|
|
augment (Callable[Example, Iterable[Example]]): Optional data augmentation
|
|
|
|
function, to extrapolate additional examples from your annotations.
|
2021-04-08 08:08:04 +00:00
|
|
|
shuffle (bool): Whether to shuffle the examples.
|
2020-06-26 17:34:12 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/corpus
|
2020-06-26 17:34:12 +00:00
|
|
|
"""
|
|
|
|
|
2020-07-29 09:36:42 +00:00
|
|
|
def __init__(
|
2020-08-05 14:00:59 +00:00
|
|
|
self,
|
2020-08-07 12:30:59 +00:00
|
|
|
path: Union[str, Path],
|
2020-08-05 14:00:59 +00:00
|
|
|
*,
|
|
|
|
limit: int = 0,
|
|
|
|
gold_preproc: bool = False,
|
2020-09-12 19:01:53 +00:00
|
|
|
max_length: int = 0,
|
2020-09-28 01:03:27 +00:00
|
|
|
augmenter: Optional[Callable] = None,
|
2021-04-08 08:08:04 +00:00
|
|
|
shuffle: bool = False,
|
2020-07-29 09:36:42 +00:00
|
|
|
) -> None:
|
2020-08-04 13:09:37 +00:00
|
|
|
self.path = util.ensure_path(path)
|
|
|
|
self.gold_preproc = gold_preproc
|
|
|
|
self.max_length = max_length
|
2020-06-26 17:34:12 +00:00
|
|
|
self.limit = limit
|
2020-09-28 01:03:27 +00:00
|
|
|
self.augmenter = augmenter if augmenter is not None else dont_augment
|
2021-04-08 08:08:04 +00:00
|
|
|
self.shuffle = shuffle
|
2020-06-26 17:34:12 +00:00
|
|
|
|
2020-08-04 13:09:37 +00:00
|
|
|
def __call__(self, nlp: "Language") -> Iterator[Example]:
|
|
|
|
"""Yield examples from the data.
|
|
|
|
|
|
|
|
nlp (Language): The current nlp object.
|
|
|
|
YIELDS (Example): The examples.
|
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/corpus#call
|
2020-08-04 13:09:37 +00:00
|
|
|
"""
|
2020-09-13 12:05:05 +00:00
|
|
|
ref_docs = self.read_docbin(nlp.vocab, walk_corpus(self.path, FILE_TYPE))
|
2021-04-08 08:08:04 +00:00
|
|
|
if self.shuffle:
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 Ignore all existing Mypy errors
* 🏗 Add Mypy check to CI
* Add types-mock and types-requests as dev requirements
* Add additional type ignore directives
* Add types packages to dev-only list in reqs test
* Add types-dataclasses for python 3.6
* Add ignore to pretrain
* 🏷 Improve type annotation on `run_command` helper
The `run_command` helper previously declared that it returned an
`Optional[subprocess.CompletedProcess]`, but it isn't actually possible
for the function to return `None`. These changes modify the type
annotation of the `run_command` helper and remove all now-unnecessary
`# type: ignore` directives.
* 🔧 Allow variable type redefinition in limited contexts
These changes modify how Mypy is configured to allow variables to have
their type automatically redefined under certain conditions. The Mypy
documentation contains the following example:
```python
def process(items: List[str]) -> None:
# 'items' has type List[str]
items = [item.split() for item in items]
# 'items' now has type List[List[str]]
...
```
This configuration change is especially helpful in reducing the number
of `# type: ignore` directives needed to handle the common pattern of:
* Accepting a filepath as a string
* Overwriting the variable using `filepath = ensure_path(filepath)`
These changes enable redefinition and remove all `# type: ignore`
directives rendered redundant by this change.
* 🏷 Add type annotation to converters mapping
* 🚨 Fix Mypy error in convert CLI argument verification
* 🏷 Improve type annotation on `resolve_dot_names` helper
* 🏷 Add type annotations for `Vocab` attributes `strings` and `vectors`
* 🏷 Add type annotations for more `Vocab` attributes
* 🏷 Add loose type annotation for gold data compilation
* 🏷 Improve `_format_labels` type annotation
* 🏷 Fix `get_lang_class` type annotation
* 🏷 Loosen return type of `Language.evaluate`
* 🏷 Don't accept `Scorer` in `handle_scores_per_type`
* 🏷 Add `string_to_list` overloads
* 🏷 Fix non-Optional command-line options
* 🙈 Ignore redefinition of `wandb_logger` in `loggers.py`
* ➕ Install `typing_extensions` in Python 3.8+
The `typing_extensions` package states that it should be used when
"writing code that must be compatible with multiple Python versions".
Since SpaCy needs to support multiple Python versions, it should be used
when newer `typing` module members are required. One example of this is
`Literal`, which is available starting with Python 3.8.
Previously SpaCy tried to import `Literal` from `typing`, falling back
to `typing_extensions` if the import failed. However, Mypy doesn't seem
to be able to understand what `Literal` means when the initial import
means. Therefore, these changes modify how `compat` imports `Literal` by
always importing it from `typing_extensions`.
These changes also modify how `typing_extensions` is installed, so that
it is a requirement for all Python versions, including those greater
than or equal to 3.8.
* 🏷 Improve type annotation for `Language.pipe`
These changes add a missing overload variant to the type signature of
`Language.pipe`. Additionally, the type signature is enhanced to allow
type checkers to differentiate between the two overload variants based
on the `as_tuple` parameter.
Fixes #8772
* ➖ Don't install `typing-extensions` in Python 3.8+
After more detailed analysis of how to implement Python version-specific
type annotations using SpaCy, it has been determined that by branching
on a comparison against `sys.version_info` can be statically analyzed by
Mypy well enough to enable us to conditionally use
`typing_extensions.Literal`. This means that we no longer need to
install `typing_extensions` for Python versions greater than or equal to
3.8! 🎉
These changes revert previous changes installing `typing-extensions`
regardless of Python version and modify how we import the `Literal` type
to ensure that Mypy treats it properly.
* resolve mypy errors for Strict pydantic types
* refactor code to avoid missing return statement
* fix types of convert CLI command
* avoid list-set confustion in debug_data
* fix typo and formatting
* small fixes to avoid type ignores
* fix types in profile CLI command and make it more efficient
* type fixes in projects CLI
* put one ignore back
* type fixes for render
* fix render types - the sequel
* fix BaseDefault in language definitions
* fix type of noun_chunks iterator - yields tuple instead of span
* fix types in language-specific modules
* 🏷 Expand accepted inputs of `get_string_id`
`get_string_id` accepts either a string (in which case it returns its
ID) or an ID (in which case it immediately returns the ID). These
changes extend the type annotation of `get_string_id` to indicate that
it can accept either strings or IDs.
* 🏷 Handle override types in `combine_score_weights`
The `combine_score_weights` function allows users to pass an `overrides`
mapping to override data extracted from the `weights` argument. Since it
allows `Optional` dictionary values, the return value may also include
`Optional` dictionary values.
These changes update the type annotations for `combine_score_weights` to
reflect this fact.
* 🏷 Fix tokenizer serialization method signatures in `DummyTokenizer`
* 🏷 Fix redefinition of `wandb_logger`
These changes fix the redefinition of `wandb_logger` by giving a
separate name to each `WandbLogger` version. For
backwards-compatibility, `spacy.train` still exports `wandb_logger_v3`
as `wandb_logger` for now.
* more fixes for typing in language
* type fixes in model definitions
* 🏷 Annotate `_RandomWords.probs` as `NDArray`
* 🏷 Annotate `tok2vec` layers to help Mypy
* 🐛 Fix `_RandomWords.probs` type annotations for Python 3.6
Also remove an import that I forgot to move to the top of the module 😅
* more fixes for matchers and other pipeline components
* quick fix for entity linker
* fixing types for spancat, textcat, etc
* bugfix for tok2vec
* type annotations for scorer
* add runtime_checkable for Protocol
* type and import fixes in tests
* mypy fixes for training utilities
* few fixes in util
* fix import
* 🐵 Remove unused `# type: ignore` directives
* 🏷 Annotate `Language._components`
* 🏷 Annotate `spacy.pipeline.Pipe`
* add doc as property to span.pyi
* small fixes and cleanup
* explicit type annotations instead of via comment
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
2021-10-14 13:21:40 +00:00
|
|
|
ref_docs = list(ref_docs) # type: ignore
|
|
|
|
random.shuffle(ref_docs) # type: ignore
|
2021-04-08 08:08:04 +00:00
|
|
|
|
2020-08-04 13:09:37 +00:00
|
|
|
if self.gold_preproc:
|
|
|
|
examples = self.make_examples_gold_preproc(nlp, ref_docs)
|
|
|
|
else:
|
2020-09-12 19:01:53 +00:00
|
|
|
examples = self.make_examples(nlp, ref_docs)
|
2020-09-28 01:03:27 +00:00
|
|
|
for real_eg in examples:
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 Ignore all existing Mypy errors
* 🏗 Add Mypy check to CI
* Add types-mock and types-requests as dev requirements
* Add additional type ignore directives
* Add types packages to dev-only list in reqs test
* Add types-dataclasses for python 3.6
* Add ignore to pretrain
* 🏷 Improve type annotation on `run_command` helper
The `run_command` helper previously declared that it returned an
`Optional[subprocess.CompletedProcess]`, but it isn't actually possible
for the function to return `None`. These changes modify the type
annotation of the `run_command` helper and remove all now-unnecessary
`# type: ignore` directives.
* 🔧 Allow variable type redefinition in limited contexts
These changes modify how Mypy is configured to allow variables to have
their type automatically redefined under certain conditions. The Mypy
documentation contains the following example:
```python
def process(items: List[str]) -> None:
# 'items' has type List[str]
items = [item.split() for item in items]
# 'items' now has type List[List[str]]
...
```
This configuration change is especially helpful in reducing the number
of `# type: ignore` directives needed to handle the common pattern of:
* Accepting a filepath as a string
* Overwriting the variable using `filepath = ensure_path(filepath)`
These changes enable redefinition and remove all `# type: ignore`
directives rendered redundant by this change.
* 🏷 Add type annotation to converters mapping
* 🚨 Fix Mypy error in convert CLI argument verification
* 🏷 Improve type annotation on `resolve_dot_names` helper
* 🏷 Add type annotations for `Vocab` attributes `strings` and `vectors`
* 🏷 Add type annotations for more `Vocab` attributes
* 🏷 Add loose type annotation for gold data compilation
* 🏷 Improve `_format_labels` type annotation
* 🏷 Fix `get_lang_class` type annotation
* 🏷 Loosen return type of `Language.evaluate`
* 🏷 Don't accept `Scorer` in `handle_scores_per_type`
* 🏷 Add `string_to_list` overloads
* 🏷 Fix non-Optional command-line options
* 🙈 Ignore redefinition of `wandb_logger` in `loggers.py`
* ➕ Install `typing_extensions` in Python 3.8+
The `typing_extensions` package states that it should be used when
"writing code that must be compatible with multiple Python versions".
Since SpaCy needs to support multiple Python versions, it should be used
when newer `typing` module members are required. One example of this is
`Literal`, which is available starting with Python 3.8.
Previously SpaCy tried to import `Literal` from `typing`, falling back
to `typing_extensions` if the import failed. However, Mypy doesn't seem
to be able to understand what `Literal` means when the initial import
means. Therefore, these changes modify how `compat` imports `Literal` by
always importing it from `typing_extensions`.
These changes also modify how `typing_extensions` is installed, so that
it is a requirement for all Python versions, including those greater
than or equal to 3.8.
* 🏷 Improve type annotation for `Language.pipe`
These changes add a missing overload variant to the type signature of
`Language.pipe`. Additionally, the type signature is enhanced to allow
type checkers to differentiate between the two overload variants based
on the `as_tuple` parameter.
Fixes #8772
* ➖ Don't install `typing-extensions` in Python 3.8+
After more detailed analysis of how to implement Python version-specific
type annotations using SpaCy, it has been determined that by branching
on a comparison against `sys.version_info` can be statically analyzed by
Mypy well enough to enable us to conditionally use
`typing_extensions.Literal`. This means that we no longer need to
install `typing_extensions` for Python versions greater than or equal to
3.8! 🎉
These changes revert previous changes installing `typing-extensions`
regardless of Python version and modify how we import the `Literal` type
to ensure that Mypy treats it properly.
* resolve mypy errors for Strict pydantic types
* refactor code to avoid missing return statement
* fix types of convert CLI command
* avoid list-set confustion in debug_data
* fix typo and formatting
* small fixes to avoid type ignores
* fix types in profile CLI command and make it more efficient
* type fixes in projects CLI
* put one ignore back
* type fixes for render
* fix render types - the sequel
* fix BaseDefault in language definitions
* fix type of noun_chunks iterator - yields tuple instead of span
* fix types in language-specific modules
* 🏷 Expand accepted inputs of `get_string_id`
`get_string_id` accepts either a string (in which case it returns its
ID) or an ID (in which case it immediately returns the ID). These
changes extend the type annotation of `get_string_id` to indicate that
it can accept either strings or IDs.
* 🏷 Handle override types in `combine_score_weights`
The `combine_score_weights` function allows users to pass an `overrides`
mapping to override data extracted from the `weights` argument. Since it
allows `Optional` dictionary values, the return value may also include
`Optional` dictionary values.
These changes update the type annotations for `combine_score_weights` to
reflect this fact.
* 🏷 Fix tokenizer serialization method signatures in `DummyTokenizer`
* 🏷 Fix redefinition of `wandb_logger`
These changes fix the redefinition of `wandb_logger` by giving a
separate name to each `WandbLogger` version. For
backwards-compatibility, `spacy.train` still exports `wandb_logger_v3`
as `wandb_logger` for now.
* more fixes for typing in language
* type fixes in model definitions
* 🏷 Annotate `_RandomWords.probs` as `NDArray`
* 🏷 Annotate `tok2vec` layers to help Mypy
* 🐛 Fix `_RandomWords.probs` type annotations for Python 3.6
Also remove an import that I forgot to move to the top of the module 😅
* more fixes for matchers and other pipeline components
* quick fix for entity linker
* fixing types for spancat, textcat, etc
* bugfix for tok2vec
* type annotations for scorer
* add runtime_checkable for Protocol
* type and import fixes in tests
* mypy fixes for training utilities
* few fixes in util
* fix import
* 🐵 Remove unused `# type: ignore` directives
* 🏷 Annotate `Language._components`
* 🏷 Annotate `spacy.pipeline.Pipe`
* add doc as property to span.pyi
* small fixes and cleanup
* explicit type annotations instead of via comment
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
2021-10-14 13:21:40 +00:00
|
|
|
for augmented_eg in self.augmenter(nlp, real_eg): # type: ignore[operator]
|
2020-09-28 01:03:27 +00:00
|
|
|
yield augmented_eg
|
2020-08-04 13:09:37 +00:00
|
|
|
|
2020-07-29 09:36:42 +00:00
|
|
|
def _make_example(
|
|
|
|
self, nlp: "Language", reference: Doc, gold_preproc: bool
|
|
|
|
) -> Example:
|
2020-07-03 10:58:16 +00:00
|
|
|
if gold_preproc or reference.has_unknown_spaces:
|
|
|
|
return Example(
|
|
|
|
Doc(
|
|
|
|
nlp.vocab,
|
|
|
|
words=[word.text for word in reference],
|
2020-07-04 12:23:44 +00:00
|
|
|
spaces=[bool(word.whitespace_) for word in reference],
|
2020-07-03 10:58:16 +00:00
|
|
|
),
|
2020-07-04 12:23:44 +00:00
|
|
|
reference,
|
2020-07-03 10:58:16 +00:00
|
|
|
)
|
|
|
|
else:
|
2020-07-04 12:23:44 +00:00
|
|
|
return Example(nlp.make_doc(reference.text), reference)
|
|
|
|
|
2020-07-29 09:36:42 +00:00
|
|
|
def make_examples(
|
2020-09-12 19:01:53 +00:00
|
|
|
self, nlp: "Language", reference_docs: Iterable[Doc]
|
2020-07-29 09:36:42 +00:00
|
|
|
) -> Iterator[Example]:
|
2020-06-26 17:34:12 +00:00
|
|
|
for reference in reference_docs:
|
2020-07-01 13:16:43 +00:00
|
|
|
if len(reference) == 0:
|
|
|
|
continue
|
2020-09-12 19:01:53 +00:00
|
|
|
elif self.max_length == 0 or len(reference) < self.max_length:
|
2020-07-03 10:58:16 +00:00
|
|
|
yield self._make_example(nlp, reference, False)
|
2021-03-19 08:43:52 +00:00
|
|
|
elif reference.has_annotation("SENT_START"):
|
2020-07-01 13:16:43 +00:00
|
|
|
for ref_sent in reference.sents:
|
|
|
|
if len(ref_sent) == 0:
|
|
|
|
continue
|
2020-09-12 19:01:53 +00:00
|
|
|
elif self.max_length == 0 or len(ref_sent) < self.max_length:
|
2020-07-03 10:58:16 +00:00
|
|
|
yield self._make_example(nlp, ref_sent.as_doc(), False)
|
|
|
|
|
2020-07-29 09:36:42 +00:00
|
|
|
def make_examples_gold_preproc(
|
|
|
|
self, nlp: "Language", reference_docs: Iterable[Doc]
|
|
|
|
) -> Iterator[Example]:
|
2020-06-26 17:34:12 +00:00
|
|
|
for reference in reference_docs:
|
2021-03-19 08:43:52 +00:00
|
|
|
if reference.has_annotation("SENT_START"):
|
2020-06-26 17:34:12 +00:00
|
|
|
ref_sents = [sent.as_doc() for sent in reference.sents]
|
|
|
|
else:
|
|
|
|
ref_sents = [reference]
|
|
|
|
for ref_sent in ref_sents:
|
2020-07-03 10:58:16 +00:00
|
|
|
eg = self._make_example(nlp, ref_sent, True)
|
2020-07-01 13:02:37 +00:00
|
|
|
if len(eg.x):
|
|
|
|
yield eg
|
2020-06-26 17:34:12 +00:00
|
|
|
|
2020-07-29 09:36:42 +00:00
|
|
|
def read_docbin(
|
|
|
|
self, vocab: Vocab, locs: Iterable[Union[str, Path]]
|
|
|
|
) -> Iterator[Doc]:
|
2021-07-02 07:48:26 +00:00
|
|
|
"""Yield training examples as example dicts"""
|
2020-06-26 17:34:12 +00:00
|
|
|
i = 0
|
|
|
|
for loc in locs:
|
|
|
|
loc = util.ensure_path(loc)
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 Ignore all existing Mypy errors
* 🏗 Add Mypy check to CI
* Add types-mock and types-requests as dev requirements
* Add additional type ignore directives
* Add types packages to dev-only list in reqs test
* Add types-dataclasses for python 3.6
* Add ignore to pretrain
* 🏷 Improve type annotation on `run_command` helper
The `run_command` helper previously declared that it returned an
`Optional[subprocess.CompletedProcess]`, but it isn't actually possible
for the function to return `None`. These changes modify the type
annotation of the `run_command` helper and remove all now-unnecessary
`# type: ignore` directives.
* 🔧 Allow variable type redefinition in limited contexts
These changes modify how Mypy is configured to allow variables to have
their type automatically redefined under certain conditions. The Mypy
documentation contains the following example:
```python
def process(items: List[str]) -> None:
# 'items' has type List[str]
items = [item.split() for item in items]
# 'items' now has type List[List[str]]
...
```
This configuration change is especially helpful in reducing the number
of `# type: ignore` directives needed to handle the common pattern of:
* Accepting a filepath as a string
* Overwriting the variable using `filepath = ensure_path(filepath)`
These changes enable redefinition and remove all `# type: ignore`
directives rendered redundant by this change.
* 🏷 Add type annotation to converters mapping
* 🚨 Fix Mypy error in convert CLI argument verification
* 🏷 Improve type annotation on `resolve_dot_names` helper
* 🏷 Add type annotations for `Vocab` attributes `strings` and `vectors`
* 🏷 Add type annotations for more `Vocab` attributes
* 🏷 Add loose type annotation for gold data compilation
* 🏷 Improve `_format_labels` type annotation
* 🏷 Fix `get_lang_class` type annotation
* 🏷 Loosen return type of `Language.evaluate`
* 🏷 Don't accept `Scorer` in `handle_scores_per_type`
* 🏷 Add `string_to_list` overloads
* 🏷 Fix non-Optional command-line options
* 🙈 Ignore redefinition of `wandb_logger` in `loggers.py`
* ➕ Install `typing_extensions` in Python 3.8+
The `typing_extensions` package states that it should be used when
"writing code that must be compatible with multiple Python versions".
Since SpaCy needs to support multiple Python versions, it should be used
when newer `typing` module members are required. One example of this is
`Literal`, which is available starting with Python 3.8.
Previously SpaCy tried to import `Literal` from `typing`, falling back
to `typing_extensions` if the import failed. However, Mypy doesn't seem
to be able to understand what `Literal` means when the initial import
means. Therefore, these changes modify how `compat` imports `Literal` by
always importing it from `typing_extensions`.
These changes also modify how `typing_extensions` is installed, so that
it is a requirement for all Python versions, including those greater
than or equal to 3.8.
* 🏷 Improve type annotation for `Language.pipe`
These changes add a missing overload variant to the type signature of
`Language.pipe`. Additionally, the type signature is enhanced to allow
type checkers to differentiate between the two overload variants based
on the `as_tuple` parameter.
Fixes #8772
* ➖ Don't install `typing-extensions` in Python 3.8+
After more detailed analysis of how to implement Python version-specific
type annotations using SpaCy, it has been determined that by branching
on a comparison against `sys.version_info` can be statically analyzed by
Mypy well enough to enable us to conditionally use
`typing_extensions.Literal`. This means that we no longer need to
install `typing_extensions` for Python versions greater than or equal to
3.8! 🎉
These changes revert previous changes installing `typing-extensions`
regardless of Python version and modify how we import the `Literal` type
to ensure that Mypy treats it properly.
* resolve mypy errors for Strict pydantic types
* refactor code to avoid missing return statement
* fix types of convert CLI command
* avoid list-set confustion in debug_data
* fix typo and formatting
* small fixes to avoid type ignores
* fix types in profile CLI command and make it more efficient
* type fixes in projects CLI
* put one ignore back
* type fixes for render
* fix render types - the sequel
* fix BaseDefault in language definitions
* fix type of noun_chunks iterator - yields tuple instead of span
* fix types in language-specific modules
* 🏷 Expand accepted inputs of `get_string_id`
`get_string_id` accepts either a string (in which case it returns its
ID) or an ID (in which case it immediately returns the ID). These
changes extend the type annotation of `get_string_id` to indicate that
it can accept either strings or IDs.
* 🏷 Handle override types in `combine_score_weights`
The `combine_score_weights` function allows users to pass an `overrides`
mapping to override data extracted from the `weights` argument. Since it
allows `Optional` dictionary values, the return value may also include
`Optional` dictionary values.
These changes update the type annotations for `combine_score_weights` to
reflect this fact.
* 🏷 Fix tokenizer serialization method signatures in `DummyTokenizer`
* 🏷 Fix redefinition of `wandb_logger`
These changes fix the redefinition of `wandb_logger` by giving a
separate name to each `WandbLogger` version. For
backwards-compatibility, `spacy.train` still exports `wandb_logger_v3`
as `wandb_logger` for now.
* more fixes for typing in language
* type fixes in model definitions
* 🏷 Annotate `_RandomWords.probs` as `NDArray`
* 🏷 Annotate `tok2vec` layers to help Mypy
* 🐛 Fix `_RandomWords.probs` type annotations for Python 3.6
Also remove an import that I forgot to move to the top of the module 😅
* more fixes for matchers and other pipeline components
* quick fix for entity linker
* fixing types for spancat, textcat, etc
* bugfix for tok2vec
* type annotations for scorer
* add runtime_checkable for Protocol
* type and import fixes in tests
* mypy fixes for training utilities
* few fixes in util
* fix import
* 🐵 Remove unused `# type: ignore` directives
* 🏷 Annotate `Language._components`
* 🏷 Annotate `spacy.pipeline.Pipe`
* add doc as property to span.pyi
* small fixes and cleanup
* explicit type annotations instead of via comment
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
2021-10-14 13:21:40 +00:00
|
|
|
if loc.parts[-1].endswith(FILE_TYPE): # type: ignore[union-attr]
|
2020-08-07 12:30:59 +00:00
|
|
|
doc_bin = DocBin().from_disk(loc)
|
2020-06-26 17:34:12 +00:00
|
|
|
docs = doc_bin.get_docs(vocab)
|
|
|
|
for doc in docs:
|
|
|
|
if len(doc):
|
|
|
|
yield doc
|
|
|
|
i += 1
|
|
|
|
if self.limit >= 1 and i >= self.limit:
|
|
|
|
break
|
2020-09-13 12:05:05 +00:00
|
|
|
|
|
|
|
|
2020-10-01 23:36:06 +00:00
|
|
|
class JsonlCorpus:
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 Ignore all existing Mypy errors
* 🏗 Add Mypy check to CI
* Add types-mock and types-requests as dev requirements
* Add additional type ignore directives
* Add types packages to dev-only list in reqs test
* Add types-dataclasses for python 3.6
* Add ignore to pretrain
* 🏷 Improve type annotation on `run_command` helper
The `run_command` helper previously declared that it returned an
`Optional[subprocess.CompletedProcess]`, but it isn't actually possible
for the function to return `None`. These changes modify the type
annotation of the `run_command` helper and remove all now-unnecessary
`# type: ignore` directives.
* 🔧 Allow variable type redefinition in limited contexts
These changes modify how Mypy is configured to allow variables to have
their type automatically redefined under certain conditions. The Mypy
documentation contains the following example:
```python
def process(items: List[str]) -> None:
# 'items' has type List[str]
items = [item.split() for item in items]
# 'items' now has type List[List[str]]
...
```
This configuration change is especially helpful in reducing the number
of `# type: ignore` directives needed to handle the common pattern of:
* Accepting a filepath as a string
* Overwriting the variable using `filepath = ensure_path(filepath)`
These changes enable redefinition and remove all `# type: ignore`
directives rendered redundant by this change.
* 🏷 Add type annotation to converters mapping
* 🚨 Fix Mypy error in convert CLI argument verification
* 🏷 Improve type annotation on `resolve_dot_names` helper
* 🏷 Add type annotations for `Vocab` attributes `strings` and `vectors`
* 🏷 Add type annotations for more `Vocab` attributes
* 🏷 Add loose type annotation for gold data compilation
* 🏷 Improve `_format_labels` type annotation
* 🏷 Fix `get_lang_class` type annotation
* 🏷 Loosen return type of `Language.evaluate`
* 🏷 Don't accept `Scorer` in `handle_scores_per_type`
* 🏷 Add `string_to_list` overloads
* 🏷 Fix non-Optional command-line options
* 🙈 Ignore redefinition of `wandb_logger` in `loggers.py`
* ➕ Install `typing_extensions` in Python 3.8+
The `typing_extensions` package states that it should be used when
"writing code that must be compatible with multiple Python versions".
Since SpaCy needs to support multiple Python versions, it should be used
when newer `typing` module members are required. One example of this is
`Literal`, which is available starting with Python 3.8.
Previously SpaCy tried to import `Literal` from `typing`, falling back
to `typing_extensions` if the import failed. However, Mypy doesn't seem
to be able to understand what `Literal` means when the initial import
means. Therefore, these changes modify how `compat` imports `Literal` by
always importing it from `typing_extensions`.
These changes also modify how `typing_extensions` is installed, so that
it is a requirement for all Python versions, including those greater
than or equal to 3.8.
* 🏷 Improve type annotation for `Language.pipe`
These changes add a missing overload variant to the type signature of
`Language.pipe`. Additionally, the type signature is enhanced to allow
type checkers to differentiate between the two overload variants based
on the `as_tuple` parameter.
Fixes #8772
* ➖ Don't install `typing-extensions` in Python 3.8+
After more detailed analysis of how to implement Python version-specific
type annotations using SpaCy, it has been determined that by branching
on a comparison against `sys.version_info` can be statically analyzed by
Mypy well enough to enable us to conditionally use
`typing_extensions.Literal`. This means that we no longer need to
install `typing_extensions` for Python versions greater than or equal to
3.8! 🎉
These changes revert previous changes installing `typing-extensions`
regardless of Python version and modify how we import the `Literal` type
to ensure that Mypy treats it properly.
* resolve mypy errors for Strict pydantic types
* refactor code to avoid missing return statement
* fix types of convert CLI command
* avoid list-set confustion in debug_data
* fix typo and formatting
* small fixes to avoid type ignores
* fix types in profile CLI command and make it more efficient
* type fixes in projects CLI
* put one ignore back
* type fixes for render
* fix render types - the sequel
* fix BaseDefault in language definitions
* fix type of noun_chunks iterator - yields tuple instead of span
* fix types in language-specific modules
* 🏷 Expand accepted inputs of `get_string_id`
`get_string_id` accepts either a string (in which case it returns its
ID) or an ID (in which case it immediately returns the ID). These
changes extend the type annotation of `get_string_id` to indicate that
it can accept either strings or IDs.
* 🏷 Handle override types in `combine_score_weights`
The `combine_score_weights` function allows users to pass an `overrides`
mapping to override data extracted from the `weights` argument. Since it
allows `Optional` dictionary values, the return value may also include
`Optional` dictionary values.
These changes update the type annotations for `combine_score_weights` to
reflect this fact.
* 🏷 Fix tokenizer serialization method signatures in `DummyTokenizer`
* 🏷 Fix redefinition of `wandb_logger`
These changes fix the redefinition of `wandb_logger` by giving a
separate name to each `WandbLogger` version. For
backwards-compatibility, `spacy.train` still exports `wandb_logger_v3`
as `wandb_logger` for now.
* more fixes for typing in language
* type fixes in model definitions
* 🏷 Annotate `_RandomWords.probs` as `NDArray`
* 🏷 Annotate `tok2vec` layers to help Mypy
* 🐛 Fix `_RandomWords.probs` type annotations for Python 3.6
Also remove an import that I forgot to move to the top of the module 😅
* more fixes for matchers and other pipeline components
* quick fix for entity linker
* fixing types for spancat, textcat, etc
* bugfix for tok2vec
* type annotations for scorer
* add runtime_checkable for Protocol
* type and import fixes in tests
* mypy fixes for training utilities
* few fixes in util
* fix import
* 🐵 Remove unused `# type: ignore` directives
* 🏷 Annotate `Language._components`
* 🏷 Annotate `spacy.pipeline.Pipe`
* add doc as property to span.pyi
* small fixes and cleanup
* explicit type annotations instead of via comment
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
2021-10-14 13:21:40 +00:00
|
|
|
"""Iterate Example objects from a file or directory of jsonl
|
2020-09-13 12:05:05 +00:00
|
|
|
formatted raw text files.
|
|
|
|
|
|
|
|
path (Path): The directory or filename to read from.
|
|
|
|
min_length (int): Minimum document length (in tokens). Shorter documents
|
|
|
|
will be skipped. Defaults to 0, which indicates no limit.
|
2020-09-14 22:32:49 +00:00
|
|
|
|
2020-09-13 12:05:05 +00:00
|
|
|
max_length (int): Maximum document length (in tokens). Longer documents will
|
|
|
|
be skipped. Defaults to 0, which indicates no limit.
|
|
|
|
limit (int): Limit corpus to a subset of examples, e.g. for debugging.
|
|
|
|
Defaults to 0, which indicates no limit.
|
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/corpus#jsonlcorpus
|
2020-09-13 12:05:05 +00:00
|
|
|
"""
|
2020-09-14 22:32:49 +00:00
|
|
|
|
2020-09-13 12:05:05 +00:00
|
|
|
file_type = "jsonl"
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
2021-11-08 10:03:47 +00:00
|
|
|
path: Optional[Union[str, Path]],
|
2020-09-13 12:05:05 +00:00
|
|
|
*,
|
|
|
|
limit: int = 0,
|
|
|
|
min_length: int = 0,
|
|
|
|
max_length: int = 0,
|
|
|
|
) -> None:
|
|
|
|
self.path = util.ensure_path(path)
|
|
|
|
self.min_length = min_length
|
|
|
|
self.max_length = max_length
|
|
|
|
self.limit = limit
|
|
|
|
|
|
|
|
def __call__(self, nlp: "Language") -> Iterator[Example]:
|
|
|
|
"""Yield examples from the data.
|
|
|
|
|
|
|
|
nlp (Language): The current nlp object.
|
2020-09-14 22:32:49 +00:00
|
|
|
YIELDS (Example): The example objects.
|
2020-09-13 12:05:05 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/corpus#jsonlcorpus-call
|
2020-09-13 12:05:05 +00:00
|
|
|
"""
|
2020-09-25 13:47:10 +00:00
|
|
|
for loc in walk_corpus(self.path, ".jsonl"):
|
2020-09-13 12:05:05 +00:00
|
|
|
records = srsly.read_jsonl(loc)
|
|
|
|
for record in records:
|
|
|
|
doc = nlp.make_doc(record["text"])
|
|
|
|
if self.min_length >= 1 and len(doc) < self.min_length:
|
|
|
|
continue
|
|
|
|
elif self.max_length >= 1 and len(doc) >= self.max_length:
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
words = [w.text for w in doc]
|
|
|
|
spaces = [bool(w.whitespace_) for w in doc]
|
|
|
|
# We don't *need* an example here, but it seems nice to
|
|
|
|
# make it match the Corpus signature.
|
|
|
|
yield Example(doc, Doc(nlp.vocab, words=words, spaces=spaces))
|
2023-01-26 10:33:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
class PlainTextCorpus:
|
|
|
|
"""Iterate Example objects from a file or directory of plain text
|
|
|
|
UTF-8 files with one line per doc.
|
|
|
|
|
|
|
|
path (Path): The directory or filename to read from.
|
|
|
|
min_length (int): Minimum document length (in tokens). Shorter documents
|
|
|
|
will be skipped. Defaults to 0, which indicates no limit.
|
|
|
|
max_length (int): Maximum document length (in tokens). Longer documents will
|
|
|
|
be skipped. Defaults to 0, which indicates no limit.
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/corpus#plaintextcorpus
|
|
|
|
"""
|
|
|
|
|
|
|
|
file_type = "txt"
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
path: Optional[Union[str, Path]],
|
|
|
|
*,
|
|
|
|
min_length: int = 0,
|
|
|
|
max_length: int = 0,
|
|
|
|
) -> None:
|
|
|
|
self.path = util.ensure_path(path)
|
|
|
|
self.min_length = min_length
|
|
|
|
self.max_length = max_length
|
|
|
|
|
|
|
|
def __call__(self, nlp: "Language") -> Iterator[Example]:
|
|
|
|
"""Yield examples from the data.
|
|
|
|
|
|
|
|
nlp (Language): The current nlp object.
|
|
|
|
YIELDS (Example): The example objects.
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/corpus#plaintextcorpus-call
|
|
|
|
"""
|
|
|
|
for loc in walk_corpus(self.path, ".txt"):
|
|
|
|
with open(loc, encoding="utf-8") as f:
|
|
|
|
for text in f:
|
|
|
|
text = text.rstrip("\r\n")
|
|
|
|
if len(text):
|
|
|
|
doc = nlp.make_doc(text)
|
|
|
|
if self.min_length >= 1 and len(doc) < self.min_length:
|
|
|
|
continue
|
|
|
|
elif self.max_length >= 1 and len(doc) > self.max_length:
|
|
|
|
continue
|
|
|
|
# We don't *need* an example here, but it seems nice to
|
|
|
|
# make it match the Corpus signature.
|
|
|
|
yield Example(doc, doc.copy())
|