dknowc-dsh 1.0.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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +131 -0
  3. package/cordis.patch.yml +17 -0
  4. package/package.json +33 -0
  5. package/skills/dknowc-official-doc-writer/README.md +156 -0
  6. package/skills/dknowc-official-doc-writer/SKILL.md +462 -0
  7. package/skills/dknowc-official-doc-writer/config/format.json +101 -0
  8. package/skills/dknowc-official-doc-writer/config/user_profile.json.example +6 -0
  9. package/skills/dknowc-official-doc-writer/official-docs/input/mcp_intro_content.md +61 -0
  10. package/skills/dknowc-official-doc-writer/reference/anti_ai_patterns.md +113 -0
  11. package/skills/dknowc-official-doc-writer/reference/fact_discipline.md +62 -0
  12. package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +138 -0
  13. package/skills/dknowc-official-doc-writer/reference/output_guide.md +288 -0
  14. package/skills/dknowc-official-doc-writer/reference/review_checklist.md +156 -0
  15. package/skills/dknowc-official-doc-writer/reference/search_guide.md +317 -0
  16. package/skills/dknowc-official-doc-writer/reference/search_intro.md +15 -0
  17. package/skills/dknowc-official-doc-writer/reference/search_policy.md +284 -0
  18. package/skills/dknowc-official-doc-writer/reference/standards/00_index.md +151 -0
  19. package/skills/dknowc-official-doc-writer/reference/standards/01_report.md +51 -0
  20. package/skills/dknowc-official-doc-writer/reference/standards/02_qingshi.md +53 -0
  21. package/skills/dknowc-official-doc-writer/reference/standards/03_pifu.md +48 -0
  22. package/skills/dknowc-official-doc-writer/reference/standards/04_tongzhi.md +51 -0
  23. package/skills/dknowc-official-doc-writer/reference/standards/05_yijian.md +55 -0
  24. package/skills/dknowc-official-doc-writer/reference/standards/06_han.md +81 -0
  25. package/skills/dknowc-official-doc-writer/reference/standards/07_minutes.md +46 -0
  26. package/skills/dknowc-official-doc-writer/reference/standards/08_tongbao.md +53 -0
  27. package/skills/dknowc-official-doc-writer/reference/standards/09_tonggao.md +45 -0
  28. package/skills/dknowc-official-doc-writer/reference/standards/10_gonggao.md +44 -0
  29. package/skills/dknowc-official-doc-writer/reference/standards/11_fuhan_approve.md +46 -0
  30. package/skills/dknowc-official-doc-writer/reference/standards/12_fuhan_objection.md +46 -0
  31. package/skills/dknowc-official-doc-writer/reference/standards/13_reminder.md +46 -0
  32. package/skills/dknowc-official-doc-writer/reference/standards/14_generic.md +41 -0
  33. package/skills/dknowc-official-doc-writer/reference/standards/15_business_docs.md +47 -0
  34. package/skills/dknowc-official-doc-writer/reference/standards/16_decision.md +47 -0
  35. package/skills/dknowc-official-doc-writer/reference/standards/17_resolution.md +45 -0
  36. package/skills/dknowc-official-doc-writer/reference/standards/18_order.md +44 -0
  37. package/skills/dknowc-official-doc-writer/reference/standards/19_gazette.md +45 -0
  38. package/skills/dknowc-official-doc-writer/reference/standards/20_motion.md +45 -0
  39. package/skills/dknowc-official-doc-writer/reference/standards/21_explanation.md +40 -0
  40. package/skills/dknowc-official-doc-writer/reference/standards/22_application.md +47 -0
  41. package/skills/dknowc-official-doc-writer/reference/standards/23_publicity.md +46 -0
  42. package/skills/dknowc-official-doc-writer/reference/standards/24_procurement.md +40 -0
  43. package/skills/dknowc-official-doc-writer/reference/standards/25_plan.md +42 -0
  44. package/skills/dknowc-official-doc-writer/reference/standards/26_summary.md +42 -0
  45. package/skills/dknowc-official-doc-writer/reference/standards/27_speech.md +43 -0
  46. package/skills/dknowc-official-doc-writer/reference/standards/28_rules.md +40 -0
  47. package/skills/dknowc-official-doc-writer/reference/standards/29_research.md +42 -0
  48. package/skills/dknowc-official-doc-writer/reference/standards/30_feasibility.md +42 -0
  49. package/skills/dknowc-official-doc-writer/reference/standards/31_review_material.md +40 -0
  50. package/skills/dknowc-official-doc-writer/reference/standards/32_ai_compute.md +41 -0
  51. package/skills/dknowc-official-doc-writer/reference/standards/99_expressions.md +569 -0
  52. package/skills/dknowc-official-doc-writer/reference/task_router.md +119 -0
  53. package/skills/dknowc-official-doc-writer/scripts/adapt_mcp_result.py +241 -0
  54. package/skills/dknowc-official-doc-writer/scripts/check_release.py +78 -0
  55. package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +575 -0
  56. package/skills/dknowc-official-doc-writer/scripts/format_document.py +1756 -0
  57. package/skills/dknowc-official-doc-writer/scripts/initialize.py +178 -0
  58. package/skills/dknowc-official-doc-writer/scripts/mcp_direct.py +158 -0
  59. package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +223 -0
  60. package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +202 -0
  61. package/skills/dknowc-official-doc-writer/scripts/prose_lint.py +242 -0
  62. package/skills/dknowc-official-doc-writer/scripts/register.mjs +218 -0
  63. package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +966 -0
  64. package/skills/dknowc-official-doc-writer/scripts/review_document.py +127 -0
  65. package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +180 -0
  66. package/skills/dknowc-official-doc-writer/scripts/template_generator.py +975 -0
  67. package/skills/dknowc-trusted-consulting/README.md +63 -0
  68. package/skills/dknowc-trusted-consulting/SKILL.md +172 -0
  69. package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +241 -0
  70. package/skills/dknowc-trusted-consulting/scripts/check_release.py +66 -0
  71. package/skills/dknowc-trusted-consulting/scripts/gov_chat.py +475 -0
  72. package/skills/dknowc-trusted-consulting/scripts/initialize.py +89 -0
  73. package/skills/dknowc-trusted-consulting/scripts/mcp_direct.py +158 -0
  74. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +181 -0
  75. package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +990 -0
  76. package/skills/dknowc-trusted-search/README.md +63 -0
  77. package/skills/dknowc-trusted-search/SKILL.md +232 -0
  78. package/skills/dknowc-trusted-search/official-docs/output/.gitkeep +0 -0
  79. package/skills/dknowc-trusted-search/official-docs/search-results/.gitkeep +0 -0
  80. package/skills/dknowc-trusted-search/scripts/adapt_mcp_result.py +241 -0
  81. package/skills/dknowc-trusted-search/scripts/check_release.py +79 -0
  82. package/skills/dknowc-trusted-search/scripts/deep_query.py +266 -0
  83. package/skills/dknowc-trusted-search/scripts/initialize.py +89 -0
  84. package/skills/dknowc-trusted-search/scripts/mcp_direct.py +158 -0
  85. package/skills/dknowc-trusted-search/scripts/register_key.mjs +181 -0
  86. package/skills/dknowc-trusted-search/scripts/render_policy_visualization.py +889 -0
  87. package/skills/dknowc-trusted-search/scripts/render_trace_html.py +1011 -0
  88. package/skills/dknowc-trusted-search/scripts/trusted_search.py +325 -0
  89. package/src/index.js +103 -0
