calkit-python 0.52.2__py3-none-any.whl → 0.52.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. calkit/agent_skills/check-reproducibility/SKILL.md +10 -0
  2. calkit/agent_skills/conventions/SKILL.md +30 -0
  3. calkit/browser_link.py +72 -0
  4. calkit/cli/__init__.py +51 -5
  5. calkit/cli/check.py +35 -4
  6. calkit/cli/latex.py +4 -1
  7. calkit/cli/main/core.py +323 -73
  8. calkit/cli/new.py +27 -5
  9. calkit/cli/notebooks.py +464 -108
  10. calkit/cli/overleaf.py +52 -0
  11. calkit/cli/quarto.py +173 -0
  12. calkit/cli/update.py +198 -51
  13. calkit/conda.py +124 -9
  14. calkit/core.py +293 -84
  15. calkit/detect.py +4 -2
  16. calkit/docx.py +0 -31
  17. calkit/dvc/core.py +61 -0
  18. calkit/environments/core.py +205 -42
  19. calkit/export.py +8 -6
  20. calkit/git.py +80 -0
  21. calkit/hub/link.py +18 -14
  22. calkit/install.py +304 -3
  23. calkit/jupyterlab/routes.py +161 -3
  24. calkit/latex.py +64 -5
  25. calkit/markdown.py +24 -20
  26. calkit/merge.py +75 -0
  27. calkit/models/core.py +161 -97
  28. calkit/models/pipeline.py +438 -28
  29. calkit/models/requirements.py +17 -0
  30. calkit/notebooks.py +1060 -20
  31. calkit/office.py +62 -0
  32. calkit/overleaf.py +9 -6
  33. calkit/pipeline/core.py +60 -5
  34. calkit/pipeline/detect.py +47 -0
  35. calkit/provenance.py +10 -3
  36. calkit/quarto.py +888 -0
  37. calkit/reproducibility.py +39 -5
  38. calkit/tables.py +184 -1
  39. calkit/tests/cli/main/test_core.py +435 -1
  40. calkit/tests/cli/test_check.py +51 -0
  41. calkit/tests/cli/test_export.py +1 -1
  42. calkit/tests/cli/test_notebooks.py +282 -3
  43. calkit/tests/cli/test_overleaf.py +85 -13
  44. calkit/tests/cli/test_quarto.py +133 -0
  45. calkit/tests/cli/test_update.py +119 -7
  46. calkit/tests/environments/test_core.py +149 -0
  47. calkit/tests/hub/test_link.py +5 -5
  48. calkit/tests/jupyterlab/test_routes.py +206 -0
  49. calkit/tests/models/test_pipeline.py +300 -7
  50. calkit/tests/pipeline/test_core.py +65 -2
  51. calkit/tests/pipeline/test_detect.py +51 -1
  52. calkit/tests/test_browser_link.py +56 -4
  53. calkit/tests/test_conda.py +105 -2
  54. calkit/tests/test_core.py +150 -4
  55. calkit/tests/test_git.py +38 -0
  56. calkit/tests/test_install.py +241 -11
  57. calkit/tests/test_latex.py +52 -0
  58. calkit/tests/test_markdown.py +23 -3
  59. calkit/tests/test_notebooks.py +609 -0
  60. calkit/tests/test_office.py +36 -0
  61. calkit/tests/test_provenance.py +36 -4
  62. calkit/tests/test_quarto.py +268 -0
  63. calkit/tests/test_reproducibility.py +18 -1
  64. calkit/tests/test_tables.py +93 -0
  65. calkit/tests/test_workspace.py +6 -0
  66. calkit/workspace.py +6 -3
  67. {calkit_python-0.52.2.data → calkit_python-0.52.3.data}/data/share/jupyter/labextensions/calkit/package.json +1 -1
  68. {calkit_python-0.52.2.data → calkit_python-0.52.3.data}/data/share/jupyter/labextensions/calkit/schemas/calkit/plugin.json +1 -1
  69. calkit_python-0.52.3.data/data/share/jupyter/labextensions/calkit/static/267.7abf4aa5898f1a79.js +156 -0
  70. calkit_python-0.52.2.data/data/share/jupyter/labextensions/calkit/static/899.f9b9f9bf705a6493.js → calkit_python-0.52.3.data/data/share/jupyter/labextensions/calkit/static/899.3ea2c9036ae36dbb.js +40 -20
  71. calkit_python-0.52.2.data/data/share/jupyter/labextensions/calkit/static/remoteEntry.109a3a8379365e59.js → calkit_python-0.52.3.data/data/share/jupyter/labextensions/calkit/static/remoteEntry.1cc2ae755070659d.js +1 -1
  72. {calkit_python-0.52.2.dist-info → calkit_python-0.52.3.dist-info}/METADATA +1 -1
  73. {calkit_python-0.52.2.dist-info → calkit_python-0.52.3.dist-info}/RECORD +84 -79
  74. calkit_python-0.52.2.data/data/share/jupyter/labextensions/calkit/static/506.c34b070098184e33.js +0 -156
  75. {calkit_python-0.52.2.data → calkit_python-0.52.3.data}/data/etc/jupyter/jupyter_server_config.d/calkit.json +0 -0
  76. {calkit_python-0.52.2.data → calkit_python-0.52.3.data}/data/share/jupyter/labextensions/calkit/schemas/calkit/package.json.orig +0 -0
  77. {calkit_python-0.52.2.data → calkit_python-0.52.3.data}/data/share/jupyter/labextensions/calkit/static/57d13a7399cec3c5.png +0 -0
  78. {calkit_python-0.52.2.data → calkit_python-0.52.3.data}/data/share/jupyter/labextensions/calkit/static/616.528427eb54a4a0c0.js +0 -0
  79. {calkit_python-0.52.2.data → calkit_python-0.52.3.data}/data/share/jupyter/labextensions/calkit/static/740.6bf87276e9e5788a.js +0 -0
  80. {calkit_python-0.52.2.data → calkit_python-0.52.3.data}/data/share/jupyter/labextensions/calkit/static/935.46ecc6bf99aa593a.js +0 -0
  81. {calkit_python-0.52.2.data → calkit_python-0.52.3.data}/data/share/jupyter/labextensions/calkit/static/style.js +0 -0
  82. {calkit_python-0.52.2.data → calkit_python-0.52.3.data}/data/share/jupyter/labextensions/calkit/static/third-party-licenses.json +0 -0
  83. {calkit_python-0.52.2.dist-info → calkit_python-0.52.3.dist-info}/WHEEL +0 -0
  84. {calkit_python-0.52.2.dist-info → calkit_python-0.52.3.dist-info}/entry_points.txt +0 -0
  85. {calkit_python-0.52.2.dist-info → calkit_python-0.52.3.dist-info}/licenses/LICENSE +0 -0
