dknowc-dsh 2.3.1 → 2.4.1
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.
- package/README.md +11 -3
- package/cordis.patch.yml +1 -1
- package/package.json +7 -4
- package/skills/dk-trace-report/SKILL.md +288 -0
- package/skills/dk-trace-report/config/examples/doc.json +56 -0
- package/skills/dk-trace-report/config/examples/legal.json +51 -0
- package/skills/dk-trace-report/config/examples/ppt.json +47 -0
- package/skills/dk-trace-report/config/examples/tax.json +46 -0
- package/skills/dk-trace-report/config/examples/trusted.json +122 -0
- package/skills/dk-trace-report/reference/sample_input.json +60 -0
- package/skills/dk-trace-report/resources/ECHARTS-NOTICE.txt +10 -0
- package/skills/dk-trace-report/resources/echarts.custom.min.js +48 -0
- package/skills/dk-trace-report/scripts/build_report_input.py +333 -0
- package/skills/{dknowc-trusted-search → dk-trace-report}/scripts/chart_embed.py +4 -1
- package/skills/{dknowc-trusted-search → dk-trace-report}/scripts/render_trace_html.py +1071 -536
- package/skills/dk-trace-report/scripts/run_paths.py +95 -0
- package/skills/dk-trace-report/scripts/trust_digest.py +77 -0
- package/skills/dknowc-legal-assistant/README.md +95 -0
- package/skills/dknowc-legal-assistant/SKILL.md +122 -0
- package/skills/dknowc-legal-assistant/attribution.json +5 -0
- package/skills/dknowc-legal-assistant/reference/answer-and-report.md +221 -0
- package/skills/dknowc-legal-assistant/reference/capability-layer.md +143 -0
- package/skills/dknowc-legal-assistant/reference/legal_claims.example.json +96 -0
- package/skills/dknowc-legal-assistant/reference/onboarding_scripts.md +198 -0
- package/skills/dknowc-legal-assistant/reference/policy_tags.json +2002 -0
- package/skills/dknowc-legal-assistant/reference/retrieval-statute.md +81 -0
- package/skills/dknowc-legal-assistant/reference/retrieval-v2.md +133 -0
- package/skills/dknowc-legal-assistant/reference/sample_search_result.md +33 -0
- package/skills/dknowc-legal-assistant/reference/sample_trace_report.html +940 -0
- package/skills/dknowc-legal-assistant/reference/tags.md +53 -0
- package/skills/dknowc-legal-assistant/reference/troubleshooting.md +50 -0
- package/skills/dknowc-legal-assistant/reference/verification-pass.md +59 -0
- package/skills/dknowc-legal-assistant/resources/echarts.custom.min.js +48 -0
- package/skills/dknowc-legal-assistant/scripts/api_key.py +68 -0
- package/skills/dknowc-legal-assistant/scripts/attribution.py +61 -0
- package/skills/dknowc-legal-assistant/scripts/calc_legal.py +375 -0
- package/skills/dknowc-legal-assistant/scripts/calc_period.py +155 -0
- package/skills/dknowc-legal-assistant/scripts/check_answer.py +664 -0
- package/skills/dknowc-legal-assistant/scripts/initialize.py +188 -0
- package/skills/dknowc-legal-assistant/scripts/legal_client.py +208 -0
- package/skills/dknowc-legal-assistant/scripts/legal_search.py +1059 -0
- package/skills/dknowc-legal-assistant/scripts/merge_search_results.py +630 -0
- package/skills/dknowc-legal-assistant/scripts/path_guard.py +92 -0
- package/skills/dknowc-legal-assistant/scripts/question_profile.py +215 -0
- package/skills/dknowc-legal-assistant/scripts/register_key.mjs +1152 -0
- package/skills/dknowc-legal-assistant/scripts/run_eval.py +109 -0
- package/skills/dknowc-legal-assistant/scripts/source_cards.py +321 -0
- package/skills/dknowc-legal-assistant/scripts/tag_catalog.py +162 -0
- package/skills/dknowc-legal-assistant/scripts/trace_report.config.json +66 -0
- package/skills/dknowc-legal-assistant/scripts/verify_claims.py +448 -0
- package/skills/dknowc-legal-assistant/scripts/websearch_convert.py +396 -0
- package/skills/dknowc-official-doc-writer/README.md +32 -21
- package/skills/dknowc-official-doc-writer/SKILL.md +28 -15
- package/skills/dknowc-official-doc-writer/config/trace_report.config.json +56 -0
- package/skills/dknowc-official-doc-writer/reference/anti_ai_patterns.md +14 -2
- package/skills/dknowc-official-doc-writer/reference/fact_discipline.md +4 -0
- package/skills/dknowc-official-doc-writer/reference/genre_writing_notes.md +4 -0
- package/skills/dknowc-official-doc-writer/reference/initialization.md +13 -8
- package/skills/dknowc-official-doc-writer/reference/local_memory_guide.md +7 -7
- package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +21 -0
- package/skills/dknowc-official-doc-writer/reference/materials_pipeline.md +64 -7
- package/skills/dknowc-official-doc-writer/reference/onboarding_scripts.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/outline_rules.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/output_guide.md +13 -13
- package/skills/dknowc-official-doc-writer/reference/research_notes.md +5 -3
- package/skills/dknowc-official-doc-writer/reference/review_checklist.md +6 -2
- package/skills/dknowc-official-doc-writer/reference/search_guide.md +44 -32
- package/skills/dknowc-official-doc-writer/reference/search_policy.md +63 -36
- package/skills/dknowc-official-doc-writer/reference/standards/01_report.md +3 -3
- package/skills/dknowc-official-doc-writer/reference/standards/02_qingshi.md +6 -3
- package/skills/dknowc-official-doc-writer/reference/standards/03_pifu.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/04_tongzhi.md +12 -3
- package/skills/dknowc-official-doc-writer/reference/standards/05_yijian.md +8 -2
- package/skills/dknowc-official-doc-writer/reference/standards/06_han.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/08_tongbao.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/09_tonggao.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/10_gonggao.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/11_fuhan_approve.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/12_fuhan_objection.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/13_reminder.md +3 -3
- package/skills/dknowc-official-doc-writer/reference/standards/14_generic.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/standards/16_decision.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/18_order.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/standards/19_gazette.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/standards/20_motion.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/22_application.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/23_publicity.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/standards/25_plan.md +2 -1
- package/skills/dknowc-official-doc-writer/reference/standards/26_summary.md +7 -1
- package/skills/dknowc-official-doc-writer/reference/standards/27_speech.md +4 -1
- package/skills/dknowc-official-doc-writer/reference/standards/99_expressions.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/task_router.md +4 -4
- package/skills/dknowc-official-doc-writer/reference/working_principles.md +4 -4
- package/skills/dknowc-official-doc-writer/reference/writing_method.md +166 -0
- package/skills/dknowc-official-doc-writer/reference/writing_rules.md +10 -4
- package/skills/dknowc-official-doc-writer/scripts/api_key.py +24 -25
- package/skills/dknowc-official-doc-writer/scripts/attribution.py +1 -1
- package/skills/dknowc-official-doc-writer/scripts/build_trace_json.py +205 -13
- package/skills/dknowc-official-doc-writer/scripts/check_materials.py +367 -22
- package/skills/dknowc-official-doc-writer/scripts/deep_convert.py +5 -0
- package/skills/dknowc-official-doc-writer/scripts/deep_query.py +2 -1
- package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +20 -7
- package/skills/dknowc-official-doc-writer/scripts/extract_reference.py +1 -0
- package/skills/dknowc-official-doc-writer/scripts/format_document.py +88 -30
- package/skills/dknowc-official-doc-writer/scripts/initialize.py +232 -6
- package/skills/dknowc-official-doc-writer/scripts/local_memory.py +2 -6
- package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +100 -7
- package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +2 -1
- package/skills/dknowc-official-doc-writer/scripts/register.mjs +265 -32
- package/skills/dknowc-official-doc-writer/scripts/review_document.py +1 -0
- package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +117 -10
- package/skills/dknowc-official-doc-writer/scripts/template_generator.py +1 -0
- package/skills/dknowc-official-doc-writer/scripts/update_skill.py +339 -0
- package/skills/dknowc-official-doc-writer/scripts/websearch_convert.py +326 -0
- package/skills/dknowc-ppt-assistant/README.md +7 -9
- package/skills/dknowc-ppt-assistant/SKILL.md +28 -19
- package/skills/dknowc-ppt-assistant/config/trace_report.config.json +65 -0
- package/skills/dknowc-ppt-assistant/references/initialization.md +20 -8
- package/skills/dknowc-ppt-assistant/references/material_usage.md +46 -9
- package/skills/dknowc-ppt-assistant/references/onboarding_scripts.md +7 -5
- package/skills/dknowc-ppt-assistant/references/sample_trace_report.html +372 -920
- package/skills/dknowc-ppt-assistant/references/search_intro.md +2 -2
- package/skills/dknowc-ppt-assistant/references/svg-authoring.md +2 -2
- package/skills/dknowc-ppt-assistant/scripts/api_key.py +5 -28
- package/skills/dknowc-ppt-assistant/scripts/build_trace_input.py +188 -0
- package/skills/dknowc-ppt-assistant/scripts/initialize.py +238 -3
- package/skills/dknowc-ppt-assistant/scripts/mcp_convert.py +1 -10
- package/skills/dknowc-ppt-assistant/scripts/merge_search_results.py +604 -0
- package/skills/dknowc-ppt-assistant/scripts/preview_slide_html.py +4 -11
- package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +224 -63
- package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +29 -12
- package/skills/dknowc-ppt-assistant/scripts/update_skill.py +314 -0
- package/skills/dknowc-ppt-assistant/scripts/websearch_convert.py +326 -0
- package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +92 -29
- package/skills/dknowc-ppt-assistant/workflows/routing.md +1 -1
- package/skills/dknowc-tax-assistant/README.md +54 -0
- package/skills/dknowc-tax-assistant/SKILL.md +99 -0
- package/skills/dknowc-tax-assistant/attribution.json +5 -0
- package/skills/dknowc-tax-assistant/reference/answer-and-report.md +100 -0
- package/skills/dknowc-tax-assistant/reference/capability-layer.md +205 -0
- package/skills/dknowc-tax-assistant/reference/onboarding_scripts.md +68 -0
- package/skills/dknowc-tax-assistant/reference/policy_tags.json +2002 -0
- package/skills/dknowc-tax-assistant/reference/retrieval-policy.md +43 -0
- package/skills/dknowc-tax-assistant/reference/retrieval-v2.md +58 -0
- package/skills/dknowc-tax-assistant/reference/tags.md +53 -0
- package/skills/dknowc-tax-assistant/reference/tax_claims.example.json +76 -0
- package/skills/dknowc-tax-assistant/reference/trace_report.config.json +46 -0
- package/skills/dknowc-tax-assistant/reference/troubleshooting.md +70 -0
- package/skills/dknowc-tax-assistant/reference/websearch-fallback.md +59 -0
- package/skills/dknowc-tax-assistant/resources/THIRD_PARTY_NOTICES.md +9 -0
- package/skills/dknowc-tax-assistant/resources/echarts.custom.min.js +48 -0
- package/skills/dknowc-tax-assistant/scripts/api_key.py +60 -0
- package/skills/dknowc-tax-assistant/scripts/attribution.py +61 -0
- package/skills/dknowc-tax-assistant/scripts/calc_period.py +156 -0
- package/skills/dknowc-tax-assistant/scripts/calc_tax.py +179 -0
- package/skills/dknowc-tax-assistant/scripts/check_answer.py +210 -0
- package/skills/dknowc-tax-assistant/scripts/initialize.py +208 -0
- package/skills/dknowc-tax-assistant/scripts/merge_search_results.py +631 -0
- package/skills/dknowc-tax-assistant/scripts/path_guard.py +23 -0
- package/skills/dknowc-tax-assistant/scripts/question_profile.py +444 -0
- package/skills/dknowc-tax-assistant/scripts/register_key.mjs +1173 -0
- package/skills/dknowc-tax-assistant/scripts/run_dir.py +149 -0
- package/skills/dknowc-tax-assistant/scripts/source_cards.py +372 -0
- package/skills/dknowc-tax-assistant/scripts/tag_catalog.py +164 -0
- package/skills/dknowc-tax-assistant/scripts/tax_client.py +218 -0
- package/skills/dknowc-tax-assistant/scripts/tax_search.py +403 -0
- package/skills/dknowc-tax-assistant/scripts/verify_claims.py +587 -0
- package/skills/dknowc-tax-assistant/scripts/websearch_convert.py +352 -0
- package/skills/dknowc-trusted-search/README.md +25 -19
- package/skills/dknowc-trusted-search/SKILL.md +205 -73
- package/skills/dknowc-trusted-search/config/trace_report.config.json +119 -0
- package/skills/dknowc-trusted-search/reference/onboarding_scripts.md +3 -3
- package/skills/dknowc-trusted-search/reference/sample_trace_report.html +286 -191
- package/skills/dknowc-trusted-search/resources/ECHARTS-NOTICE.txt +10 -0
- package/skills/dknowc-trusted-search/scripts/api_key.py +0 -1
- package/skills/dknowc-trusted-search/scripts/attribution.py +1 -1
- package/skills/dknowc-trusted-search/scripts/build_trace_input.py +173 -0
- package/skills/dknowc-trusted-search/scripts/deep_convert.py +79 -30
- package/skills/dknowc-trusted-search/scripts/deep_query.py +22 -33
- package/skills/dknowc-trusted-search/scripts/initialize.py +343 -2
- package/skills/dknowc-trusted-search/scripts/merge_search_results.py +222 -35
- package/skills/dknowc-trusted-search/scripts/register_key.mjs +241 -29
- package/skills/dknowc-trusted-search/scripts/source_display.py +59 -0
- package/skills/dknowc-trusted-search/scripts/trusted_search.py +67 -34
- package/skills/dknowc-trusted-search/scripts/update_skill.py +300 -0
- package/skills/dknowc-trusted-search/scripts/websearch_convert.py +328 -0
- package/src/index.js +18 -2
- package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +0 -2574
- package/skills/dknowc-ppt-assistant/official-docs/output/.gitkeep +0 -0
- package/skills/dknowc-ppt-assistant/official-docs/search-results/.gitkeep +0 -0
- package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +0 -2642
- package/skills/dknowc-trusted-search/official-docs/output/.gitkeep +0 -0
- package/skills/dknowc-trusted-search/official-docs/search-results/.gitkeep +0 -0
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""多路检索结果合并(法律检索/可信搜索混合输入 → 渲染器统一形态)。
|
|
3
|
+
|
|
4
|
+
背景:复杂法律问题可能产生多路产物——legal_search.py 的法条模式/语义模式产物
|
|
5
|
+
(content.data.检索文章形态)多路,或历史可信搜索产物。渲染脚本 render_trace_html.py
|
|
6
|
+
只接受单个 input_json,本脚本把任意多路产物程序化合并为渲染器可直接消费的单 JSON:
|
|
7
|
+
|
|
8
|
+
- **合并式去重**:按"规范化标题 + 源网址"双键判同一材料——
|
|
9
|
+
标题去空白/全角/开头"关于印发/关于"/结尾公文后缀词;同一材料**合并段落**(段落级
|
|
10
|
+
去重,保留各检索召回的不同段落)与**字段取并集**(保留非空字段、合并搜索条件标记);
|
|
11
|
+
不再按标题整体丢弃后篇。
|
|
12
|
+
- **旧深度产物兼容**:历史 deep_query 的 data.searches[].result + data.common_articles
|
|
13
|
+
仍可摊平为检索文章形态(子查询 query 作为默认搜索条件分组)。
|
|
14
|
+
- **policyFiles 收集**:各可信产物携带的 policyFiles 合并去重(writtenText+title 双键),
|
|
15
|
+
写入合并产物 content.data.policyFiles(文号匹配数据源)。
|
|
16
|
+
- **分组标签**:每路通过 --search-key 指定该路的搜索条件(核验报告"检索分组 tabs"
|
|
17
|
+
与过程回顾按此分组);未指定时可信产物默认"本次检索"、深度产物用子查询。
|
|
18
|
+
- **显式材料编号**(1.4.0 追加):合并产物的每篇材料带 `编号` = 它在合并结果中的
|
|
19
|
+
1-based 序号;答案角标 `[n]` 的 n 就用这个编号(渲染器优先读显式编号,不再依赖
|
|
20
|
+
数组位置)。**写答案时读 `编号` 字段,不要按"某一路材料清单里的第几条"编号。**
|
|
21
|
+
|
|
22
|
+
用法(输出统一写会话 run 目录,不写 Skill 安装目录):
|
|
23
|
+
python3 scripts/merge_search_results.py \
|
|
24
|
+
--run ./runs/20261120-legal-01 \
|
|
25
|
+
--input route1.json --search-key "政策依据路" \
|
|
26
|
+
--input route2.json --search-key "数据口径路" \
|
|
27
|
+
--output merged_all.json
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import argparse
|
|
33
|
+
import json
|
|
34
|
+
import re
|
|
35
|
+
import sys
|
|
36
|
+
import unicodedata
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
from typing import Any, Dict, List, Optional
|
|
39
|
+
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
|
|
40
|
+
|
|
41
|
+
import path_guard
|
|
42
|
+
|
|
43
|
+
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
|
44
|
+
SEARCH_RESULTS_DIR = SKILL_ROOT / "official-docs" / "search-results" # 历史常量,仅兼容旧引用
|
|
45
|
+
|
|
46
|
+
# 公文标题前后缀归一(合并去重用)
|
|
47
|
+
TITLE_PREFIX = ("关于印发", "关于", "印发", "发布", "印发《")
|
|
48
|
+
TITLE_SUFFIX = ("办法的通知", "办法", "实施细则的通知", "实施细则", "意见的通知",
|
|
49
|
+
"意见", "规定的通知", "规定", "公告", "的通知")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _norm_title(value: Any) -> str:
|
|
53
|
+
"""标题归一:全半角/大小写、去空白与书名号,去公文前后缀(变体判同一主体)。"""
|
|
54
|
+
text = unicodedata.normalize("NFKC", str(value or "")).lower()
|
|
55
|
+
text = re.sub(r"[《》〈〉「」『』\[\]【】()()\"'“”‘’]", "", text)
|
|
56
|
+
text = re.sub(r"\s+", "", text)
|
|
57
|
+
for prefix in TITLE_PREFIX:
|
|
58
|
+
if text.startswith(prefix):
|
|
59
|
+
text = text[len(prefix):]
|
|
60
|
+
break
|
|
61
|
+
for suffix in TITLE_SUFFIX:
|
|
62
|
+
if text.endswith(suffix):
|
|
63
|
+
text = text[: -len(suffix)]
|
|
64
|
+
break
|
|
65
|
+
return text
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _first_value(item: Dict[str, Any], *keys: str) -> str:
|
|
69
|
+
for key in keys:
|
|
70
|
+
value = item.get(key)
|
|
71
|
+
if value not in (None, "", [], {}):
|
|
72
|
+
return str(value).strip()
|
|
73
|
+
return ""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _norm_url(raw: Any) -> str:
|
|
77
|
+
"""URL 归一(只用于去重键):去 fragment、常见 tracking 参数、尾斜杠。"""
|
|
78
|
+
text = str(raw or "").strip()
|
|
79
|
+
if not text:
|
|
80
|
+
return ""
|
|
81
|
+
try:
|
|
82
|
+
parsed = urlparse(text)
|
|
83
|
+
except ValueError:
|
|
84
|
+
return ""
|
|
85
|
+
if parsed.scheme.lower() not in ("http", "https") or not parsed.netloc:
|
|
86
|
+
return text
|
|
87
|
+
drop = {"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content",
|
|
88
|
+
"gclid", "fbclid", "spm", "scm", "from", "share_token", "share_source",
|
|
89
|
+
"ref", "ref_src", "source", "campaign"}
|
|
90
|
+
query = [(k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=True)
|
|
91
|
+
if k.lower() not in drop]
|
|
92
|
+
path = parsed.path.rstrip("/") or "/"
|
|
93
|
+
return urlunparse((parsed.scheme.lower(), parsed.netloc.lower(), path, "",
|
|
94
|
+
urlencode(sorted(query)), ""))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _is_unofficial(article: Dict[str, Any]) -> bool:
|
|
98
|
+
"""非官方判定:外部联网标记或接口数据权威性=非权威。"""
|
|
99
|
+
return bool(article.get("非官方来源") or article.get("待核验") or article.get("pending")) or str(
|
|
100
|
+
article.get("数据权威性") or article.get("authority") or "").strip() in ("非权威", "non-authoritative")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _dedupe_paragraphs(paragraphs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
104
|
+
"""段落级去重:**按归一化内容判重**,id 仅无语料时兜底,保留顺序。
|
|
105
|
+
|
|
106
|
+
1.4.3 修复(WB 实测暴露):原实现优先按 `id` 判重,而段落实为**篇内局部编号**
|
|
107
|
+
(同一篇材料被多路召回时,各路 id 都从 1 起编)——两路带回的段落只要 id 相同,
|
|
108
|
+
后一路的**不同内容**会被当作重复整段丢弃(静默丢条款,且结果依赖 --input 顺序)。
|
|
109
|
+
实测:杭州门诊待遇条款一度在合并环节丢失,Agent 靠调整 --input 顺序才找回。
|
|
110
|
+
改为内容主键后:多路召回的不同段落全部并集保留,与输入顺序无关、结果可复现。
|
|
111
|
+
"""
|
|
112
|
+
seen: set = set()
|
|
113
|
+
out: List[Dict[str, Any]] = []
|
|
114
|
+
for p in paragraphs:
|
|
115
|
+
if not isinstance(p, dict):
|
|
116
|
+
continue
|
|
117
|
+
pid = str(p.get("id") or "")
|
|
118
|
+
content = re.sub(r"\s+", "", str(p.get("内容") or p.get("content") or ""))
|
|
119
|
+
key = f"c:{content}" if content else (f"id:{pid}" if pid else "")
|
|
120
|
+
if key and key in seen:
|
|
121
|
+
continue
|
|
122
|
+
if key:
|
|
123
|
+
seen.add(key)
|
|
124
|
+
out.append(p)
|
|
125
|
+
return out
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _merge_article(target: Dict[str, Any], incoming: Dict[str, Any]) -> None:
|
|
129
|
+
"""同材料合并:段落并集 + 字段取并集(非空优先)+ 搜索条件合并。"""
|
|
130
|
+
para_key = "段落" if "段落" in target or "段落" in incoming else "paragraphs"
|
|
131
|
+
merged_paras = list(target.get(para_key) or []) + list(incoming.get(para_key) or [])
|
|
132
|
+
target[para_key] = _dedupe_paragraphs(merged_paras)
|
|
133
|
+
for key, value in incoming.items():
|
|
134
|
+
if key in (para_key, "_route_idx", "_para_contrib"):
|
|
135
|
+
continue
|
|
136
|
+
if value not in (None, "", [], {}):
|
|
137
|
+
if key not in target or target[key] in (None, "", [], {}):
|
|
138
|
+
target[key] = value
|
|
139
|
+
for _owner, _cnt in (incoming.get("_para_contrib") or {}).items():
|
|
140
|
+
if isinstance(_owner, int) and isinstance(_cnt, int) and _cnt > 0:
|
|
141
|
+
_tpc = target.setdefault("_para_contrib", {})
|
|
142
|
+
_tpc[_owner] = _tpc.get(_owner, 0) + _cnt
|
|
143
|
+
# 检索通道:不同则顿号拼接保留双通道(2026-10-14 修复——字段并集"非空优先"会让
|
|
144
|
+
# 先入的深搜标签吃掉补搜标签,单条材料的通道归属失真;与句子指纹去重处同款)
|
|
145
|
+
for ch_key in ("检索通道", "channel"):
|
|
146
|
+
cur_ch = str(target.get(ch_key) or "").strip()
|
|
147
|
+
inc_ch = str(incoming.get(ch_key) or "").strip()
|
|
148
|
+
# 按 token(顿号分隔)去重后拼接(2026-10-16 修复):原用子串判断,
|
|
149
|
+
# "深知可信搜索" 遇 "深知深度搜索、深知可信搜索" 时整串不是子串,会把已含的
|
|
150
|
+
# token 再拼一次,产生 "深知深度搜索、深知深度搜索、深知可信搜索" 这类重复值。
|
|
151
|
+
if inc_ch:
|
|
152
|
+
toks = [t.strip() for t in cur_ch.split("、") if t.strip()]
|
|
153
|
+
for t in inc_ch.split("、"):
|
|
154
|
+
t = t.strip()
|
|
155
|
+
if t and t not in toks:
|
|
156
|
+
toks.append(t)
|
|
157
|
+
merged_ch = "、".join(toks)
|
|
158
|
+
if merged_ch != cur_ch:
|
|
159
|
+
target[ch_key] = merged_ch
|
|
160
|
+
# 搜索条件(分组标签):**不拼接**,保留首路标签作为分组归属。
|
|
161
|
+
# 旧实现把两路标签拼成 "上海市落户政策、上海:人才引进申办条件" 这类组合标签,
|
|
162
|
+
# 会把 7 路撑成 10 个分组,过程回顾条的"检索 N 次"随之虚高,材料专库也出现怪分组
|
|
163
|
+
# (2026-09-28 WB 实测:实际 7 路、报告显示 10 次)。并集信息不丢,另存 搜索条件全部。
|
|
164
|
+
for key in ("搜索条件", "search_key"):
|
|
165
|
+
cur = str(target.get(key) or "").strip()
|
|
166
|
+
inc = str(incoming.get(key) or "").strip()
|
|
167
|
+
if not cur:
|
|
168
|
+
if inc:
|
|
169
|
+
target[key] = inc
|
|
170
|
+
continue
|
|
171
|
+
if inc and inc != cur:
|
|
172
|
+
all_key = f"{key}全部"
|
|
173
|
+
vals = list(target.get(all_key) or [cur])
|
|
174
|
+
if inc not in vals:
|
|
175
|
+
vals.append(inc)
|
|
176
|
+
target[all_key] = vals
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _to_article(item: Dict[str, Any], default_key: str = "") -> Dict[str, Any]:
|
|
180
|
+
"""把深度产物条目/可信产物条目归一为检索文章字段(渲染器 source_from_article 契约)。"""
|
|
181
|
+
article = {
|
|
182
|
+
"文章标题": _first_value(item, "文章标题", "title", "标题"),
|
|
183
|
+
"数据源": _first_value(item, "数据源", "source"),
|
|
184
|
+
"来源通道": _first_value(item, "来源通道", "source_channel"),
|
|
185
|
+
"来源性质": _first_value(item, "来源性质", "source_nature"),
|
|
186
|
+
"发布日期": _first_value(item, "发布日期", "date"),
|
|
187
|
+
"发布日期可信度": _first_value(item, "发布日期可信度", "date_confidence"),
|
|
188
|
+
"源网址": _first_value(item, "源网址", "url", "原文链接"),
|
|
189
|
+
"段落": item.get("段落") if isinstance(item.get("段落"), list) else
|
|
190
|
+
[{"内容": str(item.get("内容") or item.get("paragraph") or "").strip()}] if (item.get("内容") or item.get("paragraph")) else [],
|
|
191
|
+
}
|
|
192
|
+
for snap_key in ("screenShotPath", "快照链接", "snapshot"):
|
|
193
|
+
snap = _first_value(item, snap_key)
|
|
194
|
+
if snap:
|
|
195
|
+
article["screenShotPath"] = snap
|
|
196
|
+
break
|
|
197
|
+
# 文号键链(2026-10-23):「发文字号」是 V2 可信路文章级实际键名(policy 路实测返回,
|
|
198
|
+
# 如 商办消费函〔2021〕58号)——缺它则 V2 文号全靠 policyFiles 本地匹配兜底(writtenText
|
|
199
|
+
# 偶发为空,兜底不稳);`writtenText` 为深搜接口 10-23 新增文章级键(标题命中 policyFiles
|
|
200
|
+
# 才有,部分覆盖)。中文键优先、英文键垫底,全部缺键时行为不变
|
|
201
|
+
if _first_value(item, "文号", "发文字号", "doc_number", "writtenText"):
|
|
202
|
+
article["文号"] = _first_value(item, "文号", "发文字号", "doc_number", "writtenText")
|
|
203
|
+
# 检索通道透传(1.5.0):检索脚本在产物文章级打的 检索通道 标注,渲染按接口通道拆分计数
|
|
204
|
+
if _first_value(item, "检索通道", "channel"):
|
|
205
|
+
article["检索通道"] = _first_value(item, "检索通道", "channel")
|
|
206
|
+
# 非官方来源透传(1.6.0):联网路(searchChannel=webSearch)脚本打标 非官方来源=True,
|
|
207
|
+
# 及接口 dataAuthority 返回的 数据权威性(实测联网结果为"非权威")——渲染层按双口径打徽标
|
|
208
|
+
if item.get("非官方来源"):
|
|
209
|
+
article["非官方来源"] = True
|
|
210
|
+
if _first_value(item, "数据权威性", "authority"):
|
|
211
|
+
article["数据权威性"] = _first_value(item, "数据权威性", "authority")
|
|
212
|
+
if item.get("待核验"):
|
|
213
|
+
article["待核验"] = True
|
|
214
|
+
if item.get("pending"):
|
|
215
|
+
article["pending"] = True
|
|
216
|
+
# 法律场景审计字段透传(2026-11-04):合并必须保留文章 ID 与选本/版本信息。
|
|
217
|
+
# 否则多路合并后下游按 文章Id 回填版本元数据会 KeyError(WorkBuddy 首测实测),
|
|
218
|
+
# 版本状态/标记/选本依据也会在合并时丢失,报告只能显示“未记录”。
|
|
219
|
+
for _field in (
|
|
220
|
+
"文章Id", "文章类型", "发布或实施机构", "原始标题", "文件标签",
|
|
221
|
+
"生效日期", "版本状态", "版本标记", "版本标记命中", "版本状态存疑",
|
|
222
|
+
"历次版本数", "选本依据", "核验",
|
|
223
|
+
):
|
|
224
|
+
_value = item.get(_field)
|
|
225
|
+
if _value not in (None, "", [], {}):
|
|
226
|
+
article[_field] = _value
|
|
227
|
+
key = _first_value(item, "搜索条件", "search_key", "deep_group") or default_key
|
|
228
|
+
if key:
|
|
229
|
+
article["搜索条件"] = key
|
|
230
|
+
return article
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _collect_route(input_path: Path, search_key: str,
|
|
234
|
+
articles: List[Dict[str, Any]], policy_files: List[Dict[str, Any]],
|
|
235
|
+
route_idx: int = -1) -> None:
|
|
236
|
+
"""处理一路输入:可信形态(content.data.检索文章)或深度形态(data.searches)。"""
|
|
237
|
+
data = json.loads(input_path.read_text(encoding="utf-8"))
|
|
238
|
+
policy_holder = data.get("content") if isinstance(data.get("content"), dict) else data
|
|
239
|
+
pf = (policy_holder.get("data") or {}).get("policyFiles") if isinstance(policy_holder.get("data"), dict) else []
|
|
240
|
+
for p in pf or []:
|
|
241
|
+
if isinstance(p, dict):
|
|
242
|
+
policy_files.append(dict(p))
|
|
243
|
+
|
|
244
|
+
# 1.5.1 起只处理通用形态(content.data.检索文章)——深度搜索原始产物先经
|
|
245
|
+
# deep_convert.py 转换(接口适配收敛在转换层);历史深搜形态由转换层前置解决
|
|
246
|
+
search_articles = (policy_holder.get("data") or {}).get("检索文章")
|
|
247
|
+
if isinstance(search_articles, list):
|
|
248
|
+
for item in search_articles:
|
|
249
|
+
if isinstance(item, dict):
|
|
250
|
+
_a = _to_article(item, search_key or "本次检索")
|
|
251
|
+
if route_idx >= 0:
|
|
252
|
+
_a["_route_idx"] = route_idx # 每路调用增量统计用(1.6.0),输出前剥离
|
|
253
|
+
articles.append(_a)
|
|
254
|
+
return
|
|
255
|
+
|
|
256
|
+
d = data.get("data") if isinstance(data.get("data"), dict) else {}
|
|
257
|
+
if isinstance(d.get("searches"), list):
|
|
258
|
+
raise SystemExit(
|
|
259
|
+
"错误:检测到深度搜索 v3 原始形态(data.searches)——merge 自 1.5.1 起只处理通用形态。"
|
|
260
|
+
"\n请先运行转换层:python3 scripts/deep_convert.py <深搜原始.json>,再把转换产物传给 --input。"
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def main() -> None:
|
|
265
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
266
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
267
|
+
parser = argparse.ArgumentParser(description="多路检索结果合并(可信/深度混合 → 渲染器统一形态)")
|
|
268
|
+
parser.add_argument("--input", action="append", required=True, help="输入 JSON(可多次传入,每路一个)")
|
|
269
|
+
parser.add_argument("--search-key", action="append", help="对应 --input 路次的搜索条件分组标签(可多次;只传 1 个时应用到全部输入;缺省自动)")
|
|
270
|
+
parser.add_argument("--output", "-o", help="输出文件名(落到 --run 目录,默认 merged_all.json)")
|
|
271
|
+
parser.add_argument("--run", help="会话 run 目录(也可用环境变量 DKNOWC_RUN_DIR)")
|
|
272
|
+
args = parser.parse_args()
|
|
273
|
+
|
|
274
|
+
if args.search_key and len(args.search_key) not in (1, len(args.input)):
|
|
275
|
+
raise SystemExit("错误:--search-key 数量必须与 --input 一致(或缺省;只传 1 个时应用到全部输入)。")
|
|
276
|
+
if args.search_key and len(args.search_key) == 1 and len(args.input) > 1:
|
|
277
|
+
keys = args.search_key * len(args.input)
|
|
278
|
+
else:
|
|
279
|
+
keys = args.search_key or [""] * len(args.input)
|
|
280
|
+
|
|
281
|
+
articles: List[Dict[str, Any]] = []
|
|
282
|
+
policy_files: List[Dict[str, Any]] = []
|
|
283
|
+
by_key: Dict[str, Dict[str, Any]] = {}
|
|
284
|
+
total_in = 0
|
|
285
|
+
|
|
286
|
+
for _ri, (input_path_str, key) in enumerate(zip(args.input, keys)):
|
|
287
|
+
# 相对路径按会话 run 目录解析(不再回退 Skill 内 official-docs/)
|
|
288
|
+
try:
|
|
289
|
+
raw_path = path_guard.safe_read_path(input_path_str, args.run)
|
|
290
|
+
except ValueError as exc:
|
|
291
|
+
raise SystemExit(f"错误:{exc}") from None
|
|
292
|
+
before = len(articles)
|
|
293
|
+
_collect_route(raw_path, key, articles, policy_files, route_idx=_ri)
|
|
294
|
+
total_in += len(articles) - before
|
|
295
|
+
|
|
296
|
+
# 每路调用增量统计(1.6.0,过程可信度):该路带来多少篇新材料(new_articles)、
|
|
297
|
+
# 给已有材料补充了多少段(added_paragraphs)——过程条按真实调用次数展示每条补搜的
|
|
298
|
+
# 实际贡献,避免按分组主通道统计时把补搜吞掉(对齐公文写作 3.9.0)。
|
|
299
|
+
call_stats: List[Dict[str, Any]] = [
|
|
300
|
+
{"label": (keys[i] or Path(args.input[i]).name), "file": Path(args.input[i]).name,
|
|
301
|
+
"articles_in": 0, "new_articles": 0, "added_paragraphs": 0}
|
|
302
|
+
for i in range(len(args.input))
|
|
303
|
+
]
|
|
304
|
+
|
|
305
|
+
# 合并式去重
|
|
306
|
+
for art in articles:
|
|
307
|
+
_ri = art.get("_route_idx")
|
|
308
|
+
if isinstance(_ri, int) and 0 <= _ri < len(call_stats):
|
|
309
|
+
call_stats[_ri]["articles_in"] += 1
|
|
310
|
+
title = str(art.get("文章标题") or "").strip()
|
|
311
|
+
url = str(art.get("源网址") or "").strip()
|
|
312
|
+
norm = _norm_title(title)
|
|
313
|
+
url_key = _norm_url(url) if url else ""
|
|
314
|
+
key = f"{norm}|{url_key}" if url_key else norm
|
|
315
|
+
if not key:
|
|
316
|
+
continue
|
|
317
|
+
if key in by_key:
|
|
318
|
+
target = by_key[key]
|
|
319
|
+
target_unofficial = _is_unofficial(target)
|
|
320
|
+
incoming_unofficial = _is_unofficial(art)
|
|
321
|
+
if target_unofficial != incoming_unofficial:
|
|
322
|
+
# 官方 vs 外部:官方记录整体胜出,且与 --input 顺序无关;
|
|
323
|
+
# 不吸收外部段落/数据源/日期/文号/快照/检索通道/分组。
|
|
324
|
+
if not incoming_unofficial:
|
|
325
|
+
_prev_owner = target.get("_route_idx")
|
|
326
|
+
if isinstance(_ri, int) and 0 <= _ri < len(call_stats):
|
|
327
|
+
if (isinstance(_prev_owner, int) and _prev_owner != _ri
|
|
328
|
+
and 0 <= _prev_owner < len(call_stats)):
|
|
329
|
+
call_stats[_prev_owner]["new_articles"] = max(
|
|
330
|
+
0, call_stats[_prev_owner]["new_articles"] - 1)
|
|
331
|
+
call_stats[_ri]["new_articles"] += 1
|
|
332
|
+
for _owner, _cnt in (target.get("_para_contrib") or {}).items():
|
|
333
|
+
if (isinstance(_owner, int) and 0 <= _owner < len(call_stats)
|
|
334
|
+
and isinstance(_cnt, int) and _cnt > 0):
|
|
335
|
+
call_stats[_owner]["added_paragraphs"] = max(
|
|
336
|
+
0, call_stats[_owner]["added_paragraphs"] - _cnt)
|
|
337
|
+
art["_para_contrib"] = {}
|
|
338
|
+
by_key[key] = art
|
|
339
|
+
continue
|
|
340
|
+
_before = len(target.get("段落") or [])
|
|
341
|
+
_merge_article(target, art)
|
|
342
|
+
_delta = max(0, len(target.get("段落") or []) - _before)
|
|
343
|
+
if isinstance(_ri, int) and 0 <= _ri < len(call_stats):
|
|
344
|
+
call_stats[_ri]["new_articles"] += 0
|
|
345
|
+
call_stats[_ri]["added_paragraphs"] += _delta
|
|
346
|
+
if _delta > 0:
|
|
347
|
+
_pc = target.setdefault("_para_contrib", {})
|
|
348
|
+
_pc[_ri] = _pc.get(_ri, 0) + _delta
|
|
349
|
+
else:
|
|
350
|
+
by_key[key] = art
|
|
351
|
+
if isinstance(_ri, int) and 0 <= _ri < len(call_stats):
|
|
352
|
+
call_stats[_ri]["new_articles"] += 1
|
|
353
|
+
merged = list(by_key.values())
|
|
354
|
+
|
|
355
|
+
# —— 近似重复去重(句子指纹,1.5.0)——
|
|
356
|
+
# 搜索接口对同一篇文章常返回多个标题变体条目,上面的"标题+URL"双键去重会漏掉,
|
|
357
|
+
# 表现为知识专库中同一内容出现多张卡:段落完全一致、或分段切法不同顺序略异。
|
|
358
|
+
# 按"句子集合"二次判定:一篇的句子被另一篇覆盖过半(交集≥4句且 inter/min≥0.55)
|
|
359
|
+
# 即判同一材料,保留更完整的一篇(相当时优先发文版标题),段落取并集。
|
|
360
|
+
def _norm_sent(s) -> str:
|
|
361
|
+
return re.sub(r"[\s,,、。;;::!!??「」『』“”\"'()()【】·—\[\]-]", "", str(s or ""))
|
|
362
|
+
|
|
363
|
+
def _sentence_fp(article: dict) -> set:
|
|
364
|
+
sents = set()
|
|
365
|
+
for p in (article.get("段落") or []):
|
|
366
|
+
if not isinstance(p, dict):
|
|
367
|
+
continue
|
|
368
|
+
for s in re.split(r"[。;;!??]", str(p.get("内容") or p.get("content") or "")):
|
|
369
|
+
ns = _norm_sent(s)
|
|
370
|
+
if len(ns) >= 12:
|
|
371
|
+
sents.add(ns)
|
|
372
|
+
return sents
|
|
373
|
+
|
|
374
|
+
def _is_official_title(t: str) -> bool:
|
|
375
|
+
t = t or ""
|
|
376
|
+
return ("关于印发" in t) or t.endswith("的通知") or t.endswith("的公告") or t.endswith("的意见")
|
|
377
|
+
|
|
378
|
+
_fps = [_sentence_fp(a) for a in merged]
|
|
379
|
+
_i = 0
|
|
380
|
+
_near_dup = 0
|
|
381
|
+
while _i < len(merged):
|
|
382
|
+
_j = _i + 1
|
|
383
|
+
while _j < len(merged):
|
|
384
|
+
si, sj = _fps[_i], _fps[_j]
|
|
385
|
+
inter = len(si & sj) if (si and sj) else 0
|
|
386
|
+
if inter >= 4 and inter / min(len(si), len(sj)) >= 0.55:
|
|
387
|
+
_i_unofficial = _is_unofficial(merged[_i])
|
|
388
|
+
_j_unofficial = _is_unofficial(merged[_j])
|
|
389
|
+
if _i_unofficial != _j_unofficial:
|
|
390
|
+
# 官方优先:外部近似重复不得吞掉官方卡,也不把外部段落并进官方卡
|
|
391
|
+
keep_idx = _j if _i_unofficial else _i
|
|
392
|
+
elif len(si) != len(sj):
|
|
393
|
+
keep_idx = _i if len(si) > len(sj) else _j
|
|
394
|
+
else:
|
|
395
|
+
ti = merged[_i].get("文章标题") or ""
|
|
396
|
+
tj = merged[_j].get("文章标题") or ""
|
|
397
|
+
keep_idx = _i if (_is_official_title(ti) or not _is_official_title(tj)) else _j
|
|
398
|
+
drop_idx = _j if keep_idx == _i else _i
|
|
399
|
+
keep, drop = merged[keep_idx], merged[drop_idx]
|
|
400
|
+
if _is_unofficial(keep) != _is_unofficial(drop):
|
|
401
|
+
_drop_owner = drop.get("_route_idx")
|
|
402
|
+
if (isinstance(_drop_owner, int) and 0 <= _drop_owner < len(call_stats)):
|
|
403
|
+
call_stats[_drop_owner]["new_articles"] = max(
|
|
404
|
+
0, call_stats[_drop_owner]["new_articles"] - 1)
|
|
405
|
+
for _owner, _cnt in (drop.get("_para_contrib") or {}).items():
|
|
406
|
+
if (isinstance(_owner, int) and 0 <= _owner < len(call_stats)
|
|
407
|
+
and isinstance(_cnt, int) and _cnt > 0):
|
|
408
|
+
call_stats[_owner]["added_paragraphs"] = max(
|
|
409
|
+
0, call_stats[_owner]["added_paragraphs"] - _cnt)
|
|
410
|
+
merged.pop(drop_idx)
|
|
411
|
+
_fps.pop(drop_idx)
|
|
412
|
+
_near_dup += 1
|
|
413
|
+
if drop_idx == _i:
|
|
414
|
+
_j = _i + 1
|
|
415
|
+
continue
|
|
416
|
+
# 同权威近似重复:被并卡不再是独立材料,所属路次 new_articles 回滚 -1;
|
|
417
|
+
# 被并卡的段落贡献并入保留卡,便于后续若保留卡被丢弃时完整回滚。
|
|
418
|
+
_drop_owner = drop.get("_route_idx")
|
|
419
|
+
if isinstance(_drop_owner, int) and 0 <= _drop_owner < len(call_stats):
|
|
420
|
+
call_stats[_drop_owner]["new_articles"] = max(
|
|
421
|
+
0, call_stats[_drop_owner]["new_articles"] - 1)
|
|
422
|
+
for _owner, _cnt in (drop.get("_para_contrib") or {}).items():
|
|
423
|
+
if isinstance(_owner, int) and isinstance(_cnt, int) and _cnt > 0:
|
|
424
|
+
_kpc = keep.setdefault("_para_contrib", {})
|
|
425
|
+
_kpc[_owner] = _kpc.get(_owner, 0) + _cnt
|
|
426
|
+
# 段落取并集(内容级去重;后续统一编号)
|
|
427
|
+
_seen_para = {re.sub(r"\s+", "", str(p.get("内容") or p.get("content") or ""))
|
|
428
|
+
for p in (keep.get("段落") or [])}
|
|
429
|
+
for p in (drop.get("段落") or []):
|
|
430
|
+
pc = re.sub(r"\s+", "", str(p.get("内容") or p.get("content") or ""))
|
|
431
|
+
if pc and pc not in _seen_para:
|
|
432
|
+
_seen_para.add(pc)
|
|
433
|
+
keep.setdefault("段落", []).append(p)
|
|
434
|
+
# 字段取并集:保留篇空字段用被并篇补;检索通道不同则拼接保留双通道
|
|
435
|
+
for f, v in drop.items():
|
|
436
|
+
if f in ("段落", "_route_idx", "_para_contrib"):
|
|
437
|
+
continue
|
|
438
|
+
if not keep.get(f) and v:
|
|
439
|
+
keep[f] = v
|
|
440
|
+
# 通道拼接同款 token 去重(2026-10-16,与字段并集处同口径)
|
|
441
|
+
_inc = (drop.get("检索通道") or "").strip()
|
|
442
|
+
if _inc:
|
|
443
|
+
_toks = [t.strip() for t in (keep.get("检索通道") or "").split("、") if t.strip()]
|
|
444
|
+
for _t in _inc.split("、"):
|
|
445
|
+
_t = _t.strip()
|
|
446
|
+
if _t and _t not in _toks:
|
|
447
|
+
_toks.append(_t)
|
|
448
|
+
_merged = "、".join(_toks)
|
|
449
|
+
if _merged != (keep.get("检索通道") or ""):
|
|
450
|
+
keep["检索通道"] = _merged
|
|
451
|
+
merged.pop(drop_idx)
|
|
452
|
+
_fps.pop(drop_idx)
|
|
453
|
+
_near_dup += 1
|
|
454
|
+
if drop_idx == _i:
|
|
455
|
+
_j = _i + 1 # _i 处已换成保留篇,重新向后比较
|
|
456
|
+
continue
|
|
457
|
+
_j += 1
|
|
458
|
+
_i += 1
|
|
459
|
+
|
|
460
|
+
# —— 段内污染段去重(1.5.0,修"一张卡里两段内容一样")——
|
|
461
|
+
# ① 内容完全一致 → 保留先出现的;
|
|
462
|
+
# ② "标题链拼进正文"的污染段——接口偶发把段落标题/上级标题文字拼进内容开头,
|
|
463
|
+
# 形成 内容=标题前缀+另一段内容 的超集段(渲染剥前缀后两段看起来完全一样)。
|
|
464
|
+
# 判定:归一化后一段是另一段的前缀或后缀超集(短段≥30字)→ 丢弃污染长段、保留干净段。
|
|
465
|
+
for article in merged:
|
|
466
|
+
paras = article.get("段落") or []
|
|
467
|
+
# 归一化加强(2026-11-05,T5 实测):旧版只去空白,法条模式与语义模式两份副本
|
|
468
|
+
# 全半角标点不一("(一);"vs"(一);")时同一条文比不相等、双份并存。改为去全部
|
|
469
|
+
# 空白与标点(只留字词与数字)再比对。
|
|
470
|
+
def _hard(t) -> str:
|
|
471
|
+
return re.sub(r"[\W_]+", "", str(t or ""))
|
|
472
|
+
|
|
473
|
+
texts = [_hard(p.get("内容") or p.get("content")) for p in paras]
|
|
474
|
+
# 同条号旧版混入(2026-11-05):语义召回的旧版条文段(如 2004 版条例第十四条)与
|
|
475
|
+
# 选本器选定的现行版并存一卡。标题尾级同为"第X条"的段落只保留最长的一段。
|
|
476
|
+
art_of = []
|
|
477
|
+
for p in paras:
|
|
478
|
+
m = re.search(r"第[零一二三四五六七八九十百千〇]+条", str(p.get("标题") or "").split(">")[-1])
|
|
479
|
+
art_of.append(m.group(0) if m else "")
|
|
480
|
+
drop_set = set()
|
|
481
|
+
for a in range(len(paras)):
|
|
482
|
+
ta = texts[a]
|
|
483
|
+
if len(ta) < 30 or a in drop_set:
|
|
484
|
+
continue
|
|
485
|
+
for b in range(len(paras)):
|
|
486
|
+
tb = texts[b]
|
|
487
|
+
if a == b or b in drop_set or len(tb) < 30:
|
|
488
|
+
continue
|
|
489
|
+
if ta == tb:
|
|
490
|
+
if a < b:
|
|
491
|
+
drop_set.add(b) # 完全一致:保留先出现的
|
|
492
|
+
continue
|
|
493
|
+
if art_of[a] and art_of[a] == art_of[b]:
|
|
494
|
+
# 同条号两份(跨版本/截断):留内容更长的
|
|
495
|
+
drop_set.add(a if len(ta) < len(tb) else b)
|
|
496
|
+
continue
|
|
497
|
+
if tb.startswith(ta) or tb.endswith(ta):
|
|
498
|
+
drop_set.add(b) # b 是带标题前缀的污染超集段
|
|
499
|
+
elif ta.startswith(tb) or ta.endswith(tb):
|
|
500
|
+
drop_set.add(a) # a 才是污染段
|
|
501
|
+
if drop_set:
|
|
502
|
+
article["段落"] = [p for i, p in enumerate(paras) if i not in drop_set]
|
|
503
|
+
|
|
504
|
+
# 清理内部字段:_route_idx 只用于合并期统计,不进入交付 JSON
|
|
505
|
+
for _art in merged:
|
|
506
|
+
_art.pop("_route_idx", None)
|
|
507
|
+
_art.pop("_para_contrib", None)
|
|
508
|
+
|
|
509
|
+
# 显式材料编号(1.4.0):给每篇材料盖上 `编号` = 它在合并产物中的 1-based 序号。
|
|
510
|
+
# 渲染器优先读材料上的显式编号(render_trace_html.source_from_article 的 explicit_id),
|
|
511
|
+
# 答案角标 [n] 因此锚定在一个"读得到"的编号上,不必让模型去数数组位置——
|
|
512
|
+
# 多路合并后总序号与各路内部的相对编号不同(实测:WorkBuddy 需反复确认才敢写),
|
|
513
|
+
# 数错会静默绑到另一份材料且核验单不会报警,故改为显式锚点。
|
|
514
|
+
for _idx, _art in enumerate(merged, start=1):
|
|
515
|
+
_art["编号"] = _idx
|
|
516
|
+
# 旧版标注(1.0.4 随上游内核迁移,从渲染器移到合并层):接口给了失效日期且已过期的
|
|
517
|
+
# 材料,在"核验"说明前置"旧版 · 失效于…"——上游材料卡不再有独立失效字段,
|
|
518
|
+
# 该说明经 build_report_input 映射为材料"核验"说明,卡片如实展示。
|
|
519
|
+
_expired = str(_art.get("失效日期") or _art.get("expired_at") or "").strip()
|
|
520
|
+
# 生效时间显式化(律所反馈场景六 P0:引用要能核验"生效时间"):接口给了生效日期
|
|
521
|
+
# 而核验说明未提及的,把"生效于 X"并入材料核验说明,卡片如实展示。
|
|
522
|
+
_eff = str(_art.get("生效日期") or _art.get("effectiveDate") or "").strip()
|
|
523
|
+
if _eff and _eff not in str(_art.get("核验") or ""):
|
|
524
|
+
_prev = str(_art.get("核验") or "").strip()
|
|
525
|
+
_art["核验"] = ("生效于 " + _eff + (";" + _prev if _prev else ""))
|
|
526
|
+
if _expired:
|
|
527
|
+
import re as _re
|
|
528
|
+
_m = _re.search(r"(\d{4})[年./-]?(\d{1,2})?[月./-]?(\d{1,2})?", _expired)
|
|
529
|
+
if _m:
|
|
530
|
+
_note = f"旧版 · 失效于 {_expired}"
|
|
531
|
+
_prev = str(_art.get("核验") or "").strip()
|
|
532
|
+
_art["核验"] = (_note + (";" + _prev if _prev else ""))
|
|
533
|
+
|
|
534
|
+
# policyFiles 收集去重(writtenText+title 双键)
|
|
535
|
+
pf_seen: set = set()
|
|
536
|
+
pf_out: List[Dict[str, Any]] = []
|
|
537
|
+
for p in policy_files:
|
|
538
|
+
w = str(p.get("writtenText") or p.get("发文字号") or "").strip()
|
|
539
|
+
t = str(p.get("title") or p.get("标题") or "").strip()
|
|
540
|
+
if not w and not t:
|
|
541
|
+
continue
|
|
542
|
+
pf_key = f"{w}|{t}"
|
|
543
|
+
if pf_key in pf_seen:
|
|
544
|
+
continue
|
|
545
|
+
pf_seen.add(pf_key)
|
|
546
|
+
pf_out.append(p)
|
|
547
|
+
|
|
548
|
+
out_name = args.output or "merged_all.json"
|
|
549
|
+
try:
|
|
550
|
+
out = path_guard.safe_write_path(out_name, args.run)
|
|
551
|
+
path_guard.refuse_existing(out, kind="输出")
|
|
552
|
+
except ValueError as exc:
|
|
553
|
+
raise SystemExit(f"错误:{exc}") from None
|
|
554
|
+
|
|
555
|
+
result = {
|
|
556
|
+
"search_meta": {"merged": True, "input_routes": len(args.input), "merged_from": [str(Path(x).name) for x in args.input]},
|
|
557
|
+
"content": {"data": {"检索文章": merged, "policyFiles": pf_out}},
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
# 材料池清单(1.4.3 证据侧覆盖):写答案大纲前先扫描——识别与用户情形相关、
|
|
561
|
+
# 但问题字面未覆盖的主题。清单 = 机构分布 + 文号 + 涉及金额 + 全量标题,
|
|
562
|
+
# 同时写入 search_meta.pool_summary(供程序复用)并打印到 stdout(供 Agent 扫描)。
|
|
563
|
+
def _art_org(a: Dict[str, Any]) -> str:
|
|
564
|
+
# 机构分布按发文机关统计(2026-11-13 统一口径);数据源只是抓取站点,不作机构。
|
|
565
|
+
return str(a.get("发布或实施机构") or a.get("发布机关") or "").strip() or "(未标注机构)"
|
|
566
|
+
|
|
567
|
+
org_counts: Dict[str, int] = {}
|
|
568
|
+
for a in merged:
|
|
569
|
+
key = _art_org(a)[:24]
|
|
570
|
+
org_counts[key] = org_counts.get(key, 0) + 1
|
|
571
|
+
doc_numbers: List[str] = []
|
|
572
|
+
for p in pf_out:
|
|
573
|
+
w = str(p.get("writtenText") or "").strip()
|
|
574
|
+
if w and w not in doc_numbers:
|
|
575
|
+
doc_numbers.append(w)
|
|
576
|
+
amounts: List[str] = []
|
|
577
|
+
for a in merged:
|
|
578
|
+
for seg in (a.get("段落") or []):
|
|
579
|
+
if not isinstance(seg, dict):
|
|
580
|
+
continue
|
|
581
|
+
for m2 in re.finditer(r"\d+(?:\.\d+)?(?:\s*[万亿])?元", str(seg.get("内容") or "")):
|
|
582
|
+
v = m2.group(0)
|
|
583
|
+
if v not in amounts:
|
|
584
|
+
amounts.append(v)
|
|
585
|
+
if len(amounts) >= 30:
|
|
586
|
+
break
|
|
587
|
+
pool_summary = {
|
|
588
|
+
"articles": len(merged),
|
|
589
|
+
"orgs": dict(sorted(org_counts.items(), key=lambda kv: -kv[1])[:20]),
|
|
590
|
+
"doc_numbers": doc_numbers[:40],
|
|
591
|
+
"amounts": amounts[:30],
|
|
592
|
+
"titles": [
|
|
593
|
+
{"编号": a.get("编号", i + 1), "标题": str(a.get("文章标题") or "")[:60],
|
|
594
|
+
"机构": _art_org(a)[:24], "日期": str(a.get("发布日期") or "")[:10],
|
|
595
|
+
# 摘要 = 首个非空段落前 60 字:主题藏在正文里(标题看不出)的材料同样能被扫到
|
|
596
|
+
"摘要": next((re.sub(r"\s+", " ", str(seg.get("内容") or "")).strip()[:60]
|
|
597
|
+
for seg in (a.get("段落") or [])
|
|
598
|
+
if isinstance(seg, dict) and str(seg.get("内容") or "").strip()), "")}
|
|
599
|
+
for i, a in enumerate(merged)
|
|
600
|
+
],
|
|
601
|
+
}
|
|
602
|
+
result["search_meta"]["pool_summary"] = pool_summary
|
|
603
|
+
# 每路调用增量(1.6.0):渲染过程条按真实调用次数展示每条补搜的实际贡献
|
|
604
|
+
result["search_meta"]["calls"] = call_stats
|
|
605
|
+
|
|
606
|
+
# official-docs/ 不随发布包携带(平台不接受 .gitkeep,目录由脚本运行期自动创建)
|
|
607
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
608
|
+
out.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
609
|
+
print(f"✓ 合并完成:{len(args.input)} 路 / 输入 {total_in} 篇 → 合并去重后 {len(merged)} 篇"
|
|
610
|
+
f"(policyFiles {len(pf_out)} 条)→ {out}")
|
|
611
|
+
print(" 合并产物与 legal_search.py 单路输出同构,可直接作为 render_trace_html.py 的 input_json。")
|
|
612
|
+
print("── 每路调用增量(过程可信度:该路新增 N 篇 · 为已有材料补充 K 段)──")
|
|
613
|
+
for _c in call_stats:
|
|
614
|
+
print(f" · {_c['label']}:输入 {_c['articles_in']} 篇 → 新增 {_c['new_articles']} 篇 · 补充 {_c['added_paragraphs']} 段")
|
|
615
|
+
print("── 材料池清单(证据侧覆盖:写答案大纲前先扫描,识别与用户情形相关、但问题字面未覆盖的主题)──")
|
|
616
|
+
print(" 机构分布:" + ";".join(f"{k}×{v}" for k, v in list(pool_summary["orgs"].items())[:12]))
|
|
617
|
+
if doc_numbers:
|
|
618
|
+
print(f" 文号 {len(doc_numbers)} 个:{'、'.join(doc_numbers[:12])}{'…' if len(doc_numbers) > 12 else ''}")
|
|
619
|
+
if amounts:
|
|
620
|
+
print(" 涉及金额样例:" + "、".join(amounts[:15]))
|
|
621
|
+
print(f" 标题清单({len(merged)} 篇;含首段摘要,便于识别标题看不出的主题):")
|
|
622
|
+
for t in pool_summary["titles"]:
|
|
623
|
+
line = f" {t['编号']:>3}. {t['标题']}|{t['机构']}|{t['日期']}"
|
|
624
|
+
if t.get("摘要"):
|
|
625
|
+
line += f"|{t['摘要']}"
|
|
626
|
+
print(line)
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
if __name__ == "__main__":
|
|
630
|
+
main()
|