dknowc-dsh 2.3.1 → 2.4.0
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/package.json +2 -2
- 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/official-docs/input//345/274/225/347/224/250/345/257/271/347/205/247_/351/252/214/346/224/266_materials.json +628 -0
- package/skills/dknowc-official-doc-writer/official-docs/search-results/baseline_1555.json +345 -0
- package/skills/dknowc-official-doc-writer/official-docs/search-results/baseline_my.json +728 -0
- package/skills/dknowc-official-doc-writer/official-docs/search-results/baseline_wp.json +159 -0
- package/skills/dknowc-official-doc-writer/official-docs/search-results/baseline_wp2.json +1006 -0
- package/skills/dknowc-official-doc-writer/official-docs/search-results/test_tz.json +28 -0
- package/skills/dknowc-official-doc-writer/official-docs/search-results/tmp_q.json +1419 -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 +22 -2
- 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 +15 -0
- package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +0 -2574
- 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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""
|
|
3
3
|
公文排版脚本 v2.0.0
|
|
4
|
-
严格按照 config/format.json 与 reference/standards
|
|
4
|
+
严格按照 config/format.json 与 reference/standards/*.md 的格式规范进行自动排版
|
|
5
5
|
|
|
6
6
|
【v2.0.0 更新说明】
|
|
7
7
|
- 删除所有红头文件相关代码(红头+尾表由 template_generator.py 处理)
|
|
@@ -608,6 +608,41 @@ def strip_markdown_heading(line):
|
|
|
608
608
|
return stripped
|
|
609
609
|
|
|
610
610
|
|
|
611
|
+
SUBTITLE_FONT = '楷体_GB2312'
|
|
612
|
+
SUBTITLE_SIZE = 16 # 三号
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def split_document_title(title):
|
|
616
|
+
"""长标题自动分行(机关通行排版)。
|
|
617
|
+
|
|
618
|
+
- 含破折号副标题(「主标题——副标题」):副标题另起一行,楷体三号;
|
|
619
|
+
- 主标题超过约 20 字且含「关于」:发文机关名单独一行,其余一行
|
|
620
|
+
(「中共四川省委 四川省人民政府关于……的实施意见」两行制);
|
|
621
|
+
- 其余情况保持单行。
|
|
622
|
+
"""
|
|
623
|
+
title = str(title or "").strip()
|
|
624
|
+
if not title:
|
|
625
|
+
return []
|
|
626
|
+
main, subtitle = title, ""
|
|
627
|
+
if "——" in title:
|
|
628
|
+
idx = title.find("——")
|
|
629
|
+
main = title[:idx].strip()
|
|
630
|
+
subtitle = title[idx + 2:].strip()
|
|
631
|
+
rows = []
|
|
632
|
+
if len(main) > 20 and "关于" in main:
|
|
633
|
+
idx = main.find("关于")
|
|
634
|
+
if 0 < idx <= 30:
|
|
635
|
+
rows.append({"text": main[:idx].strip(), "subtitle": False})
|
|
636
|
+
rows.append({"text": main[idx:].strip(), "subtitle": False})
|
|
637
|
+
else:
|
|
638
|
+
rows.append({"text": main, "subtitle": False})
|
|
639
|
+
else:
|
|
640
|
+
rows.append({"text": main, "subtitle": False})
|
|
641
|
+
if subtitle:
|
|
642
|
+
rows.append({"text": subtitle, "subtitle": True})
|
|
643
|
+
return [r for r in rows if r["text"]]
|
|
644
|
+
|
|
645
|
+
|
|
611
646
|
def has_markdown_title(lines):
|
|
612
647
|
"""判断正文是否已经包含 Markdown 公文标题。"""
|
|
613
648
|
return any(get_line_type(line.strip()) == 'title' for line in lines)
|
|
@@ -759,7 +794,13 @@ def _only_signature_tail(lines, index):
|
|
|
759
794
|
s = line.strip()
|
|
760
795
|
if not s or s == '[分页符]' or s.startswith('<!--'):
|
|
761
796
|
continue
|
|
762
|
-
|
|
797
|
+
# 单独一行"附件"表示附件正文页开始,其后内容属附件,不再参与落款判定
|
|
798
|
+
# (否则"附件"页的标题、表格题等正文行会让文末署名被误判为非落款,
|
|
799
|
+
# 连带成文日期也不右对齐)
|
|
800
|
+
if s == '附件':
|
|
801
|
+
break
|
|
802
|
+
# 成文日期后的「(联系人:…)」附注行属文末落款区,不影响署名判定
|
|
803
|
+
if is_date_line(s) or is_contact_info(s) or s.startswith(tail_prefixes):
|
|
763
804
|
continue
|
|
764
805
|
return False
|
|
765
806
|
return True
|
|
@@ -1222,15 +1263,35 @@ def text_width_score(text):
|
|
|
1222
1263
|
def compute_column_widths(table_rows, usable_width_dxa):
|
|
1223
1264
|
num_cols = max(len(row) for row in table_rows)
|
|
1224
1265
|
scores = []
|
|
1266
|
+
max_scores = []
|
|
1225
1267
|
for col_idx in range(num_cols):
|
|
1226
1268
|
values = [row[col_idx] if col_idx < len(row) else '' for row in table_rows]
|
|
1227
1269
|
max_score = max(text_width_score(value) for value in values) if values else 4
|
|
1228
1270
|
avg_score = sum(text_width_score(value) for value in values) / max(len(values), 1)
|
|
1271
|
+
max_scores.append(max_score)
|
|
1229
1272
|
scores.append(max(6, min(28, max_score * 0.65 + avg_score * 0.35)))
|
|
1230
1273
|
|
|
1231
1274
|
total_score = sum(scores) or num_cols
|
|
1232
|
-
|
|
1275
|
+
# 最小列宽按中文字宽设定:三号字单字约 320 twips,1300 约合 4 字,
|
|
1276
|
+
# 避免"金额""序号"这类短列表头被挤成两行
|
|
1277
|
+
min_width = 1300 if num_cols <= 6 else 1000
|
|
1233
1278
|
widths = [max(min_width, int(usable_width_dxa * score / total_score)) for score in scores]
|
|
1279
|
+
|
|
1280
|
+
# 短列按内容定型:最宽单元格(含单元格左右内边距 240twips)不超过版心 30% 的列,
|
|
1281
|
+
# 直接按其内容需求给宽,省出的宽度让给"测算说明""备注"这类长文本列,
|
|
1282
|
+
# 否则短列被挤成多行、长文本列反而留白。
|
|
1283
|
+
cell_margin = 240
|
|
1284
|
+
required = [score * 160 + cell_margin for score in max_scores]
|
|
1285
|
+
narrow = [i for i in range(num_cols) if required[i] <= usable_width_dxa * 0.30]
|
|
1286
|
+
if narrow and len(narrow) < num_cols:
|
|
1287
|
+
for i in narrow:
|
|
1288
|
+
widths[i] = max(min_width, required[i])
|
|
1289
|
+
rest = usable_width_dxa - sum(widths[i] for i in narrow)
|
|
1290
|
+
rest_score = sum(scores[i] for i in range(num_cols) if i not in narrow) or 1
|
|
1291
|
+
for i in range(num_cols):
|
|
1292
|
+
if i not in narrow:
|
|
1293
|
+
widths[i] = max(min_width, int(rest * scores[i] / rest_score))
|
|
1294
|
+
|
|
1234
1295
|
total_width = sum(widths)
|
|
1235
1296
|
if total_width != usable_width_dxa and total_width > 0:
|
|
1236
1297
|
widths[-1] += usable_width_dxa - total_width
|
|
@@ -1655,11 +1716,13 @@ def create_document(content_text, output_path=None):
|
|
|
1655
1716
|
# 公文标题(# 标题)
|
|
1656
1717
|
if line_type == 'title':
|
|
1657
1718
|
content = strip_markdown_heading(stripped)
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1719
|
+
for row in split_document_title(content):
|
|
1720
|
+
para = doc.add_paragraph()
|
|
1721
|
+
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
1722
|
+
row_font, row_size = (SUBTITLE_FONT, SUBTITLE_SIZE) if row["subtitle"] else (title_font, title_size)
|
|
1723
|
+
add_formatted_text(para, row["text"], row_font, row_size)
|
|
1724
|
+
set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.CENTER, line_spacing=title_line_spacing)
|
|
1725
|
+
set_outline_level(para, 0) # 文档标题设为1级
|
|
1663
1726
|
add_blank_paragraphs(doc, 1, body_line_spacing, body_font, body_size)
|
|
1664
1727
|
i += 1
|
|
1665
1728
|
continue
|
|
@@ -1730,35 +1793,30 @@ def create_document(content_text, output_path=None):
|
|
|
1730
1793
|
i += 1
|
|
1731
1794
|
continue
|
|
1732
1795
|
|
|
1733
|
-
#
|
|
1734
|
-
#
|
|
1796
|
+
# 联系行(成文日期之后的「(联系人:…,联系电话:…)」):机关通行附注排法——
|
|
1797
|
+
# 前空一行、左对齐、左空二字、保持圆括号。正文中间出现的独立联系段
|
|
1798
|
+
# 仍按普通正文渲染并提示(规范联系人电话写入正文事项段或置于文末)。
|
|
1735
1799
|
if is_contact_info(stripped):
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1800
|
+
if last_sign_date:
|
|
1801
|
+
add_blank_paragraphs(doc, 1, body_line_spacing, body_font, body_size)
|
|
1802
|
+
para = doc.add_paragraph()
|
|
1803
|
+
add_formatted_text(para, stripped, body_font, body_size)
|
|
1804
|
+
set_paragraph_format(para, indent_chars=2, line_spacing=body_line_spacing)
|
|
1805
|
+
i += 1
|
|
1806
|
+
continue
|
|
1807
|
+
print(f"格式提示:检测到正文中间的独立联系人段({stripped[:24]}…)——联系人电话应写入正文相关事项段,"
|
|
1808
|
+
f"或置于成文日期之后(空一行、圆括号);已按正文段落渲染。", file=sys.stderr)
|
|
1809
|
+
|
|
1810
|
+
# 落款日期:右对齐并右空二字,与署名右端对齐(署名末字同样右空二字)。
|
|
1811
|
+
# 不按署名长度动态缩进——按署名字数推"首字对齐"会把短署名(如五字机关名)
|
|
1812
|
+
# 推到行中,版式上显得"落款太靠中间"。
|
|
1745
1813
|
if should_right_align_date(lines, i):
|
|
1746
1814
|
last_sign_date = stripped
|
|
1747
|
-
date_text = re.sub(r'\s+', '', stripped)
|
|
1748
|
-
unit_len = len(re.sub(r'\s+', '', last_signing_entity))
|
|
1749
|
-
if len(date_text) > unit_len:
|
|
1750
|
-
date_indent = 2
|
|
1751
|
-
unit_indent = len(date_text) - unit_len + 4
|
|
1752
|
-
else:
|
|
1753
|
-
unit_indent = 2
|
|
1754
|
-
date_indent = max(2, unit_len - len(date_text))
|
|
1755
|
-
if last_signing_para is not None and last_signing_para._p.getparent() is not None:
|
|
1756
|
-
last_signing_para.paragraph_format.right_indent = Pt(body_size * unit_indent)
|
|
1757
1815
|
para = doc.add_paragraph()
|
|
1758
1816
|
para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
|
|
1759
1817
|
add_formatted_text(para, stripped, body_font, body_size)
|
|
1760
1818
|
set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.RIGHT, line_spacing=body_line_spacing)
|
|
1761
|
-
para.paragraph_format.right_indent = Pt(body_size *
|
|
1819
|
+
para.paragraph_format.right_indent = Pt(body_size * 2)
|
|
1762
1820
|
para.paragraph_format.keep_with_next = True
|
|
1763
1821
|
i += 1
|
|
1764
1822
|
continue
|
|
@@ -1,17 +1,42 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""检查运行环境,并按用户授权保存可选的本地写作偏好。
|
|
2
|
+
"""检查运行环境,并按用户授权保存可选的本地写作偏好。
|
|
3
|
+
|
|
4
|
+
版本自检(引导式升级):匿名查询 MaaS 技能目录公开接口,与本技能 SKILL.md 版本比较,
|
|
5
|
+
仅远端版本更高时提示(不提示降级)。结果带 24h 本地缓存、3s 超时静默失败,
|
|
6
|
+
任何失败都不阻断初始化、不影响退出语义;升级动作由 Agent 在用户明确同意后执行(见 SKILL.md)。
|
|
7
|
+
"""
|
|
3
8
|
|
|
4
9
|
import argparse
|
|
5
10
|
import json
|
|
6
11
|
import os
|
|
7
12
|
import platform
|
|
13
|
+
import re
|
|
8
14
|
import shutil
|
|
9
15
|
import sys
|
|
16
|
+
import time
|
|
17
|
+
import urllib.request
|
|
10
18
|
from pathlib import Path
|
|
11
19
|
|
|
12
20
|
|
|
13
21
|
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
|
14
22
|
API_KEY_ENV = "DKNOWC_API_KEY"
|
|
23
|
+
|
|
24
|
+
# 版本自检:MaaS 技能中心公开目录接口(与平台技能中心页面同源,免认证、不扣积分)。
|
|
25
|
+
# 目录与下载地址均为固定常量(不接受环境变量覆写,防止更新源被替换);
|
|
26
|
+
# download_url 必须落在官方 OSS 白名单前缀内,download_name 必须等于本技能包名。
|
|
27
|
+
# DKNOWC_UPDATE_CHECK=0 可整体停用自检(用户侧 opt-out)。
|
|
28
|
+
UPDATE_CATALOG_URL = "https://platform.dknowc.cn/open-api/maas/skills/v1/catalog"
|
|
29
|
+
UPDATE_TARGET_SLUG = "dknowc-official-doc-writer"
|
|
30
|
+
# 升级目标(官方 maas 包)的 SKILL.md name——与 slug/downloadName 一样是已知常量。
|
|
31
|
+
# 验包按此常量校验(防投毒=确认下载的是官方包),不用本地 name:各渠道本地 name
|
|
32
|
+
# 可能存在既定特化(如 skills-sh 为 ASCII 目录名形态),拿本地身份校验官方包会把
|
|
33
|
+
# 特化渠道的升级全部判失败。
|
|
34
|
+
UPDATE_TARGET_NAME = "深知公文写作"
|
|
35
|
+
UPDATE_DOWNLOAD_PREFIX = "https://down.dknowc.cn/upload/maas/skills/"
|
|
36
|
+
UPDATE_DOWNLOAD_NAME = "dknowc-official-doc-writer.zip"
|
|
37
|
+
UPDATE_INSTALL_DOC = "https://platform.dknowc.cn/agent-docs/skills/install.md"
|
|
38
|
+
UPDATE_CACHE_TTL_SECONDS = 24 * 3600
|
|
39
|
+
UPDATE_TIMEOUT_SECONDS = 3
|
|
15
40
|
PROFILE_PATH = SKILL_ROOT / "config" / "user_profile.json"
|
|
16
41
|
ENV_STATE_PATH = SKILL_ROOT / "config" / "environment_state.json"
|
|
17
42
|
SCRIPTS_DIR = SKILL_ROOT / "scripts"
|
|
@@ -152,7 +177,7 @@ def check_api_key_config():
|
|
|
152
177
|
if _in_dsh():
|
|
153
178
|
# dsh:优先 DSH_DKNOWC_API_KEY(与 MCP Bearer 同源);缺失时 resolve_api_key 兜底
|
|
154
179
|
# (环境变量 → 专用配置文件)。配置文件读取不受 dsh 环境清理影响,
|
|
155
|
-
# 注册后本会话脚本立即可用。无 Key
|
|
180
|
+
# 注册后本会话脚本立即可用。无 Key 仅暂停检索,不阻断纯写作任务。
|
|
156
181
|
api_key = os.environ.get("DSH_DKNOWC_API_KEY", "").strip()
|
|
157
182
|
source = "environment"
|
|
158
183
|
if not _valid_api_key(api_key):
|
|
@@ -163,10 +188,10 @@ def check_api_key_config():
|
|
|
163
188
|
api_key, source = api_key2, source2
|
|
164
189
|
except ImportError:
|
|
165
190
|
pass
|
|
166
|
-
if
|
|
167
|
-
return {"api_key_configured":
|
|
168
|
-
|
|
169
|
-
|
|
191
|
+
if _valid_api_key(api_key):
|
|
192
|
+
return {"api_key_configured": True, "api_key_source": source, "api_key_hint": None}
|
|
193
|
+
return {"api_key_configured": False, "api_key_source": None,
|
|
194
|
+
"api_key_hint": f"未检测到可用的 {API_KEY_ENV}(环境变量与专用配置文件均未找到)。运行注册脚本开通后 Key 自动写入 ~/.config/dknowc/api_key,本会话立即可用。仅检索任务受影响,纯写作任务可继续。"}
|
|
170
195
|
|
|
171
196
|
|
|
172
197
|
# 环境变量优先,缺失时从专用配置文件兜底解析(宿主进程早于 key 写入启动时不误报缺失)
|
|
@@ -202,6 +227,201 @@ def _valid_api_key(value):
|
|
|
202
227
|
return key not in {"your_api_key_here", "你的深知搜索 API Key"}
|
|
203
228
|
|
|
204
229
|
|
|
230
|
+
# —— 版本自检(引导式升级)——
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _dknowc_config_dir() -> Path:
|
|
234
|
+
# 与 api_key.py 同一套跨平台约定:macOS/Linux 用 ~/.config/dknowc,Windows 用 %APPDATA%/dknowc
|
|
235
|
+
if sys.platform == "win32":
|
|
236
|
+
base = Path(os.environ.get("APPDATA") or Path.home())
|
|
237
|
+
else:
|
|
238
|
+
base = Path(os.environ.get("XDG_CONFIG_HOME") or (Path.home() / ".config"))
|
|
239
|
+
return base / "dknowc"
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _local_skill_version() -> str:
|
|
243
|
+
try:
|
|
244
|
+
text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8", errors="ignore")
|
|
245
|
+
except OSError:
|
|
246
|
+
return ""
|
|
247
|
+
for line in text.splitlines()[:40]:
|
|
248
|
+
m = re.match(r'^version:\s*["\']?([0-9][0-9A-Za-z.\-]*)', line.strip())
|
|
249
|
+
if m:
|
|
250
|
+
return m.group(1)
|
|
251
|
+
return ""
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _channel_of_this_install() -> str:
|
|
255
|
+
try:
|
|
256
|
+
data = json.loads((SKILL_ROOT / "attribution.json").read_text(encoding="utf-8", errors="ignore"))
|
|
257
|
+
return str(data.get("channel") or "")
|
|
258
|
+
except Exception:
|
|
259
|
+
return ""
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _parse_version(version: str) -> tuple:
|
|
263
|
+
parts = []
|
|
264
|
+
for piece in str(version or "").split("."):
|
|
265
|
+
m = re.match(r"^(\d+)", piece)
|
|
266
|
+
parts.append(int(m.group(1)) if m else 0)
|
|
267
|
+
return tuple(parts) or (0,)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _update_cache_path() -> Path:
|
|
271
|
+
# 缓存按技能命名空间隔离:同机多 dknowc 技能共用 ~/.config/dknowc,
|
|
272
|
+
# 共用同一文件名会互相读到对方技能的目录条目、被包名校验拒绝,24h 内互相压制提示。
|
|
273
|
+
return _dknowc_config_dir() / "update_check_doc_writer.json"
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _read_update_cache():
|
|
277
|
+
try:
|
|
278
|
+
return json.loads(_update_cache_path().read_text(encoding="utf-8", errors="ignore"))
|
|
279
|
+
except Exception:
|
|
280
|
+
return None
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _write_update_cache(latest, download_url, download_name):
|
|
284
|
+
# 直接覆盖写 + 0600 权限;保留已记录的拒绝版本。
|
|
285
|
+
# 不用「临时文件 + os.replace」:宿主会把 rename 源文件判成"删除文件"并逐次弹确认框。
|
|
286
|
+
# 缓存是纯派生数据(目录接口可随时重查),半截写入最坏只影响一次自检提示,不影响功能。
|
|
287
|
+
try:
|
|
288
|
+
path = _update_cache_path()
|
|
289
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
290
|
+
old = _read_update_cache() or {}
|
|
291
|
+
path.write_text(json.dumps({
|
|
292
|
+
"checked_at": time.time(),
|
|
293
|
+
"latest_version": latest,
|
|
294
|
+
"download_url": download_url,
|
|
295
|
+
"download_name": download_name,
|
|
296
|
+
"declined_version": old.get("declined_version"),
|
|
297
|
+
}, ensure_ascii=False), encoding="utf-8")
|
|
298
|
+
try:
|
|
299
|
+
os.chmod(path, 0o600)
|
|
300
|
+
except OSError:
|
|
301
|
+
pass
|
|
302
|
+
except Exception:
|
|
303
|
+
pass
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def set_declined_version(version) -> bool:
|
|
307
|
+
"""记录用户拒绝的版本(原子合并写入,保留既有字段)。被拒版本不再提示,
|
|
308
|
+
目录出现更高版本时恢复提示;用户主动要求升级时不受此记录影响。
|
|
309
|
+
同样直接覆盖写(不用临时文件+replace),避免宿主把 rename 判成删除而弹确认框。"""
|
|
310
|
+
try:
|
|
311
|
+
path = _update_cache_path()
|
|
312
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
313
|
+
data = _read_update_cache() or {}
|
|
314
|
+
data["declined_version"] = str(version)
|
|
315
|
+
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
|
316
|
+
try:
|
|
317
|
+
os.chmod(path, 0o600)
|
|
318
|
+
except OSError:
|
|
319
|
+
pass
|
|
320
|
+
return True
|
|
321
|
+
except Exception:
|
|
322
|
+
return False
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _catalog_entry_is_safe(latest, download_url, download_name) -> bool:
|
|
326
|
+
"""目录条目硬校验:版本号必须是纯数字点分格式(防提示语注入),
|
|
327
|
+
下载地址必须落在官方 OSS 白名单前缀内、文件名必须等于本技能包名(防替换下载源)。"""
|
|
328
|
+
if not re.fullmatch(r"\d+(\.\d+)*", str(latest or "")):
|
|
329
|
+
return False
|
|
330
|
+
if not str(download_url or "").startswith(UPDATE_DOWNLOAD_PREFIX):
|
|
331
|
+
return False
|
|
332
|
+
if str(download_name or "") != UPDATE_DOWNLOAD_NAME:
|
|
333
|
+
return False
|
|
334
|
+
return True
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _fetch_catalog_entry():
|
|
338
|
+
# 匿名 GET 公开技能目录,按 slug 定位本技能条目;任何网络/解析失败都返回 None(静默降级)。
|
|
339
|
+
try:
|
|
340
|
+
req = urllib.request.Request(UPDATE_CATALOG_URL, headers={"User-Agent": "dknowc-official-doc-writer-update-check"})
|
|
341
|
+
with urllib.request.urlopen(req, timeout=UPDATE_TIMEOUT_SECONDS) as resp:
|
|
342
|
+
payload = json.loads(resp.read().decode("utf-8", errors="ignore"))
|
|
343
|
+
for entry in (payload or {}).get("data") or []:
|
|
344
|
+
if entry.get("slug") == UPDATE_TARGET_SLUG or entry.get("canonicalSlug") == UPDATE_TARGET_SLUG:
|
|
345
|
+
return entry
|
|
346
|
+
except Exception:
|
|
347
|
+
pass
|
|
348
|
+
return None
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def check_update() -> dict:
|
|
352
|
+
"""版本自检:远端(MaaS 目录登记版本)> 本地(SKILL.md version)才提示更新,绝不提示降级。
|
|
353
|
+
|
|
354
|
+
全程 try/except 兜底——检查失败只置 checked=false,不抛错、不影响退出码与 ready 语义。
|
|
355
|
+
"""
|
|
356
|
+
result = {
|
|
357
|
+
"checked": False, "source": None, "current_version": None, "latest_version": None,
|
|
358
|
+
"update_available": False, "download_url": None, "download_name": None,
|
|
359
|
+
"install_doc": UPDATE_INSTALL_DOC, "message": None, "reason": None,
|
|
360
|
+
}
|
|
361
|
+
try:
|
|
362
|
+
if os.environ.get("DKNOWC_UPDATE_CHECK", "").strip() == "0":
|
|
363
|
+
result["reason"] = "disabled_by_env"
|
|
364
|
+
return result
|
|
365
|
+
# volcengine 渠道包为平台特化形态(无注册 onboarding 等),不引导跨渠道替换
|
|
366
|
+
# dsh 插件:skill 更新统一走 dsh 插件 npm 更新,skill 内自升级会破坏插件补丁与完整性
|
|
367
|
+
if _channel_of_this_install() in ("volcengine", "dsh"):
|
|
368
|
+
result["reason"] = "channel_disabled"
|
|
369
|
+
return result
|
|
370
|
+
|
|
371
|
+
current = _local_skill_version()
|
|
372
|
+
result["current_version"] = current or None
|
|
373
|
+
|
|
374
|
+
cache = _read_update_cache()
|
|
375
|
+
if cache and (time.time() - float(cache.get("checked_at") or 0)) < UPDATE_CACHE_TTL_SECONDS:
|
|
376
|
+
latest = cache.get("latest_version")
|
|
377
|
+
download_url = cache.get("download_url")
|
|
378
|
+
download_name = cache.get("download_name")
|
|
379
|
+
source = "cache"
|
|
380
|
+
else:
|
|
381
|
+
entry = _fetch_catalog_entry() or {}
|
|
382
|
+
latest = entry.get("version")
|
|
383
|
+
download_url = entry.get("downloadUrl")
|
|
384
|
+
download_name = entry.get("downloadName")
|
|
385
|
+
if latest:
|
|
386
|
+
_write_update_cache(latest, download_url, download_name)
|
|
387
|
+
source = "live"
|
|
388
|
+
|
|
389
|
+
if not latest:
|
|
390
|
+
result["reason"] = "catalog_unavailable"
|
|
391
|
+
return result
|
|
392
|
+
if not _catalog_entry_is_safe(latest, download_url, download_name):
|
|
393
|
+
# 版本格式非法/下载地址不在官方白名单/包名不符:一律视为目录不可用,不提示升级
|
|
394
|
+
result["reason"] = "catalog_entry_rejected"
|
|
395
|
+
return result
|
|
396
|
+
result.update({
|
|
397
|
+
"checked": True, "source": source, "latest_version": str(latest),
|
|
398
|
+
"download_url": download_url, "download_name": download_name,
|
|
399
|
+
})
|
|
400
|
+
declined = (cache or {}).get("declined_version") if isinstance(cache, dict) else None
|
|
401
|
+
if declined and _parse_version(latest) <= _parse_version(declined):
|
|
402
|
+
# 用户已拒绝过该版本(或更早版本):不再提示,目录出现更高版本时恢复提示
|
|
403
|
+
result["reason"] = "declined"
|
|
404
|
+
return result
|
|
405
|
+
if current and _parse_version(latest) > _parse_version(current):
|
|
406
|
+
result["update_available"] = True
|
|
407
|
+
result["message"] = (
|
|
408
|
+
f"检测到「深知公文写作」有新版本 v{latest}(当前安装 v{current})。"
|
|
409
|
+
"升级说明:本技能将更新为官方发布的最新版本;"
|
|
410
|
+
"你的 API Key 与本机配置全部保留,无需重新注册。"
|
|
411
|
+
"是否现在升级?确认后我先完成升级再继续处理你的任务;"
|
|
412
|
+
"选择跳过则这个版本不再提醒、直接继续你的任务。"
|
|
413
|
+
)
|
|
414
|
+
# action:枚举值,只表达状态,不承载行为指令。message 是本地固定模板(仅用于展示);
|
|
415
|
+
# 是否提示、如何提示由 SKILL.md「版本自检与引导升级」的固定流程规定,不由数据驱动。
|
|
416
|
+
# 升级命令一律给绝对路径(按抄执行不依赖当前目录),并覆盖升级失败分支。
|
|
417
|
+
updater = str(Path(__file__).resolve().parent / "update_skill.py")
|
|
418
|
+
result["action"] = "prompt_update"
|
|
419
|
+
result["updater_path"] = updater
|
|
420
|
+
except Exception:
|
|
421
|
+
result["reason"] = result["reason"] or "error"
|
|
422
|
+
return result
|
|
423
|
+
|
|
424
|
+
|
|
205
425
|
def main():
|
|
206
426
|
parser = argparse.ArgumentParser(description="深知写作助手初始化与环境检查")
|
|
207
427
|
parser.add_argument("--organization", help="常用发文机关;不填写则使用 XX单位")
|
|
@@ -236,6 +456,12 @@ def main():
|
|
|
236
456
|
result["profile_saved"] = args.save
|
|
237
457
|
result["profile_path"] = "config/user_profile.json" if args.save else None
|
|
238
458
|
result["environment_state_path"] = "config/environment_state.json"
|
|
459
|
+
# update:版本自检结果(数据,不是指令)。update_available=true 且 action="prompt_update"
|
|
460
|
+
# 时,按 SKILL.md「版本自检与引导升级」的固定流程在开始任务前提示一次并询问用户
|
|
461
|
+
# (每会话最多一次;用户拒绝则运行 update_skill.py --decline 静默记录);
|
|
462
|
+
# checked=false(网络不可达/停用/渠道除外/reason=declined)时
|
|
463
|
+
# 不向用户提及版本话题,直接继续原任务。
|
|
464
|
+
result["update"] = check_update()
|
|
239
465
|
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
240
466
|
|
|
241
467
|
|
|
@@ -28,13 +28,9 @@ from xml.etree import ElementTree
|
|
|
28
28
|
|
|
29
29
|
|
|
30
30
|
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
|
31
|
-
|
|
32
|
-
# (~/.dknowc-writer/),跨工作区共享、插件升级不丢失;可经 DKNWOC_HOME_DIR 覆盖。
|
|
33
|
-
import os as _os
|
|
34
|
-
DATA_ROOT = Path(_os.environ.get("DKNWOC_HOME_DIR") or str(Path.home() / ".dknowc-writer")).resolve()
|
|
35
|
-
KB_ROOT = DATA_ROOT / "knowledge-base"
|
|
31
|
+
KB_ROOT = SKILL_ROOT / "knowledge-base"
|
|
36
32
|
INDEX_PATH = KB_ROOT / "_index.json"
|
|
37
|
-
PREF_PATH =
|
|
33
|
+
PREF_PATH = SKILL_ROOT / "config" / "writing_preferences.json"
|
|
38
34
|
|
|
39
35
|
KB_CATEGORIES = {
|
|
40
36
|
"unit-profile": "单位资料",
|
|
@@ -21,6 +21,7 @@ if not _ws:
|
|
|
21
21
|
_sid = _os.environ.get("DSH_SESSION_ID", "")
|
|
22
22
|
_ws = str(Path(_os.getcwd()) / "dknowc-output" / (_sid[:8] if _sid else "_default"))
|
|
23
23
|
WS_ROOT = Path(_ws).resolve()
|
|
24
|
+
|
|
24
25
|
OFFICIAL_DOCS_DIR = WS_ROOT / "official-docs"
|
|
25
26
|
SEARCH_RESULTS_DIR = OFFICIAL_DOCS_DIR / "search-results"
|
|
26
27
|
ALLOWED_INPUT_DIRS = (
|
|
@@ -73,6 +74,41 @@ def resolve_output_json(output_path: str) -> Path:
|
|
|
73
74
|
return resolved
|
|
74
75
|
|
|
75
76
|
|
|
77
|
+
# URL 归一(去重键用):去 fragment、常见 tracking 参数、尾斜杠。
|
|
78
|
+
# 与 websearch_convert.py 的 TRACKING_PARAMS 保持一致——两处规则不一致会导致
|
|
79
|
+
# 联网路(?source=wechat 等)与库内/外部路同文无法合并去重。
|
|
80
|
+
TRACKING_PARAMS = {
|
|
81
|
+
"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content",
|
|
82
|
+
"gclid", "fbclid", "spm", "scm", "from", "share_token", "share_source",
|
|
83
|
+
"ref", "ref_src", "source", "campaign",
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def normalize_url_key(raw: str) -> str:
|
|
88
|
+
"""URL 归一化为去重键:仅 http/https 保留业务参数,其余原样返回压缩文本。"""
|
|
89
|
+
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
|
|
90
|
+
text = str(raw or "").strip()
|
|
91
|
+
if not text:
|
|
92
|
+
return ""
|
|
93
|
+
try:
|
|
94
|
+
parsed = urlparse(text)
|
|
95
|
+
except ValueError:
|
|
96
|
+
return re.sub(r"\s+", "", text)
|
|
97
|
+
if parsed.scheme.lower() not in ("http", "https") or not parsed.netloc:
|
|
98
|
+
return re.sub(r"\s+", "", text)
|
|
99
|
+
query = [(k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=True)
|
|
100
|
+
if k.lower() not in TRACKING_PARAMS]
|
|
101
|
+
path = parsed.path.rstrip("/") or "/"
|
|
102
|
+
return urlunparse((parsed.scheme.lower(), parsed.netloc.lower(), path,
|
|
103
|
+
"", urlencode(sorted(query)), ""))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def is_unofficial(article: Dict) -> bool:
|
|
107
|
+
"""非官方判定:外部联网标记,或接口数据权威性=非权威。"""
|
|
108
|
+
return bool(article.get("非官方来源")) or str(
|
|
109
|
+
article.get("数据权威性") or article.get("authority") or "").strip() in ("非权威", "non-authoritative")
|
|
110
|
+
|
|
111
|
+
|
|
76
112
|
def merge_results(result_files: List[str]) -> Dict:
|
|
77
113
|
"""
|
|
78
114
|
合并多个搜索结果文件
|
|
@@ -122,11 +158,29 @@ def merge_results(result_files: List[str]) -> Dict:
|
|
|
122
158
|
regions_searched.append(region)
|
|
123
159
|
# 本文件处理前的文章/段落基线:用于计算每次调用真实新增量
|
|
124
160
|
before_article_count = len(all_articles)
|
|
161
|
+
# 官方整卡替换外部卡的次数:该场景列表长度不变(替换不计新增),
|
|
162
|
+
# 但官方卡对本路而言是新增,需在路次统计中 +1 补偿
|
|
163
|
+
replacement_credit = 0
|
|
125
164
|
before_para_total = sum(len(a.get("段落") or []) for a in all_articles)
|
|
126
165
|
# 搜索目的兜底该路 --purpose 为空时用该路 query 兜底——
|
|
127
166
|
# 若留空,文章"搜索目的"缺失,溯源报告分组键(search_key)会退化成
|
|
128
167
|
# "中国"/"浙江省"等地域碎片,材料面板筛选胶囊失去意义(避免大量篇目退化)。
|
|
129
168
|
purpose_val = search_meta.get("purpose") or search_meta.get("query") or ""
|
|
169
|
+
# 调用通道:深搜转换产物自带 channel=deep;补搜文件按文件名区分(deep_* vs 其他);
|
|
170
|
+
# 外部联网两形态——联网路(searchChannel 含 webSearch)与宿主 WebSearch 转换产物
|
|
171
|
+
# (search_meta.websearch_converted)——分别标记,供溯源报告分组与计数。
|
|
172
|
+
_search_channel_list = search_meta.get("searchChannel") or []
|
|
173
|
+
if isinstance(_search_channel_list, str):
|
|
174
|
+
_search_channel_list = [_search_channel_list]
|
|
175
|
+
if search_meta.get("websearch_converted"):
|
|
176
|
+
_channel_name = "宿主 WebSearch(公开网络)"
|
|
177
|
+
elif "webSearch" in _search_channel_list:
|
|
178
|
+
_channel_name = "深知可信搜索·联网"
|
|
179
|
+
elif (data.get("channel") == "deep"
|
|
180
|
+
or Path(str(safe_file_path)).name.startswith("deep_")):
|
|
181
|
+
_channel_name = "深知深度搜索"
|
|
182
|
+
else:
|
|
183
|
+
_channel_name = "深知可信搜索"
|
|
130
184
|
record = {
|
|
131
185
|
"file": str(safe_file_path),
|
|
132
186
|
"query": search_meta.get("query", ""),
|
|
@@ -137,11 +191,7 @@ def merge_results(result_files: List[str]) -> Dict:
|
|
|
137
191
|
"full": search_meta.get("full", False),
|
|
138
192
|
"segmentCount": search_meta.get("segmentCount"),
|
|
139
193
|
"knowledgeBase": data.get("knowledgeBase", ""),
|
|
140
|
-
|
|
141
|
-
"channel": ("深知深度搜索"
|
|
142
|
-
if (data.get("channel") == "deep"
|
|
143
|
-
or Path(str(safe_file_path)).name.startswith("deep_"))
|
|
144
|
-
else "深知可信搜索"),
|
|
194
|
+
"channel": _channel_name,
|
|
145
195
|
}
|
|
146
196
|
searches.append(record)
|
|
147
197
|
if data.get("knowledgeBase"):
|
|
@@ -178,13 +228,38 @@ def merge_results(result_files: List[str]) -> Dict:
|
|
|
178
228
|
title_key = re.sub(r"\s+", "", title or "").replace(" ", "")
|
|
179
229
|
title_key = re.sub(r"^(关于印发|关于)", "", title_key)
|
|
180
230
|
title_key = re.sub(r"(的通知|的公告|的意见|的方案|的办法|的规定|的细则|的批复|的规划|的纲要)$", "", title_key)
|
|
181
|
-
url_key =
|
|
231
|
+
url_key = normalize_url_key(url)
|
|
182
232
|
key = title_key if title_key else url_key
|
|
183
233
|
if not key:
|
|
184
234
|
all_articles.append(article)
|
|
185
235
|
continue
|
|
186
236
|
|
|
187
237
|
if key in seen_titles:
|
|
238
|
+
existing = by_key[key]
|
|
239
|
+
# 官方优先:同一材料的官方记录与外部联网记录相遇时,官方记录整体胜出——
|
|
240
|
+
# 外部篇不并入官方卡(段落、字段、通道标记均不进)。与 --input 顺序无关:
|
|
241
|
+
# 外部先入、官方后入时整卡替换;官方先入、外部后入时直接丢弃外部篇。
|
|
242
|
+
if is_unofficial(article) != is_unofficial(existing):
|
|
243
|
+
duplicates_count += 1
|
|
244
|
+
if is_unofficial(existing):
|
|
245
|
+
_prev_owner = existing.get("_route_idx")
|
|
246
|
+
if isinstance(_prev_owner, int) and 0 <= _prev_owner < len(searches):
|
|
247
|
+
# 被替换的外部卡曾计入其所属路次的"新增文章数/新增段落数",回滚防虚高
|
|
248
|
+
searches[_prev_owner]["new_articles"] = max(
|
|
249
|
+
0, searches[_prev_owner].get("new_articles", 0) - 1)
|
|
250
|
+
searches[_prev_owner]["added_paragraphs"] = max(
|
|
251
|
+
0, searches[_prev_owner].get("added_paragraphs", 0)
|
|
252
|
+
- len(existing.get("段落") or []))
|
|
253
|
+
try:
|
|
254
|
+
_pos = all_articles.index(existing)
|
|
255
|
+
except ValueError:
|
|
256
|
+
_pos = -1
|
|
257
|
+
if _pos >= 0:
|
|
258
|
+
all_articles[_pos] = article
|
|
259
|
+
by_key[key] = article
|
|
260
|
+
article["_route_idx"] = len(searches) - 1
|
|
261
|
+
replacement_credit += 1
|
|
262
|
+
continue
|
|
188
263
|
# 同一材料:合并段落(保留两篇的段落合集,段落级去重),字段取并集(保留非空者)
|
|
189
264
|
duplicates_count += 1
|
|
190
265
|
existing = by_key[key]
|
|
@@ -222,6 +297,9 @@ def merge_results(result_files: List[str]) -> Dict:
|
|
|
222
297
|
|
|
223
298
|
seen_titles.add(key)
|
|
224
299
|
by_key[key] = article
|
|
300
|
+
# 记录本篇来自哪个检索路次(内部字段,输出前清除):
|
|
301
|
+
# 官方整卡替换外部卡时据此回滚外部路次的"新增文章数"
|
|
302
|
+
article["_route_idx"] = len(searches) - 1
|
|
225
303
|
article.setdefault("搜索地域", region)
|
|
226
304
|
if search_meta.get("query"):
|
|
227
305
|
article.setdefault("搜索词", search_meta.get("query"))
|
|
@@ -237,7 +315,7 @@ def merge_results(result_files: List[str]) -> Dict:
|
|
|
237
315
|
|
|
238
316
|
# 每次调用的真实增量:新增文章数 / 新增段落数(含新文章自带段落)。
|
|
239
317
|
# 补搜的价值主要看这两个数:新增 0 篇但补充 N 段,说明补的是已有文章的条款段落。
|
|
240
|
-
record["new_articles"] = len(all_articles) - before_article_count
|
|
318
|
+
record["new_articles"] = len(all_articles) - before_article_count + replacement_credit
|
|
241
319
|
record["added_paragraphs"] = (
|
|
242
320
|
sum(len(a.get("段落") or []) for a in all_articles) - before_para_total
|
|
243
321
|
)
|
|
@@ -282,6 +360,17 @@ def merge_results(result_files: List[str]) -> Dict:
|
|
|
282
360
|
keep_idx = _i if (_is_official_title(ti) or not _is_official_title(tj)) else _j
|
|
283
361
|
drop_idx = _j if keep_idx == _i else _i
|
|
284
362
|
keep, drop = all_articles[keep_idx], all_articles[drop_idx]
|
|
363
|
+
# 官方优先:官方记录与外部联网记录判为同一材料时,官方记录整体胜出——
|
|
364
|
+
# 外部篇不并入(段落、字段、通道标记均不进官方卡),直接丢弃。
|
|
365
|
+
if is_unofficial(keep) != is_unofficial(drop):
|
|
366
|
+
keep_idx = _i if not is_unofficial(all_articles[_i]) else _j
|
|
367
|
+
drop_idx = _j if keep_idx == _i else _i
|
|
368
|
+
all_articles.pop(drop_idx)
|
|
369
|
+
fps.pop(drop_idx)
|
|
370
|
+
duplicates_count += 1
|
|
371
|
+
if drop_idx == _i:
|
|
372
|
+
_j = _i + 1 # _i 处已换成保留篇,重新向后比较
|
|
373
|
+
continue
|
|
285
374
|
# 段落取并集(内容级去重,保留各自 id;后续统一重编号)
|
|
286
375
|
_seen_para = {re.sub(r"\s+", "", str(p.get("内容") or p.get("content") or ""))
|
|
287
376
|
for p in (keep.get("段落") or [])}
|
|
@@ -337,6 +426,10 @@ def merge_results(result_files: List[str]) -> Dict:
|
|
|
337
426
|
if drop:
|
|
338
427
|
article["段落"] = [p for i, p in enumerate(paras) if i not in drop]
|
|
339
428
|
|
|
429
|
+
# 清除内部路由标记(不进入合并产物)
|
|
430
|
+
for article in all_articles:
|
|
431
|
+
article.pop("_route_idx", None)
|
|
432
|
+
|
|
340
433
|
# 重新编号段落
|
|
341
434
|
global_id = 1
|
|
342
435
|
total_paragraphs = 0
|