sync_package.py 17 KB

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