liuyibo commited on
Commit
d6c5624
·
verified ·
1 Parent(s): b66bfc4

Add environment artifact: prepare_environment.py

Browse files
Files changed (1) hide show
  1. prepare_environment.py +106 -0
prepare_environment.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Create a reviewed environment-only Docker context from a fixed Conda prefix."""
2
+ import argparse
3
+ import hashlib
4
+ import importlib.metadata
5
+ import io
6
+ import json
7
+ import os
8
+ import shutil
9
+ import tarfile
10
+ from pathlib import Path
11
+
12
+
13
+ WEIGHT_SUFFIXES = {".pt", ".ckpt", ".safetensors", ".onnx", ".model"}
14
+ SKIP_DIRS = {"__pycache__", ".git", ".cache", "conda-meta", "tests", "test"}
15
+ SKIP_NAMES = {"direct_url.json", "pip.conf", ".netrc", ".condarc", "hfkey.txt", "token", "stored_tokens", "credentials", "id_rsa", "id_ed25519", ".npmrc", ".pypirc"}
16
+ REVIEWED_BINARY_RESOURCES = {
17
+ "matplotlib/mpl-data/sample_data/goog.npz", "matplotlib/mpl-data/sample_data/jacksboro_fault_dem.npz",
18
+ "matplotlib/mpl-data/sample_data/topobathy.npz", "scipy/stats/_sobol_direction_numbers.npz",
19
+ "sentencepiece/package_data/nfkc.bin", "sentencepiece/package_data/nfkc_cf.bin",
20
+ "sentencepiece/package_data/nmt_nfkc.bin", "sentencepiece/package_data/nmt_nfkc_cf.bin",
21
+ "text_unidecode/data.bin", "whisper/assets/mel_filters.npz",
22
+ }
23
+
24
+
25
+ def main():
26
+ parser = argparse.ArgumentParser()
27
+ parser.add_argument("--prefix", type=Path, default=Path("/opt/conda/envs/hybrid"))
28
+ parser.add_argument("--out", type=Path, required=True)
29
+ args = parser.parse_args()
30
+ prefix = args.prefix.resolve()
31
+ assert prefix == Path("/opt/conda/envs/hybrid"), "Snapshot preserves its original prefix"
32
+ args.out.mkdir(parents=True, exist_ok=False)
33
+ files, excluded = [], []
34
+ for directory, dirs, names in os.walk(prefix, followlinks=False):
35
+ dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
36
+ for d in dirs:
37
+ path = Path(directory) / d
38
+ if path.is_symlink():
39
+ assert path.resolve().is_relative_to(prefix), f"External directory link: {path}"
40
+ files.append(path)
41
+ for name in sorted(names):
42
+ path = Path(directory) / name
43
+ rel = path.relative_to(prefix)
44
+ if name in SKIP_NAMES or name.startswith(".env") or path.suffix in WEIGHT_SUFFIXES or path.suffix == ".pyc":
45
+ excluded.append(str(rel))
46
+ continue
47
+ if path.suffix == ".pth" and path.parent.name != "site-packages":
48
+ excluded.append(str(rel))
49
+ continue
50
+ if path.suffix.lower() in {".bin", ".pkl", ".npz", ".h5", ".hdf5"}:
51
+ resource = str(rel).removeprefix("lib/python3.12/site-packages/")
52
+ if resource not in REVIEWED_BINARY_RESOURCES:
53
+ raise ValueError(f"Review potential model/data before including: {rel}")
54
+ if path.is_symlink():
55
+ assert path.resolve().is_relative_to(prefix), f"External file link: {path}"
56
+ files.append(path)
57
+ manifest = []
58
+ patch_prefix = b"import inspect\nif not hasattr(inspect, 'getargspec'):\n inspect.getargspec = inspect.getfullargspec\n"
59
+ with tarfile.open(args.out / "environment.tar", "x", dereference=False) as archive:
60
+ for path in sorted(set(files)):
61
+ rel = path.relative_to(prefix)
62
+ info = archive.gettarinfo(str(path), arcname=str(rel))
63
+ info.uid = info.gid = 0
64
+ info.uname = info.gname = "root"
65
+ if info.issym():
66
+ archive.addfile(info)
67
+ manifest.append({"file": str(rel), "link": info.linkname})
68
+ continue
69
+ if not info.isfile():
70
+ raise ValueError(f"Unsupported file: {rel}")
71
+ modified = str(rel) == "lib/python3.12/site-packages/chumpy/__init__.py"
72
+ if modified:
73
+ original = path.read_bytes()
74
+ data = patch_prefix + original
75
+ info.size = len(data)
76
+ archive.addfile(info, io.BytesIO(data))
77
+ digest = hashlib.sha256(data).hexdigest()
78
+ else:
79
+ h = hashlib.sha256()
80
+ with path.open("rb") as source:
81
+ for block in iter(lambda: source.read(1024 * 1024), b""):
82
+ h.update(block)
83
+ digest = h.hexdigest()
84
+ with path.open("rb") as source:
85
+ archive.addfile(info, source)
86
+ entry = {"file": str(rel), "bytes": info.size, "sha256": digest}
87
+ if modified:
88
+ entry["patch"] = "chumpy-local inspect.getargspec fallback for Python 3.12"
89
+ entry["original_sha256"] = hashlib.sha256(original).hexdigest()
90
+ manifest.append(entry)
91
+ versions = sorted({f"{dist.metadata['Name']}=={dist.version}" for dist in importlib.metadata.distributions() if dist.metadata.get("Name")})
92
+ (args.out / "requirements.snapshot.txt").write_text("\n".join(versions) + "\n")
93
+ report = {
94
+ "prefix": str(prefix), "snapshot_kind": "installed dependencies, not a pip-rebuild lock",
95
+ "excluded": excluded, "skipped_directories": sorted(SKIP_DIRS), "files": manifest,
96
+ "scope": "No project, user home, HF cache, datasets, pretrained weights or credentials; optional package test/LPIPS weights removed",
97
+ }
98
+ (args.out / "environment-inventory.json").write_text(json.dumps(report, indent=2))
99
+ source = Path(__file__).resolve().parent
100
+ for name in ("Dockerfile", "smoke_test.py"):
101
+ shutil.copy2(source / name, args.out / name)
102
+ print(json.dumps({"context": str(args.out), "tar_bytes": (args.out / "environment.tar").stat().st_size, "entries": len(manifest), "excluded_files": len(excluded)}), flush=True)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ main()