File size: 23,917 Bytes
cdb3d72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
#!/usr/bin/env python3
"""Local publish checks for PHM-Vibench without upload/download traffic."""

from __future__ import annotations

import argparse
import hashlib
import importlib.metadata
import json
import os
import subprocess
import sys
from contextlib import redirect_stdout
from io import StringIO
from pathlib import Path
from types import SimpleNamespace
from urllib.parse import urlencode
from urllib.request import ProxyHandler, Request, build_opener

from phm_vibench_manifest import (
    ARCHIVED_FILES,
    DATASET_TO_FILE,
    DEMO_FILES,
    FILE_SIZES,
    HF_ENDPOINT,
    HF_REVISION,
    LOCAL_ONLY_PATHS,
    MODELSCOPE_ENDPOINT,
    MODELSCOPE_REVISION,
    NETWORK_REDIRECT_ENV_KEYS,
    PLATFORM_TARGET_CHOICES,
    PUBLISHED_FILES,
    PUBLISHED_SMALL_FILES,
    PROXY_ENV_KEYS,
    REPO_ID,
    RM_H5_FILES,
    HF_ENDPOINT_ENV_KEYS,
    configure_hf_no_proxy,
    enforce_no_network_redirects,
    expand_platform_targets,
    format_bytes,
    total_size,
)


REPO_ROOT = Path(__file__).resolve().parents[1]
README_CARD_MARKERS = [
    "license: apache-2.0",
    "task_categories:",
    "time-series-classification",
    "tags:",
    "pretty_name: PHM-Vibench",
    "configs:",
    "path: RM_*.h5",
]
PLAIN_TEXT_PUBLISHED_FILES = ["dataset_infos.json", "published_manifest.json", "requirements.txt"]
REMOTE_TIMEOUT_SECONDS = 30
REQUIRED_PACKAGES = [
    ("huggingface_hub", "0.25"),
    ("modelscope", "1.20"),
    ("pandas", "1.5"),
    ("openpyxl", "3.1"),
    ("h5py", "3.8"),
    ("numpy", "1.23"),
]


