weaver-work-cli 0.1.49 → 0.1.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/README.md +1 -1
  2. package/dist/chunks/{attachment-content-MU2LPI5P.js → attachment-content-MBYYSQIX.js} +3 -3
  3. package/dist/chunks/{chunk-ZKEUGS2U.js → chunk-7UOXOGFL.js} +4 -4
  4. package/dist/chunks/{chunk-72MI3MBX.js → chunk-ATEXBEPD.js} +55 -15
  5. package/dist/chunks/{chunk-3NV2ETZR.js → chunk-D3TDNRFE.js} +8 -8
  6. package/dist/chunks/{chunk-6GWU63YF.js → chunk-DZOC77ZD.js} +1 -1
  7. package/dist/chunks/{chunk-K3BT54CU.js → chunk-IRMA3GVP.js} +1 -1
  8. package/dist/chunks/{chunk-3X7VOSBA.js → chunk-KLZ3ULQQ.js} +1 -1
  9. package/dist/chunks/{chunk-YLCYX7LE.js → chunk-KMRT7NAT.js} +18 -5
  10. package/dist/chunks/{chunk-NBEWUR7L.js → chunk-LALWNK6M.js} +167 -44
  11. package/dist/chunks/{chunk-BRRW7CWA.js → chunk-LM2H7SZI.js} +26 -26
  12. package/dist/chunks/{chunk-KV5SOWMS.js → chunk-LTRLF6MM.js} +4 -4
  13. package/dist/chunks/{chunk-D2QRZUW4.js → chunk-RPRFIG6I.js} +35 -28
  14. package/dist/chunks/{chunk-GEOMANP7.js → chunk-RWFRZSIP.js} +2 -2
  15. package/dist/chunks/{chunk-EJVA5ZVB.js → chunk-ZRHKGQRQ.js} +2 -2
  16. package/dist/chunks/{conflict-6347A7YK.js → conflict-D2HYKBMH.js} +2 -2
  17. package/dist/chunks/{contract-N6P2HIIE.js → contract-MFOFMM2J.js} +4284 -254
  18. package/dist/chunks/{create-flow-7WG7LVX5.js → create-flow-7ZATJVTM.js} +6 -6
  19. package/dist/chunks/{data-QO7QWOIV.js → data-WK5CQXNF.js} +17 -32
  20. package/dist/chunks/{env-LHRKSLG6.js → env-5DO4YENS.js} +2 -2
  21. package/dist/chunks/{factory-2H7Z4RWJ.js → factory-3M7D7WJC.js} +1 -1
  22. package/dist/chunks/{fna-ZVB2IILI.js → fna-ECOYBQYL.js} +328 -5
  23. package/dist/chunks/{group-chat-EW6PNDDT.js → group-chat-B2HT5NEO.js} +3 -3
  24. package/dist/chunks/{im-3RCNL5GT.js → im-TN2JYVGJ.js} +2 -2
  25. package/dist/chunks/{invoice-FXWH5GPO.js → invoice-V7ZTITUO.js} +726 -206
  26. package/dist/chunks/{meeting-N2FQBHXI.js → meeting-HZOX3CBB.js} +10 -10
  27. package/dist/chunks/{msg-parse-4GSQ2WTO.js → msg-parse-FPFVPMYI.js} +5 -1
  28. package/dist/chunks/{reception-MYOKJULO.js → reception-QGPNTGHG.js} +98 -82
  29. package/dist/chunks/{recruit-stage-FKWS5UQF.js → recruit-stage-XCMVEQA2.js} +718 -131
  30. package/dist/chunks/{registry-BUTEDK3C.js → registry-E5RQJVWN.js} +2 -2
  31. package/dist/chunks/{registry-7VZ6YJUF.js → registry-KYPFFQIH.js} +1 -1
  32. package/dist/chunks/{registry-CKUVBS53.js → registry-SJHSBO5G.js} +10 -10
  33. package/dist/chunks/{room-recommend-MBCYENQ2.js → room-recommend-5AHR4YQV.js} +4 -4
  34. package/dist/chunks/{schedule-5IFMCXME.js → schedule-KZPJUPC2.js} +4 -4
  35. package/dist/chunks/smart-extract-IXHCZE4R.js +2846 -0
  36. package/dist/chunks/{workflow-2TRU2ZSP.js → workflow-UHKCZJMY.js} +1 -1
  37. package/dist/index.js +14 -9
  38. package/dist/shortcuts/contract/host.js +11 -0
  39. package/dist/shortcuts/contract/index.js +13 -0
  40. package/dist/shortcuts/contract/manifest.js +204 -0
  41. package/dist/shortcuts/contract/operations/card-action.js +585 -0
  42. package/dist/shortcuts/contract/operations/card-ebdf-list.js +315 -0
  43. package/dist/shortcuts/contract/operations/card-plan.js +327 -0
  44. package/dist/shortcuts/contract/operations/card-risk-report.js +565 -0
  45. package/dist/shortcuts/contract/operations/elements-build.js +714 -0
  46. package/dist/shortcuts/contract/operations/elements-spec.js +216 -0
  47. package/dist/shortcuts/contract/operations/first-screen.js +563 -0
  48. package/dist/shortcuts/contract/operations/flow.js +81 -25
  49. package/dist/shortcuts/contract/operations/modeltext.js +132 -0
  50. package/dist/shortcuts/contract/operations/op-resolver.js +22 -0
  51. package/dist/shortcuts/contract/operations/performance.js +58 -7
  52. package/dist/shortcuts/contract/operations/quote.js +410 -22
  53. package/dist/shortcuts/contract/operations/registry.js +22 -0
  54. package/dist/shortcuts/contract/operations/review.js +73 -58
  55. package/dist/shortcuts/contract/operations/save-recognize.js +151 -0
  56. package/dist/shortcuts/contract/operations/summary-validate.js +293 -0
  57. package/dist/shortcuts/contract/operations/summary.js +4 -2
  58. package/dist/shortcuts/contract/operations/upload.js +48 -7
  59. package/dist/shortcuts/contract/prewarm-cache.js +90 -0
  60. package/dist/shortcuts/contract/prewarm.js +88 -0
  61. package/dist/shortcuts/contract/upload-cache.js +49 -4
  62. package/dist/shortcuts/data/index.js +1 -6
  63. package/dist/shortcuts/data/manifest.js +2 -2
  64. package/dist/shortcuts/data/operations/index.js +1 -1
  65. package/dist/shortcuts/data/operations/query.js +23 -46
  66. package/dist/shortcuts/fna/host.js +4 -2
  67. package/dist/shortcuts/fna/manifest.js +14 -5
  68. package/dist/shortcuts/fna/operations/audit.js +334 -0
  69. package/dist/shortcuts/fna/operations/registry.js +2 -0
  70. package/dist/shortcuts/im/operations/at-mention.js +6 -3
  71. package/dist/shortcuts/im/operations/msg-parse.js +35 -5
  72. package/dist/shortcuts/im/operations/msg-sync.js +3 -1
  73. package/dist/shortcuts/im/operations/msg-write.js +57 -9
  74. package/dist/shortcuts/index.js +5 -0
  75. package/dist/shortcuts/invoice/index.js +0 -12
  76. package/dist/shortcuts/invoice/manifest.js +201 -50
  77. package/dist/shortcuts/invoice/operations/registry.js +4 -2
  78. package/dist/shortcuts/invoice/operations/reim-relation.js +438 -0
  79. package/dist/shortcuts/invoice/operations/shared.js +3 -19
  80. package/dist/shortcuts/invoice/operations/upload-and-validate.js +109 -73
  81. package/dist/shortcuts/meeting/operations/from-group-chat.js +16 -2
  82. package/dist/shortcuts/reception/constants.js +3 -7
  83. package/dist/shortcuts/reception/operations/leads.js +30 -6
  84. package/dist/shortcuts/reception/operations/panels.js +3 -2
  85. package/dist/shortcuts/recruit-stage/operations/interview-arrange.js +4 -2
  86. package/dist/shortcuts/recruit-stage/operations/jd-create.js +6 -2
  87. package/dist/shortcuts/recruit-stage/operations/list.js +217 -1
  88. package/dist/shortcuts/recruit-stage/operations/resume-import.js +144 -158
  89. package/dist/shortcuts/recruit-stage/operations/search.js +348 -0
  90. package/dist/shortcuts/recruit-stage/shared.js +5 -0
  91. package/dist/shortcuts/recruit-stage/tag-lookup.js +136 -0
  92. package/dist/shortcuts/smart-extract/constants.js +79 -0
  93. package/dist/shortcuts/smart-extract/continuation.js +71 -0
  94. package/dist/shortcuts/smart-extract/errors.js +68 -0
  95. package/dist/shortcuts/smart-extract/host.js +191 -0
  96. package/dist/shortcuts/smart-extract/index.js +105 -0
  97. package/dist/shortcuts/smart-extract/ledger.js +70 -0
  98. package/dist/shortcuts/smart-extract/manifest.js +35 -0
  99. package/dist/shortcuts/smart-extract/operations/attachment.js +212 -0
  100. package/dist/shortcuts/smart-extract/operations/batch.js +67 -0
  101. package/dist/shortcuts/smart-extract/operations/config.js +118 -0
  102. package/dist/shortcuts/smart-extract/operations/fill.js +489 -0
  103. package/dist/shortcuts/smart-extract/operations/preview.js +174 -0
  104. package/dist/shortcuts/smart-extract/operations/registry.js +34 -0
  105. package/dist/shortcuts/smart-extract/operations/save.js +355 -0
  106. package/dist/shortcuts/smart-extract/operations/shared.js +191 -0
  107. package/dist/shortcuts/smart-extract/operations/structure.js +401 -0
  108. package/dist/shortcuts/smart-extract/operations/target.js +167 -0
  109. package/dist/shortcuts/smart-extract/operations/types.js +22 -0
  110. package/dist/shortcuts/smart-extract/operations/validate.js +408 -0
  111. package/dist/shortcuts/workflow/operations/read.js +77 -15
  112. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.collect.js +140 -24
  113. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.core.js +42 -14
  114. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.js +4 -6
  115. package/docs/SKILL.md +1 -1
  116. package/docs/_catalog.md +4 -1
  117. package/docs/agent-invoice.md +5 -7
  118. package/docs/data.md +5 -1
  119. package/docs/fna.md +24 -4
  120. package/docs/invoice.md +7 -5
  121. package/docs/smart-extract.md +156 -0
  122. package/package.json +1 -1
  123. package/skill-template/business-info.json +21 -1
  124. package/skill-template/domains/qiyecheng.md +6 -2
  125. package/skill-template/domains/smart-extract.md +16 -0
  126. package/skill-template/domains/yepiaotong.md +2 -2
  127. package/skills/weaver-e10-data/references/scene-and-misc.md +4 -3
  128. package/skills/weaver-e10-jinchengda/SKILL.md +159 -11
  129. package/skills/weaver-e10-jinchengda/references/contract-action-card.md +13 -8
  130. package/skills/weaver-e10-jinchengda/references/contract-action-engine.md +5 -4
  131. package/skills/weaver-e10-jinchengda/references/contract-clause-library-crud.md +44 -2
  132. package/skills/weaver-e10-jinchengda/references/contract-command-index.md +2 -2
  133. package/skills/weaver-e10-jinchengda/references/contract-element-save-record.md +220 -0
  134. package/skills/weaver-e10-jinchengda/references/contract-field-extract-new-customer.md +68 -33
  135. package/skills/weaver-e10-jinchengda/references/contract-field-extract-other-flows.md +26 -15
  136. package/skills/weaver-e10-jinchengda/references/contract-flow-launch.md +1 -1
  137. package/skills/weaver-e10-jinchengda/references/contract-modeltext-library.md +128 -0
  138. package/skills/weaver-e10-jinchengda/references/contract-multi-file.md +90 -0
  139. package/skills/weaver-e10-jinchengda/references/contract-performance-query.md +96 -2
  140. package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +167 -5
  141. package/skills/weaver-e10-jinchengda/scripts/contract_first_screen.py +200 -0
  142. package/skills/weaver-e10-jinchengda/scripts/fill_contract_from_quote.py +572 -0
  143. package/skills/weaver-e10-jinchengda/scripts/fill_plan.py +997 -0
  144. package/skills/weaver-e10-jinchengda/scripts/quote_screen.py +560 -0
  145. package/skills/weaver-e10-jinchengda/scripts/triage_contract.py +894 -0
  146. package/skills/weaver-e10-jinchengda/scripts/validate_action_card.py +93 -0
  147. package/skills/weaver-e10-jinchengda/scripts/verify_docx_placeholders.py +118 -0
  148. package/skills/weaver-e10-qiyecheng/SKILL.md +58 -7
  149. package/skills/weaver-e10-qiyecheng/references/ai-check-audit.md +118 -0
  150. package/skills/weaver-e10-qiyecheng/references/budget.md +14 -0
  151. package/skills/weaver-e10-qiyecheng/references/catalog.md +42 -3
  152. package/skills/weaver-e10-qiyecheng/references/expense-center.md +8 -0
  153. package/skills/weaver-e10-qiyecheng/references/expense-chart.md +9 -0
  154. package/skills/weaver-e10-qiyecheng/references/invoice-writeoff.md +13 -0
  155. package/skills/weaver-e10-qiyecheng/references/loan-management.md +14 -0
  156. package/skills/weaver-e10-qiyecheng/references/self-hosted-mode.md +239 -0
  157. package/skills/weaver-e10-qiyecheng/references/source-manifest.json +153 -40
  158. package/skills/weaver-e10-reception-flow/SKILL.md +43 -6
  159. package/skills/weaver-e10-reception-flow/references/guide.md +1 -1
  160. package/skills/weaver-e10-recruit-stage/SKILL.md +62 -4
  161. package/skills/weaver-e10-recruit-stage/agents/openai.yaml +42 -8
  162. package/skills/weaver-e10-recruit-stage/references/env-ziyong.md +79 -0
  163. package/skills/weaver-e10-recruit-stage/references/recruit-arrange-interview.md +11 -3
  164. package/skills/weaver-e10-recruit-stage/references/recruit-edit-interview-feedback.md +3 -2
  165. package/skills/weaver-e10-recruit-stage/references/recruit-interview-not-attended.md +153 -0
  166. package/skills/weaver-e10-recruit-stage/references/recruit-jd-create.md +7 -4
  167. package/skills/weaver-e10-recruit-stage/references/recruit-match-candidates.md +1 -1
  168. package/skills/weaver-e10-recruit-stage/references/recruit-my-positions.md +66 -0
  169. package/skills/weaver-e10-recruit-stage/references/recruit-output-links.md +156 -40
  170. package/skills/weaver-e10-recruit-stage/references/recruit-resume-import-batch.md +122 -0
  171. package/skills/weaver-e10-recruit-stage/references/recruit-resume-import.md +36 -8
  172. package/skills/weaver-e10-recruit-stage/references/recruit-search-by-tag.md +157 -0
  173. package/skills/weaver-e10-recruit-stage/references/recruit-utterance-glossary.md +35 -0
  174. package/skills/weaver-e10-smart-extract/SKILL.md +169 -0
  175. package/skills/weaver-e10-smart-extract/references/api-contract.md +71 -0
  176. package/skills/weaver-e10-smart-extract/references/result-format.md +102 -0
  177. package/skills/weaver-e10-smart-extract/references/troubleshooting.md +105 -0
  178. package/skills/weaver-e10-workflow/SKILL.md +2 -1
  179. package/skills/weaver-e10-workflow/references/todo-smart-convert.md +29 -6
  180. package/skills/weaver-e10-workflow/references/workflow-query.md +1 -1
  181. package/skills/weaver-e10-workflow/references/workflow-view.md +1 -1
  182. package/skills/weaver-e10-workflow/tools/todo-summary.cjs +162 -10
  183. package/skills/weaver-e10-yepiaotong/SKILL.md +53 -35
  184. package/skills/weaver-e10-yepiaotong/references/invoice-add.md +2 -0
  185. package/skills/weaver-e10-yepiaotong/references/invoice-file-upload.md +1 -1
  186. package/skills/weaver-e10-yepiaotong/references/invoice-import.md +19 -2
  187. package/skills/weaver-e10-yepiaotong/references/invoice-issuing-workflow.md +19 -32
  188. package/skills/weaver-e10-yepiaotong/references/invoice-ocr-preview.md +8 -2
  189. package/skills/weaver-e10-yepiaotong/references/invoice-reim-relation.md +407 -0
  190. package/skills/weaver-e10-yepiaotong/references/invoice-reim.md +18 -53
  191. package/skills/weaver-e10-yepiaotong/references/invoice-upload-and-validate.md +97 -39
  192. package/skills/weaver-e10-yepiaotong/references/reim-api-reference.md +96 -7
  193. package/skills/weaver-e10-yepiaotong/references/reim-examples.md +5 -38
  194. package/skills/weaver-e10-yepiaotong/references/reim-form-fill-rules.md +14 -14
  195. package/skills/weaver-e10-yepiaotong/references/reim-matching-rules.md +8 -4
  196. package/skills/weaver-e10-yepiaotong/references/reim-phone-subsidy-rules.md +139 -94
  197. package/skills/weaver-e10-yepiaotong/references/reim-workflow.md +131 -58
  198. package/skills/weaver-e10-yepiaotong/references/source-manifest.json +110 -43
  199. package/skills/weaver-e10-yimiaoban/SKILL.md +8 -6
  200. package/skills/weaver-e10-yimiaoban/references/msg-read.md +20 -0
  201. package/skills/weaver-e10-yimiaoban/references/msg-write.md +7 -0
  202. package/skills/weaver-e10-yimiaoban/references/source-manifest.json +18 -15
  203. package/dist/shortcuts/invoice/operations/validate-preview.js +0 -40
  204. package/skills/weaver-e10-jinchengda/scripts/plan_actions.py +0 -279
  205. package/skills/weaver-e10-jinchengda/scripts/render_action_card.py +0 -450
  206. package/skills/weaver-e10-jinchengda/scripts/render_risk_report.py +0 -358
  207. package/skills/weaver-e10-yepiaotong/references/invoice-validation-preview.md +0 -40
