mirror of
https://github.com/explosion/spaCy.git
synced 2024-12-26 18:06:29 +03:00
657af5f91f
* 🚨 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>
205 lines
8.5 KiB
Python
205 lines
8.5 KiB
Python
"""This module contains helpers and subcommands for integrating spaCy projects
|
|
with Data Version Controk (DVC). https://dvc.org"""
|
|
from typing import Dict, Any, List, Optional, Iterable
|
|
import subprocess
|
|
from pathlib import Path
|
|
from wasabi import msg
|
|
|
|
from .._util import PROJECT_FILE, load_project_config, get_hash, project_cli
|
|
from .._util import Arg, Opt, NAME, COMMAND
|
|
from ...util import working_dir, split_command, join_command, run_command
|
|
from ...util import SimpleFrozenList
|
|
|
|
|
|
DVC_CONFIG = "dvc.yaml"
|
|
DVC_DIR = ".dvc"
|
|
UPDATE_COMMAND = "dvc"
|
|
DVC_CONFIG_COMMENT = f"""# This file is auto-generated by spaCy based on your {PROJECT_FILE}. If you've
|
|
# edited your {PROJECT_FILE}, you can regenerate this file by running:
|
|
# {COMMAND} project {UPDATE_COMMAND}"""
|
|
|
|
|
|
@project_cli.command(UPDATE_COMMAND)
|
|
def project_update_dvc_cli(
|
|
# fmt: off
|
|
project_dir: Path = Arg(Path.cwd(), help="Location of project directory. Defaults to current working directory.", exists=True, file_okay=False),
|
|
workflow: Optional[str] = Arg(None, help=f"Name of workflow defined in {PROJECT_FILE}. Defaults to first workflow if not set."),
|
|
verbose: bool = Opt(False, "--verbose", "-V", help="Print more info"),
|
|
force: bool = Opt(False, "--force", "-F", help="Force update DVC config"),
|
|
# fmt: on
|
|
):
|
|
"""Auto-generate Data Version Control (DVC) config. A DVC
|
|
project can only define one pipeline, so you need to specify one workflow
|
|
defined in the project.yml. If no workflow is specified, the first defined
|
|
workflow is used. The DVC config will only be updated if the project.yml
|
|
changed.
|
|
|
|
DOCS: https://spacy.io/api/cli#project-dvc
|
|
"""
|
|
project_update_dvc(project_dir, workflow, verbose=verbose, force=force)
|
|
|
|
|
|
def project_update_dvc(
|
|
project_dir: Path,
|
|
workflow: Optional[str] = None,
|
|
*,
|
|
verbose: bool = False,
|
|
force: bool = False,
|
|
) -> None:
|
|
"""Update the auto-generated Data Version Control (DVC) config file. A DVC
|
|
project can only define one pipeline, so you need to specify one workflow
|
|
defined in the project.yml. Will only update the file if the checksum changed.
|
|
|
|
project_dir (Path): The project directory.
|
|
workflow (Optional[str]): Optional name of workflow defined in project.yml.
|
|
If not set, the first workflow will be used.
|
|
verbose (bool): Print more info.
|
|
force (bool): Force update DVC config.
|
|
"""
|
|
config = load_project_config(project_dir)
|
|
updated = update_dvc_config(
|
|
project_dir, config, workflow, verbose=verbose, force=force
|
|
)
|
|
help_msg = "To execute the workflow with DVC, run: dvc repro"
|
|
if updated:
|
|
msg.good(f"Updated DVC config from {PROJECT_FILE}", help_msg)
|
|
else:
|
|
msg.info(f"No changes found in {PROJECT_FILE}, no update needed", help_msg)
|
|
|
|
|
|
def update_dvc_config(
|
|
path: Path,
|
|
config: Dict[str, Any],
|
|
workflow: Optional[str] = None,
|
|
verbose: bool = False,
|
|
silent: bool = False,
|
|
force: bool = False,
|
|
) -> bool:
|
|
"""Re-run the DVC commands in dry mode and update dvc.yaml file in the
|
|
project directory. The file is auto-generated based on the config. The
|
|
first line of the auto-generated file specifies the hash of the config
|
|
dict, so if any of the config values change, the DVC config is regenerated.
|
|
|
|
path (Path): The path to the project directory.
|
|
config (Dict[str, Any]): The loaded project.yml.
|
|
verbose (bool): Whether to print additional info (via DVC).
|
|
silent (bool): Don't output anything (via DVC).
|
|
force (bool): Force update, even if hashes match.
|
|
RETURNS (bool): Whether the DVC config file was updated.
|
|
"""
|
|
ensure_dvc(path)
|
|
workflows = config.get("workflows", {})
|
|
workflow_names = list(workflows.keys())
|
|
check_workflows(workflow_names, workflow)
|
|
if not workflow:
|
|
workflow = workflow_names[0]
|
|
config_hash = get_hash(config)
|
|
path = path.resolve()
|
|
dvc_config_path = path / DVC_CONFIG
|
|
if dvc_config_path.exists():
|
|
# Check if the file was generated using the current config, if not, redo
|
|
with dvc_config_path.open("r", encoding="utf8") as f:
|
|
ref_hash = f.readline().strip().replace("# ", "")
|
|
if ref_hash == config_hash and not force:
|
|
return False # Nothing has changed in project.yml, don't need to update
|
|
dvc_config_path.unlink()
|
|
dvc_commands = []
|
|
config_commands = {cmd["name"]: cmd for cmd in config.get("commands", [])}
|
|
for name in workflows[workflow]:
|
|
command = config_commands[name]
|
|
deps = command.get("deps", [])
|
|
outputs = command.get("outputs", [])
|
|
outputs_no_cache = command.get("outputs_no_cache", [])
|
|
if not deps and not outputs and not outputs_no_cache:
|
|
continue
|
|
# Default to the working dir as the project path since dvc.yaml is auto-generated
|
|
# and we don't want arbitrary paths in there
|
|
project_cmd = ["python", "-m", NAME, "project", "run", name]
|
|
deps_cmd = [c for cl in [["-d", p] for p in deps] for c in cl]
|
|
outputs_cmd = [c for cl in [["-o", p] for p in outputs] for c in cl]
|
|
outputs_nc_cmd = [c for cl in [["-O", p] for p in outputs_no_cache] for c in cl]
|
|
dvc_cmd = ["run", "-n", name, "-w", str(path), "--no-exec"]
|
|
if command.get("no_skip"):
|
|
dvc_cmd.append("--always-changed")
|
|
full_cmd = [*dvc_cmd, *deps_cmd, *outputs_cmd, *outputs_nc_cmd, *project_cmd]
|
|
dvc_commands.append(join_command(full_cmd))
|
|
with working_dir(path):
|
|
dvc_flags = {"--verbose": verbose, "--quiet": silent}
|
|
run_dvc_commands(dvc_commands, flags=dvc_flags)
|
|
with dvc_config_path.open("r+", encoding="utf8") as f:
|
|
content = f.read()
|
|
f.seek(0, 0)
|
|
f.write(f"# {config_hash}\n{DVC_CONFIG_COMMENT}\n{content}")
|
|
return True
|
|
|
|
|
|
def run_dvc_commands(
|
|
commands: Iterable[str] = SimpleFrozenList(), flags: Dict[str, bool] = {}
|
|
) -> None:
|
|
"""Run a sequence of DVC commands in a subprocess, in order.
|
|
|
|
commands (List[str]): The string commands without the leading "dvc".
|
|
flags (Dict[str, bool]): Conditional flags to be added to command. Makes it
|
|
easier to pass flags like --quiet that depend on a variable or
|
|
command-line setting while avoiding lots of nested conditionals.
|
|
"""
|
|
for c in commands:
|
|
command = split_command(c)
|
|
dvc_command = ["dvc", *command]
|
|
# Add the flags if they are set to True
|
|
for flag, is_active in flags.items():
|
|
if is_active:
|
|
dvc_command.append(flag)
|
|
run_command(dvc_command)
|
|
|
|
|
|
def check_workflows(workflows: List[str], workflow: Optional[str] = None) -> None:
|
|
"""Validate workflows provided in project.yml and check that a given
|
|
workflow can be used to generate a DVC config.
|
|
|
|
workflows (List[str]): Names of the available workflows.
|
|
workflow (Optional[str]): The name of the workflow to convert.
|
|
"""
|
|
if not workflows:
|
|
msg.fail(
|
|
f"No workflows defined in {PROJECT_FILE}. To generate a DVC config, "
|
|
f"define at least one list of commands.",
|
|
exits=1,
|
|
)
|
|
if workflow is not None and workflow not in workflows:
|
|
msg.fail(
|
|
f"Workflow '{workflow}' not defined in {PROJECT_FILE}. "
|
|
f"Available workflows: {', '.join(workflows)}",
|
|
exits=1,
|
|
)
|
|
if not workflow:
|
|
msg.warn(
|
|
f"No workflow specified for DVC pipeline. Using the first workflow "
|
|
f"defined in {PROJECT_FILE}: '{workflows[0]}'"
|
|
)
|
|
|
|
|
|
def ensure_dvc(project_dir: Path) -> None:
|
|
"""Ensure that the "dvc" command is available and that the current project
|
|
directory is an initialized DVC project.
|
|
"""
|
|
try:
|
|
subprocess.run(["dvc", "--version"], stdout=subprocess.DEVNULL)
|
|
except Exception:
|
|
msg.fail(
|
|
"To use spaCy projects with DVC (Data Version Control), DVC needs "
|
|
"to be installed and the 'dvc' command needs to be available",
|
|
"You can install the Python package from pip (pip install dvc) or "
|
|
"conda (conda install -c conda-forge dvc). For more details, see the "
|
|
"documentation: https://dvc.org/doc/install",
|
|
exits=1,
|
|
)
|
|
if not (project_dir / ".dvc").exists():
|
|
msg.fail(
|
|
"Project not initialized as a DVC project",
|
|
"To initialize a DVC project, you can run 'dvc init' in the project "
|
|
"directory. For more details, see the documentation: "
|
|
"https://dvc.org/doc/command-reference/init",
|
|
exits=1,
|
|
)
|