check_configs.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. """校验 configs/*.json 能被加载、与 DEFAULTS 正确深合并(打包/上线前自检)。
  2. 用法:
  3. python scripts/check_configs.py [configs/*.json 或目录 ...]
  4. 退出码:0 全部通过;1 有问题(打印到标准错误),可直接用于 CI 或发布前门禁。
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import glob
  9. import os
  10. import sys
  11. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  12. from portcv.config import DEFAULTS, load_config # noqa: E402
  13. from portcv.plc.registers import addresses # noqa: E402
  14. def check_one(path: str) -> str:
  15. """检查单个配置文件,返回一行摘要;不通过时抛 ``AssertionError``。"""
  16. cfg = load_config(path)
  17. addr = addresses(cfg)
  18. # ``demo-*.json`` 是**第三方权重(COCO YOLOv8n,80 类)的数值冒烟配置**:只用来看
  19. # 「转换出来的 .rknn 算得对不对」,不参与本项目的 4 类契约,所以跳过类别相关断言;
  20. # 其余配置(现场模板 / 台架 / C++)仍然严格校验。
  21. is_demo = os.path.basename(path).startswith("demo-")
  22. # 1) 所有默认段都必须存在(深合并不会丢段)
  23. missing = [key for key in DEFAULTS if key not in cfg.data]
  24. assert not missing, "缺少配置段: %s" % missing
  25. # 2) 关键契约:4 个类别、12 字结果寄存器、4 字指令寄存器、方阵输入
  26. if not is_demo:
  27. assert len(cfg.labels) == 4, "model.labels 必须是 4 类(container/bed/flatbed/not_on_train)"
  28. assert int(addr["input_count"]) == 12, "结果寄存器应为 12 字"
  29. assert int(addr["holding_count"]) == 4, "指令寄存器应为 4 字"
  30. width, height = cfg.input_size
  31. assert width > 0 and height > 0 and width % 32 == 0, "model.input_size 必须为正且 32 对齐"
  32. # 3) 没写到的字段必须仍是默认值(防止"手抄模板"覆盖掉默认值)
  33. assert cfg.get_path("decision.min_votes") == DEFAULTS["decision"]["min_votes"], "未覆盖项被意外改写"
  34. if not is_demo:
  35. assert cfg.get_path("model.labels") == DEFAULTS["model"]["labels"], "类别顺序被意外改写"
  36. # 4) 后端与所需模型路径要配套
  37. backend = str(cfg.get_path("run.backend", "mock"))
  38. key = {"tensorrt": "model.engine_path", "rknn": "model.rknn_path"}.get(backend, "model.path")
  39. assert cfg.get_path(key), "backend=%s 需要 %s" % (backend, key)
  40. if backend == "rknn":
  41. assert str(cfg.get_path("model.input_format")) in ("rgb_uint8", "bgr_uint8"), \
  42. "RKNN INT8 通常需要 *_uint8 输入格式"
  43. return (
  44. "%-24s backend=%-9s source=%-6s in=%s regs=%d+%d plc=%s:%d unit=%d fps=%.1f%s"
  45. % (
  46. os.path.basename(path),
  47. backend,
  48. str(cfg.get_path("source.type")),
  49. cfg.input_size,
  50. int(addr["input_count"]),
  51. int(addr["holding_count"]),
  52. addr["host"],
  53. int(addr["port"]),
  54. int(addr["unit_id"]),
  55. float(cfg.get_path("run.max_fps", 0.0) or 0.0),
  56. " (demo:跳过 4 类契约)" if is_demo else "",
  57. )
  58. )
  59. def main(argv=None) -> int:
  60. parser = argparse.ArgumentParser(description="校验 configs/*.json")
  61. parser.add_argument("paths", nargs="*", default=None, help="配置文件或目录(默认 configs/*.json)")
  62. args = parser.parse_args(argv)
  63. targets = []
  64. for item in args.paths or [os.path.join("configs", "*.json")]:
  65. if os.path.isdir(item): # 传目录 → 取目录下的 *.json
  66. targets.extend(sorted(glob.glob(os.path.join(item, "*.json"))))
  67. elif "*" in item:
  68. targets.extend(sorted(glob.glob(item)))
  69. else:
  70. targets.append(item)
  71. if not targets:
  72. print("没有找到任何配置文件", file=sys.stderr)
  73. return 1
  74. failures = 0
  75. for path in targets:
  76. try:
  77. print(check_one(path))
  78. except Exception as exc: # config 错误一律报告而不是中断,便于一次看完
  79. failures += 1
  80. print("FAIL %s: %s" % (path, exc), file=sys.stderr)
  81. if failures:
  82. print("%d/%d 个配置有问题" % (failures, len(targets)), file=sys.stderr)
  83. return 1
  84. print("全部通过:%d 个配置文件。" % len(targets))
  85. return 0
  86. if __name__ == "__main__":
  87. raise SystemExit(main())