Repository navigation
Expand file tree
/
Copy pathverify_dist.py
More file actions
395 lines (379 loc) · 15.6 KB
/
Copy pathverify_dist.py
File metadata and controls
395 lines (379 loc) · 15.6 KB
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
"""Check licence metadata, model identity and exact bundled bytes; stdlib only."""
import argparse
import email
import hashlib
import json
import re
import sys
import tarfile
import zipfile
from pathlib import Path
root = Path(__file__).resolve().parent
version = re.search(r'^version = "([^"]+)"$', (root / "pyproject.toml").read_text(), re.M)[1]
if sys.argv[1:] == ["--version"]:
print(version)
raise SystemExit(0)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dist-dir", type=Path, default=root / "dist")
parser.add_argument(
"--wheel", type=Path, help="Specific platform wheel to verify against the same source archive"
)
parser.add_argument("--all-wheels", action="store_true", help="Verify all wheels for this version")
parser.add_argument(
"--require-native",
action="store_true",
help="Require at least one wheel with the Akiki library",
)
parser.add_argument(
"--require-arm64", action="store_true", help="Require the experimental ARM64 native wheel"
)
parser.add_argument(
"--require-desktop",
action="store_true",
help="Require Windows x64 and Intel and ARM64 macOS native wheels",
)
args = parser.parse_args()
if args.wheel and args.all_wheels:
parser.error("--wheel and --all-wheels are mutually exclusive")
wheels = (
sorted(args.dist_dir.glob(f"akiki-{version}-*.whl"))
if args.all_wheels
else [args.wheel or args.dist_dir / f"akiki-{version}-py3-none-any.whl"]
)
source = args.dist_dir / f"akiki-{version}.tar.gz"
package_dir = root / "src/akiki"
model_dir = package_dir / "models"
python_modules = {
"akiki/" + path.relative_to(package_dir).as_posix(): path
for package in (package_dir, package_dir / "audio", package_dir / "vision")
for path in package.glob("*.py")
}
expected_id = "teacher-only623-v2-s1730"
expected_hash = "0fab56bc4ea6725ec881c35973e04813a4963dc5bbf4bf5ccfe8fd7cf468c6f5"
checks = {}
def require(condition, message):
if not condition:
raise ValueError(message)
def check_no_local_artifacts(names):
local_directories = {
".akiki-lab",
".cache",
".venv",
"__pycache__",
"experiments",
"local-experiments",
"reports",
"toy-test",
"toy-test-typed-decisions",
"verification",
}
for name in names:
require(
not {"akiki_training", "akiki-training"}.intersection(Path(name).parts)
and not (
Path(name).name.startswith(("akiki_training-", "akiki-training-"))
and name.endswith((".whl", ".tar.gz"))
),
f"Private training artifact must not be distributed: {name}",
)
require(
not local_directories.intersection(Path(name).parts)
and not name.endswith((".ipynb", ".pyc", ".pyo")),
f"Local artifact must not be distributed: {name}",
)
def check_package_files(names, *, allow_native=False):
names = {name for name in names if not name.endswith("/")}
expected = set(python_modules)
expected.update(
"akiki/" + path.relative_to(package_dir).as_posix()
for path in model_dir.rglob("*")
if path.is_file()
)
if allow_native:
expected.update(
name
for name in names
if name.startswith("akiki/native/") and name.endswith((".so", ".dylib", ".dll"))
)
require(names == expected, "Unexpected/missing package files; rebuild from a clean checkout")
def check_metadata(data):
# Core metadata is UTF-8; the legacy email parser otherwise replaces
# non-ASCII description text such as the microsecond symbol.
metadata = email.message_from_string(data.decode("utf-8"))
require(
metadata["Name"] == "akiki" and metadata["Version"] == version, "Wrong package name/version"
)
require(
tuple(map(int, metadata["Metadata-Version"].split("."))) >= (2, 4),
"License-File requires metadata >=2.4",
)
require(metadata["License-Expression"] == "Apache-2.0", "Wrong licence expression")
require(
metadata.get_all("License-File") == ["LICENSE", "THIRD_PARTY_NOTICES.txt"],
"Wrong licence files",
)
require(metadata["License"] is None, "Legacy licence metadata present")
require(metadata["Description-Content-Type"] == "text/markdown", "Description must be Markdown")
require(
metadata.get_payload().replace("\r\n", "\n").strip()
== (root / "README.md").read_text().strip(),
"Stale public description: rebuild this artifact with the current README",
)
require(
set(metadata.get_all("Provides-Extra") or [])
== {"huggingface", "onnx", "pytorch", "ten-vad", "training"},
"Missing optional feature extras",
)
require(
set(metadata.get_all("Requires-Dist") or [])
== {
"numpy>=1.24",
"soundfile>=0.12",
'huggingface-hub>=0.24; extra == "huggingface"',
'onnxruntime>=1.17; extra == "onnx"',
'torch>=2.1; extra == "pytorch"',
'huggingface-hub>=0.24; extra == "ten-vad"',
'onnx>=1.16; extra == "ten-vad"',
'torch>=2.1; extra == "training"',
'transformers<6,>=4.40; extra == "training"',
'safetensors>=0.4; extra == "training"',
},
"Runtime dependencies must be optional and independently selectable",
)
return {k: metadata[k] for k in ["Metadata-Version", "License-Expression"]}
def check_models(read, names):
prefix = "akiki/models/"
local_files = sorted(path for path in model_dir.rglob("*") if path.is_file())
require(
{name for name in names if name.startswith(prefix) and not name.endswith("/")}
== {prefix + path.relative_to(model_dir).as_posix() for path in local_files},
"Unexpected/missing bundled model files",
)
for path in local_files:
require(
read(prefix + path.relative_to(model_dir).as_posix()) == path.read_bytes(),
f"Bundled bytes differ: {path.name}",
)
metadata = json.loads(read(prefix + "akiki-vad.json"))
release = json.loads(read(prefix + "release.json"))
require(
hashlib.sha256(read(prefix + "akiki-vad.onnx")).hexdigest() == expected_hash,
"Wrong released ONNX weights",
)
require(metadata["onnx_sha256"] == expected_hash, "Wrong sidecar checksum")
require(metadata["model_id"] == release["model_id"] == expected_id, "Wrong model identity")
require(
metadata["origin"]["seed"] == release["selection"]["seed"] == 1730, "Wrong release seed"
)
require(
metadata["release_selection"]["checkpoint_window"]
== release["selection"]["checkpoint_window"]
== 31,
"Wrong release checkpoint",
)
require(release["package_version"] == version, "Release/package version mismatch")
require(
hashlib.sha256(read(prefix + "akiki-vad.pt")).hexdigest()
== release["files"]["akiki-vad.pt"]["sha256"],
"Wrong released PyTorch weights",
)
receipt = json.loads(read(prefix + "akiki-vad-native/export.json"))
for filename, key in [
("config.json", "config_sha256"),
("model.safetensors", "model_safetensors_sha256"),
]:
require(
hashlib.sha256(read(prefix + "akiki-vad-native/" + filename)).hexdigest()
== receipt[key],
"Wrong Akiki model bytes",
)
require(
receipt["source_checkpoint_sha256"] == release["files"]["akiki-vad.pt"]["sha256"],
"Akiki export belongs to another checkpoint",
)
return dict(model_id=expected_id, seed=1730, checkpoint_window=31, onnx_sha256=expected_hash)
require(wheels, "No wheels found for this version")
require(
not re.search(r"/home/|/Users/|/mnt/|[A-Za-z]:\\Users\\", (root / "README.md").read_text()),
"Public README contains a private machine path",
)
native_count = 0
arm64_count = 0
native_platforms = set()
checks["wheels"] = {}
for wheel in wheels:
with zipfile.ZipFile(wheel) as archive:
check_no_local_artifacts(archive.namelist())
require(
all(
name.startswith(("akiki/", f"akiki-{version}.dist-info/"))
for name in archive.namelist()
),
"Unexpected top-level wheel files; rebuild from a clean checkout",
)
check_package_files(
[name for name in archive.namelist() if name.startswith("akiki/")],
allow_native=True,
)
info = check_metadata(archive.read(f"akiki-{version}.dist-info/METADATA"))
for name in ["LICENSE", "THIRD_PARTY_NOTICES.txt"]:
require(
archive.read(f"akiki-{version}.dist-info/licenses/{name}")
== (root / name).read_bytes(),
f"Wheel licence differs: {name}",
)
info["model"] = check_models(archive.read, archive.namelist())
for name, path in python_modules.items():
require(archive.read(name) == path.read_bytes(), f"Stale Python module: {name}")
libraries = [
name
for name in archive.namelist()
if name.startswith("akiki/native/") and name.endswith((".so", ".dylib", ".dll"))
]
wheel_metadata = email.message_from_bytes(archive.read(f"akiki-{version}.dist-info/WHEEL"))
tags = wheel_metadata.get_all("Tag") or []
python_tag, abi_tag, platform_tag = wheel.stem.rsplit("-", 3)[1:]
require(
set(tags)
== {f"{python_tag}-{abi_tag}-{platform}" for platform in platform_tag.split(".")},
"Wheel filename and internal tags differ",
)
if libraries:
require(wheel_metadata["Root-Is-Purelib"] == "false", "Native wheel marked pure")
require(all(tag.startswith("py3-none-") for tag in tags), "Wrong native Python/ABI tag")
for platform in platform_tag.split("."):
require(
platform.startswith(("manylinux", "musllinux", "macosx_", "win")),
"Native wheel needs a PyPI-compatible platform tag",
)
arm64 = platform.endswith("_aarch64")
stems = ("akiki_vad_engine", "akiki_minilm_engine")
expected = sorted(
"akiki/native/"
+ (
f"{stem}.dll"
if platform.startswith("win")
else f"lib{stem}.dylib"
if platform.startswith("macosx_")
else f"lib{stem}.so"
)
for stem in stems
)
require(
sorted(libraries) == expected,
"Native wheels must include both VAD and MiniLM libraries",
)
if platform.startswith(("manylinux", "musllinux")):
machine = 183 if arm64 else 62
for name in libraries:
header = archive.read(name)[:20]
require(
header[:6] == b"\x7fELF\x02\x01"
and int.from_bytes(header[18:20], "little") == machine,
"Bundled ELF architecture differs from the wheel tag",
)
elif platform.startswith("macosx_"):
machine = 0x0100000C if platform.endswith("_arm64") else 0x01000007
for name in libraries:
header = archive.read(name)[:8]
require(
platform.endswith(("_arm64", "_x86_64"))
and header[:4] == b"\xcf\xfa\xed\xfe"
and int.from_bytes(header[4:8], "little") == machine,
"Bundled Mach-O architecture differs from the wheel tag",
)
elif platform.startswith("win"):
machine = 0xAA64 if platform == "win_arm64" else 0x8664
for name in libraries:
data = archive.read(name)
offset = int.from_bytes(data[60:64], "little")
require(
data[:2] == b"MZ"
and data[offset : offset + 4] == b"PE\x00\x00"
and int.from_bytes(data[offset + 4 : offset + 6], "little") == machine,
"Bundled PE architecture differs from the wheel tag",
)
native_platforms.add(platform)
native_count += 1
if any(platform.endswith("_aarch64") for platform in platform_tag.split(".")):
arm64_count += 1
info["support"] = "experimental-arm64-minilm"
info["native_libraries_sha256"] = {
name: hashlib.sha256(archive.read(name)).hexdigest() for name in sorted(libraries)
}
else:
require(
tags == ["py3-none-any"] and wheel_metadata["Root-Is-Purelib"] == "true",
"Non-native wheel must be portable",
)
info["tags"] = tags
checks["wheels"][wheel.name] = info
require(
not args.require_native or native_count > 0,
"No native wheel found; build and repair the Akiki wheel before publishing",
)
require(not args.require_arm64 or arm64_count > 0, "The experimental ARM64 native wheel is missing")
require(
not args.require_desktop
or (
"win_amd64" in native_platforms
and any(re.fullmatch(r"macosx_\d+_\d+_x86_64", tag) for tag in native_platforms)
and any(re.fullmatch(r"macosx_\d+_\d+_arm64", tag) for tag in native_platforms)
),
"Windows x64 and both macOS architecture wheels are required",
)
with tarfile.open(source) as archive:
check_no_local_artifacts(archive.getnames())
def source_read(name):
return archive.extractfile(f"akiki-{version}/src/" + name).read()
checks["sdist"] = check_metadata(archive.extractfile(f"akiki-{version}/PKG-INFO").read())
require(
archive.extractfile(f"akiki-{version}/README.md").read()
== (root / "README.md").read_bytes(),
"Source README differs",
)
for name in ["LICENSE", "THIRD_PARTY_NOTICES.txt"]:
require(
archive.extractfile(f"akiki-{version}/{name}").read() == (root / name).read_bytes(),
f"Source licence differs: {name}",
)
source_prefix = f"akiki-{version}/src/"
check_package_files(
[
member.name[len(source_prefix) :]
for member in archive.getmembers()
if member.name.startswith(source_prefix + "akiki/") and member.isfile()
]
)
checks["sdist"]["model"] = check_models(
source_read,
[
name[len(source_prefix) :]
for name in archive.getnames()
if name.startswith(source_prefix) and archive.getmember(name).isfile()
],
)
result_path = (
root
/ "verification"
/ version
/ ("result.json" if args.wheel is None else f"{args.wheel.stem}.json")
)
result = {}
result.update(
version=version,
model_id=expected_id,
metadata=checks,
bundled_model_sha256=expected_hash,
artifacts={
path.name: dict(
bytes=path.stat().st_size, sha256=hashlib.sha256(path.read_bytes()).hexdigest()
)
for path in [*wheels, source]
},
)
result_path.parent.mkdir(parents=True, exist_ok=True)
result_path.write_text(json.dumps(result, indent=2) + "\n")
print(
f"Verified akiki {version}: {len(wheels)} wheel(s), {native_count} native, and source archive; current public description and exact seed 1730/window 31 weights."
)