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