def sha256_of(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for block in iter(lambda: f.read(1024 * 1024), b""):
            h.update(block)
    return h.hexdigest()


def build_manifest(*, include_sha256: bool) -> dict:
    items = []
    for rel in PUBLISHED_FILES:
        path = REPO_ROOT / rel
        item = {
            "path": rel,
            "size_bytes": path.stat().st_size if path.exists() else FILE_SIZES[rel],
            "expected_size_bytes": FILE_SIZES[rel],
            "targets": ["modelscope", "hf"],
        }
        if include_sha256:
            if not path.exists():
                raise SystemExit(f"Cannot hash missing file: {rel}")
            item["sha256"] = sha256_of(path)
        items.append(item)
    return {
        "schema_version": 1,
        "repo_id": REPO_ID,
        "hf_revision": HF_REVISION,
        "modelscope_revision": MODELSCOPE_REVISION,
        "platforms": {
            "modelscope": {"revision": MODELSCOPE_REVISION, "endpoint": MODELSCOPE_ENDPOINT},
            "hf": {"revision": HF_REVISION, "endpoint": HF_ENDPOINT},
        },
        "presets": {
            "metadata": {
                "files": ["metadata.xlsx"],
                "size_bytes": total_size(["metadata.xlsx"]),
                "requires_yes": False,
            },
            "docs": {
                "files": PUBLISHED_SMALL_FILES,
                "size_bytes": total_size(PUBLISHED_SMALL_FILES),
                "requires_yes": False,
            },
            "demo": {
                "files": DEMO_FILES,
                "size_bytes": total_size(DEMO_FILES),
                "requires_yes": False,
            },
            "all": {
                "files": PUBLISHED_FILES,
                "size_bytes": total_size(PUBLISHED_FILES),
                "requires_yes": True,
            },
        },
        "datasets": [
            {"id": dataset, "path": path, "size_bytes": FILE_SIZES[path]}
            for dataset, path in DATASET_TO_FILE.items()
        ],
        "published": items,
        "archived": [{"path": path, "reason": "legacy metadata superseded by metadata.xlsx"} for path in ARCHIVED_FILES],
        "local_only": [{"path": path, "reason": "not part of rolling platform release"} for path in LOCAL_ONLY_PATHS],
    }


def cmd_manifest(args: argparse.Namespace) -> int:
    manifest = build_manifest(include_sha256=args.sha256)
    text = json.dumps(manifest, ensure_ascii=False, indent=2)
    if args.output:
        args.output.write_text(text + "\n", encoding="utf-8")
        print("wrote", args.output)
    else:
        print(text)
    return 0


def cmd_local_check(_: argparse.Namespace) -> int:
    ok = True
    print("Published files:", len(PUBLISHED_FILES), format_bytes(total_size(PUBLISHED_FILES)))
    for rel in PUBLISHED_FILES:
        path = REPO_ROOT / rel
        if not path.exists():
            print("MISSING", rel)
            ok = False
            continue
        actual = path.stat().st_size
        expected = FILE_SIZES[rel]
        status = "OK" if actual == expected else "SIZE-MISMATCH"
        print(f"{status:<13} {rel:<36} {format_bytes(actual)}")
        if actual != expected:
            ok = False

    published = set(PUBLISHED_FILES)
    accidental = sorted(path for path in ARCHIVED_FILES + LOCAL_ONLY_PATHS if path.rstrip("/") in published)
    if accidental:
        print("BUG: non-published paths appear in published manifest:", ", ".join(accidental))
        ok = False

    present_local_only = [path for path in LOCAL_ONLY_PATHS if (REPO_ROOT / path.rstrip("/")).exists()]
    if present_local_only:
        print("Local-only paths present locally, intentionally excluded:", ", ".join(present_local_only))

    present_archived = [path for path in ARCHIVED_FILES if (REPO_ROOT / path).exists()]
    if present_archived:
        print("Archived legacy files present locally, intentionally excluded:", ", ".join(present_archived))

    readme = (REPO_ROOT / "README.md").read_text(encoding="utf-8", errors="replace")
    missing_markers = [marker for marker in README_CARD_MARKERS if marker not in readme]
    if missing_markers:
        print("README card metadata missing:", ", ".join(missing_markers))
        ok = False
    else:
        print("OK            README HF dataset card metadata present")

    for rel in PLAIN_TEXT_PUBLISHED_FILES:
        attr = subprocess.run(
            ["git", "check-attr", "-a", "--", rel],
            cwd=REPO_ROOT,
            check=False,
            text=True,
            capture_output=True,
        )
        if attr.returncode != 0:
            print(f"git check-attr failed for {rel}: {attr.stderr.strip()}")
            ok = False
            continue
        output = attr.stdout
        if "filter: unset" not in output or "text: set" not in output or "ignore: set" in output:
            print(f"Attribute issue for {rel}: expected plain text and no ignore")
            print(output.strip())
            ok = False
        else:
            print(f"OK            {rel} published as plain text")

    return 0 if ok else 1


def cmd_dry_run(args: argparse.Namespace) -> int:
    removed = enforce_no_network_redirects()
    if removed:
        print("Disabled network redirect env vars:", ", ".join(removed))

    targets = expand_platform_targets(args.platform)
    print("dry-run only: no network request, upload, download, or delete will be performed")
    for target in targets:
        revision = HF_REVISION if target == "hf" else MODELSCOPE_REVISION
        endpoint = HF_ENDPOINT if target == "hf" else "https://www.modelscope.cn"
        print(f"[{target}] repo={REPO_ID} revision={revision} endpoint={endpoint}")
        print(f"  upload {len(PUBLISHED_FILES)} files ({format_bytes(total_size(PUBLISHED_FILES))})")
        for rel in PUBLISHED_FILES:
            print(f"    + {rel:<36} {format_bytes(FILE_SIZES[rel])}")
        print(f"  ensure archived files absent: {', '.join(ARCHIVED_FILES)}")
        print(f"  never publish: {', '.join(LOCAL_ONLY_PATHS)}")
    return 0


def cmd_list_datasets(_: argparse.Namespace) -> int:
    print("Demo:", ", ".join(DEMO_FILES), format_bytes(total_size(DEMO_FILES)))
    for dataset, rel in DATASET_TO_FILE.items():
        print(f"{dataset:<18} {rel:<22} {format_bytes(FILE_SIZES[rel])}")
    return 0


def version_tuple(version: str) -> tuple[int, ...]:
    parts = []
    for part in version.replace("-", ".").split("."):
        if not part.isdigit():
            break
        parts.append(int(part))
    return tuple(parts)


def version_at_least(actual: str, minimum: str) -> bool:
    actual_parts = version_tuple(actual)
    minimum_parts = version_tuple(minimum)
    if not actual_parts:
        return False
    width = max(len(actual_parts), len(minimum_parts))
    return actual_parts + (0,) * (width - len(actual_parts)) >= minimum_parts + (0,) * (width - len(minimum_parts))


def cmd_doctor(_: argparse.Namespace) -> int:
    ok = True
    print(f"python: {sys.version.split()[0]}")
    for package, minimum in REQUIRED_PACKAGES:
        try:
            actual = importlib.metadata.version(package)
        except importlib.metadata.PackageNotFoundError:
            print(f"MISSING       {package:<18} required>={minimum}")
            ok = False
            continue
        status = "OK" if version_at_least(actual, minimum) else "TOO-OLD"
        print(f"{status:<13} {package:<18} installed={actual} required>={minimum}")
        if status != "OK":
            ok = False

    set_redirects = [key for key in NETWORK_REDIRECT_ENV_KEYS if os.environ.get(key)]
    if set_redirects:
        print("WARN          network redirect env vars currently set:", ", ".join(sorted(set_redirects)))
        print("              transfer tools strip these by default before platform API calls")
    else:
        print("OK            no proxy/mirror env vars currently set")

    missing = [rel for rel in PUBLISHED_FILES if not (REPO_ROOT / rel).exists()]
    if missing:
        print("MISSING       published files:", ", ".join(missing))
        ok = False
    else:
        print("OK            all published manifest files exist locally")

    return 0 if ok else 1


def require_no_network_redirects() -> None:
    removed = enforce_no_network_redirects()
    if removed:
        print("Disabled network redirect env vars:", ", ".join(removed))


def parse_remote_size(value) -> int | None:
    if value is None or value == "":
        return None
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


def fetch_hf_tree() -> dict[str, int | None]:
    configure_hf_no_proxy()
    try:
        from huggingface_hub import HfApi
    except ImportError as exc:
        raise SystemExit(
            "Missing dependency: huggingface_hub. Install it with `pip install -r requirements.txt`."
        ) from exc

    api = HfApi(endpoint=HF_ENDPOINT)
    try:
        entries = api.list_repo_tree(
            repo_id=REPO_ID,
            repo_type="dataset",
            revision=HF_REVISION,
            recursive=True,
            expand=True,
        )
        remote = {}
        for entry in entries:
            path = getattr(entry, "path", None)
            if path and getattr(entry, "type", "file") != "directory":
                remote[path] = parse_remote_size(getattr(entry, "size", None))
        return remote
    except (AttributeError, TypeError):
        info = api.dataset_info(
            REPO_ID,
            revision=HF_REVISION,
            files_metadata=True,
            timeout=REMOTE_TIMEOUT_SECONDS,
        )
        return {
            sibling.rfilename: parse_remote_size(getattr(sibling, "size", None))
            for sibling in info.siblings
            if getattr(sibling, "rfilename", None)
        }


def extract_modelscope_rows(payload) -> list[dict]:
    if isinstance(payload, list):
        return [item for item in payload if isinstance(item, dict)]
    if not isinstance(payload, dict):
        return []
    candidates = [payload]
    for key in ("Data", "data"):
        value = payload.get(key)
        if isinstance(value, list):
            return [item for item in value if isinstance(item, dict)]
        if isinstance(value, dict):
            candidates.append(value)
    for candidate in candidates:
        for key in ("Files", "files", "Tree", "tree"):
            value = candidate.get(key)
            if isinstance(value, list):
                return [item for item in value if isinstance(item, dict)]
    return []


def fetch_modelscope_tree() -> dict[str, int | None]:
    query = urlencode({"Revision": MODELSCOPE_REVISION, "Recursive": "true"})
    url = f"{MODELSCOPE_ENDPOINT}/api/v1/datasets/{REPO_ID}/repo/tree?{query}"
    request = Request(url, headers={"User-Agent": "PHM-Vibench-publish-check/1.0"})
    opener = build_opener(ProxyHandler({}))
    with opener.open(request, timeout=REMOTE_TIMEOUT_SECONDS) as response:
        payload = json.loads(response.read().decode("utf-8"))

    remote = {}
    for item in extract_modelscope_rows(payload):
        path = item.get("Path") or item.get("path") or item.get("Name") or item.get("name")
        if not path:
            continue
        if item.get("Type") in {"tree", "directory"} or item.get("type") in {"tree", "directory"}:
            continue
        remote[path] = parse_remote_size(item.get("Size", item.get("size")))
    return remote


def remote_has_path(remote: dict[str, int | None], path: str) -> bool:
    if path.endswith("/"):
        return any(rel.startswith(path) for rel in remote)
    return path in remote


def compare_remote_tree(target: str, remote: dict[str, int | None]) -> bool:
    ok = True
    print(f"[{target}] remote files listed:", len(remote))
    for rel in PUBLISHED_FILES:
        if rel not in remote:
            print(f"MISSING       {rel}")
            ok = False
            continue
        actual = remote[rel]
        expected = FILE_SIZES[rel]
        if actual is None:
            print(f"SIZE-UNKNOWN  {rel:<36} expected={expected}")
            ok = False
            continue
        status = "OK" if actual == expected else "SIZE-MISMATCH"
        print(f"{status:<13} {rel:<36} {format_bytes(actual)}")
        if actual != expected:
            ok = False

    for rel in ARCHIVED_FILES:
        if remote_has_path(remote, rel):
            print(f"UNEXPECTED    archived file still present: {rel}")
            ok = False

    for rel in LOCAL_ONLY_PATHS:
        if remote_has_path(remote, rel):
            print(f"UNEXPECTED    local-only path published: {rel}")
            ok = False

    return ok


def cmd_remote_verify(args: argparse.Namespace) -> int:
    require_no_network_redirects()
    targets = expand_platform_targets(args.platform)
    print("remote-verify: listing remote files only; no file upload or download is performed")
    ok = True
    for target in targets:
        try:
            if target == "hf":
                print(f"[hf] repo={REPO_ID} revision={HF_REVISION} endpoint={HF_ENDPOINT}")
                remote = fetch_hf_tree()
            else:
                print(f"[modelscope] repo={REPO_ID} revision={MODELSCOPE_REVISION} endpoint={MODELSCOPE_ENDPOINT}")
                remote = fetch_modelscope_tree()
        except Exception as exc:
            print(f"REMOTE-ERROR  {target}: {type(exc).__name__}: {exc}")
            ok = False
            continue
        ok = compare_remote_tree(target, remote) and ok
    return 0 if ok else 1


def cmd_self_test(_: argparse.Namespace) -> int:
    from download_phm_vibench import build_download_plan, build_file_index, resolve_files, verify_local
    from inspect_phm_vibench import choose_smoke_dataset, normalize_dataset_id
    from publish_phm_vibench import selected_files

    published = set(PUBLISHED_FILES)
    assert "RM_101_THU_GEARBOX.h5" not in published
    assert "cache.h5" not in published
    assert "metadata_25_10_30.xlsx" not in published
    assert all(path in FILE_SIZES for path in PUBLISHED_FILES)
    assert version_at_least("0.25.0", "0.25")
    assert version_at_least("1.20.1", "1.20")
    assert not version_at_least("0.24.9", "0.25")

    download_args = SimpleNamespace(
        include_metadata=False,
        include_docs=False,
        dataset=["RM_006_THU"],
        no_metadata=False,
        file=None,
        preset="metadata",
        yes=False,
    )
    assert resolve_files(download_args) == ["metadata.xlsx", "RM_006_THU.h5"]

    no_metadata_args = SimpleNamespace(**{**vars(download_args), "no_metadata": True})
    assert resolve_files(no_metadata_args) == ["RM_006_THU.h5"]
    assert normalize_dataset_id("rm_007_mfpt") == "RM_007_MFPT"
    assert choose_smoke_dataset(REPO_ROOT) == "RM_007_MFPT"

    comma_dataset_args = SimpleNamespace(
        include_metadata=False,
        include_docs=False,
        dataset=["rm_006_thu, RM_007_MFPT", "RM_007_MFPT"],
        no_metadata=False,
        file=None,
        preset="metadata",
        yes=False,
    )
    assert resolve_files(comma_dataset_args) == ["metadata.xlsx", "RM_006_THU.h5", "RM_007_MFPT.h5"]

    comma_file_args = SimpleNamespace(
        include_metadata=False,
        include_docs=False,
        dataset=None,
        no_metadata=False,
        file=["README.md, published_manifest.json"],
        preset="metadata",
        yes=False,
    )
    assert resolve_files(comma_file_args) == ["README.md", "published_manifest.json"]

    docs_preset_args = SimpleNamespace(
        include_metadata=False,
        include_docs=False,
        dataset=None,
        no_metadata=False,
        file=None,
        preset="docs",
        yes=False,
    )
    assert resolve_files(docs_preset_args) == PUBLISHED_SMALL_FILES
    assert not any(path.endswith(".h5") for path in resolve_files(docs_preset_args))
    file_index = build_file_index()
    assert file_index["platforms"]["modelscope"]["endpoint"] == MODELSCOPE_ENDPOINT
    assert file_index["presets"]["docs"]["files"] == PUBLISHED_SMALL_FILES
    assert file_index["presets"]["all"]["requires_yes"] is True
    assert file_index["datasets"][0]["id"] == "RM_001_CWRU"
    plan = build_download_plan(
        platform="hf",
        revision=HF_REVISION,
        out_dir=REPO_ROOT / "PHM-Vibench",
        files=["metadata.xlsx", "README.md"],
        disabled_network_redirect_env_vars=["HTTP_PROXY"],
    )
    assert plan["network_request"] is False
    assert plan["dry_run"] is True
    assert plan["total_size_bytes"] == FILE_SIZES["metadata.xlsx"] + FILE_SIZES["README.md"]
    assert plan["disabled_network_redirect_env_vars"] == ["HTTP_PROXY"]
    manifest = build_manifest(include_sha256=False)
    assert manifest["platforms"]["hf"]["endpoint"] == HF_ENDPOINT
    assert manifest["presets"]["docs"]["files"] == PUBLISHED_SMALL_FILES
    assert manifest["presets"]["all"]["requires_yes"] is True
    assert manifest["datasets"][0] == {
        "id": "RM_001_CWRU",
        "path": "RM_001_CWRU.h5",
        "size_bytes": FILE_SIZES["RM_001_CWRU.h5"],
    }

    all_dry_run_args = SimpleNamespace(
        include_metadata=False,
        include_docs=False,
        dataset=None,
        no_metadata=False,
        file=None,
        preset="all",
        yes=False,
        dry_run=True,
        verify_local=False,
    )
    assert resolve_files(all_dry_run_args) == PUBLISHED_FILES

    all_download_args = SimpleNamespace(**{**vars(all_dry_run_args), "dry_run": False})
    try:
        resolve_files(all_download_args)
    except SystemExit:
        pass
    else:
        raise AssertionError("resolve_files accepted --preset all download without --yes")

    with redirect_stdout(StringIO()) as verify_ok_out:
        assert verify_local(["README.md"], REPO_ROOT)
    assert "summary: checked=1 ok=1 missing=0 size_mismatch=0" in verify_ok_out.getvalue()
    with redirect_stdout(StringIO()) as verify_missing_out:
        assert not verify_local(["README.md"], REPO_ROOT / "__missing_phm_vibench__")
    assert "summary: checked=1 ok=0 missing=1 size_mismatch=0" in verify_missing_out.getvalue()

    with redirect_stdout(StringIO()):
        fake_remote = {path: FILE_SIZES[path] for path in PUBLISHED_FILES}
        assert compare_remote_tree("fake", fake_remote)
        assert extract_modelscope_rows({"Data": [{"Path": "metadata.xlsx", "Size": "1"}]}) == [
            {"Path": "metadata.xlsx", "Size": "1"}
        ]
        assert extract_modelscope_rows({"data": {"files": [{"Path": "README.md"}]}}) == [{"Path": "README.md"}]
        assert not compare_remote_tree("fake", {**fake_remote, "README.md": None})
        assert not compare_remote_tree("fake", {**fake_remote, "metadata.xlsx": 1})
        assert not compare_remote_tree("fake", {**fake_remote, ARCHIVED_FILES[0]: FILE_SIZES["metadata.xlsx"]})
        assert not compare_remote_tree("fake", {**fake_remote, "raw/leaked.bin": 1})

    publish_args = SimpleNamespace(file=["metadata.xlsx"])
    assert selected_files(publish_args) == ["metadata.xlsx"]
    assert expand_platform_targets("ms") == ["modelscope"]
    assert expand_platform_targets("huggingface") == ["hf"]
    assert expand_platform_targets("all") == ["hf", "modelscope"]

    bad_publish_args = SimpleNamespace(file=["cache.h5"])
    try:
        selected_files(bad_publish_args)
    except SystemExit:
        pass
    else:
        raise AssertionError("publish selected_files accepted cache.h5")

    keys = list(PROXY_ENV_KEYS) + list(HF_ENDPOINT_ENV_KEYS) + ["NO_PROXY", "no_proxy"]
    saved = {key: os.environ.get(key) for key in keys}
    try:
        for key in PROXY_ENV_KEYS:
            os.environ[key] = "http://127.0.0.1:9"
        for key in HF_ENDPOINT_ENV_KEYS:
            os.environ[key] = "https://example.invalid"
        removed = enforce_no_network_redirects()
        assert "HTTP_PROXY" in removed and "HTTPS_PROXY" in removed
        assert "HF_ENDPOINT" in removed
        assert not any(os.environ.get(key) for key in PROXY_ENV_KEYS + HF_ENDPOINT_ENV_KEYS)
        assert os.environ["NO_PROXY"] == "*"
        assert os.environ["no_proxy"] == "*"
    finally:
        for key, value in saved.items():
            if value is None:
                os.environ.pop(key, None)
            else:
                os.environ[key] = value

    print(
        "self-test OK: manifest exclusions, no-proxy guard, download selection, "
        "local verify, remote compare, publish selection"
    )
    return 0


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest="cmd", required=True)

    sub.add_parser("local-check", help="Validate local published files and exclusions")
    sub.add_parser("doctor", help="Check local dependencies and no-proxy environment status")

    dry = sub.add_parser("dry-run-upload", help="Print upload/delete plan without network access")
    dry.add_argument("--platform", choices=PLATFORM_TARGET_CHOICES, default="all")

    remote = sub.add_parser("remote-verify", help="List remote files and compare them with the manifest")
    remote.add_argument("--platform", choices=PLATFORM_TARGET_CHOICES, default="all")

    manifest = sub.add_parser("manifest", help="Print or write the publish manifest")
    manifest.add_argument("--sha256", action="store_true", help="Compute SHA256 for all files; reads about 84GB locally")
    manifest.add_argument("--output", type=Path, help="Optional output JSON path")

    sub.add_parser("list-datasets", help="List dataset ids and expected sizes")
    sub.add_parser("self-test", help="Run no-network checks for manifest and guardrails")
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    if args.cmd == "local-check":
        return cmd_local_check(args)
    if args.cmd == "doctor":
        return cmd_doctor(args)
    if args.cmd == "dry-run-upload":
        return cmd_dry_run(args)
    if args.cmd == "remote-verify":
        return cmd_remote_verify(args)
    if args.cmd == "manifest":
        return cmd_manifest(args)
    if args.cmd == "list-datasets":
        return cmd_list_datasets(args)
    if args.cmd == "self-test":
        return cmd_self_test(args)
    raise AssertionError(f"unknown command: {args.cmd}")


if __name__ == "__main__":
    sys.exit(main())