Skip to content

Commit aa17eb9

Browse files
committed
Add lazy spaCy CLI loading and static launcher
1 parent 453732d commit aa17eb9

13 files changed

Lines changed: 610 additions & 45 deletions

‎MANIFEST.in‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
recursive-include spacy *.pyi *.pyx *.pxd *.txt *.cfg *.jinja *.toml *.hh
2+
recursive-include spacy_cli *.json
23
include LICENSE
34
include README.md
45
include pyproject.toml

‎setup.cfg‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ install_requires =
6868

6969
[options.entry_points]
7070
console_scripts =
71-
spacy = spacy.cli:setup_cli
71+
spacy = spacy_cli.main:main
7272

7373
[options.extras_require]
7474
lookups =

‎setup.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ def setup_package():
213213
version=about["__version__"],
214214
ext_modules=ext_modules,
215215
cmdclass={"build_ext": build_ext_subclass},
216-
package_data={"": ["*.pyx", "*.pxd", "*.pxi"]},
216+
package_data={"": ["*.pyx", "*.pxd", "*.pxi"], "spacy_cli": ["*.json"]},
217217
)
218218

219219

‎spacy/cli/__init__.py‎

Lines changed: 76 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,82 @@
1+
import sys
2+
from importlib import import_module
3+
from typing import Iterable
4+
5+
from typer.main import get_command
16
from wasabi import msg
27

