-
Notifications
You must be signed in to change notification settings - Fork 42
/
kedro_cli.py
416 lines (338 loc) · 13.6 KB
/
kedro_cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# Copyright 2018-2019 QuantumBlack Visual Analytics Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
# NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS
# BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo
# (either separately or in combination, "QuantumBlack Trademarks") are
# trademarks of QuantumBlack. The License does not grant you any right or
# license to the QuantumBlack Trademarks. You may not use the QuantumBlack
# Trademarks or any confusingly similar mark as a trademark for your product,
# or use the QuantumBlack Trademarks in any other manner that might cause
# confusion in the marketplace, including but not limited to in advertising,
# on websites, or on software.
#
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command line tools for manipulating a Kedro project.
Intended to be invoked via `kedro`."""
from collections import Counter
from glob import iglob
import os
from pathlib import Path
import shutil
import subprocess
import sys
from typing import Iterable, List
import click
from click import secho, style
from kedro.cli import main as kedro_main
from kedro.cli.utils import (
KedroCliError,
call,
export_nodes,
forward_command,
python_call,
)
from kedro.runner import SequentialRunner
from kedro.utils import load_obj
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
# get our package onto the python path
PROJ_PATH = Path(__file__).resolve().parent
sys.path.insert(0, str(PROJ_PATH / "src"))
os.environ["PYTHONPATH"] = (
str(PROJ_PATH / "src") + os.pathsep + os.environ.get("PYTHONPATH", "")
)
os.environ["IPYTHONDIR"] = str(PROJ_PATH / ".ipython")
NO_PYTEST_MESSAGE = """
pytest is not installed. Please make sure pytest is in
src/requirements.txt and run `kedro install`.
"""
NO_NBSTRIPOUT_MESSAGE = """
nbstripout is not installed. Please make sure nbstripout is in
`src/requirements.txt` and run `kedro install`.
"""
TAG_ARG_HELP = """Construct the pipeline using only nodes which have this tag
attached. Option can be used multiple times, what results in a
pipeline constructed from nodes having any of those tags."""
ENV_ARG_HELP = """Run the pipeline in a configured environment. If not specified,
pipeline will run using environment `local`."""
NODE_ARG_HELP = """Run only nodes with specified names."""
FROM_NODES_HELP = """A list of node names which should be used as a starting point."""
TO_NODES_HELP = """A list of node names which should be used as an end point"""
PARALLEL_ARG_HELP = """Run the pipeline using the `ParallelRunner`.
If not specified, use the `SequentialRunner`. This flag cannot be used together
with --runner."""
RUNNER_ARG_HELP = """Specify a runner that you want to run the pipeline with.
This option cannot be used together with --parallel."""
CONVERT_ALL_HELP = """Extract the nodes from all notebooks in the Kedro project directory,
including sub-folders."""
OVERWRITE_HELP = """If Python file already exists for the equivalent notebook,
overwrite its contents."""
@click.group(context_settings=CONTEXT_SETTINGS, name=__file__)
def cli():
"""Command line tools for manipulating a Kedro project."""
@cli.command()
@click.option("--from-nodes", type=str, default="", help=FROM_NODES_HELP)
@click.option("--to-nodes", type=str, default="", help=TO_NODES_HELP)
@click.option(
"--node",
"-n",
"node_names",
type=str,
default=None,
multiple=True,
help=NODE_ARG_HELP,
)
@click.option(
"--runner", "-r", type=str, default=None, multiple=False, help=RUNNER_ARG_HELP
)
@click.option("--parallel", "-p", is_flag=True, multiple=False, help=PARALLEL_ARG_HELP)
@click.option("--env", "-e", type=str, default=None, multiple=False, help=ENV_ARG_HELP)
@click.option("--tag", "-t", type=str, default=None, multiple=True, help=TAG_ARG_HELP)
def run(tag, env, parallel, runner, node_names, to_nodes, from_nodes):
"""Run the pipeline."""
from causallift.run import main
from_nodes = [n for n in from_nodes.split(",") if n]
to_nodes = [n for n in to_nodes.split(",") if n]
if parallel and runner:
raise KedroCliError(
"Both --parallel and --runner options cannot be used together. "
"Please use either --parallel or --runner."
)
if parallel:
runner = "ParallelRunner"
runner_class = load_obj(runner, "kedro.runner") if runner else SequentialRunner
main(
tags=tag,
env=env,
runner=runner_class(),
node_names=node_names,
from_nodes=from_nodes,
to_nodes=to_nodes,
)
@forward_command(cli, forward_help=True)
def test(args):
"""Run the test suite."""
try:
import pytest # pylint: disable=unused-import
except ImportError:
raise KedroCliError(NO_PYTEST_MESSAGE)
else:
python_call("pytest", args)
@cli.command()
def install():
"""Install project dependencies from both requirements.txt and environment.yml (optional)."""
if (Path.cwd() / "src" / "environment.yml").is_file():
call(["conda", "install", "--file", "src/environment.yml", "--yes"])
python_call("pip", ["install", "-U", "-r", "src/requirements.txt"])
@forward_command(cli, forward_help=True)
def ipython(args):
"""Open IPython with project specific variables loaded."""
if "-h" not in args and "--help" not in args:
ipython_message()
call(["ipython"] + list(args))
@cli.command()
def package():
"""Package the project as a Python egg and wheel."""
call([sys.executable, "setup.py", "clean", "--all", "bdist_egg"], cwd="src")
call([sys.executable, "setup.py", "clean", "--all", "bdist_wheel"], cwd="src")
@cli.command("build-docs")
def build_docs():
"""Build the project documentation."""
# python_call("pip", ["install", "src/[docs]"])
# python_call("pip", ["install", "-r", "src/requirements.txt"])
# python_call("ipykernel", ["install", "--user", "--name=causallift"])
if Path("docs/build").exists():
shutil.rmtree("docs/build")
call(["sphinx-apidoc", "--module-first", "-o", "docs/source", "src/causallift"])
call(["sphinx-build", "-M", "html", "docs/source", "docs/build", "-a"])
""" Prepare to publish the Sphinx document on the GitHub Pages """
from distutils.dir_util import copy_tree
copy_tree("docs/build/html", "docs")
def replace(
pattern, # type: str
repl, # type: str
path, # type: str
):
# type: (...) -> None
p = Path(path)
p.write_text(p.read_text().replace(pattern, repl))
replace(
r"<head>",
r"<head>" "\n" r' <base href="{{site.github.url}}" charset="utf-8"/>',
"docs/index.html",
)
Path("docs/.nojekyll").touch()
Path("docs/_config.yml").touch()
@cli.command("build-reqs")
def build_reqs():
"""Build the project dependency requirements."""
requirements_path = Path.cwd() / "src" / "requirements.in"
if not requirements_path.is_file():
secho("No requirements.in found. Copying contents from requirements.txt...")
contents = (Path.cwd() / "src" / "requirements.txt").read_text()
requirements_path.write_text(contents)
python_call("piptools", ["compile", str(requirements_path)])
secho(
(
"Requirements built! Please update requirements.in "
"if you'd like to make a change in your project's dependencies, "
"and re-run build-reqs to generate the new requirements.txt."
)
)
@cli.command("activate-nbstripout")
def activate_nbstripout():
"""Install the nbstripout git hook to automatically clean notebooks."""
secho(
(
"Notebook output cells will be automatically cleared before committing"
" to git."
),
fg="yellow",
)
try:
import nbstripout # pylint: disable=unused-import
except ImportError:
raise KedroCliError(NO_NBSTRIPOUT_MESSAGE)
try:
res = subprocess.run(
["git", "rev-parse", "--git-dir"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if res.returncode:
raise KedroCliError("Not a git repository. Run `git init` first.")
except FileNotFoundError:
raise KedroCliError("Git executable not found. Install Git first.")
call(["nbstripout", "--install"])
def _build_jupyter_command(
base, # type: str
ip, # type: str
all_kernels, # type: bool
args, # type: Iterable[str]
):
# type: (...) -> List[str]
cmd = [base, "--ip=" + ip]
if not all_kernels:
cmd.append("--KernelSpecManager.whitelist=['python3']")
return cmd + list(args)
@cli.group()
def jupyter():
"""Open Jupyter Notebook / Lab with project specific variables loaded, or
convert notebooks into Kedro code.
"""
@forward_command(jupyter, "notebook", forward_help=True)
@click.option("--ip", type=str, default="127.0.0.1")
@click.option("--all-kernels", is_flag=True, default=False)
def jupyter_notebook(ip, all_kernels, args):
"""Open Jupyter Notebook with project specific variables loaded."""
if "-h" not in args and "--help" not in args:
ipython_message(all_kernels)
call(
_build_jupyter_command(
"jupyter-notebook", ip=ip, all_kernels=all_kernels, args=args
)
)
@forward_command(jupyter, "lab", forward_help=True)
@click.option("--ip", type=str, default="127.0.0.1")
@click.option("--all-kernels", is_flag=True, default=False)
def jupyter_lab(ip, all_kernels, args):
"""Open Jupyter Lab with project specific variables loaded."""
if "-h" not in args and "--help" not in args:
ipython_message(all_kernels)
call(
_build_jupyter_command("jupyter-lab", ip=ip, all_kernels=all_kernels, args=args)
)
@jupyter.command("convert")
@click.option("--all", "all_flag", is_flag=True, help=CONVERT_ALL_HELP)
@click.option("-y", "overwrite_flag", is_flag=True, help=OVERWRITE_HELP)
@click.argument(
"filepath",
type=click.Path(exists=True, dir_okay=False, resolve_path=True),
required=False,
nargs=-1,
)
def convert_notebook(all_flag, overwrite_flag, filepath):
"""Convert selected or all notebooks found in a Kedro project
to Kedro code, by exporting code from the appropriately-tagged cells:
Cells tagged as `node` will be copied over to a Python file matching
the name of the notebook, under `src/<package_name>/nodes`.
*Note*: Make sure your notebooks have unique names!
FILEPATH: Path(s) to exact notebook file(s) to be converted. Both
relative and absolute paths are accepted.
Should not be provided if --all flag is already present.
"""
from causallift.run import ProjectContext
if not filepath and not all_flag:
secho(
"Please specify a notebook filepath "
"or add '--all' to convert all notebooks."
)
return
kedro_project_path = ProjectContext(Path.cwd()).project_path
kedro_package_name = "causallift"
if all_flag:
# pathlib glob does not ignore hidden directories,
# whereas Python glob does, which is more useful in
# ensuring checkpoints will not be included
pattern = kedro_project_path / "**" / "*.ipynb"
notebooks = sorted(Path(p) for p in iglob(str(pattern), recursive=True))
else:
notebooks = [Path(f) for f in filepath]
counter = Counter(n.stem for n in notebooks)
non_unique_names = [name for name, counts in counter.items() if counts > 1]
if non_unique_names:
raise KedroCliError(
"Found non-unique notebook names! "
"Please rename the following: {}".format(", ".join(non_unique_names))
)
for notebook in notebooks:
secho("Converting notebook '{}'...".format(str(notebook)))
output_path = (
kedro_project_path
/ "src"
/ kedro_package_name
/ "nodes"
/ "{}.py".format(notebook.stem)
)
if output_path.is_file():
overwrite = overwrite_flag or click.confirm(
"Output file {} already exists. Overwrite?".format(str(output_path)),
default=False,
)
if overwrite:
export_nodes(notebook, output_path)
else:
export_nodes(notebook, output_path)
secho("Done!")
def ipython_message(all_kernels=True):
"""Show a message saying how we have configured the IPython env."""
ipy_vars = ["startup_error", "context"]
secho("-" * 79, fg="cyan")
secho("Starting a Kedro session with the following variables in scope")
secho(", ".join(ipy_vars), fg="green")
secho(
"Use the line magic {} to refresh them".format(
style("%reload_kedro", fg="green")
)
)
secho("or to see the error message if they are undefined")
if not all_kernels:
secho("The choice of kernels is limited to the default one.", fg="yellow")
secho("(restart with --all-kernels to get access to others)", fg="yellow")
secho("-" * 79, fg="cyan")
if __name__ == "__main__":
os.chdir(str(PROJ_PATH))
kedro_main()