generator.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. """Offline KiCad import and generated board-viewer asset pipeline."""
  2. from __future__ import annotations
  3. import json
  4. import os
  5. import platform
  6. import shutil
  7. import subprocess
  8. import tempfile
  9. import uuid
  10. import xml.etree.ElementTree as ET
  11. from collections.abc import Callable, Mapping
  12. from dataclasses import dataclass
  13. from datetime import UTC, datetime
  14. from pathlib import Path
  15. from typing import Any, Protocol
  16. from jsonschema import Draft202012Validator
  17. from .assets import sha256_file, validate_generated_assets
  18. from .data import build_board_data
  19. from .ipcd356 import IpCd356AlignmentError, validate_ipcd356_alignment
  20. from .pcb import parse_kicad_pcb
  21. from .photo import PhotoOverlayError, prepare_photo_overlay
  22. from .regression import BoardRegressionError, validate_product_regression
  23. ROOT = Path(__file__).resolve().parents[3]
  24. DATA_SCHEMA = ROOT / "schemas" / "board_viewer_data.schema.json"
  25. ANNOTATION_SCHEMA = ROOT / "schemas" / "board_viewer_annotations.schema.json"
  26. GENERATOR_VERSION = "1.1.0"
  27. GENERATOR_SOURCE_PATHS = {
  28. "generator_pipeline": Path(__file__).resolve(),
  29. "generator_data": ROOT / "tools" / "board-viewer" / "board_viewer" / "data.py",
  30. "generator_annotations": ROOT / "tools" / "board-viewer" / "board_viewer" / "annotations.py",
  31. "generator_eligibility": ROOT / "tools" / "board-viewer" / "board_viewer" / "eligibility.py",
  32. "generator_pcb": ROOT / "tools" / "board-viewer" / "board_viewer" / "pcb.py",
  33. "generator_sexpr": ROOT / "tools" / "board-viewer" / "board_viewer" / "sexpr.py",
  34. "generator_ipcd356": ROOT / "tools" / "board-viewer" / "board_viewer" / "ipcd356.py",
  35. "generator_photo": ROOT / "tools" / "board-viewer" / "board_viewer" / "photo.py",
  36. "generator_regression": ROOT / "tools" / "board-viewer" / "board_viewer" / "regression.py",
  37. "schema_data": DATA_SCHEMA,
  38. "schema_annotations": ANNOTATION_SCHEMA,
  39. }
  40. class GenerationError(RuntimeError):
  41. """Raised when a generated bundle cannot be completed and validated."""
  42. class CommandResult(Protocol):
  43. returncode: int
  44. stdout: str
  45. stderr: str
  46. Runner = Callable[[list[str], Path], CommandResult]
  47. @dataclass
  48. class GenerationConfig:
  49. brd_path: Path
  50. inventory_path: Path
  51. annotations_path: Path
  52. output_dir: Path
  53. kicad_cli: Path
  54. board_name: str
  55. required_kicad_version: str = "10.0.4"
  56. expected_counts: Mapping[str, int] | None = None
  57. expected_front_only: bool = True
  58. product_regression: bool = False
  59. photo_root: Path = ROOT
  60. temp_parent: Path | None = None
  61. def _default_runner(command: list[str], cwd: Path) -> subprocess.CompletedProcess[str]:
  62. return subprocess.run(
  63. command,
  64. cwd=cwd,
  65. check=False,
  66. capture_output=True,
  67. text=True,
  68. encoding="utf-8",
  69. errors="replace",
  70. )
  71. def _run_checked(runner: Runner, command: list[str], cwd: Path) -> CommandResult:
  72. result = runner(command, cwd)
  73. if result.returncode != 0:
  74. detail = (result.stderr or result.stdout or "command failed").strip()
  75. raise GenerationError(detail)
  76. return result
  77. def _load_json(path: Path) -> dict[str, Any]:
  78. try:
  79. payload = json.loads(path.read_text(encoding="utf-8"))
  80. except (OSError, json.JSONDecodeError) as exc:
  81. raise GenerationError(f"cannot read JSON {path}: {exc}") from exc
  82. if not isinstance(payload, dict):
  83. raise GenerationError(f"JSON root must be an object: {path}")
  84. return payload
  85. def _validate_schema(payload: object, schema_path: Path, label: str) -> None:
  86. schema = _load_json(schema_path)
  87. errors = sorted(Draft202012Validator(schema).iter_errors(payload), key=lambda item: list(item.path))
  88. if errors:
  89. locations = [".".join(str(part) for part in error.path) or "<root>" for error in errors[:5]]
  90. raise GenerationError(f"{label} schema validation failed at: {', '.join(locations)}")
  91. def _ensure_outside_repository(path: Path) -> Path:
  92. resolved = path.resolve()
  93. try:
  94. resolved.relative_to(ROOT.resolve())
  95. except ValueError:
  96. return resolved
  97. raise GenerationError("temporary directory must be outside repository")
  98. def _verify_inputs(config: GenerationConfig) -> Path:
  99. for path, label in (
  100. (config.brd_path, "BRD source"),
  101. (config.inventory_path, "pin inventory"),
  102. (config.annotations_path, "annotations"),
  103. (config.kicad_cli, "KiCad CLI"),
  104. ):
  105. if not Path(path).is_file():
  106. raise GenerationError(f"missing {label}: {path}")
  107. temp_parent = config.temp_parent or Path(tempfile.gettempdir())
  108. temp_parent = _ensure_outside_repository(Path(temp_parent))
  109. temp_parent.mkdir(parents=True, exist_ok=True)
  110. return temp_parent
  111. def _verify_kicad_version(config: GenerationConfig, runner: Runner, cwd: Path) -> str:
  112. result = _run_checked(runner, [str(config.kicad_cli), "--version"], cwd)
  113. version = result.stdout.strip().splitlines()[0] if result.stdout.strip() else "unknown"
  114. if version != config.required_kicad_version:
  115. raise GenerationError(
  116. f"board viewer generation requires KiCad {config.required_kicad_version}, found {version}"
  117. )
  118. return version
  119. def _write_json(path: Path, payload: object) -> None:
  120. path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
  121. def _normalize_svg(path: Path, title: str) -> tuple[float, float]:
  122. try:
  123. tree = ET.parse(path)
  124. except (OSError, ET.ParseError) as exc:
  125. raise GenerationError(f"invalid SVG {path.name}: {exc}") from exc
  126. root = tree.getroot()
  127. if root.tag.rsplit("}", 1)[-1] != "svg":
  128. raise GenerationError(f"invalid SVG root: {path.name}")
  129. title_element = next((item for item in root if item.tag.rsplit("}", 1)[-1] == "title"), None)
  130. if title_element is not None:
  131. title_element.text = title
  132. view_box = root.get("viewBox", "").replace(",", " ").split()
  133. if len(view_box) != 4:
  134. raise GenerationError(f"SVG has no usable viewBox: {path.name}")
  135. try:
  136. width, height = float(view_box[2]), float(view_box[3])
  137. except ValueError as exc:
  138. raise GenerationError(f"SVG has invalid viewBox: {path.name}") from exc
  139. ET.register_namespace("", "http://www.w3.org/2000/svg")
  140. ET.register_namespace("xlink", "http://www.w3.org/1999/xlink")
  141. tree.write(path, encoding="utf-8", xml_declaration=True)
  142. return width, height
  143. def _validate_counts(payload: Mapping[str, object], config: GenerationConfig) -> None:
  144. counts = payload["counts"]
  145. if not isinstance(counts, Mapping):
  146. raise GenerationError("generated board counts are missing")
  147. if config.expected_counts:
  148. mismatches = [
  149. f"{name}={counts.get(name)} expected {expected}"
  150. for name, expected in config.expected_counts.items()
  151. if counts.get(name) != expected
  152. ]
  153. if mismatches:
  154. raise GenerationError("board regression mismatch: " + ", ".join(mismatches))
  155. sides = counts.get("sides", {})
  156. if config.expected_front_only and isinstance(sides, Mapping) and sides.get("back") != 0:
  157. raise GenerationError(f"board regression mismatch: target back-side count is {sides.get('back')}")
  158. def _import_board(config: GenerationConfig, runner: Runner, work: Path) -> tuple[Path, dict[str, Any]]:
  159. imported = work / "board.kicad_pcb"
  160. report_path = work / "import-report.json"
  161. command = [
  162. str(config.kicad_cli),
  163. "pcb",
  164. "import",
  165. "--format",
  166. "auto",
  167. "--output",
  168. str(imported),
  169. "--report-format",
  170. "json",
  171. "--report-file",
  172. str(report_path),
  173. str(config.brd_path.resolve()),
  174. ]
  175. _run_checked(runner, command, work)
  176. if not imported.is_file() or not report_path.is_file():
  177. raise GenerationError("KiCad import did not create the board and report")
  178. report = _load_json(report_path)
  179. if report.get("errors"):
  180. raise GenerationError(f"KiCad import report contains errors: {report['errors']}")
  181. return imported, report
  182. SVG_LAYERS = {
  183. "board-mask-edge.svg": "F.Mask,Edge.Cuts",
  184. "board-silkscreen.svg": "F.SilkS,Edge.Cuts",
  185. "board-copper.svg": "F.Cu,Edge.Cuts",
  186. }
  187. def _export_svgs(
  188. config: GenerationConfig,
  189. runner: Runner,
  190. imported: Path,
  191. assets_dir: Path,
  192. board_data: Mapping[str, object],
  193. ) -> None:
  194. board_meta = board_data["board"]
  195. if not isinstance(board_meta, Mapping) or not isinstance(board_meta.get("view_box"), Mapping):
  196. raise GenerationError("generated board view box is missing")
  197. expected_width = float(board_meta["view_box"]["width"])
  198. expected_height = float(board_meta["view_box"]["height"])
  199. for filename, layers in SVG_LAYERS.items():
  200. output = assets_dir / filename
  201. command = [
  202. str(config.kicad_cli),
  203. "pcb",
  204. "export",
  205. "svg",
  206. "--mode-single",
  207. "--output",
  208. str(output),
  209. "--layers",
  210. layers,
  211. "--page-size-mode",
  212. "2",
  213. "--fit-page-to-board",
  214. "--exclude-drawing-sheet",
  215. str(imported),
  216. ]
  217. _run_checked(runner, command, assets_dir)
  218. if not output.is_file():
  219. raise GenerationError(f"KiCad SVG export did not create {filename}")
  220. width, height = _normalize_svg(output, f"FCB board viewer {filename}")
  221. if abs(width - expected_width) > 0.1 or abs(height - expected_height) > 0.1:
  222. raise GenerationError(
  223. f"SVG viewBox mismatch for {filename}: {width}x{height}, expected {expected_width}x{expected_height}"
  224. )
  225. def _export_and_validate_ipcd356(
  226. config: GenerationConfig,
  227. runner: Runner,
  228. imported: Path,
  229. work: Path,
  230. board_data: Mapping[str, object],
  231. ) -> dict[str, object]:
  232. output = work / "board.d356"
  233. command = [
  234. str(config.kicad_cli),
  235. "pcb",
  236. "export",
  237. "ipcd356",
  238. "--output",
  239. str(output),
  240. str(imported),
  241. ]
  242. _run_checked(runner, command, work)
  243. if not output.is_file():
  244. raise GenerationError("KiCad IPC-D-356 export did not create board.d356")
  245. try:
  246. return validate_ipcd356_alignment(board_data, output)
  247. except IpCd356AlignmentError as exc:
  248. raise GenerationError(f"IPC-D-356 cross-check failed: {exc}") from exc
  249. def _asset_metadata(path: Path) -> dict[str, object]:
  250. return {"sha256": sha256_file(path), "bytes": path.stat().st_size}
  251. def manifest_source_path(path: Path | str, repository_root: Path | str = ROOT) -> str:
  252. resolved = Path(path).resolve()
  253. repository = Path(repository_root).resolve()
  254. try:
  255. return resolved.relative_to(repository).as_posix()
  256. except ValueError:
  257. return str(resolved)
  258. def _publish_directory(source: Path, target: Path) -> None:
  259. target.parent.mkdir(parents=True, exist_ok=True)
  260. suffix = uuid.uuid4().hex
  261. staging = target.parent / f".{target.name}.stage-{suffix}"
  262. backup = target.parent / f".{target.name}.backup-{suffix}"
  263. shutil.copytree(source, staging)
  264. validate_generated_assets(staging)
  265. moved_old = False
  266. try:
  267. if target.exists():
  268. os.replace(target, backup)
  269. moved_old = True
  270. os.replace(staging, target)
  271. except Exception:
  272. if moved_old and backup.exists() and not target.exists():
  273. os.replace(backup, target)
  274. raise
  275. finally:
  276. if staging.exists():
  277. shutil.rmtree(staging)
  278. if backup.exists():
  279. shutil.rmtree(backup)
  280. def generate_assets(config: GenerationConfig, *, runner: Runner = _default_runner) -> dict[str, object]:
  281. temp_parent = _verify_inputs(config)
  282. inventory = _load_json(config.inventory_path)
  283. annotations = _load_json(config.annotations_path)
  284. _validate_schema(annotations, ANNOTATION_SCHEMA, "annotations")
  285. with tempfile.TemporaryDirectory(prefix="cpld-board-viewer-", dir=temp_parent) as temporary:
  286. work = Path(temporary)
  287. kicad_version = _verify_kicad_version(config, runner, work)
  288. imported, import_report = _import_board(config, runner, work)
  289. parsed = parse_kicad_pcb(imported)
  290. board_data = build_board_data(
  291. parsed,
  292. inventory,
  293. annotations,
  294. board_name=config.board_name,
  295. )
  296. assets_dir = work / "generated"
  297. assets_dir.mkdir()
  298. try:
  299. prepared_photo = prepare_photo_overlay(
  300. annotations.get("photo_overlay"),
  301. repository_root=config.photo_root,
  302. assets_dir=assets_dir,
  303. board_bounds=parsed.bounds,
  304. )
  305. except PhotoOverlayError as exc:
  306. raise GenerationError(f"photo overlay validation failed: {exc}") from exc
  307. board_data["photo_overlay"] = prepared_photo.data if prepared_photo else None
  308. _validate_counts(board_data, config)
  309. if config.product_regression:
  310. try:
  311. validate_product_regression(board_data)
  312. except BoardRegressionError as exc:
  313. raise GenerationError(f"product board regression failed: {exc}") from exc
  314. _validate_schema(board_data, DATA_SCHEMA, "board data")
  315. ipcd356_verification = _export_and_validate_ipcd356(
  316. config,
  317. runner,
  318. imported,
  319. work,
  320. board_data,
  321. )
  322. _write_json(assets_dir / "board-data.json", board_data)
  323. _write_json(assets_dir / "import-report.json", import_report)
  324. _export_svgs(config, runner, imported, assets_dir, board_data)
  325. asset_names = ["board-data.json", *SVG_LAYERS, "import-report.json"]
  326. if prepared_photo:
  327. asset_names.append(prepared_photo.asset_path.name)
  328. counts = board_data["counts"]
  329. sources = {
  330. "brd": {"path": manifest_source_path(config.brd_path), "sha256": sha256_file(config.brd_path)},
  331. "inventory": {
  332. "path": manifest_source_path(config.inventory_path),
  333. "sha256": sha256_file(config.inventory_path),
  334. },
  335. "annotations": {
  336. "path": manifest_source_path(config.annotations_path),
  337. "sha256": sha256_file(config.annotations_path),
  338. },
  339. **{
  340. name: {"path": manifest_source_path(path), "sha256": sha256_file(path)}
  341. for name, path in GENERATOR_SOURCE_PATHS.items()
  342. },
  343. }
  344. if prepared_photo:
  345. sources["photo"] = {
  346. "path": manifest_source_path(prepared_photo.source_path),
  347. "sha256": sha256_file(prepared_photo.source_path),
  348. }
  349. build_info = {
  350. "schema": "board-viewer-build-info-v1",
  351. "generated_at": datetime.now(UTC).isoformat().replace("+00:00", "Z"),
  352. "generator_version": GENERATOR_VERSION,
  353. "toolchain": {"python": platform.python_version(), "kicad": kicad_version},
  354. "sources": sources,
  355. "assets": {name: _asset_metadata(assets_dir / name) for name in asset_names},
  356. "verification": {"ipcd356": ipcd356_verification},
  357. "counts": {
  358. "footprints": counts["footprints"],
  359. "touchpoints": counts["touchpoints"],
  360. "pads": counts["pads"],
  361. },
  362. }
  363. _write_json(assets_dir / "build-info.json", build_info)
  364. validate_generated_assets(assets_dir)
  365. try:
  366. _publish_directory(assets_dir, config.output_dir)
  367. except OSError as exc:
  368. raise GenerationError(f"cannot publish generated assets: {exc}") from exc
  369. return {"status": "pass", "output_dir": str(config.output_dir), "build_info": build_info}