@@ -0,0 +1,990 @@
1
+ #!/usr/bin/env python3
2
+ """Generate an interactive local HTML trace report from DKnownAI API JSON."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import html
8
+ import json
9
+ import re
10
+ from datetime import datetime
11
+ from pathlib import Path
12
+ from typing import Any, Dict, Iterable, List, Optional
13
+
14
+
15
+ SKILL_ROOT = Path(__file__).resolve().parent.parent
16
+ # 工作区根:dsh 场景通过环境变量 DKNWOC_WS_ROOT 指向会话工作区,未设置时回退到 skill 目录(SkillHub 兼容)
17
+ import os as _os
18
+ WS_ROOT = Path(_os.environ.get("DKNWOC_WS_ROOT") or _os.getcwd()).resolve()
19
+ SEARCH_RESULTS_DIR = WS_ROOT / "official-docs" / "search-results"
20
+ OUTPUT_DIR = WS_ROOT / "official-docs" / "output"
21
+
22
+
23
+ def _resolve_input(value: str) -> Path:
24
+ """把待读取文件解析到工作区 official-docs/search-results/。
25
+
26
+ 裸文件名进 search-results/;带子路径的相对路径按 WS_ROOT 解析,
27
+ 因此 official-docs/search-results/xxx.json 这类写法也可直接使用。
28
+ """
29
+ raw = Path(value).expanduser()
30
+ if raw.is_absolute():
31
+ return raw.resolve()
32
+ if raw.parent == Path("."):
33
+ return (SEARCH_RESULTS_DIR / raw.name).resolve()
34
+ return (WS_ROOT / raw).resolve()
35
+
36
+
37
+ def _resolve_output(value: str) -> Path:
38
+ """把交付物解析到工作区 official-docs/output/,自动补 .html 后缀。"""
39
+ raw = Path(value).expanduser()
40
+ if raw.is_absolute():
41
+ resolved = raw.resolve()
42
+ elif raw.parent == Path("."):
43
+ resolved = (OUTPUT_DIR / raw.name).resolve()
44
+ else:
45
+ resolved = (WS_ROOT / raw).resolve()
46
+ if resolved.suffix.lower() not in {".html", ".htm"}:
47
+ resolved = resolved.with_suffix(".html")
48
+ return resolved
49
+
50
+
51
+ def esc(value: Any) -> str:
52
+ return html.escape(str(value or ""), quote=True)
53
+
54
+
55
+ def load_json(path: Path) -> Dict[str, Any]:
56
+ with path.open("r", encoding="utf-8") as f:
57
+ data = json.load(f)
58
+ if isinstance(data, dict):
59
+ return data
60
+ return {"data": data}
61
+
62
+
63
+ def unwrap(data: Dict[str, Any]) -> Dict[str, Any]:
64
+ if isinstance(data.get("data"), dict) and data.get("success") is True:
65
+ return data["data"]
66
+ if isinstance(data.get("content"), dict):
67
+ return data["content"]
68
+ return data
69
+
70
+
71
+ def first_str(*values: Any) -> str:
72
+ for value in values:
73
+ if isinstance(value, str) and value.strip():
74
+ return value.strip()
75
+ if value not in (None, "", [], {}) and not isinstance(value, (dict, list)):
76
+ return str(value).strip()
77
+ return ""
78
+
79
+
80
+ def short(text: Any, limit: int = 360) -> str:
81
+ value = " ".join(str(text or "").split())
82
+ if len(value) <= limit:
83
+ return value
84
+ return value[:limit].rstrip() + "..."
85
+
86
+
87
+ def strip_tags(text: str) -> str:
88
+ return re.sub(r"<[^>]+>", "", text or "")
89
+
90
+
91
+ def normalize_citations(text: str) -> str:
92
+ text = strip_tags(text)
93
+ return re.sub(r"\[\^?(\d+)\^?\]", r"[\1]", text)
94
+
95
+
96
+ def paragraph_text(item: Dict[str, Any]) -> str:
97
+ paragraphs = item.get("content") or item.get("段落") or item.get("paragraphs") or item.get("paragraphList")
98
+ if isinstance(paragraphs, list):
99
+ chunks = []
100
+ for para in paragraphs:
101
+ if isinstance(para, dict):
102
+ chunks.append(first_str(para.get("text"), para.get("内容"), para.get("content"), para.get("summary"), para.get("标题"), para.get("title")))
103
+ else:
104
+ chunks.append(str(para))
105
+ text = "\n".join(chunk for chunk in chunks if chunk)
106
+ if text:
107
+ return text
108
+ return first_str(
109
+ item.get("摘录"),
110
+ item.get("摘要"),
111
+ item.get("相关段落"),
112
+ item.get("全文"),
113
+ item.get("content"),
114
+ item.get("text"),
115
+ item.get("snippet"),
116
+ )
117
+
118
+
119
+ def content_segments(item: Dict[str, Any]) -> List[Dict[str, str]]:
120
+ paragraphs = item.get("content") or item.get("段落") or item.get("paragraphs") or item.get("paragraphList")
121
+ segments: List[Dict[str, str]] = []
122
+ if not isinstance(paragraphs, list):
123
+ return segments
124
+ for para in paragraphs:
125
+ if isinstance(para, dict):
126
+ text = first_str(para.get("text"), para.get("内容"), para.get("content"), para.get("summary"))
127
+ title = first_str(para.get("title"), para.get("标题"), para.get("name"))
128
+ pid = first_str(para.get("id"), para.get("idx"), para.get("index"), para.get("seq"), para.get("编号"))
129
+ if text or title:
130
+ segments.append({"id": pid, "title": title, "text": text})
131
+ else:
132
+ text = first_str(para)
133
+ if text:
134
+ segments.append({"id": "", "title": "", "text": text})
135
+ return segments
136
+
137
+
138
+ def source_from_article(item: Dict[str, Any], index: int, segment: Optional[Dict[str, str]] = None) -> Dict[str, str]:
139
+ vo = item.get("vo") if isinstance(item.get("vo"), dict) else {}
140
+ segment = segment or {}
141
+ explicit_id = first_str(
142
+ segment.get("id"),
143
+ item.get("角标"),
144
+ item.get("编号"),
145
+ item.get("index"),
146
+ item.get("idx"),
147
+ item.get("seq"),
148
+ item.get("serialNo"),
149
+ item.get("materialIndex"),
150
+ item.get("referenceIndex"),
151
+ item.get("引用编号"),
152
+ vo.get("index"),
153
+ vo.get("idx"),
154
+ )
155
+ if explicit_id:
156
+ match = re.search(r"\d+", explicit_id)
157
+ explicit_id = match.group(0) if match else ""
158
+ source = {
159
+ "id": explicit_id or str(index),
160
+ "title": first_str(
161
+ item.get("文章标题"),
162
+ item.get("title"),
163
+ item.get("标题"),
164
+ item.get("name"),
165
+ vo.get("showTitle"),
166
+ vo.get("title"),
167
+ "未命名材料",
168
+ ),
169
+ "agency": first_str(
170
+ item.get("unit") if not isinstance(item.get("unit"), list) else "、".join(str(x) for x in item.get("unit")[:3]),
171
+ item.get("sourceElement"),
172
+ item.get("数据源"),
173
+ item.get("发布或实施机构"),
174
+ item.get("发布机关"),
175
+ item.get("来源"),
176
+ vo.get("typeName"),
177
+ vo.get("sourceName"),
178
+ ),
179
+ "date": first_str(item.get("发布日期"), item.get("date"), item.get("发布时间"), item.get("createDate"), vo.get("dateTime"), vo.get("createDate")),
180
+ "url": first_str(item.get("sourceUrl"), item.get("source_url"), item.get("源网址"), item.get("url"), item.get("原文"), vo.get("sourceUrl"), vo.get("url")),
181
+ "policy_url": first_str(item.get("policyUrl"), item.get("policy_url"), item.get("知识专库原文"), vo.get("policyUrl")),
182
+ "excerpt": segment.get("text") or paragraph_text(item),
183
+ "section": first_str(segment.get("title")),
184
+ "kind": first_str(item.get("类型"), item.get("type"), vo.get("typeName"), "材料"),
185
+ "area": first_str(item.get("intentionArea"), item.get("area"), item.get("地域")),
186
+ "reliability": first_str(item.get("createDateReliability"), item.get("reliability"), item.get("时间可靠性")),
187
+ }
188
+ return source
189
+
190
+
191
+ def extract_articles_from_search(payload: Dict[str, Any]) -> List[Dict[str, Any]]:
192
+ content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
193
+ data = content.get("data") if isinstance(content.get("data"), dict) else content.get("data")
194
+ if isinstance(data, dict) and isinstance(data.get("检索文章"), list):
195
+ return [x for x in data["检索文章"] if isinstance(x, dict)]
196
+ return []
197
+
198
+
199
+ def extract_articles_from_deep(payload: Dict[str, Any]) -> List[Dict[str, Any]]:
200
+ events = payload.get("events")
201
+ if isinstance(events, list):
202
+ for event in events:
203
+ if isinstance(event, list) and len(event) == 2:
204
+ name, obj = event
205
+ elif isinstance(event, dict):
206
+ name, obj = event.get("event"), event
207
+ else:
208
+ continue
209
+ if name == "result" and isinstance(obj, dict):
210
+ data = obj.get("data")
211
+ result_list = data.get("list") if isinstance(data, dict) else None
212
+ if isinstance(result_list, list):
213
+ return [x for x in result_list if isinstance(x, dict)]
214
+ data = payload.get("data")
215
+ result_list = data.get("list") if isinstance(data, dict) else None
216
+ if isinstance(result_list, list):
217
+ return [x for x in result_list if isinstance(x, dict)]
218
+ return []
219
+
220
+
221
+ def extract_reference_materials(payload: Dict[str, Any]) -> List[Dict[str, Any]]:
222
+ materials = payload.get("referenceMaterials")
223
+ if isinstance(materials, list):
224
+ return [x for x in materials if isinstance(x, dict)]
225
+ return []
226
+
227
+
228
+ def extract_sources(payload: Dict[str, Any]) -> List[Dict[str, str]]:
229
+ raw_sources: List[Dict[str, Any]] = []
230
+ raw_sources.extend(extract_reference_materials(payload))
231
+ raw_sources.extend(extract_articles_from_search(payload))
232
+ raw_sources.extend(extract_articles_from_deep(payload))
233
+
234
+ sources: List[Dict[str, str]] = []
235
+ seen = set()
236
+ for item in raw_sources:
237
+ segments = content_segments(item)
238
+ candidates = segments or [None]
239
+ for segment in candidates:
240
+ source = source_from_article(item, len(sources) + 1, segment=segment)
241
+ key = (source["id"], source["title"], source["url"], source["excerpt"][:80])
242
+ if key in seen:
243
+ continue
244
+ seen.add(key)
245
+ if not source["id"]:
246
+ source["id"] = str(len(sources) + 1)
247
+ sources.append(source)
248
+ return sources
249
+
250
+
251
+ def extract_answer(payload: Dict[str, Any]) -> str:
252
+ resp = payload.get("resp")
253
+ if isinstance(resp, dict):
254
+ answer = first_str(resp.get("content"), resp.get("answer"), resp.get("text"))
255
+ if answer:
256
+ return normalize_citations(answer)
257
+ answer = first_str(payload.get("answer"), payload.get("contentText"), payload.get("text"))
258
+ if answer:
259
+ return normalize_citations(answer)
260
+ articles = extract_articles_from_search(payload)
261
+ if articles:
262
+ rows = ["统一接口召回了以下重点材料:"]
263
+ for idx, item in enumerate(articles[:8], start=1):
264
+ rows.append(f"[{idx}] {first_str(item.get('文章标题'), item.get('title'), item.get('标题'), '未命名材料')}")
265
+ return "\n".join(rows)
266
+ deep_articles = extract_articles_from_deep(payload)
267
+ if deep_articles:
268
+ rows = ["统一接口召回了以下重点材料:"]
269
+ for idx, item in enumerate(deep_articles[:8], start=1):
270
+ vo = item.get("vo") if isinstance(item.get("vo"), dict) else {}
271
+ rows.append(f"[{idx}] {first_str(vo.get('showTitle'), vo.get('title'), item.get('title'), '未命名材料')}")
272
+ return "\n".join(rows)
273
+ return "接口返回中未识别到正文内容;请查看右侧来源或原始 JSON。"
274
+
275
+
276
+ def extract_trace_url(payload: Dict[str, Any]) -> str:
277
+ return first_str(payload.get("traceUrl"), payload.get("trace_url"), payload.get("traceReportUrl"))
278
+
279
+
280
+ def extract_knowledge_base(payload: Dict[str, Any]) -> str:
281
+ content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
282
+ data = content.get("data") if isinstance(content.get("data"), dict) else {}
283
+ return first_str(
284
+ content.get("knowledgeBase"),
285
+ payload.get("knowledgeBase"),
286
+ data.get("knowledgeBase"),
287
+ payload.get("knowledgeBaseUrl"),
288
+ )
289
+
290
+
291
+ def citation_ids(answer: str) -> List[str]:
292
+ ids: List[str] = []
293
+ for match in re.finditer(r"\[(\d+)\]", answer):
294
+ item = match.group(1)
295
+ if item not in ids:
296
+ ids.append(item)
297
+ return ids
298
+
299
+
300
+ def render_inline_markdown(text: str, citation_repl) -> str:
301
+ body = esc(text)
302
+ body = re.sub(r"`([^`]+)`", r"<code>\1</code>", body)
303
+ body = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", body)
304
+ body = re.sub(r"__(.+?)__", r"<strong>\1</strong>", body)
305
+ body = re.sub(r"(?<!\*)\*([^*\n]+)\*(?!\*)", r"<em>\1</em>", body)
306
+ body = re.sub(r"(?<!_)_([^_\n]+)_(?!_)", r"<em>\1</em>", body)
307
+ body = re.sub(r"\[(\d+)\]", citation_repl, body)
308
+ return body
309
+
310
+
311
+ def is_markdown_table_separator(line: str) -> bool:
312
+ stripped = line.strip().strip("|")
313
+ if not stripped:
314
+ return False
315
+ cells = [cell.strip() for cell in stripped.split("|")]
316
+ return all(re.fullmatch(r":?-{3,}:?", cell or "") for cell in cells)
317
+
318
+
319
+ def split_markdown_table_row(line: str) -> List[str]:
320
+ return [cell.strip() for cell in line.strip().strip("|").split("|")]
321
+
322
+
323
+ def render_markdown_table(lines: List[str], citation_repl) -> str:
324
+ header = split_markdown_table_row(lines[0])
325
+ body_lines = lines[2:] if len(lines) > 1 and is_markdown_table_separator(lines[1]) else lines[1:]
326
+ head_html = "".join(f"<th>{render_inline_markdown(cell, citation_repl)}</th>" for cell in header)
327
+ rows = []
328
+ for line in body_lines:
329
+ cells = split_markdown_table_row(line)
330
+ rows.append("<tr>" + "".join(f"<td>{render_inline_markdown(cell, citation_repl)}</td>" for cell in cells) + "</tr>")
331
+ return f'<div class="answer-table-wrap"><table class="answer-table"><thead><tr>{head_html}</tr></thead><tbody>{"".join(rows)}</tbody></table></div>'
332
+
333
+
334
+ def render_excerpt_html(text: str) -> str:
335
+ value = str(text or "")
336
+ if "<table" not in value.lower():
337
+ return f'<div class="source-excerpt plain">{esc(value)}</div>'
338
+ cleaned = re.sub(r"(?is)<script.*?</script>", "", value)
339
+ cleaned = re.sub(r"(?is)<style.*?</style>", "", cleaned)
340
+ cleaned = re.sub(r"\s+on\w+\s*=\s*(['\"]).*?\1", "", cleaned)
341
+ cleaned = re.sub(r"\s+(href|src)\s*=\s*(['\"]).*?\2", "", cleaned)
342
+ allowed = {"table", "thead", "tbody", "tr", "td", "th", "br"}
343
+
344
+ def tag_repl(match: re.Match[str]) -> str:
345
+ closing, name = match.group(1), match.group(2).lower()
346
+ if name not in allowed:
347
+ return ""
348
+ return f"<{closing}{name}>"
349
+
350
+ cleaned = re.sub(r"<\s*(/?)\s*([a-zA-Z0-9]+)(?:\s+[^>]*)?>", tag_repl, cleaned)
351
+ return f'<div class="source-excerpt rich">{cleaned}</div>'
352
+
353
+
354
+ def render_source_links(url: str, policy_url: str = "") -> str:
355
+ links = []
356
+ if url and url != "接口未返回":
357
+ links.append(f'<a href="{esc(url)}" target="_blank" rel="noopener">查看原文</a>')
358
+ if policy_url:
359
+ links.append(f'<a href="{esc(policy_url)}" target="_blank" rel="noopener">知识专库原文</a>')
360
+ if not links:
361
+ return ""
362
+ return '<div class="source-links">' + "".join(f"<span>{link}</span>" for link in links) + "</div>"
363
+
364
+
365
+ def render_evidence_chips(ids: List[str], sources: List[Dict[str, str]]) -> str:
366
+ source_map = {source["id"]: source for source in sources}
367
+ chips = []
368
+ for cid in ids:
369
+ source = source_map.get(cid)
370
+ if not source:
371
+ continue
372
+ title = source.get("title") or "未命名材料"
373
+ section = source.get("section") or ""
374
+ meta = " | ".join(v for v in [source.get("agency"), source.get("date"), source.get("area"), source.get("kind")] if v)
375
+ excerpt = source.get("excerpt") or "接口返回中未识别到可展示的摘录。"
376
+ url = source.get("url")
377
+ links = render_source_links(url, source.get("policy_url", ""))
378
+ chips.append(
379
+ f"""
380
+ <details class="evidence-detail" data-source="{esc(cid)}">
381
+ <summary><b>[{esc(cid)}]</b>{esc(short(title, 64))}</summary>
382
+ <div class="evidence-panel">
383
+ <div class="evidence-title">{esc(title)}</div>
384
+ <div class="evidence-meta">{esc(meta)}</div>
385
+ {f'<div class="evidence-section">{esc(section)}</div>' if section else ''}
386
+ <p>{esc(excerpt)}</p>
387
+ {links}
388
+ </div>
389
+ </details>
390
+ """
391
+ )
392
+ if not chips:
393
+ return ""
394
+ return f'<div class="evidence-row">{"".join(chips)}</div>'
395
+
396
+
397
+ def render_answer(answer: str, sources: List[Dict[str, str]]) -> str:
398
+ valid_ids = {source["id"] for source in sources}
399
+
400
+ def repl(match: re.Match[str]) -> str:
401
+ cid = match.group(1)
402
+ disabled = "" if cid in valid_ids else " disabled"
403
+ return f'<button class="cite{disabled}" data-source="{esc(cid)}" type="button">[{esc(cid)}]</button>'
404
+
405
+ paragraphs = []
406
+ lines = answer.split("\n")
407
+ idx = 0
408
+ while idx < len(lines):
409
+ raw_block = lines[idx]
410
+ block = raw_block.strip()
411
+ if not block:
412
+ idx += 1
413
+ continue
414
+ if "|" in block and idx + 1 < len(lines) and is_markdown_table_separator(lines[idx + 1]):
415
+ table_lines = [block, lines[idx + 1].strip()]
416
+ idx += 2
417
+ while idx < len(lines) and "|" in lines[idx].strip() and lines[idx].strip():
418
+ table_lines.append(lines[idx].strip())
419
+ idx += 1
420
+ ids = citation_ids("\n".join(table_lines))
421
+ paragraphs.append(f'<div class="answer-block">{render_markdown_table(table_lines, repl)}{render_evidence_chips(ids, sources)}</div>')
422
+ continue
423
+ ids = citation_ids(block)
424
+ evidence = render_evidence_chips(ids, sources)
425
+ heading_match = re.match(r"^(#{1,4})\s+(.+)$", block)
426
+ if heading_match:
427
+ level = min(len(heading_match.group(1)) + 1, 4)
428
+ heading = render_inline_markdown(heading_match.group(2), repl)
429
+ paragraphs.append(f'<h{level} class="answer-heading">{heading}</h{level}>')
430
+ elif block in {"---", "***"}:
431
+ paragraphs.append('<hr class="answer-divider">')
432
+ elif re.match(r"^[-*]\s+", block):
433
+ body = render_inline_markdown(re.sub(r"^[-*]\s+", "", block), repl)
434
+ paragraphs.append(
435
+ f'<div class="answer-item"><span class="bullet">•</span><div><p>{body}</p>{evidence}</div></div>'
436
+ )
437
+ elif re.match(r"^\d+[.)]\s+", block):
438
+ number = re.match(r"^(\d+)[.)]\s+", block).group(1)
439
+ body = render_inline_markdown(re.sub(r"^\d+[.)]\s+", "", block), repl)
440
+ paragraphs.append(
441
+ f'<div class="answer-item numbered"><span class="bullet">{esc(number)}.</span><div><p>{body}</p>{evidence}</div></div>'
442
+ )
443
+ else:
444
+ body = render_inline_markdown(block, repl)
445
+ paragraphs.append(f'<div class="answer-block"><p>{body}</p>{evidence}</div>')
446
+ idx += 1
447
+ return "\n".join(paragraphs)
448
+
449
+
450
+ def render_sources(sources: List[Dict[str, str]]) -> str:
451
+ if not sources:
452
+ return '<p class="empty">接口返回中未识别到可展示的材料。</p>'
453
+ cards = []
454
+ for source in sources:
455
+ url = source.get("url")
456
+ links = render_source_links(url, source.get("policy_url", ""))
457
+ meta = " | ".join(v for v in [source.get("agency"), source.get("date"), source.get("area"), source.get("kind")] if v)
458
+ section = source.get("section") or ""
459
+ cards.append(
460
+ f"""
461
+ <article class="source-card" id="source-{esc(source['id'])}" data-source="{esc(source['id'])}">
462
+ <div class="source-top">
463
+ <span class="source-index">[{esc(source['id'])}]</span>
464
+ <h3>{esc(source.get("title"))}</h3>
465
+ </div>
466
+ <p class="meta">{esc(meta)}</p>
467
+ {f'<p class="section">{esc(section)}</p>' if section else ''}
468
+ {render_excerpt_html(source.get("excerpt") or "接口返回中未识别到可展示的摘录。")}
469
+ {links}
470
+ </article>
471
+ """
472
+ )
473
+ return "\n".join(cards)
474
+
475
+
476
+ def align_sources_to_answer(answer: str, sources: List[Dict[str, str]]) -> List[Dict[str, str]]:
477
+ cited = citation_ids(answer)
478
+ if not cited or not sources:
479
+ return sources
480
+ existing = {source["id"] for source in sources}
481
+ if existing.intersection(cited):
482
+ return sources
483
+ aligned = [dict(source) for source in sources]
484
+ for idx, citation in enumerate(cited):
485
+ if idx >= len(aligned):
486
+ break
487
+ aligned[idx]["id"] = citation
488
+ return aligned
489
+
490
+
491
+ def extract_question(payload: Dict[str, Any]) -> str:
492
+ content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
493
+ data = content.get("data") if isinstance(content.get("data"), dict) else {}
494
+ return first_str(
495
+ payload.get("question"),
496
+ payload.get("input"),
497
+ payload.get("query"),
498
+ data.get("用户问题"),
499
+ content.get("query"),
500
+ content.get("question"),
501
+ )
502
+
503
+
504
+ def render_entry_chip(kb_url: str, source_count: int) -> str:
505
+ if not kb_url:
506
+ return ""
507
+ count_text = f"{source_count}条来源" if source_count else "来源材料"
508
+ return (
509
+ f'<a class="kb-chip" href="{esc(kb_url)}" target="_blank" rel="noopener">'
510
+ f'<span class="kb-label">知识专库</span>'
511
+ f'<span class="kb-count">{esc(count_text)}</span>'
512
+ f'<span class="kb-arrow">查看</span>'
513
+ f'</a>'
514
+ )
515
+
516
+
517
+ def safe_output_filename(question: str, timestamp: datetime, fallback: str = "dknowc_consulting_trace") -> str:
518
+ raw = question.strip() or fallback
519
+ normalized = re.sub(r"\s+", "_", raw)
520
+ normalized = re.sub(r"[\\/:*?\"<>|#%&{}$!@`+=;',。、?!:;“”‘’()()【】《》\[\]]+", "", normalized)
521
+ normalized = normalized.strip("._-")
522
+ if not normalized:
523
+ normalized = fallback
524
+ suffix = timestamp.strftime("%Y%m%d_%H%M")
525
+ stem = normalized[:32].strip("._-") or fallback
526
+ return f"{stem}_{suffix}.html"
527
+
528
+
529
+ def render_html(payload: Dict[str, Any], title: str, answer_override: str = "", question_override: str = "", generated_at: Optional[datetime] = None) -> str:
530
+ payload = unwrap(payload)
531
+ answer = normalize_citations(answer_override) if answer_override.strip() else extract_answer(payload)
532
+ sources = align_sources_to_answer(answer, extract_sources(payload))
533
+ used = citation_ids(answer)
534
+ kb_url = extract_knowledge_base(payload)
535
+ question = question_override.strip() or extract_question(payload)
536
+ generated_at = generated_at or datetime.now()
537
+ generated = generated_at.strftime("%Y-%m-%d %H:%M")
538
+ kb_link = f'<a href="{esc(kb_url)}" target="_blank" rel="noopener">知识专库</a>' if kb_url else ""
539
+ links = kb_link
540
+ tools_html = f'<div class="tools">{links}</div>' if links else ""
541
+ question_html = f'<div class="question-bubble">{esc(question)}</div>' if question else ""
542
+ citation_warning = ""
543
+ if sources and not used:
544
+ citation_warning = (
545
+ '<div class="warning-box">'
546
+ '<b>生成检查提示:</b>本轮最终答案没有包含来源角标,因此无法在答案段落下做“结论-来源”一一对应。'
547
+ '请重新生成最终答案,并在关键结论后标注接口材料编号,例如 [1]、[2]。'
548
+ '</div>'
549
+ )
550
+ note_text = "AI综合所有相关权威材料后,参考性解读如下,建议点击角标查看所依据的材料原文。"
551
+ compact_answer_start = re.sub(r"\s+", "", answer.lstrip()[:120])
552
+ compact_note_start = re.sub(r"\s+", "", note_text[:36])
553
+ note_html = "" if compact_answer_start.startswith(compact_note_start) else f'<p class="ai-note">{esc(note_text)}</p>'
554
+ product_links_html = (
555
+ '<nav class="product-links" aria-label="产品链接">'
556
+ '<a href="https://yun.dknowc.cn/wlcb/dknowc-chat/#/" target="_blank" rel="noopener">深知晓内测</a>'
557
+ '<a href="https://www.dknowc.cn/" target="_blank" rel="noopener">深知可信智能官网</a>'
558
+ '</nav>'
559
+ )
560
+
561
+ return f"""<!doctype html>
562
+ <html lang="zh-CN">
563
+ <head>
564
+ <meta charset="utf-8">
565
+ <meta name="viewport" content="width=device-width, initial-scale=1">
566
+ <title>{esc(title)}</title>
567
+ <style>
568
+ :root {{
569
+ --purple: #6b18c9;
570
+ --purple-soft: #f4ebff;
571
+ --ink: #2f3033;
572
+ --muted: #6b7280;
573
+ --line: #e5e7eb;
574
+ --panel: #ffffff;
575
+ --page: #ffffff;
576
+ --soft: #f7f7f8;
577
+ }}
578
+ * {{ box-sizing: border-box; }}
579
+ body {{
580
+ margin: 0;
581
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
582
+ color: var(--ink);
583
+ background: var(--page);
584
+ }}
585
+ header {{
586
+ padding: 12px 28px;
587
+ background: #fff;
588
+ border-bottom: 1px solid var(--line);
589
+ position: sticky;
590
+ top: 0;
591
+ z-index: 2;
592
+ text-align: center;
593
+ }}
594
+ h1 {{ margin: 0 0 3px; font-size: 16px; letter-spacing: 0; font-weight: 700; }}
595
+ header p {{ margin: 0; color: #9ca3af; font-size: 12px; }}
596
+ .product-links {{
597
+ display: flex;
598
+ justify-content: center;
599
+ gap: 14px;
600
+ margin-top: 8px;
601
+ font-size: 12px;
602
+ }}
603
+ .product-links a {{
604
+ color: var(--purple);
605
+ text-decoration: none;
606
+ font-weight: 600;
607
+ }}
608
+ .product-links a:hover {{ text-decoration: underline; }}
609
+ .layout {{
610
+ display: grid;
611
+ grid-template-columns: minmax(0, 700px) minmax(390px, 460px);
612
+ gap: 30px;
613
+ justify-content: center;
614
+ max-width: 1220px;
615
+ margin: 0 auto;
616
+ padding: 30px 18px 40px;
617
+ }}
618
+ .conversation {{
619
+ min-width: 0;
620
+ }}
621
+ .question-bubble {{
622
+ max-width: 560px;
623
+ margin: 0 0 26px auto;
624
+ padding: 12px 16px;
625
+ border-radius: 9px;
626
+ background: var(--purple);
627
+ color: #fff;
628
+ line-height: 1.55;
629
+ font-weight: 700;
630
+ font-size: 14px;
631
+ }}
632
+ .answer {{
633
+ background: transparent;
634
+ padding: 0;
635
+ }}
636
+ .kb-chip {{
637
+ display: inline-flex;
638
+ align-items: center;
639
+ gap: 10px;
640
+ max-width: 100%;
641
+ margin: 0 0 16px;
642
+ padding: 7px 10px;
643
+ border: 1px solid var(--line);
644
+ border-radius: 7px;
645
+ color: #4b5563;
646
+ background: #fafafa;
647
+ text-decoration: none;
648
+ box-shadow: none;
649
+ font-size: 12px;
650
+ }}
651
+ .kb-chip:hover {{ border-color: #d1d5db; background: #f7f7f8; }}
652
+ .kb-label {{ font-weight: 700; color: #374151; }}
653
+ .kb-count {{
654
+ padding-left: 10px;
655
+ border-left: 1px solid var(--line);
656
+ color: #6b7280;
657
+ }}
658
+ .kb-arrow {{
659
+ color: var(--purple);
660
+ font-weight: 700;
661
+ }}
662
+ .ai-note {{ margin: 0 0 10px; color: #52525b; line-height: 1.75; font-size: 14px; }}
663
+ .answer-body {{
664
+ padding: 0;
665
+ background: transparent;
666
+ }}
667
+ .answer-block, .answer-item {{ margin: 0 0 12px; }}
668
+ .answer-item {{ display: grid; grid-template-columns: 20px minmax(0, 1fr); gap: 8px; }}
669
+ .answer-item .bullet {{ padding-top: 2px; color: #111827; font-size: 16px; line-height: 1.75; }}
670
+ .answer-item.numbered {{ grid-template-columns: 28px minmax(0, 1fr); }}
671
+ .answer p {{ margin: 0; font-size: 14px; line-height: 1.85; }}
672
+ .answer strong {{ font-weight: 700; color: #202124; }}
673
+ .answer em {{ font-style: normal; color: #4b5563; }}
674
+ .answer code {{
675
+ padding: 1px 5px;
676
+ border-radius: 4px;
677
+ background: #f3f4f6;
678
+ color: #374151;
679
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
680
+ font-size: 12px;
681
+ }}
682
+ .answer-table-wrap {{ max-width: 100%; overflow-x: auto; margin: 6px 0 8px; }}
683
+ .answer-table {{
684
+ width: 100%;
685
+ border-collapse: collapse;
686
+ border: 1px solid var(--line);
687
+ border-radius: 8px;
688
+ overflow: hidden;
689
+ font-size: 13px;
690
+ }}
691
+ .answer-table th, .answer-table td {{
692
+ padding: 9px 10px;
693
+ border: 1px solid var(--line);
694
+ text-align: left;
695
+ vertical-align: top;
696
+ line-height: 1.65;
697
+ }}
698
+ .answer-table th {{ background: #f8fafc; font-weight: 700; color: #374151; }}
699
+ .answer-heading {{ margin: 20px 0 9px; color: #111827; line-height: 1.45; letter-spacing: 0; }}
700
+ h2.answer-heading {{ font-size: 18px; }}
701
+ h3.answer-heading {{ font-size: 16px; }}
702
+ h4.answer-heading {{ font-size: 15px; }}
703
+ .answer-divider {{ border: 0; border-top: 1px solid var(--line); margin: 22px 0; }}
704
+ .warning-box {{
705
+ margin: 0 0 16px;
706
+ padding: 12px 14px;
707
+ border: 1px solid #f59e0b;
708
+ border-radius: 8px;
709
+ background: #fffbeb;
710
+ color: #92400e;
711
+ line-height: 1.7;
712
+ font-size: 14px;
713
+ }}
714
+ .cite {{
715
+ margin: 0 2px;
716
+ padding: 0 5px;
717
+ border: 0;
718
+ border-radius: 4px;
719
+ color: var(--purple);
720
+ background: var(--purple-soft);
721
+ font-weight: 700;
722
+ cursor: pointer;
723
+ vertical-align: super;
724
+ font-size: 10px;
725
+ line-height: 1.4;
726
+ }}
727
+ .cite.disabled {{ color: #9ca3af; background: #f3f4f6; cursor: default; }}
728
+ .evidence-row {{
729
+ display: flex;
730
+ flex-wrap: wrap;
731
+ gap: 6px;
732
+ margin: 5px 0 0;
733
+ }}
734
+ .evidence-detail {{
735
+ max-width: 100%;
736
+ }}
737
+ .evidence-detail summary {{
738
+ display: inline-flex;
739
+ align-items: center;
740
+ max-width: 100%;
741
+ border-radius: 999px;
742
+ padding: 4px 9px;
743
+ color: #6b7280;
744
+ background: #f3f4f6;
745
+ cursor: pointer;
746
+ overflow: hidden;
747
+ text-overflow: ellipsis;
748
+ white-space: nowrap;
749
+ list-style: none;
750
+ font-size: 12px;
751
+ }}
752
+ .evidence-detail summary::-webkit-details-marker {{ display: none; }}
753
+ .evidence-detail summary::after {{
754
+ content: "展开";
755
+ margin-left: 7px;
756
+ color: #9ca3af;
757
+ font-size: 11px;
758
+ }}
759
+ .evidence-detail[open] summary::after {{ content: "收起"; }}
760
+ .evidence-detail summary b {{ color: var(--purple); margin-right: 5px; }}
761
+ .evidence-panel {{
762
+ margin: 7px 0 4px;
763
+ padding: 12px 14px;
764
+ border: 1px solid var(--line);
765
+ border-radius: 8px;
766
+ background: #fff;
767
+ box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
768
+ }}
769
+ .evidence-title {{ font-weight: 700; font-size: 14px; margin-bottom: 5px; color: #111827; }}
770
+ .evidence-meta {{ color: var(--muted); font-size: 12px; margin-bottom: 6px; }}
771
+ .evidence-section {{ color: var(--purple); font-size: 12px; margin-bottom: 6px; font-weight: 700; }}
772
+ .evidence-panel p {{ margin: 0 0 8px; color: #374151; font-size: 13px; line-height: 1.7; }}
773
+ .evidence-panel a {{ color: var(--purple); font-weight: 700; text-decoration: none; }}
774
+ .source-links {{
775
+ display: flex;
776
+ flex-wrap: wrap;
777
+ gap: 8px;
778
+ margin-top: 8px;
779
+ }}
780
+ .source-links span {{
781
+ display: inline-flex;
782
+ }}
783
+ .source-links a {{
784
+ display: inline-flex;
785
+ align-items: center;
786
+ min-height: 24px;
787
+ padding: 3px 8px;
788
+ border-radius: 6px;
789
+ background: var(--purple-soft);
790
+ color: var(--purple);
791
+ font-weight: 700;
792
+ text-decoration: none;
793
+ font-size: 12px;
794
+ }}
795
+ .tools {{
796
+ display: flex;
797
+ flex-wrap: wrap;
798
+ gap: 8px;
799
+ margin-top: 20px;
800
+ padding-top: 16px;
801
+ border-top: 1px solid var(--line);
802
+ }}
803
+ .tools a {{
804
+ color: var(--purple);
805
+ background: var(--purple-soft);
806
+ border-radius: 999px;
807
+ padding: 7px 12px;
808
+ text-decoration: none;
809
+ font-weight: 600;
810
+ }}
811
+ .sources {{
812
+ align-self: start;
813
+ position: sticky;
814
+ top: 70px;
815
+ max-height: calc(100vh - 92px);
816
+ overflow: auto;
817
+ background: #fff;
818
+ border-left: 1px solid var(--line);
819
+ padding: 16px 0 16px 24px;
820
+ }}
821
+ .sources h2 {{ margin: 0 0 12px; font-size: 15px; }}
822
+ .searchbox {{
823
+ width: 100%;
824
+ margin: 0 0 14px;
825
+ padding: 9px 12px;
826
+ border: 1px solid var(--line);
827
+ border-radius: 8px;
828
+ color: #6b7280;
829
+ background: #fff;
830
+ }}
831
+ .source-card {{
832
+ padding: 14px 0 15px;
833
+ border: 0;
834
+ border-bottom: 1px solid #f1f1f2;
835
+ border-radius: 0;
836
+ margin-bottom: 0;
837
+ background: #fff;
838
+ }}
839
+ .source-card.active {{
840
+ margin-left: -10px;
841
+ padding-left: 10px;
842
+ border-left: 3px solid var(--purple);
843
+ background: #fbf8ff;
844
+ box-shadow: none;
845
+ }}
846
+ .source-top {{
847
+ display: grid;
848
+ grid-template-columns: auto minmax(0, 1fr);
849
+ gap: 7px;
850
+ align-items: start;
851
+ margin-bottom: 6px;
852
+ }}
853
+ .source-index {{
854
+ color: var(--purple);
855
+ background: var(--purple-soft);
856
+ border-radius: 5px;
857
+ padding: 1px 5px;
858
+ font-weight: 800;
859
+ font-size: 12px;
860
+ line-height: 1.5;
861
+ }}
862
+ .source-card h3 {{ margin: 0; font-size: 13px; line-height: 1.55; letter-spacing: 0; }}
863
+ .source-card p {{ margin: 0 0 7px; color: #374151; line-height: 1.72; font-size: 12px; }}
864
+ .source-card .meta {{ color: var(--muted); font-size: 12px; line-height: 1.55; }}
865
+ .source-card .section {{ color: var(--purple); font-size: 12px; font-weight: 700; }}
866
+ .source-card a {{ color: var(--purple); font-weight: 700; text-decoration: none; font-size: 12px; }}
867
+ .source-card .source-excerpt {{
868
+ margin: 8px 0 8px;
869
+ padding: 9px 10px;
870
+ border-radius: 7px;
871
+ background: #f8fafc;
872
+ color: #374151;
873
+ font-size: 12px;
874
+ line-height: 1.75;
875
+ }}
876
+ .source-excerpt.rich {{
877
+ overflow-x: auto;
878
+ max-width: 100%;
879
+ }}
880
+ .source-excerpt.rich table {{
881
+ width: max-content;
882
+ min-width: 100%;
883
+ border-collapse: collapse;
884
+ background: #fff;
885
+ font-size: 12px;
886
+ line-height: 1.55;
887
+ }}
888
+ .source-excerpt.rich td, .source-excerpt.rich th {{
889
+ min-width: 92px;
890
+ max-width: 220px;
891
+ padding: 7px 8px;
892
+ border: 1px solid #e5e7eb;
893
+ vertical-align: top;
894
+ word-break: break-word;
895
+ }}
896
+ .source-excerpt.rich thead td, .source-excerpt.rich th {{
897
+ background: #f3f4f6;
898
+ color: #374151;
899
+ font-weight: 700;
900
+ }}
901
+ .empty {{ color: var(--muted); }}
902
+ @media (max-width: 900px) {{
903
+ .layout {{ grid-template-columns: 1fr; padding: 14px; }}
904
+ .sources {{ position: static; max-height: none; }}
905
+ .question-bubble {{ margin-left: 0; }}
906
+ }}
907
+ </style>
908
+ </head>
909
+ <body>
910
+ <header>
911
+ <h1>{esc(title)}</h1>
912
+ <p>内容为 AI 生成,仅供参考|生成时间:{esc(generated)}</p>
913
+ {product_links_html}
914
+ </header>
915
+ <main class="layout">
916
+ <section class="conversation" aria-label="回答正文">
917
+ {question_html}
918
+ <div class="answer">
919
+ {render_entry_chip(kb_url, len(sources))}
920
+ {note_html}
921
+ {citation_warning}
922
+ <div class="answer-body">{render_answer(answer, sources)}</div>
923
+ {tools_html}
924
+ </div>
925
+ </section>
926
+ <aside class="sources" aria-label="可信来源">
927
+ <h2>可信来源</h2>
928
+ <input class="searchbox" type="search" placeholder="搜索来源标题或摘录">
929
+ {render_sources(sources)}
930
+ </aside>
931
+ </main>
932
+ <script>
933
+ const cards = Array.from(document.querySelectorAll(".source-card"));
934
+ function activate(id) {{
935
+ cards.forEach(card => card.classList.toggle("active", card.dataset.source === id));
936
+ const target = document.querySelector(`#source-${{CSS.escape(id)}}`);
937
+ if (target) target.scrollIntoView({{ block: "nearest", behavior: "smooth" }});
938
+ }}
939
+ document.querySelectorAll(".cite").forEach(button => {{
940
+ if (button.classList.contains("disabled")) return;
941
+ button.addEventListener("click", () => activate(button.dataset.source));
942
+ }});
943
+ document.querySelectorAll(".evidence-detail").forEach(detail => {{
944
+ detail.addEventListener("toggle", () => {{
945
+ if (!detail.open) return;
946
+ cards.forEach(card => card.classList.toggle("active", card.dataset.source === detail.dataset.source));
947
+ }});
948
+ }});
949
+ const searchbox = document.querySelector(".searchbox");
950
+ if (searchbox) {{
951
+ searchbox.addEventListener("input", () => {{
952
+ const value = searchbox.value.trim().toLowerCase();
953
+ cards.forEach(card => {{
954
+ card.style.display = !value || card.innerText.toLowerCase().includes(value) ? "" : "none";
955
+ }});
956
+ }});
957
+ }}
958
+ </script>
959
+ </body>
960
+ </html>
961
+ """
962
+
963
+
964
+ def main() -> None:
965
+ parser = argparse.ArgumentParser(description="生成深知可信咨询可交互可信溯源 HTML")
966
+ parser.add_argument("input_json", help="gov_chat.py 的 --json-only 输出 JSON(位于 official-docs/search-results/)")
967
+ parser.add_argument("--output", help="输出 HTML 路径;不传时根据问题自动生成短文件名到 official-docs/output/")
968
+ parser.add_argument("--title", default="深知可信咨询可信溯源", help="页面标题")
969
+ parser.add_argument("--answer-file", help="最终回答正文文件。复杂任务综合后必须传入,确保 HTML 展示的答案与聊天答案一致。")
970
+ parser.add_argument("--question", default="", help="用户问题,用于生成顶部对话气泡。")
971
+ args = parser.parse_args()
972
+
973
+ input_path = _resolve_input(args.input_json)
974
+ payload = load_json(input_path)
975
+ answer_override = ""
976
+ if args.answer_file:
977
+ answer_override = _resolve_input(args.answer_file).read_text(encoding="utf-8")
978
+ question = args.question.strip() or extract_question(unwrap(payload))
979
+ generated_at = datetime.now()
980
+ if args.output:
981
+ output = _resolve_output(args.output)
982
+ else:
983
+ output = _resolve_output(safe_output_filename(question, generated_at))
984
+ output.parent.mkdir(parents=True, exist_ok=True)
985
+ output.write_text(render_html(payload, args.title, answer_override=answer_override, question_override=args.question, generated_at=generated_at), encoding="utf-8")
986
+ print(f"已生成:{output}")
987
+
988
+
989
+ if __name__ == "__main__":
990
+ main()