torchstack64 0.3.0__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.
- torchstack64/__init__.py +101 -0
- torchstack64/artifacts/__init__.py +78 -0
- torchstack64/artifacts/bundle/__init__.py +50 -0
- torchstack64/artifacts/bundle/files.py +106 -0
- torchstack64/artifacts/bundle/folder.py +385 -0
- torchstack64/artifacts/bundle/tensors.py +75 -0
- torchstack64/artifacts/code/__init__.py +103 -0
- torchstack64/artifacts/code/copy.py +149 -0
- torchstack64/artifacts/code/importing.py +204 -0
- torchstack64/artifacts/code/inspection.py +351 -0
- torchstack64/artifacts/code/notebook.py +373 -0
- torchstack64/artifacts/code/objects.py +401 -0
- torchstack64/artifacts/loading.py +117 -0
- torchstack64/artifacts/manifest.py +220 -0
- torchstack64/artifacts/predictor/__init__.py +45 -0
- torchstack64/artifacts/predictor/bundle_predictor.py +193 -0
- torchstack64/artifacts/predictor/output_reading.py +96 -0
- torchstack64/artifacts/predictor/torch_classifier.py +106 -0
- torchstack64/artifacts/predictor/torch_predictor.py +247 -0
- torchstack64/artifacts/proofs/__init__.py +83 -0
- torchstack64/artifacts/proofs/answers.py +159 -0
- torchstack64/artifacts/proofs/example.py +248 -0
- torchstack64/artifacts/proofs/modules.py +260 -0
- torchstack64/artifacts/proofs/suite.py +560 -0
- torchstack64/artifacts/saving.py +461 -0
- torchstack64/artifacts/sources.py +166 -0
- torchstack64/callbacks/__init__.py +22 -0
- torchstack64/callbacks/base.py +43 -0
- torchstack64/callbacks/checkpointing.py +40 -0
- torchstack64/callbacks/history_plot.py +160 -0
- torchstack64/callbacks/mlflow_logger.py +217 -0
- torchstack64/callbacks/model_checks.py +295 -0
- torchstack64/callbacks/progress.py +132 -0
- torchstack64/callbacks/stack.py +85 -0
- torchstack64/core/__init__.py +59 -0
- torchstack64/core/errors.py +121 -0
- torchstack64/core/evaluation.py +52 -0
- torchstack64/core/extras.py +36 -0
- torchstack64/core/inference.py +42 -0
- torchstack64/core/labels.py +201 -0
- torchstack64/core/logging.py +110 -0
- torchstack64/data/__init__.py +10 -0
- torchstack64/data/base.py +256 -0
- torchstack64/data/labeled.py +128 -0
- torchstack64/devices/__init__.py +38 -0
- torchstack64/devices/hardware.py +43 -0
- torchstack64/devices/selection.py +82 -0
- torchstack64/metrics/__init__.py +21 -0
- torchstack64/metrics/classification.py +93 -0
- torchstack64/py.typed +0 -0
- torchstack64/training/__init__.py +83 -0
- torchstack64/training/config/__init__.py +17 -0
- torchstack64/training/config/fit.py +60 -0
- torchstack64/training/config/monitor.py +63 -0
- torchstack64/training/config/optim.py +49 -0
- torchstack64/training/config/params.py +55 -0
- torchstack64/training/config/search.py +49 -0
- torchstack64/training/results/__init__.py +19 -0
- torchstack64/training/results/fit.py +37 -0
- torchstack64/training/results/history.py +74 -0
- torchstack64/training/results/predictions.py +81 -0
- torchstack64/training/runtime/__init__.py +18 -0
- torchstack64/training/runtime/precision.py +139 -0
- torchstack64/training/runtime/randomness.py +142 -0
- torchstack64/training/runtime/runtime.py +75 -0
- torchstack64/training/runtime/transfer.py +49 -0
- torchstack64/training/runtime/weights.py +43 -0
- torchstack64/training/task/__init__.py +11 -0
- torchstack64/training/task/optim/__init__.py +9 -0
- torchstack64/training/task/optim/optimization.py +70 -0
- torchstack64/training/task/optim/schedules.py +27 -0
- torchstack64/training/task/protocol.py +58 -0
- torchstack64/training/task/supervised.py +113 -0
- torchstack64/training/trainer/__init__.py +8 -0
- torchstack64/training/trainer/adapters.py +122 -0
- torchstack64/training/trainer/contracts.py +81 -0
- torchstack64/training/trainer/hooks.py +47 -0
- torchstack64/training/trainer/meters.py +150 -0
- torchstack64/training/trainer/state.py +117 -0
- torchstack64/training/trainer/trainer.py +586 -0
- torchstack64/training/tuner/__init__.py +3 -0
- torchstack64/training/tuner/callback.py +38 -0
- torchstack64/training/tuner/space.py +82 -0
- torchstack64/training/tuner/tuner.py +137 -0
- torchstack64/utils/__init__.py +21 -0
- torchstack64/utils/logging.py +85 -0
- torchstack64/utils/mlflow.py +127 -0
- torchstack64-0.3.0.dist-info/METADATA +622 -0
- torchstack64-0.3.0.dist-info/RECORD +92 -0
- torchstack64-0.3.0.dist-info/WHEEL +5 -0
- torchstack64-0.3.0.dist-info/licenses/LICENSE +21 -0
- torchstack64-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Writing the project's own code into a bundle: what is copied, under which name, and what is refused.
|
|
2
|
+
|
|
3
|
+
Nothing here imports the code it copies: importing would run it in the training process, which is the
|
|
4
|
+
one process where a missing module would still be found and prove nothing.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import ast
|
|
10
|
+
import shutil
|
|
11
|
+
import sys
|
|
12
|
+
from collections.abc import Mapping, Sequence
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from torchstack64.artifacts.manifest import split_predictor_path
|
|
17
|
+
from torchstack64.core import BundleError
|
|
18
|
+
|
|
19
|
+
CODE_ROOT = "code"
|
|
20
|
+
BYTECODE_FOLDER = "__pycache__"
|
|
21
|
+
LIBRARY = "torchstack64" # a predictor of the library itself is imported from the installed library
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def skipped(name: str) -> bool:
|
|
25
|
+
"""What the copy leaves out: bytecode, which Python writes again on import, and hidden files (tool
|
|
26
|
+
caches, a notebook's checkpoints, a `.env` that must not travel to wherever the bundle goes)."""
|
|
27
|
+
return name == BYTECODE_FOLDER or name.startswith(".") or name.endswith((".pyc", ".pyo"))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True, init=False)
|
|
31
|
+
class BundleCode:
|
|
32
|
+
"""The project's own code to put in a bundle.
|
|
33
|
+
|
|
34
|
+
Each path is a package (a folder) or a module (a `.py` file), copied under `code/` with its own name:
|
|
35
|
+
`BundleCode("src/my_project")` is imported back as `my_project`. `modules` adds modules written from
|
|
36
|
+
text, by name: the one a save writes from the notebook cells that define a class or a function.
|
|
37
|
+
Third-party packages are not copied: the service installs them, and the manifest's `requires` says
|
|
38
|
+
which.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
paths: tuple[Path, ...]
|
|
42
|
+
modules: dict[str, str]
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self, paths: str | Path | Sequence[str | Path] = (), *, modules: Mapping[str, str] | None = None
|
|
46
|
+
) -> None:
|
|
47
|
+
listed = [paths] if isinstance(paths, str | Path) else list(paths)
|
|
48
|
+
written = dict(modules or {})
|
|
49
|
+
if not listed and not written:
|
|
50
|
+
raise ValueError("BundleCode needs at least one package or module to copy")
|
|
51
|
+
object.__setattr__(self, "paths", tuple(Path(path) for path in listed))
|
|
52
|
+
object.__setattr__(self, "modules", written)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def write_code(code: BundleCode, folder: Path) -> str:
|
|
56
|
+
"""Copies `code` into `folder/code/`, without importing anything. Returns the folder's relative path,
|
|
57
|
+
what the manifest records."""
|
|
58
|
+
target = folder / CODE_ROOT
|
|
59
|
+
target.mkdir()
|
|
60
|
+
names: list[str] = []
|
|
61
|
+
for source in code.paths:
|
|
62
|
+
name = _import_name(source)
|
|
63
|
+
if name in names:
|
|
64
|
+
raise BundleError(f"two paths of the bundle's code are both imported as {name!r}", name=name)
|
|
65
|
+
names.append(name)
|
|
66
|
+
if source.is_dir():
|
|
67
|
+
shutil.copytree(
|
|
68
|
+
source, target / name, ignore=lambda _, entries: [e for e in entries if skipped(e)]
|
|
69
|
+
)
|
|
70
|
+
else:
|
|
71
|
+
shutil.copy2(source, target / f"{name}.py")
|
|
72
|
+
for name, text in code.modules.items():
|
|
73
|
+
_check_name(name, origin=f"the module {name!r}")
|
|
74
|
+
if name in names:
|
|
75
|
+
raise BundleError(f"two parts of the bundle's code are both imported as {name!r}", name=name)
|
|
76
|
+
try:
|
|
77
|
+
ast.parse(text, filename=f"{name}.py")
|
|
78
|
+
except SyntaxError as error:
|
|
79
|
+
raise BundleError(f"the module {name!r} is not valid Python: {error}", name=name) from error
|
|
80
|
+
names.append(name)
|
|
81
|
+
(target / f"{name}.py").write_text(text, encoding="utf-8")
|
|
82
|
+
return CODE_ROOT
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def check_predictor(predictor: str, folder: Path, code: str | None) -> None:
|
|
86
|
+
"""Refuses, without importing anything, a predictor a service could not import: `"module:attribute"`,
|
|
87
|
+
from the library itself (`torchstack64...`), or from a module the bundle's code folder holds."""
|
|
88
|
+
module, _ = split_predictor_path(predictor)
|
|
89
|
+
if module.split(".")[0] == LIBRARY:
|
|
90
|
+
return
|
|
91
|
+
names = code_names(folder / code) if code is not None else []
|
|
92
|
+
if code is None or module.split(".")[0] not in names or _module_file(folder / code, module) is None:
|
|
93
|
+
raise BundleError(
|
|
94
|
+
f"the predictor {predictor!r} is not in the bundle's code, which holds {sorted(names)}",
|
|
95
|
+
predictor=predictor,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _import_name(source: Path) -> str:
|
|
100
|
+
"""The name `source` is imported by, once checked that it can be copied and imported safely."""
|
|
101
|
+
if source.is_dir():
|
|
102
|
+
name = source.name
|
|
103
|
+
elif source.is_file() and source.suffix == ".py":
|
|
104
|
+
name = source.stem
|
|
105
|
+
elif source.exists():
|
|
106
|
+
raise BundleError(
|
|
107
|
+
f"the bundle's code is packages (folders) and modules (.py files); got {source}",
|
|
108
|
+
source=str(source),
|
|
109
|
+
)
|
|
110
|
+
else:
|
|
111
|
+
raise BundleError(f"nothing to copy at {source}", source=str(source))
|
|
112
|
+
_check_name(name, origin=str(source))
|
|
113
|
+
return name
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _check_name(name: str, *, origin: str) -> None:
|
|
117
|
+
"""Refuses a name the bundle's code could not be imported by, or would hide another module with."""
|
|
118
|
+
if not name.isidentifier():
|
|
119
|
+
raise BundleError(f"{origin} cannot be imported: {name!r} is not a module name", source=origin)
|
|
120
|
+
if name in sys.stdlib_module_names or name == "torchstack64":
|
|
121
|
+
raise BundleError(
|
|
122
|
+
f"{origin} would be imported as {name!r}, which is already a module of Python or of "
|
|
123
|
+
"torchstack64; rename it: the bundle's code comes first on the import path, and would hide that "
|
|
124
|
+
"module",
|
|
125
|
+
source=origin,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _module_file(root: Path, module: str) -> Path | None:
|
|
130
|
+
"""The file that defines `module` under `root` (a module, or a package's `__init__.py`), found
|
|
131
|
+
without importing it."""
|
|
132
|
+
base = root.joinpath(*module.split("."))
|
|
133
|
+
for candidate in (base.with_name(base.name + ".py"), base / "__init__.py"):
|
|
134
|
+
if candidate.is_file():
|
|
135
|
+
return candidate
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def code_names(root: Path) -> list[str]:
|
|
140
|
+
"""The top-level modules a bundle's code folder makes importable."""
|
|
141
|
+
names = []
|
|
142
|
+
for entry in sorted(root.iterdir()):
|
|
143
|
+
if skipped(entry.name):
|
|
144
|
+
continue
|
|
145
|
+
if entry.is_dir() and entry.name.isidentifier():
|
|
146
|
+
names.append(entry.name)
|
|
147
|
+
elif entry.is_file() and entry.suffix == ".py" and entry.stem.isidentifier():
|
|
148
|
+
names.append(entry.stem)
|
|
149
|
+
return names
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Importing a bundle's own code, to read the objects it keeps and to build its predictor, and refusing what
|
|
2
|
+
would run the wrong code or fail halfway: a package the code needs that is not installed, a module of the
|
|
3
|
+
same name already in memory."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import importlib
|
|
9
|
+
import logging
|
|
10
|
+
import sys
|
|
11
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
12
|
+
from importlib import metadata
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from types import ModuleType
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
from torchstack64.artifacts.code.copy import LIBRARY, code_names, skipped
|
|
18
|
+
from torchstack64.artifacts.code.inspection import edited_after_import
|
|
19
|
+
from torchstack64.artifacts.manifest import split_predictor_path
|
|
20
|
+
from torchstack64.core import BundleError, CodeConflictError, MissingDependencyError
|
|
21
|
+
|
|
22
|
+
PYTORCH_INDEX = "https://pytorch.org/get-started/locally/"
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from torchstack64.artifacts.bundle import ArtifactBundle
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def import_bundle_code(bundle: ArtifactBundle) -> Path | None:
|
|
31
|
+
"""Makes the bundle's own code importable, and returns its folder (`None` for a bundle without code).
|
|
32
|
+
|
|
33
|
+
This lets the bundle's code run: call it only on a bundle from a source you trust, verified first (the
|
|
34
|
+
loader does both). Before anything is importable, the packages the bundle needs are looked for here
|
|
35
|
+
(`MissingDependencyError`, with the `pip` line, when one is missing). The code's folder goes on the
|
|
36
|
+
import path and stays there, so what the predictor and the bundle's objects import later is found. A
|
|
37
|
+
module of the same name that this process already imported from elsewhere is reused when its Python
|
|
38
|
+
files are the same and were not edited after that import, and refused with `CodeConflictError`
|
|
39
|
+
otherwise.
|
|
40
|
+
"""
|
|
41
|
+
return _import_code(bundle)[0]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _import_code(bundle: ArtifactBundle) -> tuple[Path | None, set[str]]:
|
|
45
|
+
"""`import_bundle_code`, and the names of the bundle's code this process had already imported from
|
|
46
|
+
elsewhere with the very same files."""
|
|
47
|
+
check_requirements(bundle.manifest.requires)
|
|
48
|
+
if bundle.manifest.code is None:
|
|
49
|
+
return None, set()
|
|
50
|
+
root = (bundle.root / bundle.manifest.code).resolve()
|
|
51
|
+
shared = _already_imported(root, code_names(root))
|
|
52
|
+
if str(root) not in sys.path:
|
|
53
|
+
sys.path.insert(0, str(root))
|
|
54
|
+
importlib.invalidate_caches()
|
|
55
|
+
return root, shared
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def import_predictor_factory(bundle: ArtifactBundle) -> Callable[[ArtifactBundle, str], Any]:
|
|
59
|
+
"""Makes the bundle's code importable and returns the predictor loader its manifest names: a class of
|
|
60
|
+
the library itself (the `TorchClassifier` that reads a classifier's network and its preparation), or a
|
|
61
|
+
class in the bundle's own code. Like `import_bundle_code`, this lets the bundle's code run."""
|
|
62
|
+
predictor = bundle.manifest.predictor
|
|
63
|
+
if predictor is None:
|
|
64
|
+
raise BundleError(
|
|
65
|
+
f"the bundle at {bundle.root} names no predictor; load it with the class that wrote it, "
|
|
66
|
+
"MyClass.load(folder)",
|
|
67
|
+
root=str(bundle.root),
|
|
68
|
+
)
|
|
69
|
+
root, shared = _import_code(bundle)
|
|
70
|
+
module_name, attribute = split_predictor_path(predictor)
|
|
71
|
+
top = module_name.split(".")[0]
|
|
72
|
+
module = importlib.import_module(module_name)
|
|
73
|
+
if top != LIBRARY and top not in shared and (root is None or not _inside(module, root)):
|
|
74
|
+
raise CodeConflictError(
|
|
75
|
+
f"{module_name!r} was imported from {_location(module)}, not from the bundle's code"
|
|
76
|
+
+ (f" at {root}" if root is not None else ""),
|
|
77
|
+
name=module_name,
|
|
78
|
+
bundle=str(root),
|
|
79
|
+
)
|
|
80
|
+
factory: Any = module
|
|
81
|
+
for part in attribute.split("."):
|
|
82
|
+
try:
|
|
83
|
+
factory = getattr(factory, part)
|
|
84
|
+
except AttributeError:
|
|
85
|
+
raise BundleError(f"the bundle's code has no {predictor!r}", predictor=predictor) from None
|
|
86
|
+
if not callable(factory):
|
|
87
|
+
raise BundleError(f"{predictor!r} in the bundle's code is not callable", predictor=predictor)
|
|
88
|
+
logger.debug("imported the predictor %s for the bundle at %s", predictor, bundle.root)
|
|
89
|
+
return factory
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _already_imported(root: Path, names: Sequence[str]) -> set[str]:
|
|
93
|
+
"""The names this process already imported from elsewhere with the very same Python files.
|
|
94
|
+
|
|
95
|
+
Any other name already imported from elsewhere is a conflict: importing the bundle's code would
|
|
96
|
+
silently run the module already in memory instead.
|
|
97
|
+
"""
|
|
98
|
+
shared: set[str] = set()
|
|
99
|
+
for name in names:
|
|
100
|
+
loaded = sys.modules.get(name)
|
|
101
|
+
if loaded is None or _inside(loaded, root):
|
|
102
|
+
continue
|
|
103
|
+
where = _location(loaded)
|
|
104
|
+
own = root / name if (root / name).is_dir() else root / f"{name}.py"
|
|
105
|
+
found = _python_files(where)
|
|
106
|
+
if found is not None and found == _python_files(own):
|
|
107
|
+
edited = edited_after_import(where) if where is not None else []
|
|
108
|
+
if edited:
|
|
109
|
+
files = ", ".join(str(path) for path in edited)
|
|
110
|
+
raise CodeConflictError(
|
|
111
|
+
f"this process imported {name!r} before {files} changed on disk: the files match the "
|
|
112
|
+
"bundle's, but the code in memory is the old one; load this bundle in a process of its "
|
|
113
|
+
"own, or restart the kernel",
|
|
114
|
+
name=name,
|
|
115
|
+
bundle=str(root),
|
|
116
|
+
edited=[str(path) for path in edited],
|
|
117
|
+
)
|
|
118
|
+
logger.debug("%r is already imported from %s with the same files as the bundle's", name, loaded)
|
|
119
|
+
shared.add(name)
|
|
120
|
+
continue
|
|
121
|
+
raise CodeConflictError(
|
|
122
|
+
f"the bundle's code carries {name!r}, and this process already imported a different {name!r} "
|
|
123
|
+
f"from {where}; load this bundle in a process of its own, or before that import",
|
|
124
|
+
name=name,
|
|
125
|
+
bundle=str(root),
|
|
126
|
+
)
|
|
127
|
+
return shared
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def check_requirements(requires: Mapping[str, str]) -> None:
|
|
131
|
+
"""Refuses, before any of the bundle's code runs, a bundle whose code needs what this environment lacks.
|
|
132
|
+
|
|
133
|
+
Each distribution `requires` names (what the code imports, as installed where the bundle was written)
|
|
134
|
+
must be installed here; otherwise `MissingDependencyError` lists them, with the `pip` line pinned to the
|
|
135
|
+
versions that wrote the bundle. A name the code imports that no distribution provided when it was
|
|
136
|
+
written (an optional `try: import ...`) is not asked for. An installed distribution of another version
|
|
137
|
+
is only logged: the code may still run, and the service decides.
|
|
138
|
+
"""
|
|
139
|
+
missing: list[tuple[str, str]] = []
|
|
140
|
+
differing: list[str] = []
|
|
141
|
+
for distribution, wanted in requires.items():
|
|
142
|
+
try:
|
|
143
|
+
here = metadata.version(distribution)
|
|
144
|
+
except metadata.PackageNotFoundError:
|
|
145
|
+
missing.append((distribution, wanted))
|
|
146
|
+
continue
|
|
147
|
+
if _base(here) != _base(wanted):
|
|
148
|
+
differing.append(f"{distribution} {wanted} (here {here})")
|
|
149
|
+
if differing:
|
|
150
|
+
logger.warning("the bundle's code was written with %s", ", ".join(differing))
|
|
151
|
+
if missing:
|
|
152
|
+
listed = ", ".join(f"{name} {version}" for name, version in missing)
|
|
153
|
+
raise MissingDependencyError(
|
|
154
|
+
f"the bundle's code needs packages that are not installed here: {listed}; {_pip_line(missing)}",
|
|
155
|
+
missing=[name for name, _ in missing],
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _pip_line(missing: Sequence[tuple[str, str]]) -> str:
|
|
160
|
+
pins = " ".join(f'"{name}=={_base(version)}"' for name, version in missing)
|
|
161
|
+
line = f"install them with: pip install {pins}"
|
|
162
|
+
builds = [f"{name} {version}" for name, version in missing if "+" in version]
|
|
163
|
+
if builds:
|
|
164
|
+
line += (
|
|
165
|
+
f" ({', '.join(builds)} came from a package index of its own, not from PyPI; for PyTorch, "
|
|
166
|
+
f"{PYTORCH_INDEX} gives the index for this machine)"
|
|
167
|
+
)
|
|
168
|
+
return line
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _base(version: str) -> str:
|
|
172
|
+
"""A version without its local part: `2.15.0+cpu` is `2.15.0`, the part PyPI knows."""
|
|
173
|
+
return version.split("+", 1)[0]
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _location(module: ModuleType) -> Path | None:
|
|
177
|
+
"""A package's folder, or a module's file."""
|
|
178
|
+
path = getattr(module, "__path__", None)
|
|
179
|
+
if path:
|
|
180
|
+
return Path(next(iter(path)))
|
|
181
|
+
file = getattr(module, "__file__", None)
|
|
182
|
+
return Path(file) if file else None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _inside(module: ModuleType, root: Path) -> bool:
|
|
186
|
+
where = _location(module)
|
|
187
|
+
return where is not None and where.resolve().is_relative_to(root)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _python_files(where: Path | None) -> dict[str, str] | None:
|
|
191
|
+
"""The SHA-256 of each Python file of a package folder or a module file, by name."""
|
|
192
|
+
if where is None or not where.exists():
|
|
193
|
+
return None
|
|
194
|
+
if where.is_file():
|
|
195
|
+
return {"": _sha256(where)}
|
|
196
|
+
return {
|
|
197
|
+
path.relative_to(where).as_posix(): _sha256(path)
|
|
198
|
+
for path in sorted(where.rglob("*.py"))
|
|
199
|
+
if not any(skipped(part) for part in path.relative_to(where).parts)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _sha256(path: Path) -> str:
|
|
204
|
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|