sync_package.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 技能包同步打包工具
  5. ==================
  6. 一条命令完成:拉最新规则 → 核验工具包 → 重建参考文档 → 更新版本 → 打 zip。
  7. 用法:
  8. python3 scripts/sync_package.py # 同步并打包到 ../dist
  9. python3 scripts/sync_package.py --out ~/dist # 指定输出目录
  10. python3 scripts/sync_package.py --check-only # 只检查,不打包(核验通过后仍会更新随包基线并重建参考表,只是不升版本、不打 zip)
  11. python3 scripts/sync_package.py --no-bump # 打包但不升版本号
  12. python3 scripts/sync_package.py --no-bump --with-credentials
  13. # 另打一个带根目录 credentials.json 的包,只用于上传托管沙箱
  14. 技能包根目录的 credentials.json 默认不进包,避免凭证随分发包外流。
  15. 规则是否变更以随包基线 references/doc-snapshot.txt 为准(不是本地快照);基线只在核验与自检都通过后才更新,
  16. 核验失败后再次运行仍会报告规则有变更。手工维护的 rules.md / known-gaps.md / mcp-mode.md 不在机器核验范围,
  17. 规则变更时须人工确认。
  18. 规则有变更时脚本会:
  19. 1. 打印变更行(新增/删除)
  20. 2. 把规则快照写进 references/doc-snapshot.txt(随包分发,离线可用)
  21. 3. 在 references/rules.md 顶部写入快照指纹与时间
  22. 4. 仍会完成打包,但退出码为 1,提示你人工确认判定表是否要跟着改;
  23. 规则用到系统提示时,还要人工同步 references/mcp-mode.md 的问题落点表(本脚本不重写该文件)
  24. 退出码:
  25. 0 = 一致,已打包
  26. 1 = 规则有变更或工具包有偏差(已打包,但需人工确认)
  27. 2 = 执行错误
  28. """
  29. import argparse
  30. import hashlib
  31. import json
  32. import os
  33. import re
  34. import sys
  35. import zipfile
  36. from datetime import datetime
  37. try:
  38. import requests
  39. import openpyxl
  40. except ImportError as e:
  41. print(f"缺少依赖:{e.name},请执行 pip3 install requests openpyxl", file=sys.stderr)
  42. sys.exit(2)
  43. HERE = os.path.dirname(os.path.abspath(__file__))
  44. SKILL_DIR = os.path.dirname(HERE)
  45. REF_DIR = os.path.join(SKILL_DIR, "references")
  46. ASSET_DIR = os.path.join(SKILL_DIR, "assets")
  47. HOME_DIR = os.path.expanduser("~/.sku_audit")
  48. SNAP_DIR = os.path.join(HOME_DIR, "snapshots")
  49. BASE = "https://open.feishu.cn/open-apis"
  50. DEFAULT_DOC = "SFQjdsMoRoxPjsx4wGhc95uxnEc"
  51. sys.path.insert(0, HERE)
  52. import rule_check # noqa: E402 比对口径与 rule_check 共用一份实现
  53. import feishu_credentials # noqa: E402
  54. def die(msg, code=2):
  55. print(f"[错误] {msg}", file=sys.stderr)
  56. sys.exit(code)
  57. def load_credentials():
  58. return feishu_credentials.load() or die(feishu_credentials.missing_message())
  59. def get_token(a, s):
  60. r = requests.post(f"{BASE}/auth/v3/tenant_access_token/internal",
  61. json={"app_id": a, "app_secret": s}, timeout=20).json()
  62. if r.get("code") != 0:
  63. die(f"获取 token 失败:{r.get('code')} {r.get('msg')}")
  64. return r["tenant_access_token"]
  65. def fetch_doc(doc_id, token):
  66. r = requests.get(f"{BASE}/docx/v1/documents/{doc_id}/raw_content",
  67. headers={"Authorization": "Bearer " + token}, timeout=30).json()
  68. if r.get("code") != 0:
  69. die(f"拉取文档失败:{r.get('code')} {r.get('msg')}")
  70. return (r.get("data") or {}).get("content", "")
  71. def baseline_changes(doc_text, quiet=False):
  72. """以随包同步基线 references/doc-snapshot.txt 判定规则是否已同步。
  73. 不用本地快照判定:本地快照每次拉取都会写入,一次核验失败的同步之后,
  74. 下次运行会把「未同步」误报成「规则未变动」。
  75. 返回 (changed, diff);包内没有基线时视为有变更。
  76. """
  77. seed = os.path.join(REF_DIR, "doc-snapshot.txt")
  78. if not os.path.exists(seed):
  79. if not quiet:
  80. print(" 技能包缺少同步基线 references/doc-snapshot.txt,按规则有变更处理")
  81. return True, []
  82. old = open(seed, encoding="utf-8").read()
  83. if rule_check.normalize(old) == rule_check.normalize(doc_text):
  84. if not quiet:
  85. print(" 与技能包同步基线一致,规则未变动")
  86. return False, []
  87. return True, rule_check.print_diffs(" 与技能包同步基线相比", old, doc_text, quiet)
  88. def find_toolbox():
  89. if not os.path.isdir(ASSET_DIR):
  90. die(f"找不到 assets 目录:{ASSET_DIR}")
  91. xs = [f for f in os.listdir(ASSET_DIR) if f.endswith(".xlsx") and not f.startswith("~$")]
  92. if not xs:
  93. die("assets 目录里没有 xlsx 工具包")
  94. xs.sort(key=lambda f: os.path.getmtime(os.path.join(ASSET_DIR, f)), reverse=True)
  95. return os.path.join(ASSET_DIR, xs[0])
  96. def table_md(rows, head):
  97. out = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
  98. for r in rows:
  99. out.append("| " + " | ".join("" if v is None else str(v).replace("|", "/") for v in r) + " |")
  100. return "\n".join(out)
  101. def export_references(toolbox):
  102. """从工具包重建 references 里的表格类文档"""
  103. wb = openpyxl.load_workbook(toolbox, data_only=True)
  104. written = []
  105. def get(prefix):
  106. for name in wb.sheetnames:
  107. if name.startswith(prefix):
  108. return wb[name]
  109. return None
  110. ws = get("02")
  111. if ws:
  112. rows = [r[:6] for r in ws.iter_rows(min_row=2, values_only=True) if r[1]]
  113. md = ["# 审核判定表(%d 项)" % len(rows), "",
  114. "> 由工具包 `02-审核判定表` 自动导出,请改工具包后重新同步,勿手工维护。", "",
  115. table_md(rows, ["#", "检查项", "判定条件", "结论", "话术模板", "规则"])]
  116. open(os.path.join(REF_DIR, "checklist.md"), "w", encoding="utf-8").write("\n".join(md))
  117. written.append(("checklist.md", len(rows)))
  118. ws = get("03")
  119. if ws:
  120. rows = [r[:5] for r in ws.iter_rows(min_row=2, values_only=True) if r[0] and r[1]]
  121. md = ["# 材质词典", "",
  122. table_md(rows, ["分类", "中文", "英文", "处理", "说明"])]
  123. open(os.path.join(REF_DIR, "material-dict.md"), "w", encoding="utf-8").write("\n".join(md))
  124. written.append(("material-dict.md", len(rows)))
  125. ws = get("04")
  126. if ws:
  127. rows = [r[:7] for r in ws.iter_rows(min_row=2, values_only=True) if r[0] and r[1]]
  128. md = ["# 认证触发词表", "",
  129. "> 只有「玩具认证(CPSC/CPC)」需审核 PDF 内容,且须同时提供 CPC 证书和第三方测试报告;其余认证文件只核是否上传,不审内容。", "",
  130. table_md(rows, ["场景", "类别", "中文关键词", "英文关键词", "需上传文件", "需审核内容", "结论 / 处理"])]
  131. open(os.path.join(REF_DIR, "cert-triggers.md"), "w", encoding="utf-8").write("\n".join(md))
  132. written.append(("cert-triggers.md", len(rows)))
  133. ws = get("05")
  134. if ws:
  135. rows = [r[:6] for r in ws.iter_rows(min_row=2, values_only=True)
  136. if r[0] and str(r[0]).isdigit()]
  137. md = ["# 应付清关编码映射", "",
  138. table_md(rows, ["#", "应收品名类别", "应付中文品名", "应付英文品名", "应付编码", "备注"]),
  139. "", "**注意**:清单口径与实际 HTS 归类存在冲突(灯类/玩具类/塑料柜类),详见 `known-gaps.md`。"]
  140. open(os.path.join(REF_DIR, "pay-code-map.md"), "w", encoding="utf-8").write("\n".join(md))
  141. written.append(("pay-code-map.md", len(rows)))
  142. ws = get("06")
  143. if ws:
  144. rows = [r[:7] for r in ws.iter_rows(min_row=2, values_only=True)
  145. if r[1] and re.match(r"^\d{4}\.\d{2}\.\d{4}$", str(r[1]))]
  146. md = ["# 单价限制清单(%d 个受限编码)" % len(rows), "",
  147. table_md(rows, ["#", "编码", "品类(推断,待确认)", "限制条件原文", "解析区间 USD/件", "判断动作", "问题标记"])]
  148. open(os.path.join(REF_DIR, "price-limits.md"), "w", encoding="utf-8").write("\n".join(md))
  149. written.append(("price-limits.md", len(rows)))
  150. return written
  151. def stamp_rules_md(doc_text, doc_id):
  152. """在 rules.md 顶部写入快照指纹"""
  153. p = os.path.join(REF_DIR, "rules.md")
  154. if not os.path.exists(p):
  155. return None
  156. txt = open(p, encoding="utf-8").read()
  157. fp = hashlib.sha1(rule_check.normalize(doc_text).encode("utf-8")).hexdigest()[:12]
  158. head = (f"> 规则快照:{datetime.now():%Y-%m-%d %H:%M} 指纹 `{fp}` "
  159. f"字符数 {len(doc_text)} 来源 docx `{doc_id}`\n"
  160. f">\n"
  161. f"> 本文是速查版,字段级细节以 `checklist.md` 为准。规则有变先跑 `scripts/rule_check.py fetch`。\n")
  162. # 去掉旧头部块(从 "> 规则快照" 或 "> 来源:" 开始连续以 > 开头的行)
  163. lines = txt.split("\n")
  164. if lines and lines[0].startswith("# "):
  165. title = lines[0]
  166. i = 1
  167. while i < len(lines) and (lines[i].strip() == "" or lines[i].startswith(">")):
  168. i += 1
  169. rest = "\n".join(lines[i:])
  170. new = title + "\n\n" + head + "\n" + rest
  171. else:
  172. new = head + "\n" + txt
  173. open(p, "w", encoding="utf-8").write(new)
  174. return fp
  175. def write_verify_report(results, toolbox, doc_fp):
  176. p = os.path.join(REF_DIR, "verification-report.md")
  177. ok = sum(1 for r in results if r[2] == "✅")
  178. warn = sum(1 for r in results if r[2] == "⚠️")
  179. bad = sum(1 for r in results if r[2] == "❌")
  180. md = [f"# 核验报告", "",
  181. f"- 生成时间:{datetime.now():%Y-%m-%d %H:%M}",
  182. f"- 工具包:`{os.path.basename(toolbox)}`",
  183. f"- 规则指纹:`{doc_fp}`",
  184. f"- 结论:✅ {ok} | ⚠️ {warn} | ❌ {bad}", "",
  185. table_md(results, ["类别", "检查项", "状态", "说明"])]
  186. open(p, "w", encoding="utf-8").write("\n".join(md))
  187. return ok, warn, bad
  188. def bump_version(skill_dir, bump=True):
  189. p = os.path.join(skill_dir, "VERSION")
  190. cur = open(p, encoding="utf-8").read().strip() if os.path.exists(p) else "1.0"
  191. if bump:
  192. try:
  193. major, minor = cur.split(".")
  194. cur = f"{major}.{int(minor) + 1}"
  195. except ValueError:
  196. cur = "1.1"
  197. open(p, "w", encoding="utf-8").write(cur + "\n")
  198. return cur
  199. def update_install_note(skill_dir, ver, nfiles, doc_fp):
  200. p = os.path.join(skill_dir, "安装说明.md")
  201. if not os.path.exists(p):
  202. return
  203. txt = open(p, encoding="utf-8").read()
  204. block = (f"## 版本\n\n"
  205. f"- 技能包 v{ver}(打包于 {datetime.now():%Y-%m-%d %H:%M})\n"
  206. f"- 规则快照指纹 `{doc_fp}`,随包附带 `references/doc-snapshot.txt`\n"
  207. f"- 含 {nfiles} 个文件\n")
  208. if "## 版本" in txt:
  209. txt = re.sub(r"## 版本[\s\S]*$", block, txt)
  210. else:
  211. txt = txt.rstrip() + "\n\n" + block
  212. open(p, "w", encoding="utf-8").write(txt)
  213. def audit_selfcheck():
  214. """审核脚本自检:确认 audit.py 能从工具包正确读到判定参数
  215. 这一步是「规则改了 → 审核脚本自动跟上」的保障:
  216. audit.py 的阈值与词表全部读自工具包,只要这里能读通,
  217. 说明脚本与当前工具包是配套的;读不到会直接退出,不会带着旧口径去审核。
  218. """
  219. p = os.path.join(HERE, "audit.py")
  220. if not os.path.exists(p):
  221. die("scripts/audit.py 缺失,审核脚本未随包。请恢复后再同步,否则分发包无法执行审核")
  222. sys.path.insert(0, HERE)
  223. import audit as A
  224. wbp = A.pick_workbook()
  225. if not wbp:
  226. die("audit.py 在 assets 下找不到工具包 xlsx")
  227. kit = A.Kit(wbp) # 参数缺失会 SystemExit,阻断打包
  228. execution = A.execution_selfcheck(kit)
  229. if execution["missing"]:
  230. die("审核执行覆盖缺项:" + "、".join(execution["missing"]) + ";规则已同步但执行器未完整落地,禁止打包")
  231. ok, need, ban = kit.material_sets()
  232. tcn, ten = kit.toy_keywords()
  233. return {
  234. "toolbox": A.kit_path.display_name(wbp),
  235. "fz06": kit.fz06_px(),
  236. "items": len([r for r in kit.check_items[1:] if r and r[0]]),
  237. "material": (len(ok), len(need), len(ban)),
  238. "toy": (len(tcn), len(ten)),
  239. "paymap": len(kit.paymap_rows()),
  240. "limits": len(kit.price_limits()),
  241. "generic": len(kit.generic_words()),
  242. "execution": execution,
  243. }
  244. def make_zip(skill_dir, out_dir, ver, with_credentials=False):
  245. """打 zip。根目录 credentials.json 默认不进包;with_credentials 仅用于上传托管沙箱的包。"""
  246. secret_file = os.path.join(skill_dir, feishu_credentials.FILE_NAME)
  247. if with_credentials and not feishu_credentials.read_file(secret_file):
  248. die(f"--with-credentials 需要技能包根目录有可用的 {feishu_credentials.FILE_NAME}"
  249. "(含 app_id 与 app_secret)")
  250. os.makedirs(out_dir, exist_ok=True)
  251. name = f"SKU审核专员-技能包_v{ver}{'-含凭证' if with_credentials else ''}.zip"
  252. path = os.path.join(out_dir, name)
  253. if os.path.exists(path):
  254. os.remove(path)
  255. base = os.path.dirname(skill_dir)
  256. with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
  257. for root, dirs, files in os.walk(skill_dir):
  258. dirs[:] = [d for d in dirs if d not in ("__pycache__", ".git")]
  259. for f in files:
  260. if f.endswith((".pyc", ".DS_Store")) or f.startswith("~$"):
  261. continue
  262. full = os.path.join(root, f)
  263. if not with_credentials and os.path.abspath(full) == os.path.abspath(secret_file):
  264. continue
  265. rel = os.path.relpath(full, base)
  266. z.write(full, rel)
  267. # 确认审核脚本真的进包了(分发包没有 audit.py 就跑不了审核)
  268. with zipfile.ZipFile(path) as z:
  269. names = z.namelist()
  270. if not any(n.endswith("scripts/audit.py") for n in names):
  271. os.remove(path)
  272. die("打包结果缺少 scripts/audit.py,已中止;请检查 scripts 目录")
  273. return path
  274. def main():
  275. ap = argparse.ArgumentParser(description="技能包同步打包")
  276. ap.add_argument("--doc", default=DEFAULT_DOC)
  277. ap.add_argument("--out", default=os.path.join(os.path.dirname(SKILL_DIR), "dist"))
  278. ap.add_argument("--check-only", action="store_true")
  279. ap.add_argument("--no-bump", action="store_true")
  280. ap.add_argument("--with-credentials", action="store_true",
  281. help="把技能包根目录的 credentials.json 一并打包(仅用于上传托管沙箱,不得外发)")
  282. args = ap.parse_args()
  283. doc_id = args.doc
  284. m = re.search(r"/docx/([A-Za-z0-9]+)", doc_id)
  285. if m:
  286. doc_id = m.group(1)
  287. print("=" * 60)
  288. print("SKU 审核技能包 · 同步打包")
  289. print("=" * 60)
  290. # 1. 拉规则
  291. a, s = load_credentials()
  292. token = get_token(a, s)
  293. doc_text = fetch_doc(doc_id, token)
  294. print(f"\n[1/7] 规则文档已拉取:{len(doc_text)} 字符")
  295. # 2. 与随包同步基线比对(本地快照只做留档)
  296. os.makedirs(SNAP_DIR, exist_ok=True)
  297. changed, diff = baseline_changes(doc_text)
  298. ts = datetime.now().strftime("%Y%m%d_%H%M%S")
  299. open(os.path.join(SNAP_DIR, f"doc_{ts}.txt"), "w", encoding="utf-8").write(doc_text)
  300. print(f" 本地快照已保存;随包基线 references/doc-snapshot.txt 待核验与自检通过后再更新")
  301. # 3. 核验工具包
  302. toolbox = find_toolbox()
  303. v = rule_check.cmd_verify(doc_text, toolbox, None, quiet=True)
  304. print(f"\n[2/7] 工具包核验:✅ {v['ok']} | ⚠️ {v['warn']} | ❌ {v['bad']}")
  305. if v["bad"]:
  306. die("规则文档与工具包存在未裁决口径或同步偏差;先确认文档问题并更新工具包,禁止重建参考文档和打包")
  307. # 3. 审核脚本自检(audit.py 参数必须与工具包配套)
  308. sc = audit_selfcheck()
  309. print(f"\n[3/7] 审核脚本自检:audit.py ↔ {sc['toolbox']}")
  310. print(f" 判定项 {sc['items']} 条 | FZ-06 阈值 {sc['fz06']}px")
  311. print(f" 材质词典 通过{sc['material'][0]} / 需细化{sc['material'][1]} / 禁用{sc['material'][2]}")
  312. print(f" 玩具触发词 {sc['toy'][0]}中{sc['toy'][1]}英 | 应付映射 {sc['paymap']} 条"
  313. f" | 单价受限 {sc['limits']} 个 | 泛称词 {sc['generic']} 个")
  314. print(f" 执行覆盖自检:期望 {len(sc['execution']['expected'])} 项 | 缺失 {len(sc['execution']['missing'])} 项")
  315. # 4. 重建参考文档(核验与自检均已通过,随包基线才更新为当前规则)
  316. open(os.path.join(REF_DIR, "doc-snapshot.txt"), "w", encoding="utf-8").write(doc_text)
  317. written = export_references(toolbox)
  318. print(f"\n[4/7] 参考文档已重建(随包规则基线 doc-snapshot.txt 已更新):")
  319. for name, n in written:
  320. print(f" {name}({n} 行)")
  321. fp = stamp_rules_md(doc_text, doc_id)
  322. print(f" rules.md 已标记指纹 {fp}")
  323. ok, warn, bad = write_verify_report(v["results"], toolbox, fp)
  324. print(f" verification-report.md 已更新")
  325. if args.check_only:
  326. print("\n[--check-only] 仅检查,未打包")
  327. sys.exit(1 if (changed or bad) else 0)
  328. # 5. 版本
  329. ver = bump_version(SKILL_DIR, bump=not args.no_bump)
  330. nfiles = sum(len([f for f in fs if not f.endswith(".pyc")]) for _, _, fs in os.walk(SKILL_DIR))
  331. update_install_note(SKILL_DIR, ver, nfiles, fp)
  332. print(f"\n[5/7] 版本:v{ver}")
  333. # 6. 打包
  334. path = make_zip(SKILL_DIR, args.out, ver, with_credentials=args.with_credentials)
  335. size = os.path.getsize(path) / 1024
  336. print(f"\n[6/7] 打包完成:{path}")
  337. print(f" {size:.0f} KB | {nfiles} 个文件")
  338. if args.with_credentials:
  339. print(" ⚠️ 本包含飞书凭证:只上传到托管沙箱的技能配置,不要外发、不要提交到代码仓")
  340. print(f"\n[7/7] 结论")
  341. if changed:
  342. print(" ⚠️ 规则有变更:请确认 references/checklist.md 与 known-gaps.md 是否需要跟改")
  343. print(" ⚠️ 新增或改动的规则若用到税率、单箱货值、推荐附加费档次等系统提示,"
  344. "请同步 references/mcp-mode.md「三类字段与问题落点」的对应表")
  345. if bad:
  346. print(f" ❌ 工具包有 {bad} 处偏差:先修工具包再重新打包")
  347. if not changed and not bad:
  348. print(" ✅ 规则与工具包一致,包可直接分发")
  349. sys.exit(1 if (changed or bad) else 0)
  350. if __name__ == "__main__":
  351. import console_io
  352. console_io.setup()
  353. main()