@@ -101,6 +101,16 @@ Judgment, done here:
101
101
  number, or edit a generated file by hand: either one is a typed value
102
102
  with extra steps.
103
103
 
104
+ <!-- TODO: needs human review -->
105
+
106
+ If a pipeline notebook computes the number, e.g., a cell prints it,
107
+ save the variable as a cell output instead of changing the notebook:
108
+ `calkit nb add-output <notebook> value --cell-id <id> --variable-name <name>`.
109
+ Then cite it as `\ckvalue{<notebook>}{<name>}`.
110
+ Use the cell that printed it, not the last one,
111
+ since the value is saved right after that cell runs.
112
+ See the conventions skill's section on notebook cells.
113
+
104
114
  5. **Run the pipeline** (`calkit run`) and check again. Do not run the
105
115
  script yourself and paste the number in: that is the failure this whole
106
116
  check exists to catch.
@@ -148,6 +148,36 @@ The error falls to \ckvalue[.2f]{results/metrics.json}{rmse}.
148
148
  The stage depends on everything included this way, so don't add
149
149
  `json-to-latex` or `map-paths` stages, or list those files in `inputs`.
150
150
 
151
+ <!-- TODO: needs human review -->
152
+
153
+ ### Values, figures, and tables from notebook cells
154
+
155
+ A `jupyter-notebook` stage can save values, figures, and tables from its
156
+ cells, so the notebook doesn't need to write files.
157
+ Offer this to anyone who'd rather not add `json.dump` or `savefig` calls.
158
+ Add them with `calkit nb add-output`, which stores them under the stage's
159
+ `cell_outputs` by cell ID.
160
+ Read IDs from the `.ipynb`, or use `--cell-index`, which adds IDs if the
161
+ notebook has none.
162
+
163
+ ```sh
164
+ calkit nb add-output analysis.ipynb value --cell-id 3f9a1c2e --variable-name k_25 --variable-name k_35
165
+ calkit nb add-output analysis.ipynb figure --cell-id 8b77d0aa --variable-name fig --output-path figures/fit.pdf
166
+ calkit nb add-output analysis.ipynb table --cell-id 1d2e4c0b --variable-name df --output-path tables/rates.tex
167
+ calkit nb outputs analysis.ipynb --json
168
+ ```
169
+
170
+ Cite a value with the notebook's path, e.g.,
171
+ `\ckvalue[.3f]{analysis.ipynb}{k_25}`, or `{rates.25C}` for a key in a
172
+ dict.
173
+ Cite figures and tables by their paths.
174
+ Each output is saved right after its cell runs,
175
+ so if a later cell changes the variable, the saved one doesn't change.
176
+ Outputs are only saved when the pipeline runs the notebook,
177
+ so run `calkit run` after adding them.
178
+ `calkit nb remove-output` stops saving one.
179
+ Don't also list a saved figure or table in the stage's `outputs`.
180
+
151
181
  ### Outputs: Git vs. DVC storage
