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
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""深知法律助手 · 30 题法条检索评测。
|
|
3
|
+
|
|
4
|
+
每部法只解析一次(001 → 003 → 002/005 → 选本),再对每个条号做切分与校验。
|
|
5
|
+
指标:法名命中 / 条号命中 / 关键词命中 / 版本标记命中。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Dict, List
|
|
16
|
+
|
|
17
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
18
|
+
import legal_search as ls # type: ignore
|
|
19
|
+
import legal_client as c # type: ignore
|
|
20
|
+
|
|
21
|
+
ROOT = Path(__file__).resolve().parent.parent
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def norm(text: str) -> str:
|
|
25
|
+
return ls.norm_title(text)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def main() -> None:
|
|
29
|
+
parser = argparse.ArgumentParser()
|
|
30
|
+
parser.add_argument("--questions", default=str(ROOT / "eval" / "questions.jsonl"))
|
|
31
|
+
parser.add_argument("--limit-laws", type=int, default=0, help="只跑前 N 部法(0=全部)")
|
|
32
|
+
parser.add_argument("--output", default=str(ROOT / "eval" / "results_latest.json"))
|
|
33
|
+
args = parser.parse_args()
|
|
34
|
+
|
|
35
|
+
questions = [json.loads(line) for line in Path(args.questions).read_text(encoding="utf-8").splitlines() if line.strip()]
|
|
36
|
+
groups: Dict[str, List[Dict[str, Any]]] = {}
|
|
37
|
+
for q in questions:
|
|
38
|
+
groups.setdefault(q["law"], []).append(q)
|
|
39
|
+
laws = list(groups.keys())
|
|
40
|
+
if args.limit_laws:
|
|
41
|
+
laws = laws[: args.limit_laws]
|
|
42
|
+
|
|
43
|
+
rows: List[Dict[str, Any]] = []
|
|
44
|
+
for law in laws:
|
|
45
|
+
started = time.time()
|
|
46
|
+
try:
|
|
47
|
+
resolved = ls.resolve_law(law, article=str(groups[law][0]["article"]))
|
|
48
|
+
except Exception as exc: # noqa: BLE001
|
|
49
|
+
for q in groups[law]:
|
|
50
|
+
rows.append({
|
|
51
|
+
"id": q["id"], "law": law, "article": q["article"],
|
|
52
|
+
"law_ok": False, "article_found": False, "keyword_ok": False,
|
|
53
|
+
"marker_ok": False, "error": str(exc), "selected": "", "source": "",
|
|
54
|
+
"latency_s": round(time.time() - started, 1),
|
|
55
|
+
})
|
|
56
|
+
print(f"[FAIL] {law}: {exc}", flush=True)
|
|
57
|
+
continue
|
|
58
|
+
|
|
59
|
+
selected_title = str(resolved.selected.candidate.get("title") or "")
|
|
60
|
+
selected_source = str(resolved.selected.candidate.get("sourceUrl") or "")
|
|
61
|
+
core = law.replace("中华人民共和国", "")
|
|
62
|
+
law_ok = (norm(core) in norm(selected_title)) or (norm(law) in norm(selected_title)) or (norm(selected_title) in norm(law))
|
|
63
|
+
for q in groups[law]:
|
|
64
|
+
article_text = ls.extract_article(resolved.selected.text, q["article"])
|
|
65
|
+
article_found = bool(article_text)
|
|
66
|
+
keyword_ok = bool(article_text and q["keyword"] in article_text)
|
|
67
|
+
rows.append({
|
|
68
|
+
"id": q["id"], "law": law, "article": q["article"],
|
|
69
|
+
"law_ok": law_ok, "article_found": article_found, "keyword_ok": keyword_ok,
|
|
70
|
+
"marker_ok": bool(resolved.selected.marker_hit),
|
|
71
|
+
"status_fallback": bool(resolved.status_fallback),
|
|
72
|
+
"selected": selected_title, "source": selected_source,
|
|
73
|
+
"status": str(resolved.selected.candidate.get("validityStatus") or ""),
|
|
74
|
+
"latest_version": resolved.marker,
|
|
75
|
+
"latency_s": round(time.time() - started, 1),
|
|
76
|
+
"error": "",
|
|
77
|
+
})
|
|
78
|
+
print(f"[OK] {law} | {selected_title[:36]} | marker={resolved.selected.marker_hit} | {len(groups[law])} 题", flush=True)
|
|
79
|
+
|
|
80
|
+
total = len(rows)
|
|
81
|
+
law_n = sum(1 for r in rows if r["law_ok"])
|
|
82
|
+
art_n = sum(1 for r in rows if r["article_found"])
|
|
83
|
+
kw_n = sum(1 for r in rows if r["keyword_ok"])
|
|
84
|
+
mk_n = sum(1 for r in rows if r["marker_ok"])
|
|
85
|
+
fb_n = sum(1 for r in rows if r.get("status_fallback"))
|
|
86
|
+
print("\n=== 明细 ===")
|
|
87
|
+
print(f"{'id':<5}{'法名':<8}{'条号':<6}{'关键词':<8}{'版本标记':<8}{'法律'}")
|
|
88
|
+
for r in rows:
|
|
89
|
+
print(f"{r['id']:<5}{'✓' if r['law_ok'] else '✗':<8}{'✓' if r['article_found'] else '✗':<6}"
|
|
90
|
+
f"{'✓' if r['keyword_ok'] else '✗':<8}{'✓' if r['marker_ok'] else '✗':<8}{r['law'][:28]}")
|
|
91
|
+
print("\n=== 汇总 ===")
|
|
92
|
+
print(f"题目数 {total}|法名命中 {law_n}/{total} ({law_n/total:.0%})|条号命中 {art_n}/{total} ({art_n/total:.0%})"
|
|
93
|
+
f"|关键词命中 {kw_n}/{total} ({kw_n/total:.0%})|版本标记命中 {mk_n}/{total} ({mk_n/total:.0%})"
|
|
94
|
+
f"|失效回退 {fb_n}/{total}")
|
|
95
|
+
|
|
96
|
+
out = {
|
|
97
|
+
"total": total,
|
|
98
|
+
"law_ok": law_n,
|
|
99
|
+
"article_found": art_n,
|
|
100
|
+
"keyword_ok": kw_n,
|
|
101
|
+
"marker_ok": mk_n,
|
|
102
|
+
"rows": rows,
|
|
103
|
+
}
|
|
104
|
+
Path(args.output).write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
105
|
+
print(f"结果已写入:{args.output}")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
if __name__ == "__main__":
|
|
109
|
+
main()
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""材料画像:把检索结果转成带地域、来源等级、文件类型、抓取状态的 source cards。
|
|
3
|
+
|
|
4
|
+
输入:legal_search.py / merge_search_results.py 的 JSON,或含“检索文章”数组的对象。
|
|
5
|
+
输出:legal_source_cards.json
|
|
6
|
+
|
|
7
|
+
设计目的:让“河北的 208 元被当成福建的 208 元”这类问题在材料层就暴露,
|
|
8
|
+
而不是等模型写进答案后再靠人发现。
|
|
9
|
+
|
|
10
|
+
用法:
|
|
11
|
+
python3 scripts/source_cards.py \
|
|
12
|
+
--input legal_merged.json \
|
|
13
|
+
--profile legal_question_profile.json \
|
|
14
|
+
--output legal_source_cards.json
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
import re
|
|
22
|
+
from datetime import date
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, Dict, List
|
|
25
|
+
from urllib.parse import urlparse
|
|
26
|
+
|
|
27
|
+
from question_profile import PROVINCES
|
|
28
|
+
from path_guard import safe_read_path, safe_write_path
|
|
29
|
+
|
|
30
|
+
PROVINCE_SHORT = {
|
|
31
|
+
p.replace("省", "").replace("市", "").replace("自治区", "").replace("特别行政区", ""): p
|
|
32
|
+
for p in PROVINCES
|
|
33
|
+
}
|
|
34
|
+
PROVINCE_DOMAIN_PREFIX = {
|
|
35
|
+
"bj": "北京市", "tj": "天津市", "he": "河北省", "sx": "山西省",
|
|
36
|
+
"nm": "内蒙古自治区", "ln": "辽宁省", "jl": "吉林省", "hl": "黑龙江省",
|
|
37
|
+
"sh": "上海市", "js": "江苏省", "zj": "浙江省", "ah": "安徽省",
|
|
38
|
+
"fj": "福建省", "jx": "江西省", "sd": "山东省", "ha": "河南省",
|
|
39
|
+
"hb": "湖北省", "hn": "湖南省", "gd": "广东省", "gx": "广西壮族自治区",
|
|
40
|
+
"hi": "海南省", "cq": "重庆市", "sc": "四川省", "gz": "贵州省",
|
|
41
|
+
"yn": "云南省", "xz": "西藏自治区", "sn": "陕西省", "gs": "甘肃省",
|
|
42
|
+
"qh": "青海省", "nx": "宁夏回族自治区", "xj": "新疆维吾尔自治区",
|
|
43
|
+
}
|
|
44
|
+
CITY_PROVINCE = {
|
|
45
|
+
"石家庄": "河北省", "福州": "福建省", "厦门": "福建省", "泉州": "福建省", "漳州": "福建省",
|
|
46
|
+
"莆田": "福建省", "三明": "福建省", "南平": "福建省", "龙岩": "福建省",
|
|
47
|
+
"宁德": "福建省", "晋江": "福建省", "永春": "福建省", "安溪": "福建省",
|
|
48
|
+
"德化": "福建省", "安吉": "浙江省", "杭州": "浙江省", "宁波": "浙江省", "温州": "浙江省",
|
|
49
|
+
"湖州": "浙江省", "嘉兴": "浙江省", "绍兴": "浙江省", "金华": "浙江省",
|
|
50
|
+
"衢州": "浙江省", "舟山": "浙江省", "台州": "浙江省", "丽水": "浙江省",
|
|
51
|
+
"广州": "广东省", "深圳": "广东省", "珠海": "广东省", "汕头": "广东省",
|
|
52
|
+
"佛山": "广东省", "韶关": "广东省", "湛江": "广东省", "肇庆": "广东省",
|
|
53
|
+
"江门": "广东省", "茂名": "广东省", "惠州": "广东省", "梅州": "广东省",
|
|
54
|
+
"汕尾": "广东省", "河源": "广东省", "阳江": "广东省", "清远": "广东省",
|
|
55
|
+
"东莞": "广东省", "中山": "广东省", "潮州": "广东省", "揭阳": "广东省",
|
|
56
|
+
"云浮": "广东省", "鹤山": "广东省", "普宁": "广东省", "茂南": "广东省",
|
|
57
|
+
}
|
|
58
|
+
NATIONAL_TERMS = (
|
|
59
|
+
"全国", "中华人民共和国", "国务院", "全国人民代表大会", "全国人大常委会",
|
|
60
|
+
"最高人民法院", "最高人民检察院", "中共中央", "国家发展改革委",
|
|
61
|
+
"人力资源和社会保障部", "财政部", "教育部", "公安部", "应急管理部",
|
|
62
|
+
"国家市场监督管理总局", "国家卫生健康委员会",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _first(item: Dict[str, Any], *keys: str) -> str:
|
|
67
|
+
for key in keys:
|
|
68
|
+
value = item.get(key)
|
|
69
|
+
if isinstance(value, str) and value.strip():
|
|
70
|
+
return value.strip()
|
|
71
|
+
return ""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
_DATE_PATTERN = re.compile(r"(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?")
|
|
75
|
+
_COMPACT_DATE = re.compile(r"^(\d{4})(\d{2})(\d{2})$")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _norm_date(value: Any) -> str:
|
|
79
|
+
"""把 2026年1月1日 / 2026.01.01 / 2026/01/01 / 20260101 统一成 ISO 日期。
|
|
80
|
+
|
|
81
|
+
数据库里的失效日期不全是 ISO 格式;按字符串直接比较会把“2026年1月1日”判成
|
|
82
|
+
未失效(2026-11-13 审核重要项)。
|
|
83
|
+
"""
|
|
84
|
+
text = str(value or "").strip()
|
|
85
|
+
if not text:
|
|
86
|
+
return ""
|
|
87
|
+
match = _DATE_PATTERN.search(text)
|
|
88
|
+
parts = match.groups() if match else None
|
|
89
|
+
if not parts:
|
|
90
|
+
compact = _COMPACT_DATE.match(text)
|
|
91
|
+
parts = compact.groups() if compact else None
|
|
92
|
+
if not parts:
|
|
93
|
+
return ""
|
|
94
|
+
try:
|
|
95
|
+
return date(int(parts[0]), int(parts[1]), int(parts[2])).isoformat()
|
|
96
|
+
except ValueError:
|
|
97
|
+
return ""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _articles(payload: Any) -> List[Dict[str, Any]]:
|
|
101
|
+
if isinstance(payload, list):
|
|
102
|
+
return [x for x in payload if isinstance(x, dict)]
|
|
103
|
+
if not isinstance(payload, dict):
|
|
104
|
+
return []
|
|
105
|
+
content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
|
|
106
|
+
data = content.get("data") if isinstance(content.get("data"), dict) else content
|
|
107
|
+
if isinstance(data, dict):
|
|
108
|
+
arts = data.get("检索文章")
|
|
109
|
+
if isinstance(arts, list):
|
|
110
|
+
return [x for x in arts if isinstance(x, dict)]
|
|
111
|
+
arts = payload.get("检索文章")
|
|
112
|
+
return [x for x in arts if isinstance(x, dict)] if isinstance(arts, list) else []
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _infer_jurisdiction(item: Dict[str, Any], text: str) -> str:
|
|
116
|
+
area = _first(item, "办理地域", "地域", "area")
|
|
117
|
+
if area in ("中国", "全国"):
|
|
118
|
+
return "全国"
|
|
119
|
+
if area:
|
|
120
|
+
return area
|
|
121
|
+
# 只从标题/机构/数据源判断,不扫描全文:政策全文常提到多个省份,
|
|
122
|
+
# 用全文匹配会把“国务院文件”误标成它正文里提到的某个省。
|
|
123
|
+
title = _first(item, "文章标题", "标题")
|
|
124
|
+
issuer = _first(item, "发布或实施机构")
|
|
125
|
+
source = _first(item, "数据源")
|
|
126
|
+
meta = " ".join([title, issuer, source])
|
|
127
|
+
issuer_text = " ".join([issuer, source])
|
|
128
|
+
|
|
129
|
+
# 标题里的省名:地方实施办法优先;但“国务院关于河北省……”这类
|
|
130
|
+
# 中央文件仍归全国,不能因为标题提到某省就当成地方文件。
|
|
131
|
+
title_province = next((p for p in PROVINCES if p in title), "")
|
|
132
|
+
if not title_province:
|
|
133
|
+
title_province = next((p for short, p in PROVINCE_SHORT.items() if short and short in title), "")
|
|
134
|
+
issuer_national = any(term in issuer_text for term in NATIONAL_TERMS)
|
|
135
|
+
if title_province and (not issuer_national or "全国人民代表大会常务委员会" in issuer):
|
|
136
|
+
return title_province
|
|
137
|
+
|
|
138
|
+
# 国务院/部委文件归全国,不能因为正文提到某省就标成该省。
|
|
139
|
+
if any(term in meta for term in NATIONAL_TERMS):
|
|
140
|
+
return "全国"
|
|
141
|
+
|
|
142
|
+
for province in PROVINCES:
|
|
143
|
+
if province in meta:
|
|
144
|
+
return province
|
|
145
|
+
for short, province in PROVINCE_SHORT.items():
|
|
146
|
+
if short and short in meta:
|
|
147
|
+
return province
|
|
148
|
+
|
|
149
|
+
# 城市名优先于 URL 前缀:heshan.gov.cn 是广东鹤山,不是河北(he)。
|
|
150
|
+
url = _first(item, "源网址", "url", "原文链接")
|
|
151
|
+
host = (urlparse(url).hostname or "").lower() if url else ""
|
|
152
|
+
labels = host.split(".") if host else []
|
|
153
|
+
label = labels[0] if labels else ""
|
|
154
|
+
if label in ("www", "m") and len(labels) > 1:
|
|
155
|
+
label = labels[1]
|
|
156
|
+
for city, province in CITY_PROVINCE.items():
|
|
157
|
+
if city in meta or (label and label.startswith(city.lower())):
|
|
158
|
+
return province
|
|
159
|
+
# 从 URL 的域名前缀补省份:fjyc.gov.cn -> 福建,zj.gov.cn -> 浙江。
|
|
160
|
+
if len(label) >= 2 and label[:2] in PROVINCE_DOMAIN_PREFIX:
|
|
161
|
+
return PROVINCE_DOMAIN_PREFIX[label[:2]]
|
|
162
|
+
return "全国" if "中国" in meta or "全国" in meta else ""
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _source_grade(item: Dict[str, Any]) -> str:
|
|
166
|
+
nature = _first(item, "来源性质", "source_nature")
|
|
167
|
+
if nature:
|
|
168
|
+
return nature
|
|
169
|
+
if item.get("非官方来源"):
|
|
170
|
+
return "未知"
|
|
171
|
+
return "官方库"
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _is_official(item: Dict[str, Any]) -> bool:
|
|
175
|
+
nature = _first(item, "来源性质", "source_nature")
|
|
176
|
+
if nature in ("次级媒体", "次级媒体/未知", "未知"):
|
|
177
|
+
return False
|
|
178
|
+
# “非官方来源=True”只表示不是深知库内材料,不否定政府网站本身的官方属性。
|
|
179
|
+
if nature in ("政府网站", "官方媒体"):
|
|
180
|
+
return True
|
|
181
|
+
if item.get("非官方来源"):
|
|
182
|
+
return False
|
|
183
|
+
return _first(item, "数据权威性", "authority") in ("权威", "authoritative", "")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _doc_type(item: Dict[str, Any]) -> str:
|
|
187
|
+
title = _first(item, "文章标题", "标题")
|
|
188
|
+
doc_no = _first(item, "发文字号", "文号")
|
|
189
|
+
issuer = _first(item, "发布或实施机构", "发布机关")
|
|
190
|
+
text = title + " " + doc_no + " " + issuer
|
|
191
|
+
if re.search(r"GB(?:/T)?\s*\d", text):
|
|
192
|
+
return "国家标准"
|
|
193
|
+
if re.search(r"日报|晚报|新闻|财经|记者", text):
|
|
194
|
+
return "新闻报道"
|
|
195
|
+
if "司法解释" in text or "批复" in text or "解释" in title:
|
|
196
|
+
return "司法解释"
|
|
197
|
+
if "条例" in text:
|
|
198
|
+
return "行政法规"
|
|
199
|
+
if re.search(r"人民政府|办公厅|人社局|财政厅|教育局|消防救援", text):
|
|
200
|
+
return "地方政策"
|
|
201
|
+
if re.search(r"通知|办法|意见|指导意见|实施细则|规定", text):
|
|
202
|
+
return "政策文件"
|
|
203
|
+
if title.endswith("法") or "中华人民共和国" in title:
|
|
204
|
+
return "法律"
|
|
205
|
+
return "其他"
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _channel(item: Dict[str, Any]) -> str:
|
|
209
|
+
raw = _first(item, "检索通道", "channel")
|
|
210
|
+
raw = re.sub(
|
|
211
|
+
r"宿主网页抓取[^、·]*|阶段[一二三]|库内政策[^、·]*|政策档案全文|条款级召回|^00[1-5]$|[((]00[1-5][))]",
|
|
212
|
+
"", raw,
|
|
213
|
+
)
|
|
214
|
+
tokens = []
|
|
215
|
+
for token in re.split(r"[、·]", raw):
|
|
216
|
+
token = token.strip()
|
|
217
|
+
if not token or token in ("联网", "可信联网", "宿主 WebSearch"):
|
|
218
|
+
continue
|
|
219
|
+
if "条款级召回" in token:
|
|
220
|
+
token = re.split(r"[((]", token, maxsplit=1)[0].strip()
|
|
221
|
+
if not token or re.fullmatch(r"00[1-5]", token) or "条款级召回" in token:
|
|
222
|
+
continue
|
|
223
|
+
if token.startswith("深知可信搜索"):
|
|
224
|
+
token = "深知可信搜索"
|
|
225
|
+
elif token.startswith("深知深度搜索"):
|
|
226
|
+
token = "深知深度搜索"
|
|
227
|
+
elif token.startswith("法律"):
|
|
228
|
+
token = "法律"
|
|
229
|
+
if token not in tokens:
|
|
230
|
+
tokens.append(token)
|
|
231
|
+
return " · ".join(tokens)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _spans(item: Dict[str, Any]) -> List[str]:
|
|
235
|
+
spans: List[str] = []
|
|
236
|
+
for para in item.get("段落") or []:
|
|
237
|
+
if isinstance(para, dict):
|
|
238
|
+
text = str(para.get("内容") or para.get("text") or "").strip()
|
|
239
|
+
else:
|
|
240
|
+
text = str(para or "").strip()
|
|
241
|
+
if text:
|
|
242
|
+
spans.append(text)
|
|
243
|
+
return spans
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def build_cards(payload: Any, question_jurisdiction: str = "", as_of: str = "") -> Dict[str, Any]:
|
|
247
|
+
cards: List[Dict[str, Any]] = []
|
|
248
|
+
for idx, item in enumerate(_articles(payload), start=1):
|
|
249
|
+
spans = _spans(item)
|
|
250
|
+
text = "\n".join(spans)
|
|
251
|
+
jurisdiction = _infer_jurisdiction(item, text)
|
|
252
|
+
expired_at = _first(item, "失效日期", "expired_at")
|
|
253
|
+
expired_iso = _norm_date(expired_at)
|
|
254
|
+
as_of_iso = _norm_date(as_of)
|
|
255
|
+
is_expired = bool(expired_iso and as_of_iso and expired_iso < as_of_iso)
|
|
256
|
+
cards.append({
|
|
257
|
+
"id": str(item.get("编号") or item.get("文章Id") or f"s{idx}"),
|
|
258
|
+
"title": _first(item, "文章标题", "标题"),
|
|
259
|
+
"issuer": _first(item, "发布或实施机构", "发布机关"),
|
|
260
|
+
"jurisdiction": jurisdiction,
|
|
261
|
+
"jurisdiction_status": "known" if jurisdiction else "unknown",
|
|
262
|
+
"doc_type": _doc_type(item),
|
|
263
|
+
"source_grade": _source_grade(item),
|
|
264
|
+
"source_channel": _first(item, "来源通道", "source_channel") or (
|
|
265
|
+
"外部联网" if item.get("非官方来源") else "深知库内"
|
|
266
|
+
),
|
|
267
|
+
"official": _is_official(item),
|
|
268
|
+
"published_at": _first(item, "发布日期", "date"),
|
|
269
|
+
"effective_at": _first(item, "生效日期", "effectiveDate"),
|
|
270
|
+
"expired_at": expired_at,
|
|
271
|
+
"is_expired": is_expired,
|
|
272
|
+
"version_note": (
|
|
273
|
+
f"材料标注失效日期 {expired_at},为旧版本;现行版本请走法条模式"
|
|
274
|
+
if is_expired else ""
|
|
275
|
+
),
|
|
276
|
+
"url": _first(item, "源网址", "url", "原文链接"),
|
|
277
|
+
"doc_number": _first(item, "发文字号", "文号"),
|
|
278
|
+
"channel": _channel(item),
|
|
279
|
+
"fetch_status": "ok" if spans else "failed",
|
|
280
|
+
"spans": spans,
|
|
281
|
+
})
|
|
282
|
+
return {
|
|
283
|
+
"question_jurisdiction": question_jurisdiction,
|
|
284
|
+
"sources": cards,
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def main() -> int:
|
|
289
|
+
parser = argparse.ArgumentParser(description="生成材料画像 source cards")
|
|
290
|
+
parser.add_argument("--input", required=True, help="检索结果 JSON(run 目录内)")
|
|
291
|
+
parser.add_argument("--profile", help="问题画像 JSON(run 目录内,读取 jurisdiction/as_of)")
|
|
292
|
+
parser.add_argument("--output", default="legal_source_cards.json", help="输出文件名(落到 --run 目录)")
|
|
293
|
+
parser.add_argument("--run", help="会话 run 目录(也可用环境变量 DKNOWC_RUN_DIR)")
|
|
294
|
+
args = parser.parse_args()
|
|
295
|
+
|
|
296
|
+
try:
|
|
297
|
+
payload = json.loads(safe_read_path(args.input, args.run).read_text(encoding="utf-8"))
|
|
298
|
+
except (OSError, json.JSONDecodeError, ValueError) as exc:
|
|
299
|
+
parser.error(f"输入不可读:{exc}")
|
|
300
|
+
question_jurisdiction = ""
|
|
301
|
+
as_of = ""
|
|
302
|
+
if args.profile:
|
|
303
|
+
try:
|
|
304
|
+
profile = json.loads(safe_read_path(args.profile, args.run).read_text(encoding="utf-8"))
|
|
305
|
+
question_jurisdiction = str(profile.get("jurisdiction") or "")
|
|
306
|
+
as_of = str(profile.get("as_of") or "")
|
|
307
|
+
except (OSError, json.JSONDecodeError, ValueError) as exc:
|
|
308
|
+
parser.error(f"profile 不可读:{exc}")
|
|
309
|
+
|
|
310
|
+
try:
|
|
311
|
+
out = safe_write_path(args.output, args.run)
|
|
312
|
+
except ValueError as exc:
|
|
313
|
+
parser.error(str(exc))
|
|
314
|
+
result = build_cards(payload, question_jurisdiction, as_of)
|
|
315
|
+
out.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
316
|
+
print(json.dumps({"output": str(out), "sources": len(result["sources"])}, ensure_ascii=False, indent=2))
|
|
317
|
+
return 0
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
if __name__ == "__main__":
|
|
321
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""政策分类标签目录:路径解析与校验(2026-11-05,业务方提供清单)。
|
|
3
|
+
|
|
4
|
+
目录来源:钉钉表格《政策分类标签清单》→ reference/policy_tags.json,裁剪版 250 条(全量 1,633 条保留在内部工作区,不随公开包分发)。
|
|
5
|
+
每条含:标签类型、一级/二级/三级分类、ICS code、最终标签名、标签ID、标签编码、创建状态。
|
|
6
|
+
|
|
7
|
+
用途:
|
|
8
|
+
1) 解析:传短名(如「金融监管行业」)自动补成接口要求的完整路径
|
|
9
|
+
(`政策/行业标签/金融监管行业`);
|
|
10
|
+
2) 校验:把可信搜索接口 V2 返回的 `文件标签` 逐个对照目录,找出目录里没有的路径;
|
|
11
|
+
3) 与 legal_search.py 集成:`--policy-labels` 自动解析短名,检索结果自动校验标签。
|
|
12
|
+
|
|
13
|
+
只读本地目录,不发起网络请求。
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import json
|
|
19
|
+
import sys
|
|
20
|
+
from collections import defaultdict
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any, Dict, Iterable, List, Optional
|
|
23
|
+
|
|
24
|
+
CATALOG_PATH = Path(__file__).resolve().parent.parent / "reference" / "policy_tags.json"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Catalog:
|
|
28
|
+
def __init__(self, entries: Iterable[Dict[str, Any]]):
|
|
29
|
+
self.entries = [e for e in entries if e.get("最终标签名")]
|
|
30
|
+
self.by_path: Dict[str, Dict[str, Any]] = {e["最终标签名"]: e for e in self.entries}
|
|
31
|
+
self.by_leaf: Dict[str, List[str]] = defaultdict(list)
|
|
32
|
+
self.by_type: Dict[str, List[str]] = defaultdict(list)
|
|
33
|
+
# 本地目录只收法律/主题/行业三类(ICS 与本 skill 无关,未收)。
|
|
34
|
+
# 用前两段作为"已覆盖前缀",目录外但类型未覆盖的标签不当作错误。
|
|
35
|
+
self.covered_prefixes = {"/".join(p.split("/")[:2]) for p in self.by_path}
|
|
36
|
+
for e in self.entries:
|
|
37
|
+
path = e["最终标签名"]
|
|
38
|
+
self.by_leaf[path.rsplit("/", 1)[-1]].append(path)
|
|
39
|
+
self.by_type[e.get("标签类型") or ""].append(path)
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def load(cls, path: Optional[Path] = None) -> "Catalog":
|
|
43
|
+
p = Path(path) if path else CATALOG_PATH
|
|
44
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
45
|
+
return cls(data)
|
|
46
|
+
|
|
47
|
+
# ---------- 解析 ----------
|
|
48
|
+
def resolve(self, name: str) -> List[str]:
|
|
49
|
+
"""把用户写法解析成目录里的完整路径。
|
|
50
|
+
|
|
51
|
+
支持三种写法:完整路径、路径后缀(如「行业标签/金融监管行业」)、叶子名。
|
|
52
|
+
返回按路径排序去重后的候选;空列表表示目录里没有。
|
|
53
|
+
"""
|
|
54
|
+
name = (name or "").strip().strip("/").replace("/", "/")
|
|
55
|
+
if not name:
|
|
56
|
+
return []
|
|
57
|
+
if name in self.by_path:
|
|
58
|
+
return [name]
|
|
59
|
+
suffix = "/" + name
|
|
60
|
+
hits = [p for p in self.by_path if p.endswith(suffix)]
|
|
61
|
+
if hits:
|
|
62
|
+
return sorted(set(hits))
|
|
63
|
+
leaf_hits = sorted(set(self.by_leaf.get(name, [])))
|
|
64
|
+
if leaf_hits:
|
|
65
|
+
return leaf_hits
|
|
66
|
+
# 父级路径(如「法律」「政策/行业标签」)本身可能不在明细里,但它是目录中
|
|
67
|
+
# 一批路径的公共前缀;接口支持前缀匹配,按前缀原样返回。
|
|
68
|
+
prefix = name + "/"
|
|
69
|
+
if any(p.startswith(prefix) for p in self.by_path):
|
|
70
|
+
return [name]
|
|
71
|
+
return []
|
|
72
|
+
|
|
73
|
+
def resolve_unique(self, name: str) -> Optional[str]:
|
|
74
|
+
hits = self.resolve(name)
|
|
75
|
+
return hits[0] if len(hits) == 1 else None
|
|
76
|
+
|
|
77
|
+
# ---------- 校验 ----------
|
|
78
|
+
def is_valid(self, path: str) -> bool:
|
|
79
|
+
return (path or "").strip() in self.by_path
|
|
80
|
+
|
|
81
|
+
def type_of(self, path: str) -> str:
|
|
82
|
+
e = self.by_path.get((path or "").strip())
|
|
83
|
+
return (e or {}).get("标签类型", "")
|
|
84
|
+
|
|
85
|
+
def unknown_in_articles(self, articles: Iterable[Dict[str, Any]]) -> List[Dict[str, str]]:
|
|
86
|
+
"""检查检索返回的文章标签,列出目录中不存在的路径及出处。"""
|
|
87
|
+
bad: List[Dict[str, str]] = []
|
|
88
|
+
for a in articles or []:
|
|
89
|
+
title = str(a.get("文章标题") or "")[:40]
|
|
90
|
+
for tag in a.get("文件标签") or []:
|
|
91
|
+
tag = str(tag or "").strip()
|
|
92
|
+
if not tag or tag in self.by_path:
|
|
93
|
+
continue
|
|
94
|
+
prefix = "/".join(tag.split("/")[:2])
|
|
95
|
+
if prefix not in self.covered_prefixes:
|
|
96
|
+
continue # 本地目录未收录该类(如 ICS),不算目录外
|
|
97
|
+
bad.append({"文章": title, "文件标签": tag})
|
|
98
|
+
return bad
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def resolve_many(labels: Iterable[str], catalog: Optional[Catalog] = None) -> List[str]:
|
|
102
|
+
"""把一组标签写法解析成完整路径;解析不到或歧义的保留原值(交给接口判定)。"""
|
|
103
|
+
cat = catalog or Catalog.load()
|
|
104
|
+
out: List[str] = []
|
|
105
|
+
for raw in labels:
|
|
106
|
+
raw = (raw or "").strip()
|
|
107
|
+
if not raw:
|
|
108
|
+
continue
|
|
109
|
+
path = cat.resolve_unique(raw)
|
|
110
|
+
if path is None and not cat.resolve(raw):
|
|
111
|
+
print(f"标签目录:未找到「{raw}」,按原值传给接口", file=sys.stderr)
|
|
112
|
+
elif path is None:
|
|
113
|
+
print(f"标签目录:「{raw}」命中多个路径,按原值传给接口({'; '.join(cat.resolve(raw)[:4])})",
|
|
114
|
+
file=sys.stderr)
|
|
115
|
+
out.append(path or raw)
|
|
116
|
+
return out
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def describe(entries: Iterable[Dict[str, Any]]) -> str:
|
|
120
|
+
from collections import Counter
|
|
121
|
+
c = Counter(e.get("标签类型") or "" for e in entries)
|
|
122
|
+
return "|".join(f"{k} {v}" for k, v in sorted(c.items()))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def main() -> None:
|
|
126
|
+
ap = argparse.ArgumentParser(description="政策分类标签目录:解析短名 / 校验接口返回标签")
|
|
127
|
+
ap.add_argument("--resolve", help="按完整路径、路径后缀或叶子名解析完整路径")
|
|
128
|
+
ap.add_argument("--check", help="校验 legal_search.py 输出 JSON 里所有 文件标签")
|
|
129
|
+
ap.add_argument("--type", help="列出某一标签类型下的全部路径(如 【DT】行业标签)")
|
|
130
|
+
ap.add_argument("--catalog", help="目录 JSON 路径(默认 skill 内 reference/policy_tags.json)")
|
|
131
|
+
args = ap.parse_args()
|
|
132
|
+
cat = Catalog.load(Path(args.catalog) if args.catalog else None)
|
|
133
|
+
|
|
134
|
+
if args.resolve:
|
|
135
|
+
hits = cat.resolve(args.resolve)
|
|
136
|
+
if not hits:
|
|
137
|
+
print("未找到")
|
|
138
|
+
raise SystemExit(1)
|
|
139
|
+
for h in hits:
|
|
140
|
+
print(h)
|
|
141
|
+
return
|
|
142
|
+
|
|
143
|
+
if args.type:
|
|
144
|
+
for p in sorted(cat.by_type.get(args.type, [])):
|
|
145
|
+
print(p)
|
|
146
|
+
return
|
|
147
|
+
|
|
148
|
+
if args.check:
|
|
149
|
+
data = json.loads(Path(args.check).read_text(encoding="utf-8"))
|
|
150
|
+
arts = ((data.get("content") or {}).get("data") or {}).get("检索文章") or []
|
|
151
|
+
bad = cat.unknown_in_articles(arts)
|
|
152
|
+
total = sum(len(a.get("文件标签") or []) for a in arts)
|
|
153
|
+
print(f"文章 {len(arts)} 篇,标签 {total} 个,目录外 {len(bad)} 个")
|
|
154
|
+
for b in bad:
|
|
155
|
+
print(f" ✗ {b['文件标签']} ← {b['文章']}")
|
|
156
|
+
return
|
|
157
|
+
|
|
158
|
+
print(f"目录条目:{len(cat.entries)}({describe(cat.entries)})")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
if __name__ == "__main__":
|
|
162
|
+
main()
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"brand": {
|
|
3
|
+
"product_name": "深知法律助手"
|
|
4
|
+
},
|
|
5
|
+
"channels": {
|
|
6
|
+
"route_keywords": {
|
|
7
|
+
"deep": [
|
|
8
|
+
"深度"
|
|
9
|
+
],
|
|
10
|
+
"trusted": [
|
|
11
|
+
"可信",
|
|
12
|
+
"法律"
|
|
13
|
+
]
|
|
14
|
+
},
|
|
15
|
+
"labels": {
|
|
16
|
+
"deep": "深度搜索",
|
|
17
|
+
"trusted": "可信补搜"
|
|
18
|
+
},
|
|
19
|
+
"summary": {
|
|
20
|
+
"deep": "深度搜索 {deep} 路",
|
|
21
|
+
"trusted": "可信补搜 {trusted} 路",
|
|
22
|
+
"fallback": "深知法律检索 {n} 组材料"
|
|
23
|
+
},
|
|
24
|
+
"step1_fallback": "深知法律检索",
|
|
25
|
+
"internal_token_filter": [
|
|
26
|
+
"联网",
|
|
27
|
+
"可信联网",
|
|
28
|
+
"宿主 WebSearch",
|
|
29
|
+
"宿主网页抓取",
|
|
30
|
+
"阶段一",
|
|
31
|
+
"阶段二",
|
|
32
|
+
"阶段三",
|
|
33
|
+
"补充检索",
|
|
34
|
+
"库内政策",
|
|
35
|
+
"政策档案全文",
|
|
36
|
+
"条款级召回",
|
|
37
|
+
"001",
|
|
38
|
+
"002",
|
|
39
|
+
"003",
|
|
40
|
+
"004",
|
|
41
|
+
"005"
|
|
42
|
+
],
|
|
43
|
+
"tokens": {
|
|
44
|
+
"深知可信搜索·法律": "深知可信搜索",
|
|
45
|
+
"深知可信搜索·联网": "深知可信搜索"
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"agent_track": {
|
|
49
|
+
"enabled": true,
|
|
50
|
+
"require_evidence": true
|
|
51
|
+
},
|
|
52
|
+
"official_host_allow": [
|
|
53
|
+
"mpfa.org.hk"
|
|
54
|
+
],
|
|
55
|
+
"stage": {
|
|
56
|
+
"enable": false
|
|
57
|
+
},
|
|
58
|
+
"charts": {
|
|
59
|
+
"enable": true
|
|
60
|
+
},
|
|
61
|
+
"verify": {
|
|
62
|
+
"enabled": true,
|
|
63
|
+
"required": true,
|
|
64
|
+
"compare_digests": true
|
|
65
|
+
}
|
|
66
|
+
}
|