reprospec 0.1.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.
reprospec/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """reprospec: capture, compare, and lint ML environments."""
2
+
3
+ __version__ = "0.1.0"
reprospec/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow `python -m reprospec`."""
2
+
3
+ from reprospec.cli import main
4
+
5
+ raise SystemExit(main())
reprospec/capture.py ADDED
@@ -0,0 +1,151 @@
1
+ """The capture command: run every probe and assemble one manifest."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+
11
+ from reprospec import __version__
12
+ from reprospec.manifest import Manifest, Tool
13
+ from reprospec.probes.accelerator import probe_accelerator
14
+ from reprospec.probes.host import probe_host
15
+ from reprospec.probes.python_env import ProbeError, default_python, probe_python_env
16
+ from reprospec.probes.system import System
17
+
18
+
19
+ def capture(
20
+ python: str,
21
+ *,
22
+ system: System | None = None,
23
+ env: dict[str, str] | None = None,
24
+ now: datetime | None = None,
25
+ home: str | None = None,
26
+ ) -> tuple[Manifest, list[str]]:
27
+ """Capture the environment of the interpreter at `python`.
28
+
29
+ Returns the manifest and a list of warnings (problems that didn't stop the
30
+ capture). Raises ProbeError if the interpreter can't be inspected at all.
31
+ """
32
+ system = system or System()
33
+ host = probe_host(system)
34
+ py_env = probe_python_env(python, env=env)
35
+ accelerator = probe_accelerator(host, py_env.frameworks, system)
36
+
37
+ py_env.python.executable = tidy_path(py_env.python.executable, home)
38
+ stamp = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
39
+ manifest = Manifest(
40
+ captured_at=stamp.strftime("%Y-%m-%dT%H:%M:%SZ"),
41
+ tool=Tool(version=__version__),
42
+ host=host,
43
+ accelerator=accelerator,
44
+ python=py_env.python,
45
+ frameworks=py_env.frameworks,
46
+ env=py_env.env,
47
+ )
48
+ # Put lists in canonical order, so the returned manifest equals the one
49
+ # that will be read back from disk.
50
+ return Manifest.from_dict(manifest.to_dict()), py_env.warnings
51
+
52
+
53
+ def tidy_path(path: str, home: str | None = None) -> str:
54
+ """Replace the home folder with ~ so manifests don't reveal usernames."""
55
+ home = str(Path.home()) if home is None else home
56
+ home = home.rstrip("/\\")
57
+ if not home or not path:
58
+ return path
59
+ if path == home:
60
+ return "~"
61
+ for sep in {os.sep, "/"}:
62
+ if path.startswith(home + sep):
63
+ return "~" + path[len(home) :]
64
+ return path
65
+
66
+
67
+ def summarize(manifest: Manifest) -> list[str]:
68
+ """A few human-readable lines about what was captured."""
69
+ py = manifest.python
70
+ lines = [f"Inspected {py.executable} (Python {py.version}, {py.arch})"]
71
+ if manifest.is_rosetta:
72
+ lines.append(" note: this Python runs under Rosetta (x86_64 on an arm64 Mac)")
73
+
74
+ acc = manifest.accelerator
75
+ names = sorted({d.name for d in acc.devices if d.name})
76
+ detail = f" ({', '.join(names)})" if names else ""
77
+ lines.append(f"Accelerator: {acc.backend}{detail}")
78
+
79
+ if manifest.frameworks:
80
+ found = ", ".join(
81
+ f"{name} {fw.version}" for name, fw in sorted(manifest.frameworks.items())
82
+ )
83
+ lines.append(f"Frameworks: {found}")
84
+ else:
85
+ lines.append("Frameworks: none found")
86
+ lines.append(f"Packages: {len(py.packages)}")
87
+ return lines
88
+
89
+
90
+ # --- command line -------------------------------------------------------------
91
+
92
+
93
+ def add_parser(subparsers: argparse._SubParsersAction) -> None:
94
+ parser = subparsers.add_parser(
95
+ "capture",
96
+ help="record this environment as a manifest",
97
+ description=(
98
+ "Record the current ML environment as a manifest: hardware, "
99
+ "accelerator, Python, packages, frameworks and the environment "
100
+ "variables that affect results."
101
+ ),
102
+ )
103
+ parser.add_argument(
104
+ "--python",
105
+ metavar="PATH",
106
+ help="interpreter to inspect (default: the active virtualenv or conda "
107
+ "env, otherwise python3 on your PATH)",
108
+ )
109
+ parser.add_argument(
110
+ "-o",
111
+ "--output",
112
+ metavar="FILE",
113
+ help="write the manifest to FILE (default: standard output)",
114
+ )
115
+ parser.add_argument(
116
+ "-q",
117
+ "--quiet",
118
+ action="store_true",
119
+ help="don't print the summary",
120
+ )
121
+ parser.set_defaults(handler=run)
122
+
123
+
124
+ def run(args: argparse.Namespace) -> int:
125
+ python = args.python or default_python()
126
+ try:
127
+ manifest, warnings = capture(python)
128
+ except ProbeError as e:
129
+ print(f"reprospec: error: {e}", file=sys.stderr)
130
+ return 1
131
+
132
+ if not args.quiet:
133
+ for line in summarize(manifest):
134
+ print(line, file=sys.stderr)
135
+ for warning in warnings:
136
+ print(f"warning: {warning}", file=sys.stderr)
137
+
138
+ if args.output and args.output != "-":
139
+ try:
140
+ manifest.save(args.output)
141
+ except OSError as e:
142
+ print(
143
+ f"reprospec: error: couldn't write {args.output}: {e.strerror or e}",
144
+ file=sys.stderr,
145
+ )
146
+ return 1
147
+ if not args.quiet:
148
+ print(f"Wrote {args.output}", file=sys.stderr)
149
+ else:
150
+ sys.stdout.write(manifest.to_json())
151
+ return 0
reprospec/cli.py ADDED
@@ -0,0 +1,42 @@
1
+ """Command-line entry point.
2
+
3
+ Each command lives in its own module, which provides `add_parser` to register
4
+ its arguments and a handler that returns the exit code.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import platform
11
+ import sys
12
+ from collections.abc import Sequence
13
+
14
+ from reprospec import __version__, capture, diff, doctor
15
+
16
+
17
+ def build_parser() -> argparse.ArgumentParser:
18
+ parser = argparse.ArgumentParser(
19
+ prog="reprospec",
20
+ description="Capture, compare, and lint ML environments.",
21
+ )
22
+ parser.add_argument(
23
+ "--version",
24
+ action="version",
25
+ version=f"reprospec {__version__} (Python {platform.python_version()}, "
26
+ f"{platform.system()} {platform.machine()})",
27
+ )
28
+ subparsers = parser.add_subparsers(dest="command", metavar="<command>")
29
+ capture.add_parser(subparsers)
30
+ diff.add_parser(subparsers)
31
+ doctor.add_parser(subparsers)
32
+ return parser
33
+
34
+
35
+ def main(argv: Sequence[str] | None = None) -> int:
36
+ parser = build_parser()
37
+ args = parser.parse_args(argv)
38
+
39
+ if args.command is None:
40
+ parser.print_help(sys.stderr)
41
+ return 2
42
+ return args.handler(args)