#!/usr/bin/env python3 """Build beginner-facing algorithm kits. No Go/proto/RTL/reviews inside user zips.""" from __future__ import annotations import hashlib import json import os import shutil import stat import subprocess import sys import tempfile import zipfile from datetime import datetime, timezone from pathlib import Path from package_hth_review import write_zip_file VERSION = "0.3.0" USERKIT_EXCLUDE = { ".git", "go.mod", "go.sum", ".proto", "rtl", "review", "systemd", ".brd", ".pdf", "ddr", } def _sha(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def _host() -> Path: return Path(__file__).resolve().parents[1] def _sdk() -> Path: return _host() / "sdk" / "python" def _userkit() -> Path: return _host() / "sdk" / "userkit" def _out_dir() -> Path: dest = Path(os.environ.get("HTH_PACKAGE_DIR") or os.environ.get("TEMP") or "/tmp") dest.mkdir(parents=True, exist_ok=True) return dest def _commit() -> str: return os.environ.get("HTH_GIT_COMMIT") or "unknown" def _write_sums_and_attest(zip_path: Path, kind: str, names: list[str]) -> None: digest = _sha(zip_path.read_bytes()) (zip_path.parent / (zip_path.name + ".sha256")).write_text( f"{digest} {zip_path.name}\n", encoding="utf-8" ) att = { "filename": zip_path.name, "bytes": zip_path.stat().st_size, "sha256": digest, "git_commit": _commit(), "version": VERSION, "packager": "host/tools/package_hth_user_kits.py", "kind": kind, "top_level": names, "hardware_validation": "NOT RUN", "real_actuator_validation": "NOT RUN", } (zip_path.parent / (zip_path.name + ".attestation.json")).write_text( json.dumps(att, indent=2) + "\n", encoding="utf-8" ) print(f"{zip_path}") print(f" bytes={zip_path.stat().st_size} sha256={digest}") def _add_common_docs(items: list[tuple[str, bytes, int]], prefix: str) -> None: uk = _userkit() sdk = _sdk() host = _host() def add(rel: str, data: bytes, mode: int = 0o644) -> None: items.append((f"{prefix}/{rel}", data, mode)) add("README_FIRST_zh-CN.txt", (uk / "README_FIRST_zh-CN.txt").read_bytes()) add("docs/README_10_MINUTES.md", (host / "docs" / "simple" / "README_10_MINUTES.md").read_bytes()) add("docs/ALGORITHM_API.md", (host / "docs" / "simple" / "ALGORITHM_API.md").read_bytes()) add("app/quickstart.py", (sdk / "examples" / "quickstart.py").read_bytes()) add("app/policy_template.py", (sdk / "examples" / "policy_template.py").read_bytes()) add("app/closed_loop_demo.py", (sdk / "examples" / "closed_loop_demo.py").read_bytes()) add("app/offline_replay_demo.py", (sdk / "examples" / "offline_replay_demo.py").read_bytes()) add("app/algorithm_quickstart.ipynb", (sdk / "examples" / "algorithm_quickstart.ipynb").read_bytes()) add( "sample_replay/sample.jsonl", (sdk / "hth_sdk" / "data" / "sample_replay.jsonl").read_bytes(), ) add( "scenarios/README.md", b"SIMULATION ONLY\nNOT IDENTIFIED FROM REAL HARDWARE\nNOT A PHYSICAL VALIDATION MODEL\n", ) add("logs/.keep", b"") def _zip(path: Path, items: list[tuple[str, bytes, int]]) -> list[str]: items = sorted(items, key=lambda x: x[0]) sums = [f"{_sha(data)} {name.split('/', 1)[1]}" for name, data, _ in items] items.append((f"{items[0][0].split('/', 1)[0]}/SHA256SUMS", ("\n".join(sums) + "\n").encode(), 0o644)) items.sort(key=lambda x: x[0]) with zipfile.ZipFile(path, "w") as zf: for name, data, mode in items: write_zip_file(zf, name, data, mode) return sorted({name.split("/", 1)[0] for name, _, _ in items}) def find_wheel() -> Path: env = os.environ.get("HTH_SDK_WHEEL") if env and Path(env).is_file(): return Path(env) dist = sorted((_sdk() / "dist").glob("hth_sdk-*.whl")) if (_sdk() / "dist").is_dir() else [] if dist: return dist[-1] raise SystemExit("set HTH_SDK_WHEEL or build host/sdk/python wheel first") def _script_bytes(name: str) -> bytes: data = (_userkit() / Path(name).name).read_bytes() if name.endswith(".cmd"): text = data.decode("utf-8-sig") data = text.replace("\r\n", "\n").replace("\n", "\r\n").encode("ascii", "strict") return data def _script(name: str, mode: int = 0o755) -> tuple[str, bytes, int]: return name, _script_bytes(name), mode def build_python_kit(wheel: Path, out_dir: Path) -> Path: prefix = f"hth-algorithm-python-kit-{VERSION}" items: list[tuple[str, bytes, int]] = [] _add_common_docs(items, prefix) items.append((f"{prefix}/{wheel.name}", wheel.read_bytes(), 0o644)) items.append((f"{prefix}/WHEEL.txt", (wheel.name + "\n").encode(), 0o644)) items.append((f"{prefix}/install_kit.py", (_userkit() / "install_kit.py").read_bytes(), 0o755)) for name in ( "INSTALL.cmd", "INSTALL.sh", "START_HERE.cmd", "START_HERE.sh", "RUN_DEMO.cmd", "RUN_DEMO.sh", "RUN_POLICY.cmd", "RUN_POLICY.sh", "SELF_TEST.cmd", "SELF_TEST.sh", ): mode = 0o755 if name.endswith(".sh") else 0o644 items.append((f"{prefix}/{name}", _script_bytes(name), mode)) zip_path = out_dir / f"{prefix}.zip" top = _zip(zip_path, items) _write_sums_and_attest(zip_path, "algorithm-python-kit", top) return zip_path def _copy_full_windows_python(dest: Path) -> Path: src = Path(sys.executable).resolve().parent if not (src / "python.exe").is_file(): raise SystemExit(f"cannot stage Windows Python from {src}") if dest.exists(): shutil.rmtree(dest) shutil.copytree( src, dest, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "Scripts\\pip*", "Doc", "tcl"), ) return dest def _prepare_windows_embed(cache: Path) -> Path: cached = cache / "python-embed" if (cached / "python.exe").is_file() and ((cached / "Lib" / "site-packages").is_dir() or (cached / "Lib").is_dir()): return cached zip_path = Path(os.environ.get("HTH_PYTHON_EMBED_ZIP") or "") if not zip_path.is_file(): for cand in ( cache / "python-3.12.10-embed-amd64.zip", Path(os.environ.get("TEMP") or ".") / "python-3.12.10-embed-amd64.zip", ): if cand.is_file(): zip_path = cand break if not zip_path.is_file(): url = os.environ.get( "HTH_PYTHON_EMBED_URL", "https://www.python.org/ftp/python/3.12.10/python-3.12.10-embed-amd64.zip", ) cache.mkdir(parents=True, exist_ok=True) zip_path = cache / "python-3.12.10-embed-amd64.zip" try: _download(url, zip_path) except SystemExit: return _copy_full_windows_python(cached) if cached.exists(): shutil.rmtree(cached) cached.mkdir(parents=True) with zipfile.ZipFile(zip_path) as zf: zf.extractall(cached) pth = next(cached.glob("python*._pth"), None) if pth is not None: pth.write_text("python312.zip\n.\nLib\\site-packages\nimport site\n", encoding="utf-8") get_pip = cache / "get-pip.py" if not get_pip.is_file(): try: _download("https://bootstrap.pypa.io/get-pip.py", get_pip) except SystemExit: return _copy_full_windows_python(cached) try: subprocess.check_call([str(cached / "python.exe"), str(get_pip), "--no-warn-script-location"]) except (subprocess.CalledProcessError, FileNotFoundError): return _copy_full_windows_python(cached) return cached def _download(url: str, dest: Path) -> None: dest.parent.mkdir(parents=True, exist_ok=True) try: import urllib.request with urllib.request.urlopen(url, timeout=60) as resp, dest.open("wb") as fh: shutil.copyfileobj(resp, fh) except Exception as exc: raise SystemExit(f"cannot download {url}: {exc}") from exc def build_windows_portable(wheel: Path, out_dir: Path) -> Path: cache = Path(os.environ.get("HTH_TOOL_CACHE") or os.environ.get("LOCALAPPDATA") or tempfile.gettempdir()) / "hth-build" embed = _prepare_windows_embed(cache) stage = Path(tempfile.mkdtemp(prefix="hth-win-portable-")) runtime = stage / "runtime" shutil.copytree(embed, runtime) subprocess.check_call( [ str(runtime / "python.exe"), "-m", "pip", "install", "--no-warn-script-location", "--disable-pip-version-check", str(wheel), ] ) prefix = f"hth-algorithm-portable-win64-{VERSION}" items: list[tuple[str, bytes, int]] = [] _add_common_docs(items, prefix) for name in ("START_HERE.cmd", "RUN_DEMO.cmd", "RUN_POLICY.cmd", "SELF_TEST.cmd"): items.append((f"{prefix}/{name}", _script_bytes(name), 0o644)) items.append( ( f"{prefix}/CONNECT.txt", ( "Windows 便携包只支持 HTH.demo() / HTH.mock() / HTH.replay()。\n" "HTH.connect() 会返回清晰错误,因为本包不提供真实设备连接。\n" ).encode("utf-8"), 0o644, ) ) for path in runtime.rglob("*"): if path.is_file(): rel = path.relative_to(stage).as_posix() items.append((f"{prefix}/{rel}", path.read_bytes(), 0o644)) zip_path = out_dir / f"{prefix}.zip" top = _zip(zip_path, items) _write_sums_and_attest(zip_path, "algorithm-portable-win64", top) shutil.rmtree(stage, ignore_errors=True) return zip_path def _linux_runtime_root() -> Path | None: env = os.environ.get("HTH_LINUX_PYTHON_ROOT") if env and Path(env, "bin", "python3").exists(): return Path(env) for cand in (Path("/opt/python-3.12"), Path("/opt/python-3.13"), Path("/opt/python-3.11")): if (cand / "bin" / "python3").exists(): return cand return None def _prepare_linux_standalone(cache: Path) -> Path: dest = cache / "linux-python" if (dest / "bin" / "python3").exists() or (dest / "python" / "bin" / "python3").exists(): root = dest if (dest / "bin" / "python3").exists() else dest / "python" return root url = os.environ.get( "HTH_LINUX_PYTHON_URL", "https://github.com/astral-sh/python-build-standalone/releases/download/20250409/cpython-3.12.10+20250409-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz", ) tgz = cache / "cpython-3.12.10-linux-x86_64-install_only_stripped.tar.gz" if not tgz.is_file(): _download(url, tgz) if dest.exists(): shutil.rmtree(dest) dest.mkdir(parents=True) import tarfile with tarfile.open(tgz, "r:gz") as tf: for member in tf.getmembers(): name = member.name.replace("\\", "/") if "/share/" in name or name.endswith(".exe"): continue try: tf.extract(member, dest, filter="data") except (OSError, KeyError): continue if (dest / "bin" / "python3").exists(): return dest if (dest / "python" / "bin" / "python3").exists(): return dest / "python" raise SystemExit(f"linux python layout unexpected under {dest}") def _install_pure_wheel(runtime: Path, wheel: Path) -> None: site = None for cand in runtime.glob("lib/python3.*/site-packages"): site = cand break if site is None: raise SystemExit(f"no site-packages under {runtime}") with zipfile.ZipFile(wheel) as zf: zf.extractall(site) def build_linux_portable(wheel: Path, out_dir: Path) -> Path: runtime_src = _linux_runtime_root() prefix = f"hth-algorithm-portable-linux-x86_64-{VERSION}" items: list[tuple[str, bytes, int]] = [] _add_common_docs(items, prefix) for name in ("START_HERE.sh", "RUN_DEMO.sh", "RUN_POLICY.sh", "SELF_TEST.sh"): items.append((f"{prefix}/{name}", _script_bytes(name), 0o755)) cache = Path(os.environ.get("HTH_TOOL_CACHE") or os.environ.get("LOCALAPPDATA") or tempfile.gettempdir()) / "hth-build" stage = Path(tempfile.mkdtemp(prefix="hth-linux-portable-")) runtime = stage / "runtime" if runtime_src is not None and os.name != "nt": shutil.copytree(runtime_src, runtime, symlinks=True, ignore=shutil.ignore_patterns("__pycache__")) py = runtime / "bin" / "python3" subprocess.check_call([str(py), "-m", "pip", "install", "--no-warn-script-location", str(wheel)]) else: src = _prepare_linux_standalone(cache) shutil.copytree(src, runtime, symlinks=True) _install_pure_wheel(runtime, wheel) for path in runtime.rglob("*"): if path.is_file() or path.is_symlink(): rel = path.relative_to(stage).as_posix() try: mode = path.stat().st_mode except OSError: continue perm = 0o755 if (mode & stat.S_IXUSR) or path.suffix in {".so", ""} and "bin/" in rel else 0o644 if path.name in {"python3", "python", "pip3"} or "/bin/" in rel: perm = 0o755 try: data = path.read_bytes() except OSError: continue items.append((f"{prefix}/{rel}", data, perm)) zip_path = out_dir / f"{prefix}.zip" top = _zip(zip_path, items) _write_sums_and_attest(zip_path, "algorithm-portable-linux-x86_64", top) shutil.rmtree(stage, ignore_errors=True) return zip_path def main() -> int: wheel = find_wheel() out = _out_dir() kind = os.environ.get("HTH_USER_KIT", "all") if kind in {"all", "python"}: build_python_kit(wheel, out) if kind in {"all", "win"} and os.name == "nt": build_windows_portable(wheel, out) if kind in {"all", "linux"}: build_linux_portable(wheel, out) return 0 if __name__ == "__main__": raise SystemExit(main())