152
182
 
153
183
  By default, outputs are stored with DVC (large file storage). Use
calkit/browser_link.py CHANGED
@@ -100,6 +100,7 @@ CONCURRENT_REQUEST_TYPES = (
100
100
  "publication.synctex",
101
101
  "publication.source",
102
102
  "project.originSuggestions",
103
+ "project.printedNumbers",
103
104
  "folder.choose",
104
105
  "job.get",
105
106
  "job.log",
@@ -412,6 +413,32 @@ def get_result(msg: dict) -> Any:
412
413
  result = get_origin_suggestions(
413
414
  path, get_content_paths(paths[0]), wdir=paths[0]
414
415
  )
416
+ elif kind == "project.printedNumbers":
417
+ owner, name = split_project(msg.get("project"))
418
+ paths = get_checkout_paths(owner, name)
419
+ if not paths:
420
+ raise ValueError(f"{owner}/{name} isn't on this machine")
421
+ result = get_printed_numbers(paths[0])
422
+ elif kind == "project.addCellOutput":
423
+ from calkit.notebooks import add_cell_outputs
424
+
425
+ owner, name = split_project(msg.get("project"))
426
+ paths = get_checkout_paths(owner, name)
427
+ if not paths:
428
+ raise ValueError(f"{owner}/{name} isn't on this machine")
429
+ notebook = get_project_path(paths[0], msg.get("notebook"), "notebook")
430
+ result = add_cell_outputs(
431
+ notebook,
432
+ [
433
+ {
434
+ "kind": "value",
435
+ "cell_id": msg.get("cell_id"),
436
+ "variable_name": msg.get("variable_name"),
437
+ }
438
+ ],
439
+ stage=msg.get("stage"),
440
+ wdir=paths[0],
441
+ )
415
442
  elif kind in ("publication.pdf", "publication.synctex"):
416
443
  owner, name = split_project(msg.get("project"))
417
444
  paths = get_checkout_paths(owner, name)
@@ -1790,6 +1817,51 @@ def get_stage_status(stale: list, has_run: bool) -> dict:
1790
1817
  }
1791
1818
 
1792
1819
 
1820
+ def get_printed_numbers(wdir: str) -> list[dict]:
1821
+ """Numbers the pipeline's notebooks printed, by notebook and cell, from
1822
+ their saved outputs, or the copy the pipeline ran if they're saved
1823
+ without, which a number typed into a document may have been copied from.
1824
+ """
1825
+ import calkit.notebooks
1826
+
1827
+ ck_info = calkit.load_calkit_info(wdir=wdir, read_only=True)
1828
+ stages = (ck_info.get("pipeline") or {}).get("stages") or {}
1829
+ found = []
1830
+ for name, stage in stages.items():
1831
+ # A parameterized notebook's values are cited by file, not notebook
1832
+ if (
1833
+ not isinstance(stage, dict)
1834
+ or stage.get("kind") != "jupyter-notebook"
1835
+ or stage.get("parameters")
1836
+ or not isinstance(stage.get("notebook_path"), str)
1837
+ ):
1838
+ continue
1839
+ notebook = calkit.notebooks.get_stage_notebook_path(stage)
1840
+ executed = calkit.notebooks.get_executed_notebook_path(
1841
+ stage["notebook_path"], "notebook"
1842
+ )
1843
+ for path in (
1844
+ notebook,
1845
+ os.path.join(stage.get("wdir") or "", executed),
1846
+ ):
1847
+ fpath = os.path.join(wdir, path)
1848
+ try:
1849
+ if os.path.getsize(fpath) > MAX_VALUE_FILE_BYTES * 5:
1850
+ continue
1851
+ with open(fpath, encoding="utf-8") as f:
1852
+ printed = calkit.notebooks.find_printed_numbers(
1853
+ json.load(f)
1854
+ )
1855
+ except (OSError, ValueError):
1856
+ continue
1857
+ if printed:
1858
+ found += [
1859
+ {"notebook": notebook, "stage": name} | p for p in printed
1860
+ ]
1861
+ break
1862
+ return found
1863
+
1864
+
1793
1865
  def get_content_paths(wdir: str) -> list[str]:
