PHM-Vibench / scripts /check_publish_plan.py
Richie-17's picture
publish toolkit: scripts/check_publish_plan.py
cdb3d72 verified
Raw
History Blame Contribute Delete
23.9 kB
#!/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())