@@ -0,0 +1,894 @@
1
+ # -*- coding: utf-8 -*-
2
+ """合同首屏第 1 轮:本地抽正文 + 指纹打分定 flowKey + 生成摘要数据 JSON。
3
+
4
+ 设计要点(2026-11-11):
5
+ - 纯本地、零网络、亚秒级,不消耗工具轮次;
6
+ - 直接输出 flowKey,让第 2 轮无需再让模型"看完正文再判断";
7
+ - 判定只按合同内容,不查询客户主数据(2026-11-11 业务明确);
8
+ - 摘要只产出紧凑数据 JSON,HTML 交给 `contract summary render` 渲染。
9
+
10
+ 用法:
11
+ python triage_contract.py --file "D:/contracts/合同.docx" --out-dir "D:/tmp/out"
12
+
13
+ 产出:
14
+ <out-dir>/contract_text.txt 正文纯文本
15
+ <out-dir>/triage.json 判定结果 + 要素 + 摘要数据
16
+ <out-dir>/summary_data.json 可直接喂给 contract summary render
17
+ 退出码:0 成功(含判不出类型);1 正文抽取失败;2 参数错误
18
+ """
19
+ import argparse
20
+ import io
21
+ import json
22
+ import os
23
+ import re
24
+ import sys
25
+ import zipfile
26
+
27
+
28
+ # ────────────────────────── 1. 正文抽取 ──────────────────────────
29
+ def _xml_to_text(xml):
30
+ """OOXML → 纯文本。段落换行,单元格用竖线分隔,保留表格可读性。"""
31
+ x = re.sub(r"</w:p>", "\n", xml)
32
+ x = re.sub(r"</w:tr>", "\n", x)
33
+ x = re.sub(r"</w:tc>", " | ", x)
34
+ x = re.sub(r"<w:tab[^>]*/>", "\t", x)
35
+ x = re.sub(r"<w:br[^>]*/>", "\n", x)
36
+ x = re.sub(r"<[^>]+>", "", x)
37
+ for a, b in (("&lt;", "<"), ("&gt;", ">"), ("&amp;", "&"), ("&quot;", '"'), ("&apos;", "'")):
38
+ x = x.replace(a, b)
39
+ x = re.sub(r"[ \t]+\n", "\n", x)
40
+ x = re.sub(r"\n{3,}", "\n\n", x)
41
+ return x.strip()
42
+
43
+
44
+ def extract_docx(path):
45
+ with zipfile.ZipFile(path) as z:
46
+ names = z.namelist()
47
+ parts = [n for n in ("word/document.xml",) if n in names]
48
+ if not parts:
49
+ raise RuntimeError("docx 内未找到 word/document.xml")
50
+ xml = z.read("word/document.xml").decode("utf-8", "replace")
51
+ return _xml_to_text(xml)
52
+
53
+
54
+ def extract_doc(path):
55
+ # 老式 .doc 无 OOXML,只能尽力抽可见 ASCII/GBK 片段,仅作降级
56
+ raw = open(path, "rb").read()
57
+ try:
58
+ txt = raw.decode("gbk", "ignore")
59
+ except Exception:
60
+ txt = raw.decode("utf-16", "ignore")
61
+ txt = re.sub(r"[^\u4e00-\u9fa5A-Za-z0-9,。、;:()()【】%¥\.\-\s]", " ", txt)
62
+ return re.sub(r"\s{2,}", "\n", txt).strip()
63
+
64
+
65
+ def extract_pdf(path):
66
+ try:
67
+ from pypdf import PdfReader # noqa
68
+ except Exception:
69
+ try:
70
+ from PyPDF2 import PdfReader # noqa
71
+ except Exception:
72
+ raise RuntimeError("未安装 pypdf/PyPDF2,无法抽 PDF 文本层;请改用 docx 或先用 parse_document 兜底")
73
+ reader = PdfReader(path)
74
+ return "\n".join((pg.extract_text() or "") for pg in reader.pages).strip()
75
+
76
+
77
+ def extract_text(path):
78
+ ext = os.path.splitext(path)[1].lower()
79
+ if ext == ".docx":
80
+ return extract_docx(path)
81
+ if ext == ".doc":
82
+ return extract_doc(path)
83
+ if ext == ".pdf":
84
+ return extract_pdf(path)
85
+ if ext in (".txt", ".md"):
86
+ return io.open(path, encoding="utf-8", errors="replace").read()
87
+ raise RuntimeError("不支持的文件类型:%s(仅 .docx/.doc/.pdf/.txt)" % ext)
88
+
89
+
90
+ # ────────────────────────── 2. 指纹打分 ──────────────────────────
91
+ # key = flowKey;label = 指纹编号;prio 越小越优先(标题已明确指向的类别优先于新客户)
92
+ TITLE_RULES = [
93
+ {"key": "老客户增值", "label": "F2", "pat": r"增值服务"},
94
+ {"key": "常规二次销售", "label": "F3", "pat": r"年度维护"},
95
+ {"key": "常规二次销售", "label": "F4", "pat": r"第三方产品"},
96
+ {"key": "常规二次销售", "label": "F5", "pat": r"用户使用许可增购|许可增购|增购"},
97
+ {"key": "老客户增值", "label": "F6", "pat": r"升级合同|升级服务合同|版本升级"},
98
+ {"key": "新客户", "label": "F1", "pat": r"(软件)?产品及实施服务购买合同"},
99
+ ]
100
+
101
+ QY_SUO_TITLE = r"契约锁"
102
+ QY_SUO_CORE = r"(电子签章平台|电子签平台|电子签约平台|契约锁平台)"
103
+
104
+ F5_TRIPLE = ["原有", "本次购买", "共有"]
105
+ F6_MIGRATION = r"升级为|升级包|升级服务|版本迁移"
106
+ F1_SUBJECT_WORDS = ["系统软件产品费用", "软件产品费用", "e-cology产品购买", "e-cology 产品购买"]
107
+
108
+ F3_CHAPTERS = ["服务范围", "服务期限", "服务内容", "合同标的及付费方式"]
109
+ F1_CHAPTERS = ["授予使用许可权", "产品交付"]
110
+ F2_SUBJECT = ["软件功能费用", "实施开发服务费用"]
111
+
112
+
113
+ def norm(s):
114
+ """全角→半角、去空白,用于关键词匹配(不改原文,仅用于比对)。"""
115
+ out = []
116
+ for ch in s:
117
+ o = ord(ch)
118
+ if o == 0x3000:
119
+ out.append(" ")
120
+ elif 0xFF01 <= o <= 0xFF5E:
121
+ out.append(chr(o - 0xFEE0))
122
+ else:
123
+ out.append(ch)
124
+ return re.sub(r"\s+", "", "".join(out))
125
+
126
+
127
+ def detect_title(text):
128
+ lines = [l.strip() for l in text.splitlines() if l.strip()]
129
+ cands = []
130
+ for l in lines[:40]:
131
+ if len(l) <= 60 and "合同" in l and not l.startswith(("第", "TOC", "目录")):
132
+ cands.append(l)
133
+ if cands:
134
+ return max(cands, key=len)
135
+ return lines[0] if lines else ""
136
+
137
+
138
+ def count_chapters(text):
139
+ return len(re.findall(r"第[一二三四五六七八九十百]+章", text))
140
+
141
+
142
+ def score(text, title):
143
+ """返回 (flowKey, score, basis, label, confidence, needsConfirm, evidence[], candidates{})"""
144
+ ntext, ntitle = norm(text), norm(title)
145
+ ev, cand = [], {}
146
+
147
+ def add(k, s, why):
148
+ cand[k] = cand.get(k, 0) + s
149
+ ev.append({"type": k, "score": s, "reason": why})
150
+
151
+ # D1 契约锁闸门:只认标题或"平台类核心标的",不认明细里出现一次电子签
152
+ if re.search(QY_SUO_TITLE, title) or re.search(QY_SUO_CORE, title):
153
+ return ("契约锁", 100, "title", "D1", 0.95, False,
154
+ [{"type": "契约锁", "score": 100, "reason": "标题即契约锁/电子签平台"}], {"契约锁": 100})
155
+
156
+ # D2-a 标题正则(100 分,决定性)
157
+ title_hits = []
158
+ for r in TITLE_RULES:
159
+ if re.search(r["pat"], ntitle):
160
+ title_hits.append(r)
161
+ if title_hits:
162
+ # 标题已明确指向增值/升级/维护/第三方/增购 → 该类优先,新客户让位
163
+ non_f1 = [r for r in title_hits if r["label"] != "F1"]
164
+ pick = (non_f1 or title_hits)[0]
165
+ s = 100 if not non_f1 else 100
166
+ return (pick["key"], s, "title", pick["label"], 0.95, False,
167
+ [{"type": pick["key"], "score": 100, "reason": "标题命中 %s 正则:%s" % (pick["label"], pick["pat"])}],
168
+ {pick["key"]: 100})
169
+
170
+ # D2-b 正文强指纹
171
+ if all(w in ntext for w in F5_TRIPLE):
172
+ add("常规二次销售", 85, "存量增量三连(原有+本次购买+共有)")
173
+ if re.search(F6_MIGRATION, ntext):
174
+ add("老客户增值", 85, "版本迁移句式(升级为/升级包/升级服务/版本迁移)")
175
+ if all(norm(c) in ntext for c in F3_CHAPTERS):
176
+ add("常规二次销售", 80, "F3 独有章节四连(服务范围/期限/内容/标的及付费方式)")
177
+ if norm("交付内容") in ntext and norm("产品交付") not in ntext:
178
+ add("常规二次销售", 80, "F4 独有章节「交付内容」且无「产品交付」")
179
+ if all(norm(c) in ntext for c in F1_CHAPTERS):
180
+ add("新客户", 80, "F1 加分章节(授予使用许可权 + 产品交付)")
181
+ if any(norm(w) in ntext for w in F1_SUBJECT_WORDS):
182
+ add("新客户", 80, "F1 标的达标词(系统软件产品费用/软件产品费用/e-cology产品购买)")
183
+ if all(norm(w) in ntext for w in F2_SUBJECT):
184
+ add("老客户增值", 70, "F2 标的语义(软件功能费用 + 实施开发服务费用)")
185
+
186
+ # 章节数加权
187
+ ch = count_chapters(text)
188
+ chap_map = {16: "新客户", 14: "老客户增值", 12: "常规二次销售", 11: "常规二次销售"}
189
+ if ch in chap_map:
190
+ add(chap_map[ch], 10, "章节数 %d 与某类模板一致(仅加权)" % ch)
191
+ # 反信号
192
+ if "知识产权" not in ntext:
193
+ cand["常规二次销售"] = cand.get("常规二次销售", 0) - 20
194
+ ev.append({"type": "常规二次销售", "score": -20, "reason": "反信号:无「知识产权」章"})
195
+
196
+ if not cand:
197
+ return (None, 0, None, None, 0.0, True, [], {})
198
+
199
+ best = max(cand.items(), key=lambda kv: kv[1])
200
+ key, sc = best[0], best[1]
201
+ if sc >= 80:
202
+ conf, need = 0.9, False
203
+ elif sc >= 60:
204
+ conf, need = 0.65, True
205
+ else:
206
+ return (None, sc, None, None, 0.3, True, ev, cand)
207
+ label = next((x["label"] for x in TITLE_RULES if x["key"] == key), "D2")
208
+ return (key, sc, "structure" if sc < 85 else "subject-semantic", label, conf, need, ev, cand)
209
+
210
+
211
+ # ────────────────────────── 3. 要素线索(仅定位,不取值) ──────────────────────────
212
+ # 2026-11-11 改造:合同措辞千变万化,正则不具备语义理解能力。
213
+ # 本段只输出线索(关键词命中行号 + 片段),供模型读正文时快速定位;
214
+ # 任何字段的实际取值一律由模型语义判断后写入 elements.json / summary_data.json。
215
+ MONEY = r"[¥¥]?\s*([0-9][0-9,,]*(?:\.[0-9]{1,2})?)"
216
+
217
+ HINT_PATTERNS = [
218
+ ("甲方", r"甲方"),
219
+ ("乙方", r"乙方"),
220
+ ("丙方", r"丙方"),
221
+ ("最终用户", r"最终用户"),
222
+ ("签订时间", r"签订时间|签署日期|签订日期"),
223
+ ("签订地点", r"签订地点|签署地点"),
224
+ ("合同总额", r"合同标的总额|总额|合计|合同总价"),
225
+ ("付款方式", r"付款方式|付款阶段|付款比例"),
226
+ ("交付地点", r"交付地点|服务地点|履行地点"),
227
+ ("生效条件", r"生效条件|盖章后生效|生效"),
228
+ ("发票税率", r"增值税|发票|税率"),
229
+ ("合同编号", r"合同编号"),
230
+ ("维护费", r"维护费|维护服务"),
231
+ ("验收", r"验收"),
232
+ ("知识产权", r"知识产权"),
233
+ ("保密", r"保密"),
234
+ ("违约责任", r"违约责任"),
235
+ ("争议解决", r"争议|仲裁|诉讼"),
236
+ ("交付期限", r"交付期限|服务期限|履行期限"),
237
+ ]
238
+
239
+ OUR_COMPANY_WORDS = ("泛微网络", "泛微软件")
240
+
241
+
242
+ def regex_hints(text):
243
+ """只给行号与片段,不返回任何字段值。"""
244
+ hints = []
245
+ for kind, pat in HINT_PATTERNS:
246
+ n = 0
247
+ for m in re.finditer(pat, text):
248
+ ln = text.count("\n", 0, m.start()) + 1
249
+ seg = " ".join(text[m.start(): m.start() + 120].split())
250
+ hints.append({"kind": kind, "line": ln, "snippet": seg[:120]})
251
+ n += 1
252
+ if n >= 2:
253
+ break
254
+ return hints
255
+
256
+
257
+
258
+ # ────────────────────────── 4. 摘要骨架(交模型语义填写) ──────────────────────────
259
+ FLOW_LABEL = {
260
+ "新客户": "新客户购买合同",
261
+ "老客户增值": "老客户增值合同",
262
+ "常规二次销售": "常规二次销售合同",
263
+ "契约锁": "契约锁合同",
264
+ }
265
+
266
+ BASE_ELEMENT_ROWS = [
267
+ ("合同类型", "四类归属 + 细分,如「新客户(标准产品及实施服务)」"),
268
+ ("合同总额", "小写金额 + 人民币大写;原文占位标记(如 120,000)原样保留,禁止换算"),
269
+ ("甲方(签约相对方)", "甲方全称;代理签约时注明「代理签约,最终用户 XX」"),
270
+ ("乙方(我方)", "我方签约主体全称;与甲方不重复展示"),
271
+ ("合同标的", "主项 1~3 个 + 「另 N 项」"),
272
+ ("付款方式", "比例序列 + 触发节点,如「40%/40%/20%|签约后 / 调研后 / 验收后」"),
273
+ ("履行或服务期限", "起止日期;无则「未识别」"),
274
+ ("交付或服务地点", "抽不到写「未识别」;禁止用签订地点顶替"),
275
+ ("签订时间", "具体日期;留空写「留空待填」"),
276
+ ("签订地点", "城市"),
277
+ ("生效条件", "如「双方盖章后生效」"),
278
+ ("发票类型与税率", "如「13% 增值税专用发票」;税率不得计入付款比例"),
279
+ ("合同编号", "有则填,无则「未识别」"),
280
+ ("文件信息", "文件名 + 解析字数"),
281
+ ]
282
+
283
+ TYPE_EXTRA_ROWS = {
284
+ "新客户": [
285
+ ("产品交付方式", "现场实施 / 远程 / 分阶段"),
286
+ ("许可范围", "用户数、模块范围、部署方式"),
287
+ ("实施周期", "开工至验收的周期约定"),
288
+ ],
289
+ "老客户增值": [
290
+ ("功能模块清单", "本次新增或升级的模块"),
291
+ ("实施开发范围", "含不含定制开发"),
292
+ ("验收标准", "验收条件与依据"),
293
+ ],
294
+ "常规二次销售": [
295
+ ("服务范围", "含不含硬件 / 数据库"),
296
+ ("响应时限", "SLA 约定"),
297
+ ("维护内容清单", "维护事项枚举"),
298
+ ],
299
+ "契约锁": [
300
+ ("用印方式", "物理用印 / 电子用印"),
301
+ ("签署方式", "顺序签 / 并行签"),
302
+ ("印章类型", "公章 / 合同章 / 法人章"),
303
+ ],
304
+ }
305
+
306
+ SECTIONS_SPEC = [
307
+ "头部:badge(四类归属)+ title + meta(文件名 + 解析字数)",
308
+ "业务分类归属(reasons):一句话结论 + 2~3 条依据",
309
+ "要素卡(table):上面列出的必填行 + 类型补充行,共 14~18 行",
310
+ "标的明细(table,可选):编号 / 名称 / 单价 / 数量 / 金额,不做求和校验",
311
+ "付款节点(table,可选):阶段 / 比例 / 金额 / 触发条件",
312
+ "其他关键条款(list):只写事实,抽不到的条款不占行",
313
+ "下一步(next):一句话说明在右侧卡片里选择",
314
+ ]
315
+
316
+ CONSTRAINTS = [
317
+ "禁止使用 grid 类型:CLI 渲染器只输出空容器,内容会整段丢失,一律用 table",
318
+ "摘要只做客观呈现:禁止 alert / checks 风险段、禁止 ⚠️/✅ 标记、禁止「建议核对」类措辞",
319
+ "金额中的原文占位标记(如 120,000)原样保留,禁止换算成数字",
320
+ "税率(如 13% 增值税)不得计入付款比例;付款比例总和一般不超过 100%",
321
+ "交付地点不得用签订地点顶替;两者都没有就写「未识别」",
322
+ "所有取值必须来自 contract_text.txt 原文语义;取不到写「未识别」,禁止推测",
323
+ "签约相对方是甲方;资信查询对象取甲方,不是最终用户",
324
+ ]
325
+
326
+ # ── P5(2026-11-11):把 validate_summary.py 的校验口径内联进骨架。
327
+ # 历史问题:模型为确认 rows 结构、type 合法值,额外花 2 轮去读校验器源码。
328
+ # 内联后模型只读骨架就能写对,省 2 轮往返。
329
+ SUMMARY_FORMAT = {
330
+ "topLevel": {
331
+ "badge": "四类归属,与 flowKey 一致",
332
+ "title": "合同标题",
333
+ "subtitle": "文件名 | 解析字数",
334
+ "sections": "数组,元素按 allowedTypes 组合",
335
+ },
336
+ "allowedTypes": {
337
+ "reasons": {"items": ["字符串", "..."]},
338
+ "table": {"rows": [["标签", "值"], ["标签", "值"]]},
339
+ "list": {"items": ["字符串", "..."]},
340
+ "next": {"text": "字符串"},
341
+ },
342
+ "forbiddenTypes": ["grid", "alert", "checks"],
343
+ "hardRules": [
344
+ "table 的 rows 每行只放「标签 + 值」成对出现;禁止对象形式;每行不得出现更多取值",
345
+ "禁止 grid:渲染器只输出空容器,内容整段丢失",
346
+ "禁止 alert / checks:摘要只做客观呈现,风险内容归「合同预审」",
347
+ "以下 4 个标签必须出现在某个 table 的 rows 里:合同类型 / 合同总额 / 甲方 / 乙方",
348
+ "税率不得计入付款比例;付款比例合计不超过 100%",
349
+ "取不到的值写「未识别」,禁止推测或换算原文占位标记",
350
+ ],
351
+ "requiredRowLabels": ["合同类型", "合同总额", "甲方", "乙方"],
352
+ }
353
+
354
+ # ai_fill.json 的 elements 填空骨架(阶段1 直出,模型就地填值)
355
+ ELEMENTS_TEMPLATE = {
356
+ "partyA": "",
357
+ "partyB": "",
358
+ "partyC": "",
359
+ "finalUser": "",
360
+ "signDate": "",
361
+ "signPlace": "",
362
+ "deliveryPlace": "",
363
+ "effectiveCondition": "",
364
+ "contractNo": "",
365
+ "totalAmount": "",
366
+ "invoiceTax": "",
367
+ "version": "",
368
+ "payments": [{"node": "", "ratio": "", "amount": ""}],
369
+ "items": [{"name": "", "price": "", "discount": "", "amount": ""}],
370
+ "terms": [{"name": "", "content": ""}],
371
+ "missing": [],
372
+ }
373
+
374
+
375
+ def build_summary_template(flow_key, title, file_name, text_len, rows):
376
+ """ai_fill.json 的 summary 填空骨架:sections 结构与口径一次给全。"""
377
+ labels = [r["row"] for r in rows]
378
+ return {
379
+ "badge": flow_key,
380
+ "title": title or "",
381
+ "subtitle": "%s | 解析 %d 字" % (file_name, text_len),
382
+ "sections": [
383
+ {"title": "业务分类归属", "type": "reasons",
384
+ "items": ["结论:<四类之一 + 一句话>",
385
+ "依据一:<章节或标的层面的依据>",
386
+ "依据二:<合同内容层面的依据>"]},
387
+ {"title": "合同要素", "type": "table",
388
+ "rows": [[lb, ""] for lb in labels]},
389
+ {"title": "标的明细", "type": "table",
390
+ "rows": [["编号 1|<标的名称>", "<单价> → <金额>"], ["合计", ""]]},
391
+ {"title": "付款节点", "type": "table",
392
+ "rows": [["<触发节点>", "比例 <x>%|金额 <金额>|<条件>"], ["合计", "100%"]]},
393
+ {"title": "其他关键条款", "type": "list",
394
+ "items": ["<条款名>:<一句话事实>"]},
395
+ {"title": "下一步", "type": "next",
396
+ "text": "可在右侧卡片中选择:发起对应合同流程、AI 预审或查对方资信。"},
397
+ ],
398
+ }
399
+
400
+
401
+ _TABLE_PROSE_MIN = 60
402
+
403
+
404
+ def _is_prose_boundary(line):
405
+ """判断某行是否可作为表格块的边界(章节标题或成句散文)。
406
+
407
+ 表格行以 `|` 开头,永不作边界;空行也不作边界(表格内大量空行)。
408
+ """
409
+ t = (line or "").strip()
410
+ if not t:
411
+ return False
412
+ if t.startswith("|"):
413
+ return False
414
+ if re.match(r"^第[一二三四五六七八九十百零〇\d]+章", t):
415
+ return True
416
+ if len(t) >= _TABLE_PROSE_MIN and re.search(r"[。;]", t):
417
+ return True
418
+ return False
419
+
420
+
421
+ def _table_block_lines(lines):
422
+ """返回表格块覆盖的行下标集合(含块内空行、单元格行与表标题行)。
423
+
424
+ 为什么表格不能按行筛:合同标的 / 功能清单 / 付款节点这类表格,单元格内容是
425
+ 「人事管理」「资产管理」「工作流程」等模块名,本身不含甲方/金额/日期等要素
426
+ 关键词,行级命中会把整张表丢掉。2026-11-12 实测:8899 字合同 L135~L253 的
427
+ 整张标的明细表在区段视图里一行都没有,直接导致专项方案(聚才林-人事管理、
428
+ 资管家-资产管理)整批漏抽——模型不是抽不出,是根本没看到这两行原文。
429
+ 故表格一律**按块整块保留**,绝不做逐行过滤。
430
+ """
431
+ blocks = set()
432
+ n = len(lines)
433
+ i = 0
434
+ while i < n:
435
+ if not lines[i].strip().startswith("|"):
436
+ i += 1
437
+ continue
438
+ lo = i
439
+ while lo - 1 >= 0 and not _is_prose_boundary(lines[lo - 1]):
440
+ lo -= 1
441
+ hi = i
442
+ while hi + 1 < n and not _is_prose_boundary(lines[hi + 1]):
443
+ hi += 1
444
+ cells = sum(1 for j in range(lo, hi + 1) if lines[j].strip().startswith("|"))
445
+ # 至少 2 行单元格才算表格,避免把孤立的分隔符当成表格而误吞大段正文
446
+ if cells >= 2:
447
+ blocks.update(range(lo, hi + 1))
448
+ i = hi + 1
449
+ return blocks
450
+
451
+
452
+ def build_section_view(text, hints, max_chars=24000):
453
+ """要素区段视图(**辅助定位产物**):抬头 + 要素命中行(±1 行)+ 表格块 + 签署尾部。
454
+
455
+ 2026-11-12 用户明确:要素抽取与专项识别**一律以 contract_text.txt 全文为准**,
456
+ 本视图只用于快速定位行号,不得作为唯一输入。
457
+
458
+ 2026-11-12 修复(P0):此前只保留要素命中行,表格按行被筛掉——合同标的
459
+ 1.8 人事管理、1.10 资产管理等模块行不含要素关键词,整张表消失,专项方案整批
460
+ 漏抽。现改为表格块整块保留,上限同步提到 24000 字,避免再次把表切断。
461
+
462
+ 2026-11-11 修复(保留):上限原为 3600 字,切断位置正好落在「合同标的」表与
463
+ 「付款方式」表之前,金额与付款比例看不到,模型被迫回读全文。
464
+ """
465
+ lines = text.splitlines()
466
+ if not lines:
467
+ return ""
468
+ keep = set()
469
+ for i in range(min(40, len(lines))):
470
+ keep.add(i)
471
+ for i in range(max(0, len(lines) - 40), len(lines)):
472
+ keep.add(i)
473
+ for h in hints or []:
474
+ base = (h.get("line") or 0) - 1
475
+ for d in (-1, 0, 1):
476
+ j = base + d
477
+ if 0 <= j < len(lines):
478
+ keep.add(j)
479
+ # 表格块整块保留,优先于任何行级过滤
480
+ keep |= _table_block_lines(lines)
481
+ body, prev = [], None
482
+ for i in sorted(keep):
483
+ if prev is not None and i != prev + 1:
484
+ body.append("...")
485
+ s = lines[i].strip()
486
+ if s:
487
+ body.append("L%d: %s" % (i + 1, s[:220]))
488
+ prev = i
489
+ blob = "\n".join(body)
490
+ if len(blob) > max_chars:
491
+ # 按行边界截断:硬切会把一行切成半句,看起来像一条完整取值(2026-11-11 修复)
492
+ cut = blob.rfind("\n", 0, max_chars)
493
+ blob = blob[:cut if cut > 0 else max_chars] + \
494
+ "\n...(区段视图已截断,完整正文见 contract_text.txt)"
495
+ return ("要素区段视图(L=原文行号;辅助定位用,含抬头 + 要素命中行 + 表格块 + 签署尾部;"
496
+ "取值一律以 contract_text.txt 全文为准)\n" + blob + "\n")
497
+
498
+
499
+ def split_ai_fill(path, out_dir):
500
+ """把 ai_fill.json 拆成 elements.json 与 summary_data.json。
501
+
502
+ 返回 (elements_path, summary_path, warnings)。
503
+ """
504
+ warns = []
505
+ el_p = sm_p = ""
506
+ try:
507
+ data = json.loads(io.open(path, encoding="utf-8-sig").read())
508
+ except Exception as e:
509
+ return "", "", ["ai_fill.json 解析失败:%s" % e]
510
+ if not isinstance(data, dict):
511
+ return "", "", ["ai_fill.json 顶层必须是对象"]
512
+ el = data.get("elements")
513
+ if isinstance(el, dict):
514
+ el_p = os.path.join(out_dir, "elements.json")
515
+ io.open(el_p, "w", encoding="utf-8", newline="\n").write(
516
+ json.dumps(el, ensure_ascii=False, indent=2))
517
+ sm = data.get("summary")
518
+ if isinstance(sm, dict):
519
+ sm_p = os.path.join(out_dir, "summary_data.json")
520
+ io.open(sm_p, "w", encoding="utf-8", newline="\n").write(
521
+ json.dumps(sm, ensure_ascii=False, indent=2))
522
+ if not el_p and not sm_p:
523
+ warns.append("ai_fill.json 里没有 elements 或 summary 对象")
524
+ return el_p, sm_p, warns
525
+
526
+
527
+ def build_summary_skeleton(flow_key, title, text, file_name=""):
528
+ rows = [{"row": k, "how": v} for k, v in BASE_ELEMENT_ROWS]
529
+ for k, v in TYPE_EXTRA_ROWS.get(flow_key or "", []):
530
+ rows.append({"row": k, "how": v})
531
+ return {
532
+ "instruction": "阶段1 已产出 ai_fill.json:在它的 elements / summary 里就地填空,"
533
+ "再用 --ai-fill 一条命令进阶段2(省一轮写文件)。"
534
+ "要素取值**必须以 contract_text.txt 全文为准**(禁止只看区段视图);"
535
+ "contract_sections.txt 仅用于快速定位行号,不得作为唯一输入。"
536
+ "本骨架只给必填行与口径,不提供任何字段取值。",
537
+ "flowKey": flow_key,
538
+ "flowLabel": FLOW_LABEL.get(flow_key or "", flow_key or "待确认"),
539
+ "titleFromText": title,
540
+ "fileName": file_name,
541
+ "textLength": len(text),
542
+ "requiredElementRows": rows,
543
+ "elementRowCount": len(rows),
544
+ "sectionsSpec": SECTIONS_SPEC,
545
+ "constraints": CONSTRAINTS,
546
+ "aiFillHint": {
547
+ "file": "ai_fill.json",
548
+ "how": "elements 按 elementsContract 填值;summary 按 sectionTemplate 填值;"
549
+ "阶段2 只需 --ai-fill ai_fill.json,无需再写 elements.json / summary_data.json",
550
+ "sectionsView": "contract_sections.txt(区段视图,辅助定位用:含抬头、要素命中行、"
551
+ "表格块与签署尾部;取值一律回 contract_text.txt 全文核对,"
552
+ "禁止只看视图下结论)",
553
+ },
554
+ "summaryFormat": SUMMARY_FORMAT,
555
+ "sectionTemplate": build_summary_template(flow_key, title, file_name, len(text), rows),
556
+ "elementsContract": {
557
+ "partyA": "甲方全称",
558
+ "partyB": "乙方(我方)全称",
559
+ "partyC": "丙方全称,无则空串",
560
+ "finalUser": "最终用户全称,无则空串",
561
+ "signDate": "签订时间 YYYY年MM月DD日",
562
+ "signPlace": "签订地点",
563
+ "deliveryPlace": "交付/服务地点",
564
+ "effectiveCondition": "生效条件",
565
+ "contractNo": "合同编号",
566
+ "totalAmount": "合同总额,原文标记原样保留",
567
+ "invoiceTax": "发票类型与税率",
568
+ "version": "产品版本,无则空串",
569
+ "payments": [{"node": "触发节点", "ratio": "40%", "amount": "金额"}],
570
+ "items": [{"name": "标的名称", "price": "单价", "discount": "折扣", "amount": "金额"}],
571
+ "terms": [{"name": "条款名", "content": "一句话事实"}],
572
+ "missing": ["原文缺失或留空的字段名"],
573
+ },
574
+ }
575
+
576
+
577
+
578
+ # ────────────────────────── 5. 主流程 ──────────────────────────
579
+ def _reuse_stage2(args):
580
+ """阶段2 复用:直接读已有 triage.json,只合并 elements 与 summary_data。
581
+
582
+ P0-②(2026-11-11):阶段1 已产出 triage.json,阶段2 再跑一遍正文抽取与
583
+ 指纹打分属于纯重复计算(大合同 3~5 秒)。复用后不再读 docx。
584
+ """
585
+ p_triage = os.path.join(args.out_dir, "triage.json")
586
+ try:
587
+ result = json.loads(io.open(p_triage, encoding="utf-8-sig").read())
588
+ except Exception as e:
589
+ sys.stderr.write("TRIAGE_REUSE_FAIL: %s\n" % e)
590
+ return 2
591
+
592
+ warnings = list(result.get("warnings") or []) + list(getattr(args, "_ai_fill_warn", []))
593
+ elements = result.get("elements") or {}
594
+ elements_source = result.get("elementsSource") or "ai_semantic_pending"
595
+
596
+ if args.elements:
597
+ if os.path.isfile(args.elements):
598
+ try:
599
+ elements = json.loads(io.open(args.elements, encoding="utf-8-sig").read())
600
+ elements_source = "ai_semantic"
601
+ except Exception as e:
602
+ sys.stderr.write("ELEMENTS_PARSE_FAIL: %s\n" % e)
603
+ return 2
604
+ else:
605
+ warnings.append("elements.json 不存在,已跳过:%s" % args.elements)
606
+
607
+ if not isinstance(elements, dict):
608
+ elements = {}
609
+ result["elements"] = elements
610
+ result["elementsSource"] = elements_source
611
+
612
+ # 签约相对方:甲方 → 丙方 → 最终用户,排除我方主体(与阶段1口径一致)
613
+ for key in ("partyA", "partyC", "finalUser"):
614
+ v = (elements.get(key) or "").strip()
615
+ if v and not any(w in v for w in OUR_COMPANY_WORDS):
616
+ result["counterparty"] = v
617
+ break
618
+
619
+ result["warnings"] = warnings
620
+ io.open(p_triage, "w", encoding="utf-8", newline="\n").write(
621
+ json.dumps(result, ensure_ascii=False, indent=2))
622
+
623
+ outputs = {
624
+ "text": os.path.join(args.out_dir, "contract_text.txt"),
625
+ "triage": p_triage,
626
+ "skeleton": os.path.join(args.out_dir, "summary_skeleton.json"),
627
+ }
628
+
629
+ summary_state = "pending_ai"
630
+ if args.summary_data:
631
+ if os.path.isfile(args.summary_data):
632
+ try:
633
+ sm = json.loads(io.open(args.summary_data, encoding="utf-8-sig").read())
634
+ p_sum = os.path.join(args.out_dir, "summary_data.json")
635
+ io.open(p_sum, "w", encoding="utf-8", newline="\n").write(
636
+ json.dumps(sm, ensure_ascii=False, indent=2))
637
+ outputs["summary"] = p_sum
638
+ summary_state = "ai_semantic"
639
+ except Exception as e:
640
+ warnings.append("summary_data.json 解析失败:%s" % e)
641
+ result["warnings"] = warnings
642
+ else:
643
+ warnings.append("summary_data.json 不存在:%s" % args.summary_data)
644
+ result["warnings"] = warnings
645
+
646
+ skel_rows = 0
647
+ if os.path.isfile(outputs["skeleton"]):
648
+ try:
649
+ skel_rows = json.loads(
650
+ io.open(outputs["skeleton"], encoding="utf-8-sig").read()).get("elementRowCount", 0)
651
+ except Exception:
652
+ skel_rows = 0
653
+
654
+ print(json.dumps({
655
+ "ok": True,
656
+ "reusedTriage": True,
657
+ "flowKey": result.get("flowKey"),
658
+ "typeScore": result.get("typeScore"),
659
+ "fingerprint": result.get("fingerprint"),
660
+ "needsConfirm": result.get("needsConfirm"),
661
+ "title": result.get("title"),
662
+ "elementsSource": elements_source,
663
+ "summaryState": summary_state,
664
+ "hintCount": len(result.get("hints") or []),
665
+ "elementRowCount": skel_rows,
666
+ "counterparty": result.get("counterparty", ""),
667
+ "warnings": warnings,
668
+ "outputs": outputs,
669
+ }, ensure_ascii=False))
670
+ return 0
671
+
672
+
673
+ def main():
674
+ ap = argparse.ArgumentParser(
675
+ description="合同首屏第1轮:抽正文 + 指纹定 flowKey + 出 AI 语义提取骨架")
676
+ ap.add_argument("--file", required=True, help="主合同文件绝对路径(.docx/.doc/.pdf/.txt)")
677
+ ap.add_argument("--attach", nargs="*", default=[],
678
+ help="随附文件(协议/补充协议/清单等)绝对路径;正文按序合并在主文件之后,"
679
+ "flowKey 判定仍只看主文件")
680
+ ap.add_argument("--out-dir", required=True, help="产物目录")
681
+ ap.add_argument("--elements", default="",
682
+ help="模型语义提取的 elements.json;给了就合并进 triage.json 供 fill_elements 使用")
683
+ ap.add_argument("--summary-data", default="",
684
+ help="模型语义生成的 summary_data.json;给了就校验并落地为最终摘要数据")
685
+ ap.add_argument("--reuse", action="store_true",
686
+ help="阶段2 复用已有 triage.json:只合并 elements/summary_data,"
687
+ "跳过正文抽取与指纹打分(P0-②)")
688
+ ap.add_argument("--ai-fill", default="",
689
+ help="P5:模型填好的 ai_fill.json(同时含 elements 与 summary),"
690
+ "一条参数替代 --elements + --summary-data,省一轮写文件")
691
+ args = ap.parse_args()
692
+
693
+ # P5(2026-11-11):--ai-fill 先拆成 elements.json / summary_data.json,
694
+ # 后续逻辑(含 --reuse 路径)完全复用原有两个参数,不新增分支。
695
+ _ai_fill_warn = []
696
+ args._ai_fill_warn = _ai_fill_warn
697
+ if args.ai_fill:
698
+ os.makedirs(args.out_dir, exist_ok=True)
699
+ if os.path.isfile(args.ai_fill):
700
+ p_el, p_sm, w = split_ai_fill(args.ai_fill, args.out_dir)
701
+ _ai_fill_warn.extend(w)
702
+ if p_el and not args.elements:
703
+ args.elements = p_el
704
+ if p_sm and not args.summary_data:
705
+ args.summary_data = p_sm
706
+ else:
707
+ _ai_fill_warn.append("ai_fill.json 不存在:%s" % args.ai_fill)
708
+
709
+ # P0-②:阶段2 显式 --reuse 且 triage.json 已存在时,直接复用,不再读 docx
710
+ if args.reuse and os.path.isfile(os.path.join(args.out_dir, "triage.json")):
711
+ return _reuse_stage2(args)
712
+
713
+ if not os.path.isfile(args.file):
714
+ sys.stderr.write("FILE_NOT_FOUND: %s\n" % args.file)
715
+ return 2
716
+ os.makedirs(args.out_dir, exist_ok=True)
717
+
718
+ # ── 多文件:主文件在前,随附文件按序合并在后;同时记录「行号 → 文件」归属
719
+ src_files = [{"index": 0, "role": "primary", "path": os.path.abspath(args.file),
720
+ "name": os.path.basename(args.file)}]
721
+ seen = [src_files[0]["path"]]
722
+ for a in (args.attach or []):
723
+ ap_ = os.path.abspath(a) if a else ""
724
+ if not ap_ or ap_ in seen:
725
+ continue
726
+ if not os.path.isfile(ap_):
727
+ sys.stderr.write("ATTACH_NOT_FOUND: %s\n" % a)
728
+ return 2
729
+ seen.append(ap_)
730
+ src_files.append({"index": len(src_files), "role": "attachment",
731
+ "path": ap_, "name": os.path.basename(ap_)})
732
+
733
+ merged_lines, line_map, primary_text = [], [], ""
734
+ for sf in src_files:
735
+ try:
736
+ seg = extract_text(sf["path"])
737
+ except Exception as e:
738
+ sys.stderr.write("EXTRACT_FAIL[%s]: %s\n" % (sf["name"], e))
739
+ return 1
740
+ sf["textLength"] = len(seg)
741
+ if sf["index"] == 0:
742
+ primary_text = seg
743
+ else:
744
+ for ln in ("", "===== 随附文件 %d:%s =====" % (sf["index"], sf["name"]), ""):
745
+ merged_lines.append(ln)
746
+ line_map.append(sf["index"])
747
+ for ln in seg.split("\n"):
748
+ merged_lines.append(ln)
749
+ line_map.append(sf["index"])
750
+ text = "\n".join(merged_lines)
751
+ assert len(line_map) == len(merged_lines), "lineMap 与正文行数不一致"
752
+
753
+ if len(primary_text) < 100:
754
+ sys.stderr.write("TEXT_TOO_SHORT: 主文件仅抽到 %d 字,可能是扫描件或加密文件,"
755
+ "请改用 parse_document 兜底\n" % len(primary_text))
756
+ return 1
757
+
758
+ # 判定只看主文件:随附协议常含「补充/变更」等字样,混入会误改 flowKey
759
+ title = detect_title(primary_text)
760
+ flow_key, sc, basis, label, conf, need, evidence, cand = score(primary_text, title)
761
+ skeleton = build_summary_skeleton(flow_key, title, primary_text, os.path.basename(args.file))
762
+ hints = regex_hints(text)
763
+
764
+ # 要素只认模型语义结果;脚本不再猜取值
765
+ elements, elements_source, warnings = {}, "ai_semantic_pending", []
766
+ if args.elements:
767
+ if os.path.isfile(args.elements):
768
+ try:
769
+ elements = json.loads(io.open(args.elements, encoding="utf-8-sig").read())
770
+ elements_source = "ai_semantic"
771
+ except Exception as e:
772
+ sys.stderr.write("ELEMENTS_PARSE_FAIL: %s\n" % e)
773
+ return 2
774
+ else:
775
+ warnings.append("elements.json 不存在,已跳过:%s" % args.elements)
776
+ elif not args.summary_data:
777
+ warnings.append("未提供 elements.json:要素为空,发起流程表单需人工填写")
778
+
779
+ # 签约相对方:优先甲方,且排除我方主体(付款义务与信用风险都在甲方)
780
+ def _pick_counterparty(el):
781
+ a = (el.get("partyA") or "").strip()
782
+ c = (el.get("partyC") or "").strip()
783
+ f = (el.get("finalUser") or "").strip()
784
+ if a and not any(w in a for w in OUR_COMPANY_WORDS):
785
+ return a
786
+ if c and not any(w in c for w in OUR_COMPANY_WORDS):
787
+ return c
788
+ return f
789
+
790
+ counterparty = _pick_counterparty(elements)
791
+
792
+ result = {
793
+ "file": {"path": os.path.abspath(args.file), "name": os.path.basename(args.file),
794
+ "size": os.path.getsize(args.file),
795
+ "attachments": [{"name": f["name"], "path": f["path"],
796
+ "textLength": f["textLength"]}
797
+ for f in src_files if f["role"] == "attachment"]},
798
+ "sourceFiles": [{"index": f["index"], "role": f["role"], "name": f["name"]}
799
+ for f in src_files],
800
+ "fileCount": len(src_files),
801
+ "textLength": len(primary_text),
802
+ "mergedTextLength": len(text),
803
+ "title": title,
804
+ "flowKey": flow_key,
805
+ "typeScore": sc,
806
+ "typeBasis": basis,
807
+ "fingerprint": label,
808
+ "confidence": conf,
809
+ "needsConfirm": need,
810
+ "candidates": cand,
811
+ "evidence": evidence,
812
+ "elements": elements,
813
+ "elementsSource": elements_source,
814
+ "hints": hints,
815
+ "chapterCount": count_chapters(text),
816
+ "counterparty": counterparty,
817
+ "warnings": warnings,
818
+ }
819
+
820
+ p_src = os.path.join(args.out_dir, "text_sources.json")
821
+ io.open(p_src, "w", encoding="utf-8", newline="\n").write(
822
+ json.dumps({"files": src_files, "lineMap": line_map}, ensure_ascii=False))
823
+ p_text = os.path.join(args.out_dir, "contract_text.txt")
824
+ p_triage = os.path.join(args.out_dir, "triage.json")
825
+ p_skel = os.path.join(args.out_dir, "summary_skeleton.json")
826
+ io.open(p_text, "w", encoding="utf-8", newline="\n").write(text)
827
+ io.open(p_triage, "w", encoding="utf-8", newline="\n").write(
828
+ json.dumps(result, ensure_ascii=False, indent=2))
829
+ io.open(p_skel, "w", encoding="utf-8", newline="\n").write(
830
+ json.dumps(skeleton, ensure_ascii=False, indent=2))
831
+
832
+ # P5(2026-11-11):阶段1 直出 ai_fill.json(elements + summary 合并填空板),
833
+ # 模型一次 write_file 即可,阶段2 用 --ai-fill 一条参数读回,省 1 轮。
834
+ p_fill = os.path.join(args.out_dir, "ai_fill.json")
835
+ io.open(p_fill, "w", encoding="utf-8", newline="\n").write(
836
+ json.dumps({
837
+ "instruction": "就地填值:elements 按 elementsContract,summary 按 sectionTemplate;"
838
+ "table 的 rows 每行只放「标签 + 值」成对出现,禁止 grid。"
839
+ "填完直接跑阶段2 --ai-fill ai_fill.json。",
840
+ "flowKey": flow_key,
841
+ "file": {"name": os.path.basename(args.file), "textLength": len(text)},
842
+ "elements": ELEMENTS_TEMPLATE,
843
+ "summary": build_summary_template(
844
+ flow_key, title, os.path.basename(args.file), len(text),
845
+ skeleton["requiredElementRows"]),
846
+ }, ensure_ascii=False, indent=2))
847
+
848
+ # P5:要素区段视图(带行号),避免为找要素读完整正文
849
+ p_sec = os.path.join(args.out_dir, "contract_sections.txt")
850
+ io.open(p_sec, "w", encoding="utf-8", newline="\n").write(
851
+ build_section_view(text, hints))
852
+
853
+ # P4:flowKey / counterparty 已写入 triage.json,不再写 txt 中转文件
854
+ warnings.extend(_ai_fill_warn)
855
+
856
+ outputs = {"text": p_text, "triage": p_triage, "skeleton": p_skel,
857
+ "aiFill": p_fill, "sections": p_sec, "sources": p_src}
858
+ summary_state = "pending_ai"
859
+ if args.summary_data:
860
+ if os.path.isfile(args.summary_data):
861
+ try:
862
+ sm = json.loads(io.open(args.summary_data, encoding="utf-8-sig").read())
863
+ p_sum = os.path.join(args.out_dir, "summary_data.json")
864
+ io.open(p_sum, "w", encoding="utf-8", newline="\n").write(
865
+ json.dumps(sm, ensure_ascii=False, indent=2))
866
+ outputs["summary"] = p_sum
867
+ summary_state = "ai_semantic"
868
+ except Exception as e:
869
+ warnings.append("summary_data.json 解析失败:%s" % e)
870
+ else:
871
+ warnings.append("summary_data.json 不存在:%s" % args.summary_data)
872
+
873
+ print(json.dumps({
874
+ "ok": True,
875
+ "flowKey": flow_key,
876
+ "typeScore": sc,
877
+ "fingerprint": label,
878
+ "needsConfirm": need,
879
+ "title": title,
880
+ "elementsSource": elements_source,
881
+ "summaryState": summary_state,
882
+ "hintCount": len(hints),
883
+ "elementRowCount": skeleton["elementRowCount"],
884
+ "fileCount": len(src_files),
885
+ "counterparty": counterparty,
886
+ "warnings": warnings,
887
+ "outputs": outputs,
888
+ }, ensure_ascii=False))
889
+ return 0
890
+
891
+
892
+
893
+ if __name__ == "__main__":
894
+ sys.exit(main())