3-
# Needed for testing
4-
from . import download as download_module # noqa: F401
5-
from ._util import app, setup_cli # noqa: F401
6-
from .apply import apply # noqa: F401
7-
from .assemble import assemble_cli # noqa: F401
8-
9-
# These are the actual functions, NOT the wrapped CLI commands. The CLI commands
10-
# are registered automatically and won't have to be imported here.
11-
from .benchmark_speed import benchmark_speed_cli # noqa: F401
12-
from .convert import convert # noqa: F401
13-
from .debug_config import debug_config # noqa: F401
14-
from .debug_data import debug_data # noqa: F401
15-
from .debug_diff import debug_diff # noqa: F401
16-
from .debug_model import debug_model # noqa: F401
17-
from .download import download # noqa: F401
18-
from .evaluate import evaluate # noqa: F401
19-
from .find_function import find_function # noqa: F401
20-
from .find_threshold import find_threshold # noqa: F401
21-
from .info import info # noqa: F401
22-
from .init_config import fill_config, init_config # noqa: F401
23-
from .init_pipeline import init_pipeline_cli # noqa: F401
24-
from .package import package # noqa: F401
25-
from .pretrain import pretrain # noqa: F401
26-
from .profile import profile # noqa: F401
27-
from .project.assets import project_assets # type: ignore[attr-defined] # noqa: F401
28-
from .project.clone import project_clone # type: ignore[attr-defined] # noqa: F401
29-
from .project.document import ( # type: ignore[attr-defined] # noqa: F401
30-
project_document,
8+
from ..util import registry
9+
from ._dispatch import (
10+
GROUP_MODULES,
11+
PUBLIC_ATTRS,
12+
SUBCOMMAND_MODULES,
13+
TOP_LEVEL_MODULES,
3114
)
32-
from .project.dvc import project_update_dvc # type: ignore[attr-defined] # noqa: F401
33-
from .project.pull import project_pull # type: ignore[attr-defined] # noqa: F401
34-
from .project.push import project_push # type: ignore[attr-defined] # noqa: F401
35-
from .project.run import project_run # type: ignore[attr-defined] # noqa: F401
36-
from .train import train_cli # type: ignore[attr-defined] # noqa: F401
37-
from .validate import validate # type: ignore[attr-defined] # noqa: F401
15+
from ._dispatch import iter_builtin_modules
16+
from ._util import COMMAND, add_project_cli, app
17+
18+
HELP_OPTIONS = {"--help", "-h"}
19+
ROOT_OPTIONS = HELP_OPTIONS | {"--install-completion", "--show-completion"}
20+
21+
__all__ = [
22+
"app",
23+
"load_all_commands",
24+
"load_for_argv",
25+
"setup_cli",
26+
*sorted(PUBLIC_ATTRS),
27+
]
28+
29+
30+
def _import_modules(module_names: Iterable[str]) -> None:
31+
for module_name in module_names:
32+
import_module(module_name)
33+
34+
35+
def load_all_commands() -> None:
36+
_import_modules(iter_builtin_modules())
37+
add_project_cli()
38+
39+
40+
def load_for_argv(argv: Iterable[str]) -> None:
41+
args = list(argv)
42+
if not args or args[0] in ROOT_OPTIONS or args[0].startswith("-"):
43+
load_all_commands()
44+
return
45+
command = args[0]
46+
if command == "project":
47+
add_project_cli()
48+
return
49+
if command in GROUP_MODULES:
50+
subcommand = args[1] if len(args) > 1 and not args[1].startswith("-") else None
51+
if subcommand is not None and (command, subcommand) in SUBCOMMAND_MODULES:
52+
_import_modules(SUBCOMMAND_MODULES[(command, subcommand)])
53+
return
54+
_import_modules(GROUP_MODULES[command])
55+
return
56+
if command in TOP_LEVEL_MODULES:
57+
_import_modules(TOP_LEVEL_MODULES[command])
58+
59+
60+
def setup_cli() -> None:
61+
# Make sure entry-point CLI integrations are imported before command dispatch.
62+
registry.cli.get_all()
63+
load_for_argv(sys.argv[1:])
64+
command = get_command(app)
65+
command(prog_name=COMMAND)
66+
67+
68+
def __getattr__(name: str):
69+
if name not in PUBLIC_ATTRS:
70+
raise AttributeError(f"module 'spacy.cli' has no attribute {name!r}")
71+
module_name, attr_name = PUBLIC_ATTRS[name]
72+
module = import_module(module_name)
73+
value = module if attr_name is None else getattr(module, attr_name)
74+
globals()[name] = value
75+
return value
76+
77+
78+
def __dir__():
79+
return sorted(set(globals()) | set(PUBLIC_ATTRS))
3880

3981

4082
@app.command("link", no_args_is_help=True, deprecated=True, hidden=True)

‎spacy/cli/_dispatch.py‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
from typing import Dict, Iterable, Optional, Tuple
2+
3+
4+
CommandPath = Tuple[str, ...]
5+
6+
7+
TOP_LEVEL_MODULES: Dict[str, Tuple[str, ...]] = {
8+
"apply": ("spacy.cli.apply",),
9+
"assemble": ("spacy.cli.assemble",),
10+
"convert": ("spacy.cli.convert",),
11+
"debug-data": ("spacy.cli.debug_data",),
12+
"download": ("spacy.cli.download",),
13+
"evaluate": ("spacy.cli.evaluate",),
14+
"find-function": ("spacy.cli.find_function",),
15+
"find-threshold": ("spacy.cli.find_threshold",),
16+
"info": ("spacy.cli.info",),
17+
"package": ("spacy.cli.package",),
18+
"pretrain": ("spacy.cli.pretrain",),
19+
"profile": ("spacy.cli.profile",),
20+
"train": ("spacy.cli.train",),
21+
"validate": ("spacy.cli.validate",),
22+
}
23+
24+
25+
GROUP_MODULES: Dict[str, Tuple[str, ...]] = {
26+
"benchmark": (
27+
"spacy.cli.benchmark_speed",
28+
"spacy.cli.evaluate",
29+
),
30+
"debug": (
31+
"spacy.cli.debug_config",
32+
"spacy.cli.debug_data",
33+
"spacy.cli.debug_diff",
34+
"spacy.cli.debug_model",
35+
"spacy.cli.profile",
36+
),
37+
"init": (
38+
"spacy.cli.init_config",
39+
"spacy.cli.init_pipeline",
40+
),
41+
}
42+
43+
44+
SUBCOMMAND_MODULES: Dict[CommandPath, Tuple[str, ...]] = {
45+
("benchmark", "accuracy"): ("spacy.cli.evaluate",),
46+
("benchmark", "speed"): ("spacy.cli.benchmark_speed",),
47+
("debug", "config"): ("spacy.cli.debug_config",),
48+
("debug", "data"): ("spacy.cli.debug_data",),
49+
("debug", "diff-config"): ("spacy.cli.debug_diff",),
50+
("debug", "model"): ("spacy.cli.debug_model",),
51+
("debug", "profile"): ("spacy.cli.profile",),
52+
("init", "config"): ("spacy.cli.init_config",),
53+
("init", "fill-config"): ("spacy.cli.init_config",),
54+
("init", "labels"): ("spacy.cli.init_pipeline",),
55+
("init", "nlp"): ("spacy.cli.init_pipeline",),
56+
("init", "vectors"): ("spacy.cli.init_pipeline",),
57+
}
58+
59+
60+
PUBLIC_ATTRS: Dict[str, Tuple[str, Optional[str]]] = {
61+
"app": ("spacy.cli._util", "app"),
62+
"apply": ("spacy.cli.apply", "apply"),
63+
"assemble_cli": ("spacy.cli.assemble", "assemble_cli"),
64+
"benchmark_speed_cli": ("spacy.cli.benchmark_speed", "benchmark_speed_cli"),
65+
"convert": ("spacy.cli.convert", "convert"),
66+
"debug_config": ("spacy.cli.debug_config", "debug_config"),
67+
"debug_data": ("spacy.cli.debug_data", "debug_data"),
68+
"debug_diff": ("spacy.cli.debug_diff", "debug_diff"),
69+
"debug_model": ("spacy.cli.debug_model", "debug_model"),
70+
"download": ("spacy.cli.download", "download"),
71+
"download_module": ("spacy.cli.download", None),
72+
"evaluate": ("spacy.cli.evaluate", "evaluate"),
73+
"fill_config": ("spacy.cli.init_config", "fill_config"),
74+
"find_function": ("spacy.cli.find_function", "find_function"),
75+
"find_threshold": ("spacy.cli.find_threshold", "find_threshold"),
76+
"info": ("spacy.cli.info", "info"),
77+
"init_config": ("spacy.cli.init_config", "init_config"),
78+
"init_pipeline_cli": ("spacy.cli.init_pipeline", "init_pipeline_cli"),
79+
"package": ("spacy.cli.package", "package"),
80+
"pretrain": ("spacy.cli.pretrain", "pretrain"),
81+
"profile": ("spacy.cli.profile", "profile"),
82+
"project_assets": ("spacy.cli.project.assets", "project_assets"),
83+
"project_clone": ("spacy.cli.project.clone", "project_clone"),
84+
"project_document": ("spacy.cli.project.document", "project_document"),
85+
"project_pull": ("spacy.cli.project.pull", "project_pull"),
86+
"project_push": ("spacy.cli.project.push", "project_push"),
87+
"project_run": ("spacy.cli.project.run", "project_run"),
88+
"project_update_dvc": ("spacy.cli.project.dvc", "project_update_dvc"),
89+
"train_cli": ("spacy.cli.train", "train_cli"),
90+
"validate": ("spacy.cli.validate", "validate"),
91+
}
92+
93+
94+
def iter_builtin_modules() -> Iterable[str]:
95+
seen = set()
96+
for modules in TOP_LEVEL_MODULES.values():
97+
for module in modules:
98+
if module not in seen:
99+
seen.add(module)
100+
yield module
101+
for modules in GROUP_MODULES.values():
102+
for module in modules:
103+
if module not in seen:
104+
seen.add(module)
105+
yield module

‎spacy/cli/_util.py‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,7 @@
2323
from click.shell_completion import split_arg_string
2424
from thinc.api import Config, ConfigValidationError, require_gpu
2525
from thinc.util import gpu_is_available
26-
from typer.main import get_command
2726
from wasabi import Printer, msg
28-
from weasel import app as project_cli
2927

3028
from .. import about
3129
from ..compat import Literal
@@ -72,19 +70,21 @@
7270
benchmark_cli = typer.Typer(name="benchmark", help=BENCHMARK_HELP, no_args_is_help=True)
7371
debug_cli = typer.Typer(name="debug", help=DEBUG_HELP, no_args_is_help=True)
7472
init_cli = typer.Typer(name="init", help=INIT_HELP, no_args_is_help=True)
73+
_PROJECT_CLI_ADDED = False
7574

76-
app.add_typer(project_cli, name="project", help=PROJECT_HELP, no_args_is_help=True)
7775
app.add_typer(debug_cli)
7876
app.add_typer(benchmark_cli)
7977
app.add_typer(init_cli)
8078

8179

82-
def setup_cli() -> None:
83-
# Make sure the entry-point for CLI runs, so that they get imported.
84-
registry.cli.get_all()
85-
# Ensure that the help messages always display the correct prompt
86-
command = get_command(app)
87-
command(prog_name=COMMAND)
80+
def add_project_cli() -> None:
81+
global _PROJECT_CLI_ADDED
82+
if _PROJECT_CLI_ADDED:
83+
return
84+
from weasel import app as project_cli
85+
86+
app.add_typer(project_cli, name="project", help=PROJECT_HELP, no_args_is_help=True)
87+
_PROJECT_CLI_ADDED = True
8888

8989

9090
def parse_config_overrides(

‎spacy/tests/test_cli_app.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,16 @@
66
import srsly
77
from typer.testing import CliRunner
88

9+
from spacy.cli import load_all_commands
910
from spacy.cli._util import app, get_git_version
1011
from spacy.tokens import Doc, DocBin, Span
1112

1213
from .util import make_tempdir, normalize_whitespace
1314

1415

16+
load_all_commands()
17+
18+
1519
def has_git():
1620
try:
1721
get_git_version()

0 commit comments

Comments
 (0)