| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 技能包同步打包工具
- ==================
- 一条命令完成:拉最新规则 → 核验工具包 → 重建参考文档 → 更新版本 → 打 zip。
- 用法:
- python3 scripts/sync_package.py # 同步并打包到 ../dist
- python3 scripts/sync_package.py --out ~/dist # 指定输出目录
- python3 scripts/sync_package.py --check-only # 只检查,不打包(核验通过后仍会更新随包基线并重建参考表,只是不升版本、不打 zip)
- python3 scripts/sync_package.py --no-bump # 打包但不升版本号
- 规则是否变更以随包基线 references/doc-snapshot.txt 为准(不是本地快照);基线只在核验与自检都通过后才更新,
- 核验失败后再次运行仍会报告规则有变更。手工维护的 rules.md / known-gaps.md / mcp-mode.md 不在机器核验范围,
- 规则变更时须人工确认。
- 规则有变更时脚本会:
- 1. 打印变更行(新增/删除)
- 2. 把规则快照写进 references/doc-snapshot.txt(随包分发,离线可用)
- 3. 在 references/rules.md 顶部写入快照指纹与时间
- 4. 仍会完成打包,但退出码为 1,提示你人工确认判定表是否要跟着改;
- 规则用到系统提示时,还要人工同步 references/mcp-mode.md 的问题落点表(本脚本不重写该文件)
- 退出码:
- 0 = 一致,已打包
- 1 = 规则有变更或工具包有偏差(已打包,但需人工确认)
- 2 = 执行错误
- """
- import argparse
- import hashlib
- import json
- import os
- import re
- import sys
- import zipfile
- from datetime import datetime
- try:
- import requests
- import openpyxl
- except ImportError as e:
- print(f"缺少依赖:{e.name},请执行 pip3 install requests openpyxl", file=sys.stderr)
- sys.exit(2)
- HERE = os.path.dirname(os.path.abspath(__file__))
- SKILL_DIR = os.path.dirname(HERE)
- REF_DIR = os.path.join(SKILL_DIR, "references")
- ASSET_DIR = os.path.join(SKILL_DIR, "assets")
- HOME_DIR = os.path.expanduser("~/.sku_audit")
- SNAP_DIR = os.path.join(HOME_DIR, "snapshots")
- BASE = "https://open.feishu.cn/open-apis"
- DEFAULT_DOC = "SFQjdsMoRoxPjsx4wGhc95uxnEc"
- sys.path.insert(0, HERE)
- import rule_check # noqa: E402 比对口径与 rule_check 共用一份实现
- def die(msg, code=2):
- print(f"[错误] {msg}", file=sys.stderr)
- sys.exit(code)
- def load_credentials():
- a = os.environ.get("FEISHU_APP_ID")
- s = os.environ.get("FEISHU_APP_SECRET")
- if a and s:
- return a, s
- p = os.path.join(HOME_DIR, "credentials.json")
- if os.path.exists(p):
- d = json.load(open(p, encoding="utf-8"))
- if d.get("app_id") and d.get("app_secret"):
- return d["app_id"], d["app_secret"]
- die(f"未找到凭证:设置 FEISHU_APP_ID / FEISHU_APP_SECRET,或写入 {p}")
- def get_token(a, s):
- r = requests.post(f"{BASE}/auth/v3/tenant_access_token/internal",
- json={"app_id": a, "app_secret": s}, timeout=20).json()
- if r.get("code") != 0:
- die(f"获取 token 失败:{r.get('code')} {r.get('msg')}")
- return r["tenant_access_token"]
- def fetch_doc(doc_id, token):
- r = requests.get(f"{BASE}/docx/v1/documents/{doc_id}/raw_content",
- headers={"Authorization": "Bearer " + token}, timeout=30).json()
- if r.get("code") != 0:
- die(f"拉取文档失败:{r.get('code')} {r.get('msg')}")
- return (r.get("data") or {}).get("content", "")
- def baseline_changes(doc_text, quiet=False):
- """以随包同步基线 references/doc-snapshot.txt 判定规则是否已同步。
- 不用本地快照判定:本地快照每次拉取都会写入,一次核验失败的同步之后,
- 下次运行会把「未同步」误报成「规则未变动」。
- 返回 (changed, diff);包内没有基线时视为有变更。
- """
- seed = os.path.join(REF_DIR, "doc-snapshot.txt")
- if not os.path.exists(seed):
- if not quiet:
- print(" 技能包缺少同步基线 references/doc-snapshot.txt,按规则有变更处理")
- return True, []
- old = open(seed, encoding="utf-8").read()
- if rule_check.normalize(old) == rule_check.normalize(doc_text):
- if not quiet:
- print(" 与技能包同步基线一致,规则未变动")
- return False, []
- return True, rule_check.print_diffs(" 与技能包同步基线相比", old, doc_text, quiet)
- def find_toolbox():
- if not os.path.isdir(ASSET_DIR):
- die(f"找不到 assets 目录:{ASSET_DIR}")
- xs = [f for f in os.listdir(ASSET_DIR) if f.endswith(".xlsx") and not f.startswith("~$")]
- if not xs:
- die("assets 目录里没有 xlsx 工具包")
- xs.sort(key=lambda f: os.path.getmtime(os.path.join(ASSET_DIR, f)), reverse=True)
- return os.path.join(ASSET_DIR, xs[0])
- def table_md(rows, head):
- out = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
- for r in rows:
- out.append("| " + " | ".join("" if v is None else str(v).replace("|", "/") for v in r) + " |")
- return "\n".join(out)
- def export_references(toolbox):
- """从工具包重建 references 里的表格类文档"""
- wb = openpyxl.load_workbook(toolbox, data_only=True)
- written = []
- def get(prefix):
- for name in wb.sheetnames:
- if name.startswith(prefix):
- return wb[name]
- return None
- ws = get("02")
- if ws:
- rows = [r[:6] for r in ws.iter_rows(min_row=2, values_only=True) if r[1]]
- md = ["# 审核判定表(%d 项)" % len(rows), "",
- "> 由工具包 `02-审核判定表` 自动导出,请改工具包后重新同步,勿手工维护。", "",
- table_md(rows, ["#", "检查项", "判定条件", "结论", "话术模板", "规则"])]
- open(os.path.join(REF_DIR, "checklist.md"), "w", encoding="utf-8").write("\n".join(md))
- written.append(("checklist.md", len(rows)))
- ws = get("03")
- if ws:
- rows = [r[:5] for r in ws.iter_rows(min_row=2, values_only=True) if r[0] and r[1]]
- md = ["# 材质词典", "",
- table_md(rows, ["分类", "中文", "英文", "处理", "说明"])]
- open(os.path.join(REF_DIR, "material-dict.md"), "w", encoding="utf-8").write("\n".join(md))
- written.append(("material-dict.md", len(rows)))
- ws = get("04")
- if ws:
- rows = [r[:7] for r in ws.iter_rows(min_row=2, values_only=True) if r[0] and r[1]]
- md = ["# 认证触发词表", "",
- "> 只有「玩具认证(CPSC/CPC)」需审核 PDF 内容,且须同时提供 CPC 证书和第三方测试报告;其余认证文件只核是否上传,不审内容。", "",
- table_md(rows, ["场景", "类别", "中文关键词", "英文关键词", "需上传文件", "需审核内容", "结论 / 处理"])]
- open(os.path.join(REF_DIR, "cert-triggers.md"), "w", encoding="utf-8").write("\n".join(md))
- written.append(("cert-triggers.md", len(rows)))
- ws = get("05")
- if ws:
- rows = [r[:6] for r in ws.iter_rows(min_row=2, values_only=True)
- if r[0] and str(r[0]).isdigit()]
- md = ["# 应付清关编码映射", "",
- table_md(rows, ["#", "应收品名类别", "应付中文品名", "应付英文品名", "应付编码", "备注"]),
- "", "**注意**:清单口径与实际 HTS 归类存在冲突(灯类/玩具类/塑料柜类),详见 `known-gaps.md`。"]
- open(os.path.join(REF_DIR, "pay-code-map.md"), "w", encoding="utf-8").write("\n".join(md))
- written.append(("pay-code-map.md", len(rows)))
- ws = get("06")
- if ws:
- rows = [r[:7] for r in ws.iter_rows(min_row=2, values_only=True)
- if r[1] and re.match(r"^\d{4}\.\d{2}\.\d{4}$", str(r[1]))]
- md = ["# 单价限制清单(%d 个受限编码)" % len(rows), "",
- table_md(rows, ["#", "编码", "品类(推断,待确认)", "限制条件原文", "解析区间 USD/件", "判断动作", "问题标记"])]
- open(os.path.join(REF_DIR, "price-limits.md"), "w", encoding="utf-8").write("\n".join(md))
- written.append(("price-limits.md", len(rows)))
- return written
- def stamp_rules_md(doc_text, doc_id):
- """在 rules.md 顶部写入快照指纹"""
- p = os.path.join(REF_DIR, "rules.md")
- if not os.path.exists(p):
- return None
- txt = open(p, encoding="utf-8").read()
- fp = hashlib.sha1(rule_check.normalize(doc_text).encode("utf-8")).hexdigest()[:12]
- head = (f"> 规则快照:{datetime.now():%Y-%m-%d %H:%M} 指纹 `{fp}` "
- f"字符数 {len(doc_text)} 来源 docx `{doc_id}`\n"
- f">\n"
- f"> 本文是速查版,字段级细节以 `checklist.md` 为准。规则有变先跑 `scripts/rule_check.py fetch`。\n")
- # 去掉旧头部块(从 "> 规则快照" 或 "> 来源:" 开始连续以 > 开头的行)
- lines = txt.split("\n")
- if lines and lines[0].startswith("# "):
- title = lines[0]
- i = 1
- while i < len(lines) and (lines[i].strip() == "" or lines[i].startswith(">")):
- i += 1
- rest = "\n".join(lines[i:])
- new = title + "\n\n" + head + "\n" + rest
- else:
- new = head + "\n" + txt
- open(p, "w", encoding="utf-8").write(new)
- return fp
- def write_verify_report(results, toolbox, doc_fp):
- p = os.path.join(REF_DIR, "verification-report.md")
- ok = sum(1 for r in results if r[2] == "✅")
- warn = sum(1 for r in results if r[2] == "⚠️")
- bad = sum(1 for r in results if r[2] == "❌")
- md = [f"# 核验报告", "",
- f"- 生成时间:{datetime.now():%Y-%m-%d %H:%M}",
- f"- 工具包:`{os.path.basename(toolbox)}`",
- f"- 规则指纹:`{doc_fp}`",
- f"- 结论:✅ {ok} | ⚠️ {warn} | ❌ {bad}", "",
- table_md(results, ["类别", "检查项", "状态", "说明"])]
- open(p, "w", encoding="utf-8").write("\n".join(md))
- return ok, warn, bad
- def bump_version(skill_dir, bump=True):
- p = os.path.join(skill_dir, "VERSION")
- cur = open(p, encoding="utf-8").read().strip() if os.path.exists(p) else "1.0"
- if bump:
- try:
- major, minor = cur.split(".")
- cur = f"{major}.{int(minor) + 1}"
- except ValueError:
- cur = "1.1"
- open(p, "w", encoding="utf-8").write(cur + "\n")
- return cur
- def update_install_note(skill_dir, ver, nfiles, doc_fp):
- p = os.path.join(skill_dir, "安装说明.md")
- if not os.path.exists(p):
- return
- txt = open(p, encoding="utf-8").read()
- block = (f"## 版本\n\n"
- f"- 技能包 v{ver}(打包于 {datetime.now():%Y-%m-%d %H:%M})\n"
- f"- 规则快照指纹 `{doc_fp}`,随包附带 `references/doc-snapshot.txt`\n"
- f"- 含 {nfiles} 个文件\n")
- if "## 版本" in txt:
- txt = re.sub(r"## 版本[\s\S]*$", block, txt)
- else:
- txt = txt.rstrip() + "\n\n" + block
- open(p, "w", encoding="utf-8").write(txt)
- def audit_selfcheck():
- """审核脚本自检:确认 audit.py 能从工具包正确读到判定参数
- 这一步是「规则改了 → 审核脚本自动跟上」的保障:
- audit.py 的阈值与词表全部读自工具包,只要这里能读通,
- 说明脚本与当前工具包是配套的;读不到会直接退出,不会带着旧口径去审核。
- """
- p = os.path.join(HERE, "audit.py")
- if not os.path.exists(p):
- die("scripts/audit.py 缺失,审核脚本未随包。请恢复后再同步,否则分发包无法执行审核")
- sys.path.insert(0, HERE)
- import audit as A
- wbp = A.pick_workbook()
- if not wbp:
- die("audit.py 在 assets 下找不到工具包 xlsx")
- kit = A.Kit(wbp) # 参数缺失会 SystemExit,阻断打包
- execution = A.execution_selfcheck(kit)
- if execution["missing"]:
- die("审核执行覆盖缺项:" + "、".join(execution["missing"]) + ";规则已同步但执行器未完整落地,禁止打包")
- ok, need, ban = kit.material_sets()
- tcn, ten = kit.toy_keywords()
- return {
- "toolbox": os.path.basename(wbp),
- "fz06": kit.fz06_px(),
- "items": len([r for r in kit.check_items[1:] if r and r[0]]),
- "material": (len(ok), len(need), len(ban)),
- "toy": (len(tcn), len(ten)),
- "paymap": len(kit.paymap_rows()),
- "limits": len(kit.price_limits()),
- "generic": len(kit.generic_words()),
- "execution": execution,
- }
- def make_zip(skill_dir, out_dir, ver):
- os.makedirs(out_dir, exist_ok=True)
- name = f"SKU审核专员-技能包_v{ver}.zip"
- path = os.path.join(out_dir, name)
- if os.path.exists(path):
- os.remove(path)
- base = os.path.dirname(skill_dir)
- with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
- for root, dirs, files in os.walk(skill_dir):
- dirs[:] = [d for d in dirs if d not in ("__pycache__", ".git")]
- for f in files:
- if f.endswith((".pyc", ".DS_Store")) or f.startswith("~$"):
- continue
- full = os.path.join(root, f)
- rel = os.path.relpath(full, base)
- z.write(full, rel)
- # 确认审核脚本真的进包了(分发包没有 audit.py 就跑不了审核)
- with zipfile.ZipFile(path) as z:
- names = z.namelist()
- if not any(n.endswith("scripts/audit.py") for n in names):
- os.remove(path)
- die("打包结果缺少 scripts/audit.py,已中止;请检查 scripts 目录")
- return path
- def main():
- ap = argparse.ArgumentParser(description="技能包同步打包")
- ap.add_argument("--doc", default=DEFAULT_DOC)
- ap.add_argument("--out", default=os.path.join(os.path.dirname(SKILL_DIR), "dist"))
- ap.add_argument("--check-only", action="store_true")
- ap.add_argument("--no-bump", action="store_true")
- args = ap.parse_args()
- doc_id = args.doc
- m = re.search(r"/docx/([A-Za-z0-9]+)", doc_id)
- if m:
- doc_id = m.group(1)
- print("=" * 60)
- print("SKU 审核技能包 · 同步打包")
- print("=" * 60)
- # 1. 拉规则
- a, s = load_credentials()
- token = get_token(a, s)
- doc_text = fetch_doc(doc_id, token)
- print(f"\n[1/7] 规则文档已拉取:{len(doc_text)} 字符")
- # 2. 与随包同步基线比对(本地快照只做留档)
- os.makedirs(SNAP_DIR, exist_ok=True)
- changed, diff = baseline_changes(doc_text)
- ts = datetime.now().strftime("%Y%m%d_%H%M%S")
- open(os.path.join(SNAP_DIR, f"doc_{ts}.txt"), "w", encoding="utf-8").write(doc_text)
- print(f" 本地快照已保存;随包基线 references/doc-snapshot.txt 待核验与自检通过后再更新")
- # 3. 核验工具包
- toolbox = find_toolbox()
- v = rule_check.cmd_verify(doc_text, toolbox, None, quiet=True)
- print(f"\n[2/7] 工具包核验:✅ {v['ok']} | ⚠️ {v['warn']} | ❌ {v['bad']}")
- if v["bad"]:
- die("规则文档与工具包存在未裁决口径或同步偏差;先确认文档问题并更新工具包,禁止重建参考文档和打包")
- # 3. 审核脚本自检(audit.py 参数必须与工具包配套)
- sc = audit_selfcheck()
- print(f"\n[3/7] 审核脚本自检:audit.py ↔ {sc['toolbox']}")
- print(f" 判定项 {sc['items']} 条 | FZ-06 阈值 {sc['fz06']}px")
- print(f" 材质词典 通过{sc['material'][0]} / 需细化{sc['material'][1]} / 禁用{sc['material'][2]}")
- print(f" 玩具触发词 {sc['toy'][0]}中{sc['toy'][1]}英 | 应付映射 {sc['paymap']} 条"
- f" | 单价受限 {sc['limits']} 个 | 泛称词 {sc['generic']} 个")
- print(f" 执行覆盖自检:期望 {len(sc['execution']['expected'])} 项 | 缺失 {len(sc['execution']['missing'])} 项")
- # 4. 重建参考文档(核验与自检均已通过,随包基线才更新为当前规则)
- open(os.path.join(REF_DIR, "doc-snapshot.txt"), "w", encoding="utf-8").write(doc_text)
- written = export_references(toolbox)
- print(f"\n[4/7] 参考文档已重建(随包规则基线 doc-snapshot.txt 已更新):")
- for name, n in written:
- print(f" {name}({n} 行)")
- fp = stamp_rules_md(doc_text, doc_id)
- print(f" rules.md 已标记指纹 {fp}")
- ok, warn, bad = write_verify_report(v["results"], toolbox, fp)
- print(f" verification-report.md 已更新")
- if args.check_only:
- print("\n[--check-only] 仅检查,未打包")
- sys.exit(1 if (changed or bad) else 0)
- # 5. 版本
- ver = bump_version(SKILL_DIR, bump=not args.no_bump)
- nfiles = sum(len([f for f in fs if not f.endswith(".pyc")]) for _, _, fs in os.walk(SKILL_DIR))
- update_install_note(SKILL_DIR, ver, nfiles, fp)
- print(f"\n[5/7] 版本:v{ver}")
- # 6. 打包
- path = make_zip(SKILL_DIR, args.out, ver)
- size = os.path.getsize(path) / 1024
- print(f"\n[6/7] 打包完成:{path}")
- print(f" {size:.0f} KB | {nfiles} 个文件")
- print(f"\n[7/7] 结论")
- if changed:
- print(" ⚠️ 规则有变更:请确认 references/checklist.md 与 known-gaps.md 是否需要跟改")
- print(" ⚠️ 新增或改动的规则若用到税率、单箱货值、推荐附加费档次等系统提示,"
- "请同步 references/mcp-mode.md「三类字段与问题落点」的对应表")
- if bad:
- print(f" ❌ 工具包有 {bad} 处偏差:先修工具包再重新打包")
- if not changed and not bad:
- print(" ✅ 规则与工具包一致,包可直接分发")
- sys.exit(1 if (changed or bad) else 0)
- if __name__ == "__main__":
- main()
|