package_hth_user_kits.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. #!/usr/bin/env python3
  2. """Build beginner-facing algorithm kits. No Go/proto/RTL/reviews inside user zips."""
  3. from __future__ import annotations
  4. import hashlib
  5. import json
  6. import os
  7. import shutil
  8. import stat
  9. import subprocess
  10. import sys
  11. import tempfile
  12. import zipfile
  13. from datetime import datetime, timezone
  14. from pathlib import Path, PurePosixPath
  15. from package_hth_review import write_zip_file
  16. VERSION = "0.3.0"
  17. USERKIT_EXCLUDE = {
  18. ".git",
  19. "go.mod",
  20. "go.sum",
  21. ".proto",
  22. "rtl",
  23. "review",
  24. "systemd",
  25. ".brd",
  26. ".pdf",
  27. "ddr",
  28. }
  29. def _sha(data: bytes) -> str:
  30. return hashlib.sha256(data).hexdigest()
  31. def _host() -> Path:
  32. return Path(__file__).resolve().parents[1]
  33. def _sdk() -> Path:
  34. return _host() / "sdk" / "python"
  35. def _userkit() -> Path:
  36. return _host() / "sdk" / "userkit"
  37. def _out_dir() -> Path:
  38. dest = Path(os.environ.get("HTH_PACKAGE_DIR") or os.environ.get("TEMP") or "/tmp")
  39. dest.mkdir(parents=True, exist_ok=True)
  40. return dest
  41. def _commit() -> str:
  42. return os.environ.get("HTH_GIT_COMMIT") or "unknown"
  43. def _write_sums_and_attest(zip_path: Path, kind: str, names: list[str]) -> None:
  44. digest = _sha(zip_path.read_bytes())
  45. (zip_path.parent / (zip_path.name + ".sha256")).write_text(
  46. f"{digest} {zip_path.name}\n", encoding="utf-8"
  47. )
  48. att = {
  49. "filename": zip_path.name,
  50. "bytes": zip_path.stat().st_size,
  51. "sha256": digest,
  52. "git_commit": _commit(),
  53. "version": VERSION,
  54. "packager": "host/tools/package_hth_user_kits.py",
  55. "kind": kind,
  56. "top_level": names,
  57. "hardware_validation": "NOT RUN",
  58. "real_actuator_validation": "NOT RUN",
  59. }
  60. (zip_path.parent / (zip_path.name + ".attestation.json")).write_text(
  61. json.dumps(att, indent=2) + "\n", encoding="utf-8"
  62. )
  63. print(f"{zip_path}")
  64. print(f" bytes={zip_path.stat().st_size} sha256={digest}")
  65. def _add_common_docs(items: list[tuple[str, bytes, int]], prefix: str) -> None:
  66. uk = _userkit()
  67. sdk = _sdk()
  68. host = _host()
  69. def add(rel: str, data: bytes, mode: int = 0o644) -> None:
  70. items.append((f"{prefix}/{rel}", data, mode))
  71. add("README_FIRST_zh-CN.txt", (uk / "README_FIRST_zh-CN.txt").read_bytes())
  72. add("docs/README_10_MINUTES.md", (host / "docs" / "simple" / "README_10_MINUTES.md").read_bytes())
  73. add("docs/ALGORITHM_API.md", (host / "docs" / "simple" / "ALGORITHM_API.md").read_bytes())
  74. add("app/quickstart.py", (sdk / "examples" / "quickstart.py").read_bytes())
  75. add("app/policy_template.py", (sdk / "examples" / "policy_template.py").read_bytes())
  76. add("app/closed_loop_demo.py", (sdk / "examples" / "closed_loop_demo.py").read_bytes())
  77. add("app/offline_replay_demo.py", (sdk / "examples" / "offline_replay_demo.py").read_bytes())
  78. add("app/algorithm_quickstart.ipynb", (sdk / "examples" / "algorithm_quickstart.ipynb").read_bytes())
  79. add(
  80. "sample_replay/sample.jsonl",
  81. (sdk / "hth_sdk" / "data" / "sample_replay.jsonl").read_bytes(),
  82. )
  83. add(
  84. "scenarios/README.md",
  85. b"SIMULATION ONLY\nNOT IDENTIFIED FROM REAL HARDWARE\nNOT A PHYSICAL VALIDATION MODEL\n",
  86. )
  87. add("logs/.keep", b"")
  88. def _zip(path: Path, items: list[tuple[str, bytes, int]]) -> list[str]:
  89. items = sorted(items, key=lambda x: x[0])
  90. sums = [f"{_sha(data)} {name.split('/', 1)[1]}" for name, data, _ in items]
  91. items.append((f"{items[0][0].split('/', 1)[0]}/SHA256SUMS", ("\n".join(sums) + "\n").encode(), 0o644))
  92. items.sort(key=lambda x: x[0])
  93. with zipfile.ZipFile(path, "w") as zf:
  94. for name, data, mode in items:
  95. write_zip_file(zf, name, data, mode)
  96. return sorted({name.split("/", 1)[0] for name, _, _ in items})
  97. def find_wheel() -> Path:
  98. env = os.environ.get("HTH_SDK_WHEEL")
  99. if env and Path(env).is_file():
  100. return Path(env)
  101. dist = sorted((_sdk() / "dist").glob("hth_sdk-*.whl")) if (_sdk() / "dist").is_dir() else []
  102. if dist:
  103. return dist[-1]
  104. raise SystemExit("set HTH_SDK_WHEEL or build sdk/python wheel first")
  105. def _script_bytes(name: str) -> bytes:
  106. data = (_userkit() / Path(name).name).read_bytes()
  107. if name.endswith(".cmd"):
  108. text = data.decode("utf-8-sig")
  109. data = text.replace("\r\n", "\n").replace("\n", "\r\n").encode("ascii", "strict")
  110. return data
  111. def _script(name: str, mode: int = 0o755) -> tuple[str, bytes, int]:
  112. return name, _script_bytes(name), mode
  113. def build_python_kit(wheel: Path, out_dir: Path) -> Path:
  114. prefix = f"hth-algorithm-python-kit-{VERSION}"
  115. items: list[tuple[str, bytes, int]] = []
  116. _add_common_docs(items, prefix)
  117. items.append((f"{prefix}/{wheel.name}", wheel.read_bytes(), 0o644))
  118. items.append((f"{prefix}/WHEEL.txt", (wheel.name + "\n").encode(), 0o644))
  119. items.append((f"{prefix}/install_kit.py", (_userkit() / "install_kit.py").read_bytes(), 0o755))
  120. for name in (
  121. "INSTALL.cmd",
  122. "INSTALL.sh",
  123. "START_HERE.cmd",
  124. "START_HERE.sh",
  125. "RUN_DEMO.cmd",
  126. "RUN_DEMO.sh",
  127. "RUN_POLICY.cmd",
  128. "RUN_POLICY.sh",
  129. "SELF_TEST.cmd",
  130. "SELF_TEST.sh",
  131. ):
  132. mode = 0o755 if name.endswith(".sh") else 0o644
  133. items.append((f"{prefix}/{name}", _script_bytes(name), mode))
  134. zip_path = out_dir / f"{prefix}.zip"
  135. top = _zip(zip_path, items)
  136. _write_sums_and_attest(zip_path, "algorithm-python-kit", top)
  137. return zip_path
  138. def _copy_full_windows_python(dest: Path) -> Path:
  139. src = Path(sys.executable).resolve().parent
  140. if not (src / "python.exe").is_file():
  141. raise SystemExit(f"cannot stage Windows Python from {src}")
  142. if dest.exists():
  143. shutil.rmtree(dest)
  144. shutil.copytree(
  145. src,
  146. dest,
  147. ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "Scripts\\pip*", "Doc", "tcl"),
  148. )
  149. return dest
  150. def _prepare_windows_embed(cache: Path) -> Path:
  151. cached = cache / "python-embed"
  152. if (cached / "python.exe").is_file() and ((cached / "Lib" / "site-packages").is_dir() or (cached / "Lib").is_dir()):
  153. return cached
  154. zip_path = Path(os.environ.get("HTH_PYTHON_EMBED_ZIP") or "")
  155. if not zip_path.is_file():
  156. for cand in (
  157. cache / "python-3.12.10-embed-amd64.zip",
  158. Path(os.environ.get("TEMP") or ".") / "python-3.12.10-embed-amd64.zip",
  159. ):
  160. if cand.is_file():
  161. zip_path = cand
  162. break
  163. if not zip_path.is_file():
  164. url = os.environ.get(
  165. "HTH_PYTHON_EMBED_URL",
  166. "https://www.python.org/ftp/python/3.12.10/python-3.12.10-embed-amd64.zip",
  167. )
  168. cache.mkdir(parents=True, exist_ok=True)
  169. zip_path = cache / "python-3.12.10-embed-amd64.zip"
  170. try:
  171. _download(url, zip_path)
  172. except SystemExit:
  173. return _copy_full_windows_python(cached)
  174. if cached.exists():
  175. shutil.rmtree(cached)
  176. cached.mkdir(parents=True)
  177. with zipfile.ZipFile(zip_path) as zf:
  178. zf.extractall(cached)
  179. pth = next(cached.glob("python*._pth"), None)
  180. if pth is not None:
  181. pth.write_text("python312.zip\n.\nLib\\site-packages\nimport site\n", encoding="utf-8")
  182. get_pip = cache / "get-pip.py"
  183. if not get_pip.is_file():
  184. try:
  185. _download("https://bootstrap.pypa.io/get-pip.py", get_pip)
  186. except SystemExit:
  187. return _copy_full_windows_python(cached)
  188. try:
  189. subprocess.check_call([str(cached / "python.exe"), str(get_pip), "--no-warn-script-location"])
  190. except (subprocess.CalledProcessError, FileNotFoundError):
  191. return _copy_full_windows_python(cached)
  192. return cached
  193. def _download(url: str, dest: Path) -> None:
  194. dest.parent.mkdir(parents=True, exist_ok=True)
  195. try:
  196. import urllib.request
  197. with urllib.request.urlopen(url, timeout=60) as resp, dest.open("wb") as fh:
  198. shutil.copyfileobj(resp, fh)
  199. except Exception as exc:
  200. raise SystemExit(f"cannot download {url}: {exc}") from exc
  201. def build_windows_portable(wheel: Path, out_dir: Path) -> Path:
  202. cache = Path(os.environ.get("HTH_TOOL_CACHE") or os.environ.get("LOCALAPPDATA") or tempfile.gettempdir()) / "hth-build"
  203. embed = _prepare_windows_embed(cache)
  204. stage = Path(tempfile.mkdtemp(prefix="hth-win-portable-"))
  205. runtime = stage / "runtime"
  206. shutil.copytree(embed, runtime)
  207. subprocess.check_call(
  208. [
  209. str(runtime / "python.exe"),
  210. "-m",
  211. "pip",
  212. "install",
  213. "--no-warn-script-location",
  214. "--disable-pip-version-check",
  215. str(wheel),
  216. ]
  217. )
  218. prefix = f"hth-algorithm-portable-win64-{VERSION}"
  219. items: list[tuple[str, bytes, int]] = []
  220. _add_common_docs(items, prefix)
  221. for name in ("START_HERE.cmd", "RUN_DEMO.cmd", "RUN_POLICY.cmd", "SELF_TEST.cmd"):
  222. items.append((f"{prefix}/{name}", _script_bytes(name), 0o644))
  223. items.append(
  224. (
  225. f"{prefix}/CONNECT.txt",
  226. (
  227. "Windows 便携包只支持 HTH.demo() / HTH.mock() / HTH.replay()。\n"
  228. "HTH.connect() 会返回清晰错误,因为本包不提供真实设备连接。\n"
  229. ).encode("utf-8"),
  230. 0o644,
  231. )
  232. )
  233. for path in runtime.rglob("*"):
  234. if path.is_file():
  235. rel = path.relative_to(stage).as_posix()
  236. items.append((f"{prefix}/{rel}", path.read_bytes(), 0o644))
  237. zip_path = out_dir / f"{prefix}.zip"
  238. top = _zip(zip_path, items)
  239. _write_sums_and_attest(zip_path, "algorithm-portable-win64", top)
  240. shutil.rmtree(stage, ignore_errors=True)
  241. return zip_path
  242. def _linux_runtime_root() -> Path | None:
  243. env = os.environ.get("HTH_LINUX_PYTHON_ROOT")
  244. if env and Path(env, "bin", "python3").exists():
  245. return Path(env)
  246. for cand in (Path("/opt/python-3.12"), Path("/opt/python-3.13"), Path("/opt/python-3.11")):
  247. if (cand / "bin" / "python3").exists():
  248. return cand
  249. return None
  250. def _safe_tar_member(member: object) -> bool:
  251. """Python 3.11 fallback for tarfile's 3.12 ``filter='data'`` policy."""
  252. name = PurePosixPath(str(getattr(member, "name", "")).replace("\\", "/"))
  253. if not name.parts or name.is_absolute() or ".." in name.parts:
  254. return False
  255. if any(bool(getattr(member, probe)()) for probe in ("isdev", "isfifo")):
  256. return False
  257. if bool(getattr(member, "issym")()) or bool(getattr(member, "islnk")()):
  258. target = PurePosixPath(str(getattr(member, "linkname", "")).replace("\\", "/"))
  259. if not target.parts or target.is_absolute() or ".." in target.parts:
  260. return False
  261. return True
  262. def _prepare_linux_standalone(cache: Path) -> Path:
  263. dest = cache / "linux-python"
  264. if (dest / "bin" / "python3").exists() or (dest / "python" / "bin" / "python3").exists():
  265. root = dest if (dest / "bin" / "python3").exists() else dest / "python"
  266. return root
  267. url = os.environ.get(
  268. "HTH_LINUX_PYTHON_URL",
  269. "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",
  270. )
  271. tgz = cache / "cpython-3.12.10-linux-x86_64-install_only_stripped.tar.gz"
  272. if not tgz.is_file():
  273. _download(url, tgz)
  274. if dest.exists():
  275. shutil.rmtree(dest)
  276. dest.mkdir(parents=True)
  277. import tarfile
  278. with tarfile.open(tgz, "r:gz") as tf:
  279. for member in tf.getmembers():
  280. name = member.name.replace("\\", "/")
  281. if "/share/" in name or name.endswith(".exe"):
  282. continue
  283. try:
  284. if sys.version_info >= (3, 12):
  285. tf.extract(member, dest, filter="data")
  286. elif _safe_tar_member(member):
  287. tf.extract(member, dest)
  288. except (OSError, KeyError):
  289. continue
  290. if (dest / "bin" / "python3").exists():
  291. return dest
  292. if (dest / "python" / "bin" / "python3").exists():
  293. return dest / "python"
  294. raise SystemExit(f"linux python layout unexpected under {dest}")
  295. def _install_pure_wheel(runtime: Path, wheel: Path) -> None:
  296. site = None
  297. for cand in runtime.glob("lib/python3.*/site-packages"):
  298. site = cand
  299. break
  300. if site is None:
  301. raise SystemExit(f"no site-packages under {runtime}")
  302. with zipfile.ZipFile(wheel) as zf:
  303. zf.extractall(site)
  304. def build_linux_portable(wheel: Path, out_dir: Path) -> Path:
  305. runtime_src = _linux_runtime_root()
  306. prefix = f"hth-algorithm-portable-linux-x86_64-{VERSION}"
  307. items: list[tuple[str, bytes, int]] = []
  308. _add_common_docs(items, prefix)
  309. for name in ("START_HERE.sh", "RUN_DEMO.sh", "RUN_POLICY.sh", "SELF_TEST.sh"):
  310. items.append((f"{prefix}/{name}", _script_bytes(name), 0o755))
  311. cache = Path(os.environ.get("HTH_TOOL_CACHE") or os.environ.get("LOCALAPPDATA") or tempfile.gettempdir()) / "hth-build"
  312. stage = Path(tempfile.mkdtemp(prefix="hth-linux-portable-"))
  313. runtime = stage / "runtime"
  314. if runtime_src is not None and os.name != "nt":
  315. shutil.copytree(runtime_src, runtime, symlinks=True, ignore=shutil.ignore_patterns("__pycache__"))
  316. py = runtime / "bin" / "python3"
  317. subprocess.check_call([str(py), "-m", "pip", "install", "--no-warn-script-location", str(wheel)])
  318. else:
  319. src = _prepare_linux_standalone(cache)
  320. shutil.copytree(src, runtime, symlinks=True)
  321. _install_pure_wheel(runtime, wheel)
  322. for path in runtime.rglob("*"):
  323. if path.is_file() or path.is_symlink():
  324. rel = path.relative_to(stage).as_posix()
  325. try:
  326. mode = path.stat().st_mode
  327. except OSError:
  328. continue
  329. perm = 0o755 if (mode & stat.S_IXUSR) or path.suffix in {".so", ""} and "bin/" in rel else 0o644
  330. if path.name in {"python3", "python", "pip3"} or "/bin/" in rel:
  331. perm = 0o755
  332. try:
  333. data = path.read_bytes()
  334. except OSError:
  335. continue
  336. items.append((f"{prefix}/{rel}", data, perm))
  337. zip_path = out_dir / f"{prefix}.zip"
  338. top = _zip(zip_path, items)
  339. _write_sums_and_attest(zip_path, "algorithm-portable-linux-x86_64", top)
  340. shutil.rmtree(stage, ignore_errors=True)
  341. return zip_path
  342. def main() -> int:
  343. wheel = find_wheel()
  344. out = _out_dir()
  345. kind = os.environ.get("HTH_USER_KIT", "all")
  346. if kind in {"all", "python"}:
  347. build_python_kit(wheel, out)
  348. if kind in {"all", "win"} and os.name == "nt":
  349. build_windows_portable(wheel, out)
  350. if kind in {"all", "linux"}:
  351. build_linux_portable(wheel, out)
  352. return 0
  353. if __name__ == "__main__":
  354. raise SystemExit(main())