1794
1866
  """Every file in a checkout someone might pick, as the hub lists a
1795
1867
  project's: what Git tracks, and what the pipeline makes with DVC, by its
calkit/cli/__init__.py CHANGED
@@ -24,6 +24,17 @@ def run() -> None:
24
24
 
25
25
  from calkit.core import is_mintty
26
26
 
27
+ # pythonw, e.g., the hub link started at login, has no streams, so
28
+ # they go nowhere until something takes their fds, e.g., a log
29
+ for fd, name in ((1, "stdout"), (2, "stderr")):
30
+ if getattr(sys, name) is None:
31
+ devnull = os.open(os.devnull, os.O_WRONLY | os.O_BINARY)
32
+ os.dup2(devnull, fd)
33
+ os.close(devnull)
34
+ stream = open(
35
+ fd, "w", encoding="utf-8", buffering=1, closefd=False
36
+ )
37
+ setattr(sys, name, stream)
27
38
  # mintty shows UTF-8, so emoji needn't be replaced, and output is
28
39
  # line buffered as it would be to a terminal
29
40
  for stream in (sys.stdout, sys.stderr):
@@ -31,11 +42,46 @@ def run() -> None:
31
42
  stream.reconfigure(encoding="utf-8", line_buffering=True)
32
43
  from .main import app
33
44
 
34
- # Completion lists commands, so needs them all
35
- if any(k.startswith("_") and k.endswith("_COMPLETE") for k in os.environ):
36
- app()
37
- else:
38
- _only_invoked(app, sys.argv[1:])()
45
+ try:
46
+ # Completion lists commands, so needs them all
47
+ if any(
48
+ k.startswith("_") and k.endswith("_COMPLETE") for k in os.environ
49
+ ):
50
+ app()
51
+ else:
52
+ _only_invoked(app, sys.argv[1:])()
53
+ except ImportError as e:
54
+ # GitPython can't be imported without Git, which a new machine,
55
+ # e.g., on Windows, may not have
56
+ if "git executable" not in str(e):
57
+ raise
58
+ import subprocess
59
+
60
+ from calkit import install
61
+ from calkit.core import get_calkit_cmd, is_tty
62
+
63
+ # Where Git runs, installing it won't help, e.g., since
64
+ # GIT_PYTHON_GIT_EXECUTABLE points elsewhere
65
+ if install.can_run_git():
66
+ raise
67
+ print("Git not found", file=sys.stderr)
68
+ unsupported = install.get_unsupported_message("git")
69
+ if unsupported:
70
+ print(unsupported, file=sys.stderr)
71
+ sys.exit(1)
72
+ if not install.prompt_and_install("git", interactive=is_tty()):
73
+ sys.exit(1)
74
+ # Where it's installed but still doesn't run, running again would
75
+ # just offer it again
76
+ if not install.can_run_git():
77
+ print(
78
+ "Git installed but doesn't run; restart your shell and "
79
+ "run again",
80
+ file=sys.stderr,
81
+ )
82
+ sys.exit(1)
83
+ # The command stopped partway, so run it again from the start
84
+ sys.exit(subprocess.call([*get_calkit_cmd(), *sys.argv[1:]]))
39
85
 
40
86
 
41
87
  def _only_invoked(
calkit/cli/check.py CHANGED
@@ -566,6 +566,7 @@ def check_environment(
566
566
  alt_lock_fpaths=alt_lock_fpaths,
567
567
  relaxed=True, # TODO: Add option?
568
568
  quiet=not verbose,
569
+ prefix=env.get("prefix"),
569
570
  )
570
571
  elif env["kind"] == "pixi":
571
572
  cmd = ["pixi", "install"]
@@ -587,6 +588,12 @@ def check_environment(
587
588
  env_dir = os.path.dirname(env["path"])
588
589
  if env_dir:
589
590
  cmd += ["--directory", env_dir]
591
+ try:
592
+ extras = calkit.environments.get_uv_extras(env)
593
+ except ValueError as e:
594
+ raise_error(str(e))
595
+ for extra in extras:
596
+ cmd += ["--extra", extra]
590
597
  if verbose:
591
598
  typer.echo(f"Running command: {cmd}")
592
599
  try:
@@ -1327,6 +1334,13 @@ def check_conda_env(
1327
1334
  quiet: Annotated[
1328
1335
  bool, typer.Option("--quiet", "-q", help="Be quiet.")
1329
1336
  ] = False,
1337
+ prefix: Annotated[
1338
+ str | None,
1339
+ typer.Option(
1340
+ "--prefix",
1341
+ help="Where the environment is kept, overriding the spec's.",
1342
+ ),
1343
+ ] = None,
1330
1344
  ) -> None:
1331
1345
  log_func: Callable[..., None]
1332
1346
  if quiet:
@@ -1342,6 +1356,7 @@ def check_conda_env(
1342
1356
  log_func=log_func,
1343
1357
  relaxed=relaxed,
1344
1358
  verbose=not quiet,
1359
+ prefix=prefix,
1345
1360
  )
1346
1361
  except Exception as e:
1347
1362
  warn_app_control(output=str(e), maybe=True)
@@ -1553,13 +1568,21 @@ def check_venv(
1553
1568
  return
1554
1569
  # Local packages are installed from the spec, since their paths
1555
1570
  # differ between machines
1556
- with open(lock_fpath_full, encoding="utf-8") as f:
1557
- frozen = f.read()
1571
+ # Read as written, since pip writes it through the shell, e.g., with
1572
+ # CRLF on Windows, whatever Git checks it out with
1573
+ with open(lock_fpath_full, encoding="utf-8", newline="") as f:
1574
+ written = f.read()
1575
+ frozen = written.replace("\r\n", "\n")
1558
1576
  lock = "".join(
1559
1577
  ln for ln in frozen.splitlines(keepends=True) if not is_local(ln)
1560
1578
  )
1561
- if lock != frozen:
1562
- with open(lock_fpath_full, "w", encoding="utf-8") as f:
1579
+ newline = calkit.git.get_checkout_newline(lock_fpath_full)
1580
+ if lock != frozen or (
1581
+ newline is not None and lock.replace("\n", newline) != written
1582
+ ):
1583
+ with open(
1584
+ lock_fpath_full, "w", encoding="utf-8", newline=newline
1585
+ ) as f:
1563
1586
  f.write(lock)
1564
1587
  lock_changed = lock != lock_before
1565
1588
  # All platforms are relocked together, so they agree; an existing
@@ -1999,11 +2022,19 @@ def check_stage_runs() -> None:
1999
2022
  problems = []
2000
2023
  for lock_dir in lock_dirs:
2001
2024
  lock_stages = calkit.dvc.read_lock_stages(lock_dir)
2025
+ # DVC writes a frozen stage's entry whenever it verifies the stage's
2026
+ # outputs rather than running it, so there's no run to match
2027
+ try:
2028
+ frozen = calkit.pipeline.frozen_stage_base_names(wdir=lock_dir)
2029
+ except Exception:
2030
+ frozen = set()
2002
2031
  for lock_name, locked in sorted(lock_stages.items()):
2003
2032
  if not isinstance(locked, dict) or lock_name in removed.get(
2004
2033
  lock_dir, set()
2005
2034
  ):
2006
2035
  continue
2036
+ if lock_name.split("@")[0] in frozen:
2037
+ continue
2007
2038
  name = (
2008
2039
  lock_name
2009
2040
  if lock_dir is None
calkit/cli/latex.py CHANGED
@@ -2395,6 +2395,7 @@ def to_docx(
2395
2395
 
2396
2396
  import calkit.docx
2397
2397
  import calkit.git
2398
+ import calkit.office
2398
2399
  import calkit.pipeline
2399
2400
  from calkit.models.docx import LatexDocxExport
2400
2401
  from calkit.models.pipeline import LatexStage
@@ -2832,7 +2833,9 @@ def to_docx(
2832
2833
  if os.path.exists(output) and not force:
2833
2834
  raise_error(f"{output} already exists; use --force to overwrite it")
2834
2835
  if engine is None:
2835
- engine = "word" if calkit.docx.word_installed() else "libreoffice"
2836
+ engine = (
2837
+ "word" if calkit.office.app_installed("word") else "libreoffice"
2838
+ )
2836
2839
  # Converted beside the output, then read in and removed, so a failed
2837
2840
  # export doesn't leave the bare conversion where the export goes
2838
2841
  bare = Path(output).with_suffix(".bare.docx").as_posix()