@arcticdata/dsh-datarc-skills 0.0.0-stage → 26.39.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 +20 -2
- package/cordis.patch.yml +4 -0
- package/icon.svg +4 -0
- package/index.js +35 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +37 -4
- package/skills/datarc-access-permissions/SKILL.md +30 -0
- package/skills/datarc-access-permissions/references/api.md +31 -0
- package/skills/datarc-access-permissions/references/write-order.md +16 -0
- package/skills/datarc-analysis-report/SKILL.md +125 -0
- package/skills/datarc-analysis-report/agents/openai.yaml +6 -0
- package/skills/datarc-analysis-report/references/analyst-frameworks.md +215 -0
- package/skills/datarc-analysis-report/references/api-contracts.md +478 -0
- package/skills/datarc-analysis-report/references/direct-card-fallback-design.md +66 -0
- package/skills/datarc-analysis-report/references/human-in-the-loop.md +142 -0
- package/skills/datarc-analysis-report/references/loop-personalization-policy.md +138 -0
- package/skills/datarc-analysis-report/references/manifest-example.json +779 -0
- package/skills/datarc-analysis-report/references/narrative-schema.md +160 -0
- package/skills/datarc-analysis-report/references/question-syntax.md +151 -0
- package/skills/datarc-analysis-report/scripts/run_analysis_report.py +2225 -0
- package/skills/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -0
- package/skills/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -0
- package/skills/datarc-data-search/SKILL.md +243 -0
- package/skills/datarc-data-search/scripts/calculate.py +116 -0
- package/skills/datarc-data-search/scripts/data-search.mjs +628 -0
- package/skills/datarc-data-search/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-data-search/scripts/search-result.mjs +211 -0
- package/skills/datarc-dataseek-batch-evaluation/SKILL.md +59 -0
- package/skills/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -0
- package/skills/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -0
- package/skills/datarc-dataseek-batch-evaluation/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -0
- package/skills/datarc-dataseek-search/SKILL.md +96 -0
- package/skills/datarc-dataseek-search/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -0
- package/skills/datarc-dataseek-semantic-debugging/SKILL.md +44 -0
- package/skills/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -0
- package/skills/datarc-dataseek-semantic-debugging/evals/evals.json +165 -0
- package/skills/datarc-dataseek-semantic-debugging/references/dataset.md +77 -0
- package/skills/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -0
- package/skills/datarc-dataseek-semantic-debugging/references/interventions.md +64 -0
- package/skills/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -0
- package/skills/datarc-dataseek-semantic-debugging/references/rollback.md +11 -0
- package/skills/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -0
- package/skills/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -0
- package/skills/datarc-dataseek-testset-generation/SKILL.md +47 -0
- package/skills/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -0
- package/skills/datarc-datasource/SKILL.md +97 -0
- package/skills/datarc-oauth/SKILL.md +47 -0
- package/skills/datarc-oauth/scripts/auth.mjs +130 -0
- package/skills/datarc-oauth/scripts/credentials.mjs +237 -0
- package/skills/datarc-report-add-card/SKILL.md +90 -0
- package/skills/datarc-report-add-card/agents/openai.yaml +4 -0
- package/skills/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-report-add-card/scripts/report-card.mjs +439 -0
- package/skills/datarc-semantic-alias/SKILL.md +20 -0
- package/skills/datarc-semantic-alias/scripts/alias-plan.mjs +422 -0
- package/skills/datarc-semantic-alias/scripts/alias.mjs +11 -0
- package/skills/datarc-semantic-calibration/SKILL.md +20 -0
- package/skills/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -0
- package/skills/datarc-semantic-calibration/scripts/calibration.mjs +11 -0
- package/skills/datarc-semantic-core/SKILL.md +12 -0
- package/skills/datarc-semantic-core/scripts/artifact-journal.mjs +830 -0
- package/skills/datarc-semantic-core/scripts/canonical.mjs +48 -0
- package/skills/datarc-semantic-core/scripts/case-model.mjs +608 -0
- package/skills/datarc-semantic-core/scripts/cli.mjs +180 -0
- package/skills/datarc-semantic-core/scripts/datarc-client.mjs +180 -0
- package/skills/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -0
- package/skills/datarc-semantic-core/scripts/interventions.mjs +693 -0
- package/skills/datarc-semantic-core/scripts/live-resolution.mjs +305 -0
- package/skills/datarc-semantic-core/scripts/model-scope.mjs +49 -0
- package/skills/datarc-semantic-core/scripts/reproduction.mjs +330 -0
- package/skills/datarc-semantic-core/scripts/semantic-cli.mjs +740 -0
- package/skills/datarc-semantic-core/scripts/shared.mjs +312 -0
- package/skills/datarc-semantic-core/scripts/verification.mjs +1014 -0
- package/skills/datarc-semantic-dataset/SKILL.md +20 -0
- package/skills/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -0
- package/skills/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -0
- package/skills/datarc-semantic-dataset/scripts/dataset.mjs +11 -0
- package/skills/datarc-semantic-knowledge/SKILL.md +38 -0
- package/skills/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -0
- package/skills/datarc-semantic-knowledge/references/knowledge-generation.json +16 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -0
- package/skills/datarc-semantic-prompt/SKILL.md +20 -0
- package/skills/datarc-semantic-prompt/scripts/prompt-plan.mjs +447 -0
- package/skills/datarc-semantic-prompt/scripts/prompt.mjs +15 -0
- package/skills/datarc-semantic-synonym/SKILL.md +20 -0
- package/skills/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -0
- package/skills/datarc-semantic-synonym/scripts/synonym.mjs +11 -0
- package/skills/datarc-viz-analysis-report/SKILL.md +108 -0
- package/skills/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -0
- package/skills/datarc-viz-analysis-report/assets/echarts.min.js +45 -0
- package/skills/datarc-viz-analysis-report/references/api-contracts.md +163 -0
- package/skills/datarc-viz-analysis-report/references/derivation-log.md +157 -0
- package/skills/datarc-viz-analysis-report/references/evidence-framework.md +76 -0
- package/skills/datarc-viz-analysis-report/references/html-template.md +92 -0
- package/skills/datarc-viz-analysis-report/references/provenance-format.md +56 -0
- package/skills/datarc-viz-analysis-report/references/question-syntax.md +151 -0
- package/skills/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -0
- package/skills/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -0
- package/skills/datarc-workspace-configuration/SKILL.md +59 -0
- package/skills/datarc-workspace-configuration/references/artifacts.md +75 -0
- package/skills/datarc-workspace-configuration/references/verification.md +20 -0
- package/skills/datarc-workspace-configuration/scripts/configuration.mjs +662 -0
- package/skills/datarc-workspace-context/SKILL.md +43 -0
- package/skills/datarc-workspace-context/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-context/scripts/datarc-client.mjs +31 -0
- package/skills/datarc-workspace-context/scripts/query-display.mjs +114 -0
- package/skills/datarc-workspace-context/scripts/workspace-context.mjs +58 -0
- package/skills/datarc-workspace-custom-tables/SKILL.md +89 -0
- package/skills/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -0
- package/skills/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -0
- package/skills/datarc-workspace-keywords/SKILL.md +197 -0
- package/skills/datarc-workspace-keywords/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-keywords/references/api-fields.md +79 -0
- package/skills/datarc-workspace-keywords/references/derived-measures.md +177 -0
- package/skills/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -0
- package/skills/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -0
- package/skills/datarc-workspace-membership/SKILL.md +29 -0
- package/skills/datarc-workspace-membership/references/api.md +19 -0
- package/skills/datarc-workspace-modeling/SKILL.md +209 -0
- package/skills/datarc-workspace-modeling/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-modeling/references/join-preview.md +38 -0
- package/skills/datarc-workspace-modeling/references/model-plan.md +300 -0
- package/skills/datarc-workspace-modeling/references/model-tags.md +95 -0
- package/skills/datarc-workspace-modeling/references/modeling-contract.json +29 -0
- package/skills/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -0
- package/skills/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -0
- package/skills/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -0
- package/skills/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -0
- package/skills-index.json +194 -0
|
@@ -0,0 +1,1708 @@
|
|
|
1
|
+
"""Render a self-contained single-file HTML visualization report.
|
|
2
|
+
|
|
3
|
+
Reads the traceability ledger written during datarc-viz-analysis-report
|
|
4
|
+
(plan meta, fetched cards, derivation log, chart specs), verifies that every
|
|
5
|
+
plotted datum comes verbatim from an API payload or from a fully logged
|
|
6
|
+
derivation, and emits one offline HTML file with inline Apache ECharts.
|
|
7
|
+
|
|
8
|
+
Pure standard library; performs no network access.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import json
|
|
15
|
+
import math
|
|
16
|
+
import sys
|
|
17
|
+
from html import escape
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
ECHARTS_ASSET_PATH = Path(__file__).resolve().parent.parent / "assets" / "echarts.min.js"
|
|
22
|
+
SUPPORTED_CHART_TYPES = ("bar", "line", "pie", "scatter", "table")
|
|
23
|
+
SUPPORTED_LANGUAGES = ("zh-CN", "en-US")
|
|
24
|
+
BUILTIN_FORMULAS = {
|
|
25
|
+
"growth_rate": "({0}[t] − {0}[t−1]) / {0}[t−1]",
|
|
26
|
+
"share": "{0} / Σ({0})",
|
|
27
|
+
"ratio": "{0} / {1}",
|
|
28
|
+
"difference": "{0} − {1}",
|
|
29
|
+
}
|
|
30
|
+
SUPPORTED_METHOD_TYPES = (*BUILTIN_FORMULAS, "formula", "python")
|
|
31
|
+
SUPPORTED_VALUE_FORMATS = ("number", "percent")
|
|
32
|
+
SUPPORTED_SERIES_TYPES = ("bar", "line")
|
|
33
|
+
SUPPORTED_Y_AXES = ("left", "right")
|
|
34
|
+
SUPPORTED_EVIDENCE_ROLES = ("primary", "comparator", "diagnostic", "validation")
|
|
35
|
+
SUPPORTED_CLAIM_KINDS = ("fact", "inference", "recommendation", "limitation")
|
|
36
|
+
SUPPORTED_CONFIDENCES = ("high", "medium", "low")
|
|
37
|
+
MIN_CHAPTER_CARDS = 2
|
|
38
|
+
MAX_INPUT_BYTES = 50 * 1024 * 1024
|
|
39
|
+
MAX_PIE_CATEGORIES = 6
|
|
40
|
+
DATAZOOM_CATEGORY_THRESHOLD = 12
|
|
41
|
+
DUAL_AXIS_MAGNITUDE_RATIO = 100
|
|
42
|
+
DERIVATION_KEYS = (
|
|
43
|
+
"derivation_id",
|
|
44
|
+
"source_card_ids",
|
|
45
|
+
"input_fields",
|
|
46
|
+
"output_column",
|
|
47
|
+
"method",
|
|
48
|
+
"key_field",
|
|
49
|
+
"keys",
|
|
50
|
+
"key_card_id",
|
|
51
|
+
)
|
|
52
|
+
_RERUN_HINT = "修正该条目后重新执行 python3 render_viz_report.py <输入JSON> -o <输出HTML> 即可重新组装"
|
|
53
|
+
|
|
54
|
+
# 报告固定 UI 文案;output_language 决定整套取值,正文不再混排两种语言。
|
|
55
|
+
_UI_STRINGS: dict[str, dict[str, str]] = {
|
|
56
|
+
"zh-CN": {
|
|
57
|
+
"summary_title": "总结与建议",
|
|
58
|
+
"recommendations": "建议",
|
|
59
|
+
"appendix": "附录",
|
|
60
|
+
"appendix_a": "附录A 全量来源明细",
|
|
61
|
+
"appendix_b": "附录B 计算方式披露",
|
|
62
|
+
"appendix_c": "附录C 被排除路径留痕",
|
|
63
|
+
"download_csv": "下载 CSV",
|
|
64
|
+
"workspace_label": "工作区:",
|
|
65
|
+
"generated_at_label": " · 生成时间:",
|
|
66
|
+
"footer": "本报告由 datarc-viz-analysis-report 渲染脚本生成;交互图表基于内联 Apache ECharts 5.6.0(Apache License 2.0);正文与图表均不含外部链接。",
|
|
67
|
+
"load_fail": "图表库未能加载:本报告依赖内联脚本,请确认文件完整后重新打开",
|
|
68
|
+
"source_label": "数据来源:",
|
|
69
|
+
"query_label": "查询:",
|
|
70
|
+
"fetched_at_label": " · 检索时间:",
|
|
71
|
+
"rows_label": " · 数据 {n} 行",
|
|
72
|
+
"derived_note": ";含派生数据({cols}),计算方式见附录B",
|
|
73
|
+
"missing": "缺失",
|
|
74
|
+
"card_word": "卡片",
|
|
75
|
+
"outputs_label": "产出值:",
|
|
76
|
+
"recomputed": "已按来源行复算",
|
|
77
|
+
"custom_calculation": "自定义计算,未自动复算",
|
|
78
|
+
"deriv_based": "基于卡 {sources} 的「{fields}」:",
|
|
79
|
+
"deriv_id_suffix": "(id={did})",
|
|
80
|
+
"excluded_intro": "问题“{q}”——{reason}",
|
|
81
|
+
"toc_title": "目录",
|
|
82
|
+
"appendix_d": "附录D 执行元数据",
|
|
83
|
+
"purpose_label": "本章要回答:",
|
|
84
|
+
"role_primary": "主证据",
|
|
85
|
+
"role_comparator": "对比基准",
|
|
86
|
+
"role_diagnostic": "拆解诊断",
|
|
87
|
+
"role_validation": "交叉验证",
|
|
88
|
+
},
|
|
89
|
+
"en-US": {
|
|
90
|
+
"summary_title": "Summary & Recommendations",
|
|
91
|
+
"recommendations": "Recommendations",
|
|
92
|
+
"appendix": "Appendix",
|
|
93
|
+
"appendix_a": "Appendix A Source Data",
|
|
94
|
+
"appendix_b": "Appendix B Derivation Log",
|
|
95
|
+
"appendix_c": "Appendix C Excluded Paths",
|
|
96
|
+
"download_csv": "Download CSV",
|
|
97
|
+
"workspace_label": "Workspace: ",
|
|
98
|
+
"generated_at_label": " · Generated at: ",
|
|
99
|
+
"footer": "Generated by the datarc-viz-analysis-report renderer; interactive charts are powered by inline Apache ECharts 5.6.0 (Apache License 2.0); no external links in this document.",
|
|
100
|
+
"load_fail": "Chart library failed to load: this report relies on the inline script. Make sure the file is complete, then reopen it.",
|
|
101
|
+
"source_label": "Data source: ",
|
|
102
|
+
"query_label": "Query: ",
|
|
103
|
+
"fetched_at_label": " · Fetched at: ",
|
|
104
|
+
"rows_label": " · {n} rows",
|
|
105
|
+
"derived_note": "; includes derived data ({cols}), see Appendix B",
|
|
106
|
+
"missing": "N/A",
|
|
107
|
+
"card_word": "Card",
|
|
108
|
+
"outputs_label": "Outputs: ",
|
|
109
|
+
"recomputed": "Recomputed from source rows",
|
|
110
|
+
"custom_calculation": "Custom calculation, not automatically verified",
|
|
111
|
+
"deriv_based": "based on card {sources}, fields “{fields}”: ",
|
|
112
|
+
"deriv_id_suffix": " (id={did})",
|
|
113
|
+
"excluded_intro": "Question “{q}” — {reason}",
|
|
114
|
+
"toc_title": "Contents",
|
|
115
|
+
"appendix_d": "Appendix D Execution Metadata",
|
|
116
|
+
"purpose_label": "Decision question: ",
|
|
117
|
+
"role_primary": "Primary",
|
|
118
|
+
"role_comparator": "Comparator",
|
|
119
|
+
"role_diagnostic": "Diagnostic",
|
|
120
|
+
"role_validation": "Validation",
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _ui(output_language: str) -> dict[str, str]:
|
|
126
|
+
"""Return the fixed UI string table for the report language."""
|
|
127
|
+
return _UI_STRINGS.get(output_language, _UI_STRINGS["zh-CN"])
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
_CSS = """
|
|
131
|
+
body{font-family:'PingFang SC','Microsoft YaHei',system-ui,sans-serif;margin:0;color:#24292f;background:#fafbfc}
|
|
132
|
+
main,.appendix,.report-header,.report-footer{max-width:960px;margin-left:auto;margin-right:auto;padding-left:24px;padding-right:24px}
|
|
133
|
+
.report-header{padding-top:32px;padding-bottom:12px}
|
|
134
|
+
.report-header h1{font-size:26px;margin:0 0 8px}
|
|
135
|
+
.report-header .meta{color:#57606a;font-size:14px;margin:0}
|
|
136
|
+
.chart-block{background:#fff;border:1px solid #d0d7de;border-radius:8px;padding:20px 24px;margin:20px 0}
|
|
137
|
+
.chart-block h2{font-size:18px;margin:0 0 12px}
|
|
138
|
+
.role-badge{display:inline-block;font-size:12px;font-weight:400;border-radius:10px;padding:1px 10px;margin-left:8px;vertical-align:middle}
|
|
139
|
+
.role-badge.role-primary{background:#eef6ff;color:#1d4ed8;border:1px solid #a5c8f0}
|
|
140
|
+
.role-badge.role-comparator{background:#f0fdf4;color:#15803d;border:1px solid #bbf7d0}
|
|
141
|
+
.role-badge.role-diagnostic{background:#fff7ed;color:#c2410c;border:1px solid #fed7aa}
|
|
142
|
+
.role-badge.role-validation{background:#faf5ff;color:#7e22ce;border:1px solid #e9d5ff}
|
|
143
|
+
.chapter > p.purpose{color:#24292f;font-size:14px;margin:10px 0 2px;line-height:1.6;white-space:pre-wrap}
|
|
144
|
+
.chart-canvas{width:100%;height:360px}
|
|
145
|
+
.data-table{border-collapse:collapse;width:100%;margin:12px 0;font-size:14px}
|
|
146
|
+
.data-table th,.data-table td{border:1px solid #d0d7de;padding:6px 10px;text-align:left}
|
|
147
|
+
.data-table th{background:#f6f8fa}
|
|
148
|
+
.toc{background:#fff;border:1px solid #d0d7de;border-radius:8px;padding:14px 22px;margin:20px 0}
|
|
149
|
+
.toc h2{font-size:16px;margin:0 0 8px}
|
|
150
|
+
.toc ol{margin:0;padding-left:22px}
|
|
151
|
+
.toc li{font-size:14px;line-height:1.8}
|
|
152
|
+
.toc a{color:#2563eb;text-decoration:none}
|
|
153
|
+
.interpretation{margin:10px 0 4px;font-size:15px;line-height:1.6;white-space:pre-wrap}
|
|
154
|
+
.footnote{color:#6e7781;font-size:12px;margin:4px 0 0}
|
|
155
|
+
.appendix h2{font-size:18px;border-bottom:1px solid #d0d7de;padding-bottom:8px}
|
|
156
|
+
.appendix h3{font-size:15px;margin:18px 0 6px}
|
|
157
|
+
.appendix code,pre{font-family:SFMono-Regular,Consolas,monospace;font-size:13px}
|
|
158
|
+
.deriv-expression{display:block;background:#f6f8fa;border:1px solid #d0d7de;border-radius:6px;padding:8px 12px;margin:6px 0;white-space:pre-wrap}
|
|
159
|
+
.excluded-item,.deriv-meta{color:#57606a;font-size:14px;line-height:1.6}
|
|
160
|
+
.report-footer{padding-bottom:40px;color:#8b949e;font-size:12px}
|
|
161
|
+
.executive-summary{background:#eef6ff;border:1px solid #a5c8f0;border-left:4px solid #2563eb;border-radius:8px;padding:18px 22px;margin:20px 0}
|
|
162
|
+
.executive-summary h2{margin:0 0 10px;font-size:20px}
|
|
163
|
+
.executive-summary .summary{font-size:15px;line-height:1.7;margin:0 0 12px;white-space:pre-wrap}
|
|
164
|
+
.executive-summary .recommendations-title{font-size:15px;margin:0 0 6px}
|
|
165
|
+
.executive-summary ol.recommendations{margin:0;padding-left:22px}
|
|
166
|
+
.executive-summary ol.recommendations li{font-size:14px;line-height:1.7}
|
|
167
|
+
.chapter > h2{font-size:21px;margin:28px 0 4px;padding-bottom:6px;border-bottom:2px solid #d0d7de}
|
|
168
|
+
.chapter > p.digest{color:#57606a;font-size:14px;margin:6px 0 14px;line-height:1.6;white-space:pre-wrap}
|
|
169
|
+
.appendix-card{border:1px solid #d0d7de;border-radius:8px;background:#fff;padding:10px 18px;margin:14px 0}
|
|
170
|
+
.appendix-card > summary{display:flex;align-items:center;justify-content:space-between;gap:12px;cursor:pointer;list-style:none;font-size:14px}
|
|
171
|
+
.appendix-card > summary::-webkit-details-marker{display:none}
|
|
172
|
+
.appendix-summary-title{font-weight:600}
|
|
173
|
+
.appendix-summary-meta{color:#57606a;font-size:13px;flex:1}
|
|
174
|
+
.appendix-card[open]{padding-bottom:16px}
|
|
175
|
+
.download-btn{background:#2563eb;color:#fff;border:none;border-radius:6px;padding:6px 14px;font-size:13px;cursor:pointer;white-space:nowrap}
|
|
176
|
+
.download-btn:hover{background:#1d4ed8}
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
_BOOTSTRAP_JS = """
|
|
180
|
+
(function () {
|
|
181
|
+
function boot() {
|
|
182
|
+
var specs = window.VIZ_REPORT_DATA || [];
|
|
183
|
+
var instances = [];
|
|
184
|
+
Array.prototype.forEach.call(document.querySelectorAll('.chart-canvas'), function (node) {
|
|
185
|
+
node.textContent = '';
|
|
186
|
+
});
|
|
187
|
+
if (typeof echarts === 'undefined') {
|
|
188
|
+
Array.prototype.forEach.call(document.querySelectorAll('.chart-canvas'), function (node) {
|
|
189
|
+
node.textContent = __VIZ_LOAD_FAIL__;
|
|
190
|
+
});
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
specs.forEach(function (spec) {
|
|
194
|
+
var el = document.getElementById('chart-' + spec.domId);
|
|
195
|
+
if (!el) { return; }
|
|
196
|
+
var instance = echarts.init(el);
|
|
197
|
+
instance.setOption(window.__vizDecorate(spec.option));
|
|
198
|
+
instances.push(instance);
|
|
199
|
+
});
|
|
200
|
+
window.addEventListener('resize', function () {
|
|
201
|
+
instances.forEach(function (instance) { instance.resize(); });
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
if (document.readyState === 'loading') {
|
|
205
|
+
document.addEventListener('DOMContentLoaded', boot);
|
|
206
|
+
} else {
|
|
207
|
+
boot();
|
|
208
|
+
}
|
|
209
|
+
})();
|
|
210
|
+
"""
|
|
211
|
+
|
|
212
|
+
_FORMATTER_JS = """
|
|
213
|
+
window.__vizFmtNumber = function (value) {
|
|
214
|
+
if (typeof value !== 'number' || !isFinite(value)) { return '-'; }
|
|
215
|
+
var magnitude = Math.abs(value);
|
|
216
|
+
var digits = magnitude >= 1000 ? 0 : (magnitude >= 1 ? 2 : 4);
|
|
217
|
+
return value.toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: digits });
|
|
218
|
+
};
|
|
219
|
+
window.__vizFmtPercent = function (value) {
|
|
220
|
+
if (typeof value !== 'number' || !isFinite(value)) { return '-'; }
|
|
221
|
+
return (value * 100).toFixed(1) + '%';
|
|
222
|
+
};
|
|
223
|
+
window.__vizEscapeText = function (text) {
|
|
224
|
+
var raw = text === null || text === undefined ? '' : String(text);
|
|
225
|
+
return raw.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
|
226
|
+
};
|
|
227
|
+
window.__vizDecorate = function (option) {
|
|
228
|
+
var fmtMap = option.__vizSeriesFmt;
|
|
229
|
+
if (fmtMap && option.tooltip) {
|
|
230
|
+
option.tooltip.formatter = function (params) {
|
|
231
|
+
var list = Array.isArray(params) ? params : [params];
|
|
232
|
+
var lines = [];
|
|
233
|
+
var title = '';
|
|
234
|
+
for (var i = 0; i < list.length; i++) {
|
|
235
|
+
var point = list[i];
|
|
236
|
+
if (i === 0) { title = window.__vizEscapeText(point.axisValueLabel || point.name || ''); }
|
|
237
|
+
var kind = fmtMap[point.seriesName] || 'number';
|
|
238
|
+
var fmt = kind === 'percent' ? window.__vizFmtPercent : window.__vizFmtNumber;
|
|
239
|
+
var raw = point.value;
|
|
240
|
+
var text = Array.isArray(raw) ? '(' + fmt(raw[0]) + ', ' + fmt(raw[1]) + ')' : fmt(raw);
|
|
241
|
+
lines.push(point.marker + ' ' + window.__vizEscapeText(point.seriesName) + ': ' + text);
|
|
242
|
+
}
|
|
243
|
+
return (title ? title + '<br/>' : '') + lines.join('<br/>');
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
var percentAxes = option.__vizPercentAxes || [];
|
|
247
|
+
var axes = [];
|
|
248
|
+
if (option.yAxis) { axes = Array.isArray(option.yAxis) ? option.yAxis : [option.yAxis]; }
|
|
249
|
+
for (var axisIndex = 0; axisIndex < axes.length; axisIndex++) {
|
|
250
|
+
axes[axisIndex].axisLabel = {
|
|
251
|
+
formatter: (function (isPercent) {
|
|
252
|
+
return function (tick) { return isPercent ? window.__vizFmtPercent(tick) : window.__vizFmtNumber(tick); };
|
|
253
|
+
})(percentAxes.indexOf(axisIndex) >= 0)
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
delete option.__vizSeriesFmt;
|
|
257
|
+
delete option.__vizPercentAxes;
|
|
258
|
+
return option;
|
|
259
|
+
};
|
|
260
|
+
"""
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
_UTF8_BOM = chr(0xFEFF)
|
|
264
|
+
|
|
265
|
+
_BOOTSTRAP_CSV_JS = """
|
|
266
|
+
window.__vizCsvCell = function (value) {
|
|
267
|
+
var text = value === null || value === undefined ? '' : String(value);
|
|
268
|
+
var isNumericLike = /^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/.test(text);
|
|
269
|
+
if (/^[=+@\\t\\r]/.test(text) || (text.charAt(0) === '-' && !isNumericLike)) {
|
|
270
|
+
text = "'" + text;
|
|
271
|
+
}
|
|
272
|
+
return /["\\r\\n,]/.test(text) ? '"' + text.replace(/"/g, '""') + '"' : text;
|
|
273
|
+
};
|
|
274
|
+
window.VIZ_DOWNLOAD_CSV = function (cardIndex) {
|
|
275
|
+
var entry = (window.VIZ_APPENDIX_CARDS || [])[cardIndex];
|
|
276
|
+
if (!entry) { return; }
|
|
277
|
+
var rows = entry.rows.map(function (row) { return row.map(window.__vizCsvCell).join(','); });
|
|
278
|
+
var blob = new Blob([window.VIZ_APPENDIX_BOM + rows.join('\\r\\n')], { type: 'text/csv;charset=utf-8;' });
|
|
279
|
+
var link = document.createElement('a');
|
|
280
|
+
link.href = URL.createObjectURL(blob);
|
|
281
|
+
link.download = String(entry.cardId).replace(/[^0-9A-Za-z_.-]+/g, '_') + '.csv';
|
|
282
|
+
document.body.appendChild(link);
|
|
283
|
+
link.click();
|
|
284
|
+
document.body.removeChild(link);
|
|
285
|
+
setTimeout(function () { URL.revokeObjectURL(link.href); }, 0);
|
|
286
|
+
};
|
|
287
|
+
"""
|
|
288
|
+
_BOOTSTRAP_CSV_JS = _BOOTSTRAP_CSV_JS + "\nwindow.VIZ_APPENDIX_BOM = '" + _UTF8_BOM + "';\n"
|
|
289
|
+
# 格式化函数必须先于 IIFE 定义:readyState 非 loading 时 boot 会立即执行并调用 __vizDecorate。
|
|
290
|
+
_BOOTSTRAP_JS = _FORMATTER_JS + "\n" + _BOOTSTRAP_JS + "\n" + _BOOTSTRAP_CSV_JS
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
class ReportContractError(ValueError):
|
|
294
|
+
"""The renderer input violates the provenance contract."""
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def load_input(input_path: str | Path) -> dict[str, Any]:
|
|
298
|
+
"""Load and basic-check the renderer input JSON written by the agent."""
|
|
299
|
+
path = Path(input_path)
|
|
300
|
+
try:
|
|
301
|
+
size = path.stat().st_size
|
|
302
|
+
except OSError as exc:
|
|
303
|
+
raise ReportContractError(f"无法读取渲染输入文件:{path}({exc})。请确认路径正确且文件已写出后,重跑组装命令。") from exc
|
|
304
|
+
if size > MAX_INPUT_BYTES:
|
|
305
|
+
raise ReportContractError(
|
|
306
|
+
f"渲染输入文件超过 50 MiB 上限(当前 {size} 字节),渲染器不做无界读取。请先缩减不进入图表与附录的探索卡 payload,再重跑组装命令。"
|
|
307
|
+
)
|
|
308
|
+
try:
|
|
309
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
310
|
+
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
|
|
311
|
+
raise ReportContractError(
|
|
312
|
+
f"渲染输入不是合法 UTF-8 JSON:{path}({exc})。请检查生成该文件的写入步骤是否被截断,修复内容后重跑组装命令。"
|
|
313
|
+
) from exc
|
|
314
|
+
if not isinstance(data, dict):
|
|
315
|
+
raise ReportContractError(
|
|
316
|
+
"渲染输入顶层必须是 JSON 对象(含 plan_meta/cards/charts 键),当前解析结果不是对象。"
|
|
317
|
+
"请按 references/derivation-log.md 的『渲染输入 JSON 总览』补齐结构后重跑。"
|
|
318
|
+
)
|
|
319
|
+
return data
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def load_echarts_asset(asset_path: str | Path = ECHARTS_ASSET_PATH) -> str:
|
|
323
|
+
"""Read the vendored minified ECharts build for inlining."""
|
|
324
|
+
path = Path(asset_path)
|
|
325
|
+
try:
|
|
326
|
+
content = path.read_text(encoding="utf-8")
|
|
327
|
+
except OSError:
|
|
328
|
+
raise ReportContractError(
|
|
329
|
+
"缺少内联图表库:未找到 assets/echarts.min.js(期望位置 "
|
|
330
|
+
"code/cdn/datarc-skill/datarc-viz-analysis-report/assets/echarts.min.js)。"
|
|
331
|
+
"请在该 Skill 目录执行 curl -sSL https://cdn.jsdelivr.net/npm/echarts@5.6.0/dist/echarts.min.js"
|
|
332
|
+
" -o assets/echarts.min.js 补回文件后重跑;若网络受限请联系维护者换源。"
|
|
333
|
+
) from None
|
|
334
|
+
if len(content) < 100_000 or "Licensed to the Apache Software Foundation" not in content:
|
|
335
|
+
raise ReportContractError(
|
|
336
|
+
f"内联图表库疑似损坏或不完整:{len(content)} 字符且未见 Apache 许可 banner。"
|
|
337
|
+
"请删除该文件,用原地址 https://cdn.jsdelivr.net/npm/echarts@5.6.0/dist/echarts.min.js"
|
|
338
|
+
" 重新下载覆盖后重跑;不要手工编辑这个 vendor 文件。"
|
|
339
|
+
)
|
|
340
|
+
return content
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def validate_derivations(
|
|
344
|
+
derivations: Any,
|
|
345
|
+
cards: list[dict[str, Any]],
|
|
346
|
+
) -> dict[str, dict[str, Any]]:
|
|
347
|
+
"""Validate every derivation log entry and index them by id."""
|
|
348
|
+
_require_list(derivations, "derivations")
|
|
349
|
+
cards_by_id = {card["card_id"]: card for card in cards}
|
|
350
|
+
header_fields: set[tuple[str, str]] = set()
|
|
351
|
+
for card in cards:
|
|
352
|
+
for cell in card["payload_rows"][0]:
|
|
353
|
+
header_fields.add((str(cell), card["card_id"]))
|
|
354
|
+
indexed: dict[str, dict[str, Any]] = {}
|
|
355
|
+
for position, entry in enumerate(derivations, start=1):
|
|
356
|
+
_require_mapping(entry, f"derivations 第 {position} 条")
|
|
357
|
+
missing = [key for key in DERIVATION_KEYS if not entry.get(key)]
|
|
358
|
+
if missing:
|
|
359
|
+
raise ReportContractError(
|
|
360
|
+
f"派生记录不完整:derivations 第 {position} 条缺少必填键 {missing}。完整的字段格式见 references/derivation-log.md;{_RERUN_HINT}。"
|
|
361
|
+
)
|
|
362
|
+
derivation_id = _require_text(entry["derivation_id"], "derivation_id")
|
|
363
|
+
for field in ("source_card_ids", "input_fields"):
|
|
364
|
+
if not isinstance(entry[field], list) or not all(isinstance(item, str) and item for item in entry[field]):
|
|
365
|
+
raise ReportContractError(f"派生记录 {derivation_id} 的 {field} 必须是非空字符串列表。请按来源卡和表头填写后重跑。")
|
|
366
|
+
for field in ("output_column", "key_card_id", "key_field"):
|
|
367
|
+
_require_text(entry[field], f"派生记录 {derivation_id} 的 {field}")
|
|
368
|
+
if derivation_id in indexed:
|
|
369
|
+
raise ReportContractError(
|
|
370
|
+
f"派生记录 ID 重复:{derivation_id} 出现了两次。请给每次计算分配唯一 ID(例如 d-refund-rate、d-diff-vs-target)后重跑。"
|
|
371
|
+
)
|
|
372
|
+
unknown_cards = [cid for cid in entry["source_card_ids"] if cid not in cards_by_id]
|
|
373
|
+
if unknown_cards:
|
|
374
|
+
raise ReportContractError(
|
|
375
|
+
f"派生记录 {derivation_id} 引用了账本中不存在的来源卡 {unknown_cards}。请把 source_card_ids 改成 cards 数组里真实存在的卡 ID 后重跑。"
|
|
376
|
+
)
|
|
377
|
+
unbound_fields = [field for field in entry["input_fields"] if not any((str(field), cid) in header_fields for cid in entry["source_card_ids"])]
|
|
378
|
+
if unbound_fields:
|
|
379
|
+
raise ReportContractError(
|
|
380
|
+
f"派生记录 {derivation_id} 的输入字段 {unbound_fields} 不在任何来源卡的表头行里。"
|
|
381
|
+
"请改用卡片实际返回的列名(对应卡 payload_rows 首行的原值)后重跑。"
|
|
382
|
+
)
|
|
383
|
+
method = entry["method"]
|
|
384
|
+
if not isinstance(method, dict) or method.get("type") not in SUPPORTED_METHOD_TYPES:
|
|
385
|
+
raise ReportContractError(
|
|
386
|
+
f"派生记录 {derivation_id} 的 method.type 不支持。请从 {'、'.join(SUPPORTED_METHOD_TYPES)} 中选择一种计算方式后重跑。"
|
|
387
|
+
)
|
|
388
|
+
operation = method["type"]
|
|
389
|
+
if operation in BUILTIN_FORMULAS:
|
|
390
|
+
indexed[derivation_id] = _compute_derivation(entry, cards_by_id)
|
|
391
|
+
continue
|
|
392
|
+
if not isinstance(method.get("expression"), str) or not method["expression"].strip():
|
|
393
|
+
raise ReportContractError(f"派生记录 {derivation_id} 缺少自定义计算公式。请补写实际执行的公式或代码片段后重跑。")
|
|
394
|
+
if not isinstance(entry.get("output_values"), list):
|
|
395
|
+
raise ReportContractError(f"派生记录 {derivation_id} 的 output_values 必须是数组。请填入实际计算结果后重跑。")
|
|
396
|
+
missing_binding = [key for key in ("key_field", "keys", "key_card_id") if not entry.get(key)]
|
|
397
|
+
if missing_binding:
|
|
398
|
+
raise ReportContractError(
|
|
399
|
+
f"派生记录 {derivation_id} 缺少行对齐必填键 {missing_binding}:"
|
|
400
|
+
"key_field 声明分组列(来源卡表头原列名),keys 是与 output_values 顺序一一对应的分组键数组,"
|
|
401
|
+
"key_card_id 指明分组键所在卡。请补齐后重跑。"
|
|
402
|
+
)
|
|
403
|
+
key_card = cards_by_id.get(entry["key_card_id"])
|
|
404
|
+
if key_card is None or entry["key_card_id"] not in entry["source_card_ids"]:
|
|
405
|
+
raise ReportContractError(
|
|
406
|
+
f"派生记录 {derivation_id} 的 key_card_id {entry['key_card_id']!r} 必须是其 source_card_ids 中的一张卡。"
|
|
407
|
+
"请把分组键列所在的卡 ID 填入后重跑。"
|
|
408
|
+
)
|
|
409
|
+
key_index = _header_index(key_card, f"派生记录 {derivation_id} 的 key_card")
|
|
410
|
+
if entry["key_field"] not in key_index:
|
|
411
|
+
raise ReportContractError(
|
|
412
|
+
f"派生记录 {derivation_id} 的 key_field {entry['key_field']!r} 不在 key_card 表头里。请改用该卡 payload_rows 首行的原列名后重跑。"
|
|
413
|
+
)
|
|
414
|
+
keys = entry["keys"]
|
|
415
|
+
if not isinstance(keys, list) or not keys or len(keys) != len(entry["output_values"]):
|
|
416
|
+
raise ReportContractError(
|
|
417
|
+
f"派生记录 {derivation_id} 的 keys 必须是与 output_values 等长且顺序一一对应的数组。请按相同行序回填分组键后重跑。"
|
|
418
|
+
)
|
|
419
|
+
key_column_values = [row[key_index[entry["key_field"]]] for row in key_card["payload_rows"][1:]]
|
|
420
|
+
unmatched_keys = [k for k in keys if not any(_same_value(k, cell) for cell in key_column_values)]
|
|
421
|
+
if unmatched_keys:
|
|
422
|
+
raise ReportContractError(
|
|
423
|
+
f"派生记录 {derivation_id} 的 keys {unmatched_keys} 未出现在 key_card 的 {entry['key_field']} 列中。"
|
|
424
|
+
"请核对分组键取值与来源行一致后重跑。"
|
|
425
|
+
)
|
|
426
|
+
indexed[derivation_id] = entry
|
|
427
|
+
return indexed
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def validate_executive_summary(executive_summary: Any) -> None:
|
|
431
|
+
"""Enforce the mandatory top-level summary-and-recommendations block."""
|
|
432
|
+
if not isinstance(executive_summary, dict):
|
|
433
|
+
raise ReportContractError(
|
|
434
|
+
"plan_meta 之外的顶层键 executive_summary 必须是对象:{'summary': '全局总结…', 'recommendations': ['至少一条建议']}。"
|
|
435
|
+
"请按 references/derivation-log.md 的示例补齐后重跑组装命令。"
|
|
436
|
+
)
|
|
437
|
+
_require_text(executive_summary.get("summary"), "executive_summary.summary")
|
|
438
|
+
recommendations = executive_summary.get("recommendations")
|
|
439
|
+
if not isinstance(recommendations, list) or not recommendations:
|
|
440
|
+
raise ReportContractError("executive_summary.recommendations 必须是非空数组:请把本次分析给业务方的可执行建议逐条列出(至少一条)后重跑。")
|
|
441
|
+
for position, item in enumerate(recommendations, start=1):
|
|
442
|
+
_require_text(item, f"executive_summary.recommendations 第 {position} 条")
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def validate_chapter_structure(chapters: Any, charts: list[dict[str, Any]]) -> None:
|
|
446
|
+
"""Validate total-then-part chapters, exact chart ownership, and evidence depth.
|
|
447
|
+
|
|
448
|
+
除结构与归属外,这里强制执行证据充分性下限:每章至少 MIN_CHAPTER_CARDS 张图、
|
|
449
|
+
至少两种证据角色且至少一张 primary;depends_on 只允许引用更早的章节形成递进链。
|
|
450
|
+
"""
|
|
451
|
+
if not isinstance(chapters, list) or not chapters:
|
|
452
|
+
raise ReportContractError(
|
|
453
|
+
"渲染输入缺少有效的顶层键 chapters:报告按总分结构组装,至少需要一个章节承载全部图表。"
|
|
454
|
+
"请为每章给出 {chapter_id, title, purpose, digest, chart_ids} 并把每张图归入唯一章节后重跑。"
|
|
455
|
+
)
|
|
456
|
+
known_chart_ids = [chart["chart_id"] for chart in charts]
|
|
457
|
+
known_set = set(known_chart_ids)
|
|
458
|
+
role_by_chart = {chart["chart_id"]: chart.get("evidence_role") for chart in charts}
|
|
459
|
+
seen_chapter_ids: set[str] = set()
|
|
460
|
+
ownership: dict[str, str] = {}
|
|
461
|
+
for position, chapter in enumerate(chapters, start=1):
|
|
462
|
+
_require_mapping(chapter, f"chapters 第 {position} 条")
|
|
463
|
+
chapter_id = _require_text(chapter.get("chapter_id"), f"chapters 第 {position} 条的 chapter_id")
|
|
464
|
+
if chapter_id in seen_chapter_ids:
|
|
465
|
+
raise ReportContractError(f"chapter_id 重复:{chapter_id} 出现两次,章节结构无法定位。请改名其中一个章节的 ID 后重跑。")
|
|
466
|
+
_require_text(chapter.get("title"), f"章节 {chapter_id} 的 title")
|
|
467
|
+
_require_text(chapter.get("purpose"), f"章节 {chapter_id} 的 purpose")
|
|
468
|
+
_require_text(chapter.get("digest"), f"章节 {chapter_id} 的 digest")
|
|
469
|
+
depends_on = chapter.get("depends_on", [])
|
|
470
|
+
if not isinstance(depends_on, list):
|
|
471
|
+
raise ReportContractError(f"章节 {chapter_id} 的 depends_on 必须是章节 ID 数组。请修正后重跑。")
|
|
472
|
+
unknown_dependencies = [dependency for dependency in depends_on if dependency not in seen_chapter_ids]
|
|
473
|
+
if unknown_dependencies:
|
|
474
|
+
raise ReportContractError(
|
|
475
|
+
f"章节 {chapter_id} 的 depends_on 引用了 {unknown_dependencies}:只能引用排在它之前的章节(空依赖为并行分支,引用前章形成递进)。"
|
|
476
|
+
"请调整章节顺序或修正引用后重跑。"
|
|
477
|
+
)
|
|
478
|
+
chart_ids = chapter.get("chart_ids")
|
|
479
|
+
if not isinstance(chart_ids, list) or not chart_ids:
|
|
480
|
+
raise ReportContractError(f"章节 {chapter_id} 的 chart_ids 必须是非空数组;若该章确实无图,请合并进相邻章节后重跑。")
|
|
481
|
+
if len(chart_ids) < MIN_CHAPTER_CARDS:
|
|
482
|
+
raise ReportContractError(
|
|
483
|
+
f"章节 {chapter_id} 只有 {len(chart_ids)} 张图,低于每章 {MIN_CHAPTER_CARDS} 张的证据下限(chapterEvidencePlan 的 minCards)。"
|
|
484
|
+
"单图章节不构成证据链:请为该章补充互补证据图,或把它并入语义兼容的相邻章节后重跑。"
|
|
485
|
+
)
|
|
486
|
+
for chart_id in chart_ids:
|
|
487
|
+
if not isinstance(chart_id, str) or chart_id not in known_set:
|
|
488
|
+
raise ReportContractError(
|
|
489
|
+
f"章节 {chapter_id} 的 chart_ids 引用了不存在的图表 {chart_id!r}。"
|
|
490
|
+
f"请改成 charts 数组中真实存在的 chart_id(当前可选:{known_chart_ids})后重跑。"
|
|
491
|
+
)
|
|
492
|
+
previous_chapter = ownership.get(chart_id)
|
|
493
|
+
if previous_chapter is not None:
|
|
494
|
+
raise ReportContractError(
|
|
495
|
+
f"图表 {chart_id} 被多个章节引用({previous_chapter} 与 {chapter_id})。每张图必须且只能归入一章;"
|
|
496
|
+
f"请从多余的章节 chart_ids 中移除该图后重跑。"
|
|
497
|
+
)
|
|
498
|
+
ownership[chart_id] = chapter_id
|
|
499
|
+
roles = [role_by_chart[chart_id] for chart_id in chart_ids]
|
|
500
|
+
if "primary" not in roles:
|
|
501
|
+
raise ReportContractError(
|
|
502
|
+
f"章节 {chapter_id} 缺少 evidence_role=primary 的主证据图。每章必须有一张直接回答本章决策问题的主图;"
|
|
503
|
+
"请把本章最核心的一张图标记为 primary,或调整章节划分后重跑。"
|
|
504
|
+
)
|
|
505
|
+
if len(set(roles)) < 2:
|
|
506
|
+
raise ReportContractError(
|
|
507
|
+
f"章节 {chapter_id} 的全部图表都是同一证据角色({roles[0]})。同一角色的平铺不构成互补证据:"
|
|
508
|
+
"请按 chapterEvidencePlan 为每张图分配互补角色(primary/comparator/diagnostic/validation)后重跑。"
|
|
509
|
+
)
|
|
510
|
+
seen_chapter_ids.add(chapter_id)
|
|
511
|
+
orphan_charts = [chart_id for chart_id in known_chart_ids if chart_id not in ownership]
|
|
512
|
+
if orphan_charts:
|
|
513
|
+
raise ReportContractError(
|
|
514
|
+
f"存在未被任何章节引用的孤儿图 {orphan_charts}。总分结构要求每张图都归属一章:"
|
|
515
|
+
f"请把它们加入 chapters 中主题最贴近章节的 chart_ids(或为其新建专章并写好小结)后重跑。"
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def validate_claims(
|
|
520
|
+
claims: Any,
|
|
521
|
+
cards: list[dict[str, Any]],
|
|
522
|
+
chapters: list[dict[str, Any]],
|
|
523
|
+
charts: list[dict[str, Any]],
|
|
524
|
+
) -> None:
|
|
525
|
+
"""Validate the structured claim contract (evidence-sufficiency gate).
|
|
526
|
+
|
|
527
|
+
fact 至少 1 条证据卡;inference/recommendation 至少 2 个不同来源卡;limitation 可为空。
|
|
528
|
+
每章至少引用 2 条 fact 与 1 条 inference 或 limitation;claim 原文必须出现在引用章节的
|
|
529
|
+
digest 或本章图解读中——结构化声明不能只留在 JSON 里。
|
|
530
|
+
"""
|
|
531
|
+
_require_list(claims, "claims")
|
|
532
|
+
if not claims:
|
|
533
|
+
raise ReportContractError(
|
|
534
|
+
"claims 为空:报告必须把结论登记为结构化 claim(fact/inference/recommendation/limitation,含 confidence 与证据卡引用)。"
|
|
535
|
+
"请按 references/derivation-log.md 的 claims 契约逐条登记后重跑。"
|
|
536
|
+
)
|
|
537
|
+
card_ids = {card["card_id"] for card in cards}
|
|
538
|
+
claims_by_id: dict[str, dict[str, Any]] = {}
|
|
539
|
+
for position, claim in enumerate(claims, start=1):
|
|
540
|
+
_require_mapping(claim, f"claims 第 {position} 条")
|
|
541
|
+
claim_id = _require_text(claim.get("claim_id"), f"claims 第 {position} 条的 claim_id")
|
|
542
|
+
if claim_id in claims_by_id:
|
|
543
|
+
raise ReportContractError(f"claim_id 重复:{claim_id} 出现两次。请给每条结论分配唯一 ID 后重跑。")
|
|
544
|
+
kind = claim.get("kind")
|
|
545
|
+
if kind not in SUPPORTED_CLAIM_KINDS:
|
|
546
|
+
raise ReportContractError(f"claim {claim_id} 的 kind 只接受 {'/'.join(SUPPORTED_CLAIM_KINDS)},当前为 {kind!r}。请按结论性质归类后重跑。")
|
|
547
|
+
_require_text(claim.get("text"), f"claim {claim_id} 的 text")
|
|
548
|
+
confidence = claim.get("confidence")
|
|
549
|
+
if confidence not in SUPPORTED_CONFIDENCES:
|
|
550
|
+
raise ReportContractError(
|
|
551
|
+
f"claim {claim_id} 的 confidence 只接受 {'/'.join(SUPPORTED_CONFIDENCES)},当前为 {confidence!r}。请标注置信度后重跑。"
|
|
552
|
+
)
|
|
553
|
+
evidence = claim.get("evidence_card_ids", [])
|
|
554
|
+
if not isinstance(evidence, list):
|
|
555
|
+
raise ReportContractError(f"claim {claim_id} 的 evidence_card_ids 必须是卡 ID 数组。请修正后重跑。")
|
|
556
|
+
unknown_cards = [card_id for card_id in evidence if card_id not in card_ids]
|
|
557
|
+
if unknown_cards:
|
|
558
|
+
raise ReportContractError(f"claim {claim_id} 引用了账本中不存在的证据卡 {unknown_cards}。请改成 cards 数组里真实存在的卡 ID 后重跑。")
|
|
559
|
+
if kind == "fact" and not evidence:
|
|
560
|
+
raise ReportContractError(
|
|
561
|
+
f"claim {claim_id} 是 fact 但没有证据卡:事实性结论必须能由至少一张卡直接核对。请补充 evidence_card_ids 后重跑。"
|
|
562
|
+
)
|
|
563
|
+
if kind in ("inference", "recommendation") and len(set(evidence)) < 2:
|
|
564
|
+
raise ReportContractError(
|
|
565
|
+
f"claim {claim_id} 是 {kind} 但证据卡不足 2 个不同来源:推断与建议必须由至少两个不同问题的证据共同支撑,单证据不得下判断。"
|
|
566
|
+
"请补充证据卡引用,或把结论降级为带 limitation 的陈述后重跑。"
|
|
567
|
+
)
|
|
568
|
+
claims_by_id[claim_id] = claim
|
|
569
|
+
interpretation_by_chart = {chart["chart_id"]: chart["interpretation"] for chart in charts}
|
|
570
|
+
referenced: set[str] = set()
|
|
571
|
+
for chapter in chapters:
|
|
572
|
+
chapter_id = chapter["chapter_id"]
|
|
573
|
+
claim_refs = chapter.get("claim_refs", [])
|
|
574
|
+
if not isinstance(claim_refs, list):
|
|
575
|
+
raise ReportContractError(f"章节 {chapter_id} 的 claim_refs 必须是 claim ID 数组。请修正后重跑。")
|
|
576
|
+
unknown_refs = [ref for ref in claim_refs if ref not in claims_by_id]
|
|
577
|
+
if unknown_refs:
|
|
578
|
+
raise ReportContractError(
|
|
579
|
+
f"章节 {chapter_id} 的 claim_refs 引用了不存在的 claim {unknown_refs}。请改成 claims 数组里真实存在的 ID 后重跑。"
|
|
580
|
+
)
|
|
581
|
+
kinds = [claims_by_id[ref]["kind"] for ref in claim_refs]
|
|
582
|
+
if kinds.count("fact") < 2:
|
|
583
|
+
raise ReportContractError(
|
|
584
|
+
f"章节 {chapter_id} 只引用了 {kinds.count('fact')} 条 fact(要求至少 2 条)。每章结论必须建立在至少两条可核对的事实上;"
|
|
585
|
+
"请把本章图表中的事实性读数登记为 fact claim 并引用后重跑。"
|
|
586
|
+
)
|
|
587
|
+
if not any(kind in ("inference", "limitation") for kind in kinds):
|
|
588
|
+
raise ReportContractError(
|
|
589
|
+
f"章节 {chapter_id} 缺少 inference 或 limitation 引用:只有事实罗列的章节不构成分析。请补充一条推断(含证据)或如实写明本章局限后重跑。"
|
|
590
|
+
)
|
|
591
|
+
chapter_texts = [chapter["digest"]] + [interpretation_by_chart[chart_id] for chart_id in chapter["chart_ids"]]
|
|
592
|
+
for ref in claim_refs:
|
|
593
|
+
claim_text = claims_by_id[ref]["text"]
|
|
594
|
+
if not any(claim_text in body for body in chapter_texts):
|
|
595
|
+
raise ReportContractError(
|
|
596
|
+
f"claim {ref} 的原文未出现在章节 {chapter_id} 的 digest 或本章图解读中:结构化声明必须与正文一致。"
|
|
597
|
+
"请把该结论原样写进章节小结或图解读(或在 claim 中改成与正文一致的文字)后重跑。"
|
|
598
|
+
)
|
|
599
|
+
referenced.update(claim_refs)
|
|
600
|
+
orphan_claims = [claim_id for claim_id in claims_by_id if claim_id not in referenced]
|
|
601
|
+
if orphan_claims:
|
|
602
|
+
raise ReportContractError(
|
|
603
|
+
f"存在未被任何章节引用的孤儿 claim {orphan_claims}。每条登记结论都必须落位到章节:请引用它们或从 claims 中移除后重跑。"
|
|
604
|
+
)
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def validate_chart_tracing(
|
|
608
|
+
chart: dict[str, Any],
|
|
609
|
+
card: dict[str, Any],
|
|
610
|
+
derivations_by_id: dict[str, Any],
|
|
611
|
+
) -> list[str]:
|
|
612
|
+
"""Verify every plotted datum is row-aligned to its declared source column.
|
|
613
|
+
|
|
614
|
+
Direct values must match (category, series) cell pairs taken from the same
|
|
615
|
+
payload row; derived values must follow the derivation's key order. Returns
|
|
616
|
+
the derivation columns consumed by this chart, in encounter order.
|
|
617
|
+
"""
|
|
618
|
+
chart_id = chart["chart_id"]
|
|
619
|
+
card_id = chart["source_card_id"]
|
|
620
|
+
index = _header_index(card, f"来源卡 {card_id}")
|
|
621
|
+
body_rows = card["payload_rows"][1:]
|
|
622
|
+
used_columns: list[str] = []
|
|
623
|
+
if chart["chart_type"] == "table":
|
|
624
|
+
_trace_table(chart, card_id, index, body_rows, derivations_by_id, used_columns)
|
|
625
|
+
return used_columns
|
|
626
|
+
|
|
627
|
+
categories = chart.get("categories") or {}
|
|
628
|
+
cat_direct: int | None = None
|
|
629
|
+
cat_derivation: dict[str, Any] | None = None
|
|
630
|
+
cat_keys: list[Any] | None = None
|
|
631
|
+
cat_values: list[Any] | None = None
|
|
632
|
+
if categories:
|
|
633
|
+
cat_derivation = _resolve_derivation(categories, f"图表 {chart_id} 类目轴", chart_id, derivations_by_id, used_columns)
|
|
634
|
+
if cat_derivation is None:
|
|
635
|
+
cat_direct = _column_index(categories, index, f"图表 {chart_id} 的 categories", card_id)
|
|
636
|
+
cat_values = categories["values"]
|
|
637
|
+
else:
|
|
638
|
+
if cat_derivation["key_card_id"] != card_id:
|
|
639
|
+
raise ReportContractError(
|
|
640
|
+
f"图表 {chart_id} 类目轴引用的派生记录 {cat_derivation['derivation_id']} 的 key_card_id 不是本图来源卡,"
|
|
641
|
+
"行级对齐要求派生分组键与图表同卡。请调整派生记录的 key_card_id 或图表 source_card_id 后重跑。"
|
|
642
|
+
)
|
|
643
|
+
cat_keys = cat_derivation["keys"]
|
|
644
|
+
values = categories.get("values")
|
|
645
|
+
if not isinstance(values, list) or len(values) != len(cat_keys):
|
|
646
|
+
raise ReportContractError(
|
|
647
|
+
f"图表 {chart_id} 类目轴 values 长度与派生记录 {cat_derivation['derivation_id']} 的 keys 不一致。"
|
|
648
|
+
"请按 keys 顺序逐项回填 values 后重跑。"
|
|
649
|
+
)
|
|
650
|
+
mismatched = _mismatch_indices(values, cat_keys)
|
|
651
|
+
if mismatched:
|
|
652
|
+
raise ReportContractError(
|
|
653
|
+
f"图表 {chart_id} 类目轴 values 与派生记录 {cat_derivation['derivation_id']} 的 keys 在第 {mismatched} 项不一致(顺序敏感)。"
|
|
654
|
+
"请逐项对齐后重跑。"
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
if chart["chart_type"] == "scatter" and cat_direct is None and cat_derivation is None:
|
|
658
|
+
x_item, y_item = chart["series"][0], chart["series"][1]
|
|
659
|
+
x_index = _column_index(x_item, index, f"图表 {chart_id} 系列『{x_item['name']}』的 series", card_id)
|
|
660
|
+
y_index = _column_index(y_item, index, f"图表 {chart_id} 系列『{y_item['name']}』的 series", card_id)
|
|
661
|
+
for i, (vx, vy) in enumerate(zip(x_item["data"], y_item["data"])):
|
|
662
|
+
if vx is None or vy is None:
|
|
663
|
+
continue
|
|
664
|
+
if not _row_tuple_exists(body_rows, [(x_item["field"], vx, x_index), (y_item["field"], vy, y_index)]):
|
|
665
|
+
raise ReportContractError(
|
|
666
|
+
f"越源数值:图表 {chart_id} 散点第 {i + 1} 项 ({vx!r}, {vy!r}) 未在来源卡 {card_id} 同一行"
|
|
667
|
+
f"({x_item['field']}×{y_item['field']})同时出现。请按行提取数据后重跑。"
|
|
668
|
+
)
|
|
669
|
+
return used_columns
|
|
670
|
+
|
|
671
|
+
key_index: int | None = None
|
|
672
|
+
if cat_derivation is not None:
|
|
673
|
+
key_index = index[cat_derivation["key_field"]]
|
|
674
|
+
direct_series: list[tuple[str, str, int, list[Any]]] = []
|
|
675
|
+
for series_item in chart["series"]:
|
|
676
|
+
label = f"图表 {chart_id} 系列『{series_item['name']}』"
|
|
677
|
+
derivation = _resolve_derivation(series_item, label, chart_id, derivations_by_id, used_columns)
|
|
678
|
+
data = series_item["data"]
|
|
679
|
+
if derivation is not None:
|
|
680
|
+
if derivation["key_card_id"] != card_id:
|
|
681
|
+
raise ReportContractError(
|
|
682
|
+
f"{label} 引用的派生记录 {derivation['derivation_id']} 的 key_card_id 不是本图来源卡,"
|
|
683
|
+
"行级对齐要求引用派生的图表与分组键所在卡同源(见 references/derivation-log.md 的 key_card_id 契约)。"
|
|
684
|
+
"请调整派生记录的 key_card_id 或图表 source_card_id 后重跑。"
|
|
685
|
+
)
|
|
686
|
+
_trace_series_derived(chart_id, label, series_item, derivation, cat_values, cat_keys, data)
|
|
687
|
+
continue
|
|
688
|
+
series_index = _column_index(series_item, index, label + " 的 series", card_id)
|
|
689
|
+
if cat_direct is None and key_index is None:
|
|
690
|
+
raise ReportContractError(f"图表 {chart_id} 的直接取值系列必须能对齐类目:请为 categories 与 series 声明 field 列绑定后重跑。")
|
|
691
|
+
direct_series.append((label, series_item["field"], series_index, data))
|
|
692
|
+
if direct_series:
|
|
693
|
+
# 整行元组校验:同一数据点的类目与全部直接系列取值必须落在来源卡的同一行。
|
|
694
|
+
# 来源卡存在重复类目时,逐系列单独校验会放行从不同行拼凑的组合。
|
|
695
|
+
if cat_direct is not None:
|
|
696
|
+
axis_field, axis_column, axis_values = categories["field"], cat_direct, cat_values
|
|
697
|
+
else:
|
|
698
|
+
axis_field, axis_column, axis_values = cat_derivation["key_field"], key_index, cat_keys
|
|
699
|
+
for i, axis_value in enumerate(axis_values):
|
|
700
|
+
bindings = [(axis_field, axis_value, axis_column)]
|
|
701
|
+
bindings.extend((field, data[i], series_index) for _, field, series_index, data in direct_series if data[i] is not None)
|
|
702
|
+
if not _row_tuple_exists(body_rows, bindings):
|
|
703
|
+
described = "、".join(f"{field}={value!r}" for field, value, _ in bindings)
|
|
704
|
+
raise ReportContractError(
|
|
705
|
+
f"越源数值:图表 {chart_id} 第 {i + 1} 个数据点的取值组合({described})未在来源卡 {card_id} 的同一行同时出现。"
|
|
706
|
+
"请按行提取数据,不得对调行序或跨列拼凑后重跑。"
|
|
707
|
+
)
|
|
708
|
+
return used_columns
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def build_footnote(
|
|
712
|
+
card: dict[str, Any],
|
|
713
|
+
workspace_name: str,
|
|
714
|
+
t: dict[str, str],
|
|
715
|
+
derivation_columns: list[str] | tuple[str, ...] = (),
|
|
716
|
+
) -> str:
|
|
717
|
+
"""Build the per-chart provenance footnote line (see provenance-format.md)."""
|
|
718
|
+
row_count = max(len(card["payload_rows"]) - 1, 0)
|
|
719
|
+
footnote = (
|
|
720
|
+
t["source_label"]
|
|
721
|
+
+ workspace_name
|
|
722
|
+
+ " · "
|
|
723
|
+
+ t["query_label"]
|
|
724
|
+
+ "“"
|
|
725
|
+
+ card["question"]
|
|
726
|
+
+ "”"
|
|
727
|
+
+ t["fetched_at_label"]
|
|
728
|
+
+ card["fetched_at"]
|
|
729
|
+
+ t["rows_label"].format(n=row_count)
|
|
730
|
+
)
|
|
731
|
+
if derivation_columns:
|
|
732
|
+
joined = "、".join(derivation_columns)
|
|
733
|
+
footnote += t["derived_note"].format(cols=joined)
|
|
734
|
+
return footnote
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def build_chart_option(chart: dict[str, Any]) -> dict[str, Any] | None:
|
|
738
|
+
"""Build the ECharts option dict for interactive charts; None for tables."""
|
|
739
|
+
chart_type = chart["chart_type"]
|
|
740
|
+
if chart_type == "table":
|
|
741
|
+
return None
|
|
742
|
+
series_items = chart["series"]
|
|
743
|
+
category_labels = (chart.get("categories") or {}).get("values", [])
|
|
744
|
+
if chart_type in ("bar", "line"):
|
|
745
|
+
return _build_category_option(chart_type, series_items, category_labels)
|
|
746
|
+
if chart_type == "pie":
|
|
747
|
+
pie_points = [
|
|
748
|
+
{"name": str(category_labels[i]), "value": series_items[0]["data"][i]}
|
|
749
|
+
for i in range(min(len(category_labels), len(series_items[0]["data"])))
|
|
750
|
+
]
|
|
751
|
+
return {
|
|
752
|
+
"tooltip": {"trigger": "item"},
|
|
753
|
+
"legend": {"orient": "vertical", "left": "left"},
|
|
754
|
+
"series": [{"type": "pie", "radius": "60%", "data": pie_points}],
|
|
755
|
+
"__vizSeriesFmt": {series_items[0]["name"]: series_items[0].get("value_format", "number")},
|
|
756
|
+
}
|
|
757
|
+
x_values = series_items[0]["data"]
|
|
758
|
+
y_values = series_items[1]["data"]
|
|
759
|
+
points = [[x_values[i], y_values[i]] for i in range(min(len(x_values), len(y_values)))]
|
|
760
|
+
return {
|
|
761
|
+
"tooltip": {"trigger": "item"},
|
|
762
|
+
"grid": {"left": "3%", "right": "4%", "bottom": "3%", "containLabel": True},
|
|
763
|
+
"xAxis": {"type": "value", "name": series_items[0]["name"]},
|
|
764
|
+
"yAxis": {"type": "value", "name": series_items[1]["name"]},
|
|
765
|
+
"series": [{"type": "scatter", "symbolSize": 10, "data": points}],
|
|
766
|
+
"__vizSeriesFmt": {item["name"]: item.get("value_format", "number") for item in series_items},
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
def _build_category_option(chart_type: str, series_items: list[dict[str, Any]], category_labels: list[Any]) -> dict[str, Any]:
|
|
771
|
+
"""Build a bar/line option with per-series type, optional dual value axes.
|
|
772
|
+
|
|
773
|
+
量纲差达到 DUAL_AXIS_MAGNITUDE_RATIO 时自动把低量纲系列放到右轴(量率同图
|
|
774
|
+
不再互相压扁);系列可用 type 声明 bar/line 混合、用 y_axis 显式指定轴。
|
|
775
|
+
"""
|
|
776
|
+
if any(item.get("y_axis") == "right" for item in series_items):
|
|
777
|
+
axis_index_by_series = [1 if item.get("y_axis") == "right" else 0 for item in series_items]
|
|
778
|
+
else:
|
|
779
|
+
axis_index_by_series = _auto_axis_assignment(series_items)
|
|
780
|
+
dual_axis = any(index == 1 for index in axis_index_by_series)
|
|
781
|
+
series: list[dict[str, Any]] = []
|
|
782
|
+
for position, item in enumerate(series_items):
|
|
783
|
+
spec: dict[str, Any] = {
|
|
784
|
+
"name": item["name"],
|
|
785
|
+
"type": item.get("type", chart_type),
|
|
786
|
+
"data": item["data"],
|
|
787
|
+
}
|
|
788
|
+
if dual_axis:
|
|
789
|
+
spec["yAxisIndex"] = axis_index_by_series[position]
|
|
790
|
+
if item.get("stack"):
|
|
791
|
+
spec["stack"] = item["stack"]
|
|
792
|
+
series.append(spec)
|
|
793
|
+
if dual_axis:
|
|
794
|
+
y_axis: dict[str, Any] | list[dict[str, Any]] = [
|
|
795
|
+
{"type": "value", "name": _axis_name(series_items, axis_index_by_series, 0)},
|
|
796
|
+
{"type": "value", "name": _axis_name(series_items, axis_index_by_series, 1)},
|
|
797
|
+
]
|
|
798
|
+
else:
|
|
799
|
+
y_axis = {"type": "value"}
|
|
800
|
+
option: dict[str, Any] = {
|
|
801
|
+
"tooltip": {"trigger": "axis"},
|
|
802
|
+
"grid": {"left": "3%", "right": "4%", "bottom": "3%", "containLabel": True},
|
|
803
|
+
"xAxis": {"type": "category", "data": category_labels},
|
|
804
|
+
"yAxis": y_axis,
|
|
805
|
+
"series": series,
|
|
806
|
+
"__vizSeriesFmt": {item["name"]: item.get("value_format", "number") for item in series_items},
|
|
807
|
+
"__vizPercentAxes": _percent_axis_indices(series_items, axis_index_by_series, dual_axis),
|
|
808
|
+
}
|
|
809
|
+
if len(series_items) > 1:
|
|
810
|
+
option["legend"] = {"data": [item["name"] for item in series_items]}
|
|
811
|
+
if len(category_labels) > DATAZOOM_CATEGORY_THRESHOLD:
|
|
812
|
+
option["dataZoom"] = [{"type": "slider"}, {"type": "inside"}]
|
|
813
|
+
return option
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
def _series_magnitude(data: list[Any]) -> float | None:
|
|
817
|
+
"""Largest absolute numeric value in a series; None when no non-zero number."""
|
|
818
|
+
values = [abs(item) for item in data if isinstance(item, (int, float)) and not isinstance(item, bool) and item != 0]
|
|
819
|
+
return max(values) if values else None
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
def _auto_axis_assignment(series_items: list[dict[str, Any]]) -> list[int]:
|
|
823
|
+
"""Assign series to left/right value axis by magnitude gap (right = 1)."""
|
|
824
|
+
magnitudes = [_series_magnitude(item["data"]) for item in series_items]
|
|
825
|
+
known = [magnitude for magnitude in magnitudes if magnitude]
|
|
826
|
+
if len(known) < 2:
|
|
827
|
+
return [0] * len(series_items)
|
|
828
|
+
largest = max(known)
|
|
829
|
+
smallest = min(known)
|
|
830
|
+
if largest / smallest < DUAL_AXIS_MAGNITUDE_RATIO:
|
|
831
|
+
return [0] * len(series_items)
|
|
832
|
+
threshold = largest / DUAL_AXIS_MAGNITUDE_RATIO
|
|
833
|
+
return [1 if magnitude and magnitude <= threshold else 0 for magnitude in magnitudes]
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def _axis_name(series_items: list[dict[str, Any]], axis_index_by_series: list[int], axis: int) -> str:
|
|
837
|
+
"""Name a value axis after its member series so dual-axis charts stay readable."""
|
|
838
|
+
names = [item["name"] for item, index in zip(series_items, axis_index_by_series) if index == axis]
|
|
839
|
+
label = "/".join(names)
|
|
840
|
+
return label if len(label) <= 20 else label[:19] + "…"
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
def _percent_axis_indices(series_items: list[dict[str, Any]], axis_index_by_series: list[int], dual_axis: bool) -> list[int]:
|
|
844
|
+
"""Axes whose every member series declares value_format=percent."""
|
|
845
|
+
if not dual_axis:
|
|
846
|
+
return [0] if all(item.get("value_format") == "percent" for item in series_items) else []
|
|
847
|
+
result: list[int] = []
|
|
848
|
+
for axis in (0, 1):
|
|
849
|
+
members = [item for item, index in zip(series_items, axis_index_by_series) if index == axis]
|
|
850
|
+
if members and all(item.get("value_format") == "percent" for item in members):
|
|
851
|
+
result.append(axis)
|
|
852
|
+
return result
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
def render_report(report_input: dict[str, Any], echarts_js: str | None = None) -> str:
|
|
856
|
+
"""Validate the whole ledger and assemble the final HTML document."""
|
|
857
|
+
plan_meta = report_input.get("plan_meta")
|
|
858
|
+
_require_mapping(plan_meta, "plan_meta")
|
|
859
|
+
title = _require_text(plan_meta.get("title"), "plan_meta.title")
|
|
860
|
+
workspace_name = _require_text(plan_meta.get("workspace_name"), "plan_meta.workspace_name")
|
|
861
|
+
output_language = plan_meta.get("output_language")
|
|
862
|
+
if output_language not in SUPPORTED_LANGUAGES:
|
|
863
|
+
raise ReportContractError(
|
|
864
|
+
f"plan_meta.output_language 只接受 zh-CN 或 en-US,当前值 {output_language!r} 无效。"
|
|
865
|
+
"请按 references/api-contracts.md 的输出语言规则解析一次并回填后重跑。"
|
|
866
|
+
)
|
|
867
|
+
generated_at = plan_meta.get("generated_at")
|
|
868
|
+
execution_meta = plan_meta.get("execution")
|
|
869
|
+
if execution_meta is not None:
|
|
870
|
+
if not isinstance(execution_meta, dict) or not execution_meta:
|
|
871
|
+
raise ReportContractError('plan_meta.execution 必须是非空对象(如 {"实际轮数": "2", "应用SOP": "无"}),不需要时整键省略。请修正后重跑。')
|
|
872
|
+
for meta_key, meta_value in execution_meta.items():
|
|
873
|
+
_require_text(meta_key, "plan_meta.execution 的键")
|
|
874
|
+
if (
|
|
875
|
+
not isinstance(meta_value, (str, int, float))
|
|
876
|
+
or isinstance(meta_value, bool)
|
|
877
|
+
or (isinstance(meta_value, str) and not meta_value.strip())
|
|
878
|
+
):
|
|
879
|
+
raise ReportContractError(f"plan_meta.execution[{meta_key!r}] 的值必须是非空字符串或数字。请修正后重跑。")
|
|
880
|
+
ui = _ui(output_language)
|
|
881
|
+
|
|
882
|
+
cards = report_input.get("cards")
|
|
883
|
+
_require_list(cards, "cards")
|
|
884
|
+
seen_card_ids: set[str] = set()
|
|
885
|
+
for position, card in enumerate(cards, start=1):
|
|
886
|
+
_require_mapping(card, f"cards 第 {position} 条")
|
|
887
|
+
for key in ("card_id", "question", "fetched_at"):
|
|
888
|
+
_require_text(card.get(key), f"cards 第 {position} 条的 {key}")
|
|
889
|
+
rows = card.get("payload_rows")
|
|
890
|
+
if not isinstance(rows, list) or not rows or not all(isinstance(row, list) for row in rows):
|
|
891
|
+
raise ReportContractError(
|
|
892
|
+
f"卡片 {card.get('card_id', '?')} 的 payload_rows 必须是二维数组且首行为表头,当前不符合。"
|
|
893
|
+
"请把 taskType 8 聚合出的完整行级数据按行填入后重跑。"
|
|
894
|
+
)
|
|
895
|
+
header_width = len(rows[0])
|
|
896
|
+
if header_width == 0:
|
|
897
|
+
raise ReportContractError(
|
|
898
|
+
f"卡片 {card.get('card_id', '?')} 的 payload_rows 表头行为空:字段级溯源按表头列名定位字段,请回填 taskType 8 返回的完整表头后重跑。"
|
|
899
|
+
)
|
|
900
|
+
ragged_rows = [position for position, row in enumerate(rows[1:], start=2) if len(row) != header_width]
|
|
901
|
+
if ragged_rows:
|
|
902
|
+
raise ReportContractError(
|
|
903
|
+
f"卡片 {card.get('card_id', '?')} 的 payload_rows 第 {ragged_rows} 行与表头 {header_width} 列不等长"
|
|
904
|
+
"(第 1 行是表头),溯源无法按列下标对齐。请补齐缺列或删去多余列,保持每行与表头等长后重跑。"
|
|
905
|
+
)
|
|
906
|
+
if card["card_id"] in seen_card_ids:
|
|
907
|
+
raise ReportContractError(
|
|
908
|
+
f"卡片 ID 重复:{card['card_id']} 在 cards 里出现两次。溯源账本要求卡 ID 全局唯一,请给重复的一方换成计划中独立问题的 ID 后重跑。"
|
|
909
|
+
)
|
|
910
|
+
seen_card_ids.add(card["card_id"])
|
|
911
|
+
_header_index(card, f"卡片 {card['card_id']}") # 重名列在加载期即拒绝,与逐图溯源共用同一判定。
|
|
912
|
+
cards_by_id = {card["card_id"]: card for card in cards}
|
|
913
|
+
derivations_by_id = validate_derivations(report_input.get("derivations", []), cards)
|
|
914
|
+
|
|
915
|
+
if "executive_summary" not in report_input:
|
|
916
|
+
raise ReportContractError(
|
|
917
|
+
"渲染输入缺少必填顶层键 executive_summary:总分组装需要全局『总结与建议』区块。"
|
|
918
|
+
"请按 references/derivation-log.md 补充 {'summary': '全局总结文字', 'recommendations': ['至少一条建议']} 后重跑。"
|
|
919
|
+
)
|
|
920
|
+
validate_executive_summary(report_input["executive_summary"])
|
|
921
|
+
if "chapters" not in report_input:
|
|
922
|
+
raise ReportContractError(
|
|
923
|
+
"渲染输入缺少必填顶层键 chapters:报告按总分结构组装,需要章节定义来承载全部图表。"
|
|
924
|
+
"请为每个分析主题建立 {chapter_id, title, digest, chart_ids} 章节,把每张图归入唯一章节后重跑。"
|
|
925
|
+
)
|
|
926
|
+
|
|
927
|
+
charts = report_input.get("charts")
|
|
928
|
+
_require_list(charts, "charts")
|
|
929
|
+
if not charts:
|
|
930
|
+
raise ReportContractError(
|
|
931
|
+
"charts 为空:可视化报告至少需要一张支撑结论的图表或明细表。请回到已批准的查询计划挑选入图证据,填写 charts 数组后重跑。"
|
|
932
|
+
)
|
|
933
|
+
seen_chart_ids: set[str] = set()
|
|
934
|
+
sections_by_chart: dict[str, str] = {}
|
|
935
|
+
interactive_specs: list[dict[str, Any]] = []
|
|
936
|
+
charts = [_hydrate_series(chart, derivations_by_id) for chart in charts]
|
|
937
|
+
for position, chart in enumerate(charts, start=1):
|
|
938
|
+
_require_mapping(chart, f"charts 第 {position} 条")
|
|
939
|
+
_validate_chart_shape(chart, seen_chart_ids)
|
|
940
|
+
seen_chart_ids.add(chart["chart_id"])
|
|
941
|
+
card = cards_by_id.get(chart["source_card_id"])
|
|
942
|
+
if card is None:
|
|
943
|
+
raise ReportContractError(
|
|
944
|
+
f"图表 {chart['chart_id']} 的 source_card_id {chart['source_card_id']!r} 不在 cards 账本里。"
|
|
945
|
+
"每张图必须指向一张已取数成功的卡片;请核对卡 ID 或补齐对应取数后重跑。"
|
|
946
|
+
)
|
|
947
|
+
used_columns = validate_chart_tracing(chart, card, derivations_by_id)
|
|
948
|
+
footnote = build_footnote(card, workspace_name, ui, derivation_columns=used_columns)
|
|
949
|
+
sections_by_chart[chart["chart_id"]] = _chart_section_html(chart, footnote, ui)
|
|
950
|
+
option = build_chart_option(chart)
|
|
951
|
+
if option is not None:
|
|
952
|
+
interactive_specs.append({"domId": chart["chart_id"], "option": option})
|
|
953
|
+
|
|
954
|
+
chapters = report_input["chapters"]
|
|
955
|
+
validate_chapter_structure(chapters, charts)
|
|
956
|
+
validate_claims(report_input.get("claims"), cards, chapters, charts)
|
|
957
|
+
|
|
958
|
+
excluded_paths = report_input.get("excluded_paths", [])
|
|
959
|
+
appendix_html, appendix_cards = _appendix_section_html(cards, derivations_by_id, excluded_paths, execution_meta, ui)
|
|
960
|
+
echarts_library = echarts_js if echarts_js is not None else load_echarts_asset()
|
|
961
|
+
body_blocks: list[str] = []
|
|
962
|
+
if len(chapters) >= 2:
|
|
963
|
+
body_blocks.append(_toc_html(chapters, ui))
|
|
964
|
+
body_blocks.append(_executive_section_html(report_input["executive_summary"], ui))
|
|
965
|
+
for chapter in chapters:
|
|
966
|
+
chapter_sections = [sections_by_chart[chart_id] for chart_id in chapter["chart_ids"]]
|
|
967
|
+
body_blocks.append(_chapter_section_html(chapter, chapter_sections, ui))
|
|
968
|
+
return _document_html(
|
|
969
|
+
title,
|
|
970
|
+
workspace_name,
|
|
971
|
+
generated_at,
|
|
972
|
+
output_language,
|
|
973
|
+
ui,
|
|
974
|
+
body_blocks,
|
|
975
|
+
appendix_html,
|
|
976
|
+
echarts_library,
|
|
977
|
+
interactive_specs,
|
|
978
|
+
appendix_cards,
|
|
979
|
+
)
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
def write_report(html_document: str, output_path: str | Path) -> Path:
|
|
983
|
+
"""Persist the finished document with deterministic newlines."""
|
|
984
|
+
path = Path(output_path)
|
|
985
|
+
path.write_text(html_document, encoding="utf-8", newline="\n")
|
|
986
|
+
return path
|
|
987
|
+
|
|
988
|
+
|
|
989
|
+
def main(argv: list[str] | None = None) -> int:
|
|
990
|
+
parser = argparse.ArgumentParser(description="组装自包含单文件 HTML 可视化分析报告(纯标准库、无网络请求)")
|
|
991
|
+
parser.add_argument("input_json", help="溯源账本与图表规格 JSON 文件,格式见 references/derivation-log.md")
|
|
992
|
+
parser.add_argument("-o", "--output", required=True, help="输出的单文件 HTML 路径")
|
|
993
|
+
args = parser.parse_args(argv)
|
|
994
|
+
try:
|
|
995
|
+
report_input = load_input(args.input_json)
|
|
996
|
+
document = render_report(report_input)
|
|
997
|
+
output_path = write_report(document, args.output)
|
|
998
|
+
except ReportContractError as exc:
|
|
999
|
+
sys.stderr.write(f"[datarc-viz-analysis-report] 组装失败:{exc}\n")
|
|
1000
|
+
return 1
|
|
1001
|
+
chart_count = len(report_input.get("charts", []))
|
|
1002
|
+
card_count = len(report_input.get("cards", []))
|
|
1003
|
+
sys.stdout.write(f"组装完成:{chart_count} 张图表 · {card_count} 张来源卡 · 已写出 {output_path}\n")
|
|
1004
|
+
return 0
|
|
1005
|
+
|
|
1006
|
+
|
|
1007
|
+
def _hydrate_series(chart: Any, derivations: dict[str, dict[str, Any]]) -> Any:
|
|
1008
|
+
"""Fill series that reference a derivation with its recomputed values, before any chart validation."""
|
|
1009
|
+
if not isinstance(chart, dict) or not isinstance(chart.get("series"), list):
|
|
1010
|
+
return chart
|
|
1011
|
+
series = []
|
|
1012
|
+
for item in chart["series"]:
|
|
1013
|
+
if isinstance(item, dict) and "data" not in item and isinstance(item.get("derivation_id"), str):
|
|
1014
|
+
derived = derivations.get(item["derivation_id"])
|
|
1015
|
+
if derived is not None:
|
|
1016
|
+
item = {**item, "data": derived["output_values"]}
|
|
1017
|
+
series.append(item)
|
|
1018
|
+
return {**chart, "series": series}
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
def _compute_derivation(entry: dict[str, Any], cards: dict[str, dict[str, Any]]) -> dict[str, Any]:
|
|
1022
|
+
"""Recompute a built-in from source rows; previous-period comparisons follow the declared key order."""
|
|
1023
|
+
operation = entry["method"]["type"]
|
|
1024
|
+
fields, sources, keys = entry["input_fields"], entry["source_card_ids"], entry["keys"]
|
|
1025
|
+
label = f"派生记录 {entry['derivation_id']}"
|
|
1026
|
+
field_count = 2 if operation in ("ratio", "difference") else 1
|
|
1027
|
+
if len(fields) != field_count or len(sources) not in {1, field_count} or entry["key_card_id"] not in sources:
|
|
1028
|
+
raise ReportContractError(f"{label} 的运算参数不匹配。请按 {operation} 的操作数顺序指定字段和来源卡后重跑。")
|
|
1029
|
+
if not isinstance(keys, list) or not keys or any(type(key) not in (str, int, float) for key in keys) or len(set(keys)) != len(keys):
|
|
1030
|
+
raise ReportContractError(f"{label} 的 keys 需要唯一的分组键。请核对来源行并按展示顺序填写后重跑。")
|
|
1031
|
+
operands = []
|
|
1032
|
+
for position, field in enumerate(fields):
|
|
1033
|
+
card = cards[sources[0] if len(sources) == 1 else sources[position]]
|
|
1034
|
+
index = _header_index(card, label)
|
|
1035
|
+
if entry["key_field"] not in index or field not in index:
|
|
1036
|
+
raise ReportContractError(f"{label} 在来源卡 {card['card_id']} 中找不到键列或字段 {field}。请按实际表头重跑。")
|
|
1037
|
+
column = {}
|
|
1038
|
+
for row in card["payload_rows"][1:]:
|
|
1039
|
+
key, value = row[index[entry["key_field"]]], row[index[field]]
|
|
1040
|
+
if type(key) not in (str, int, float) or key in column:
|
|
1041
|
+
raise ReportContractError(f"{label} 的来源键缺失或重复。请先按键聚合到唯一一行再重跑。")
|
|
1042
|
+
if value is not None and (type(value) not in (int, float) or (isinstance(value, float) and not math.isfinite(value))):
|
|
1043
|
+
raise ReportContractError(f"{label} 的 {field} 含非数值。请核对指标,保留真实缺失值后重跑。")
|
|
1044
|
+
column[key] = value
|
|
1045
|
+
if any(key not in column for key in keys):
|
|
1046
|
+
raise ReportContractError(f"{label} 有分组键未匹配来源卡 {card['card_id']}。请核对两个来源的粒度和键值后重跑。")
|
|
1047
|
+
operands.append(column)
|
|
1048
|
+
|
|
1049
|
+
left = operands[0]
|
|
1050
|
+
if operation == "growth_rate":
|
|
1051
|
+
right = dict(zip(keys, [None, *(left[key] for key in keys)], strict=False))
|
|
1052
|
+
elif operation == "share":
|
|
1053
|
+
total = None if None in left.values() else sum(left.values())
|
|
1054
|
+
if isinstance(total, float) and not math.isfinite(total):
|
|
1055
|
+
raise ReportContractError(f"{label} 的分母合计超出数值范围。请调整指标单位后重跑。")
|
|
1056
|
+
right = dict.fromkeys(keys, total)
|
|
1057
|
+
else:
|
|
1058
|
+
right = operands[1]
|
|
1059
|
+
outputs = []
|
|
1060
|
+
for key in keys:
|
|
1061
|
+
current, reference = left[key], right[key]
|
|
1062
|
+
value = None
|
|
1063
|
+
if current is not None and reference is not None:
|
|
1064
|
+
try:
|
|
1065
|
+
if operation == "difference":
|
|
1066
|
+
value = current - reference
|
|
1067
|
+
elif reference != 0:
|
|
1068
|
+
numerator = current - reference if operation == "growth_rate" else current
|
|
1069
|
+
value = numerator / reference
|
|
1070
|
+
except OverflowError as exc:
|
|
1071
|
+
raise ReportContractError(f"{label} 的结果超出数值范围。请调整指标单位后重跑。") from exc
|
|
1072
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
1073
|
+
raise ReportContractError(f"{label} 的结果超出数值范围。请调整指标单位后重跑。")
|
|
1074
|
+
outputs.append(value)
|
|
1075
|
+
if "output_values" in entry and (
|
|
1076
|
+
not isinstance(entry["output_values"], list) or len(entry["output_values"]) != len(keys) or _mismatch_indices(entry["output_values"], outputs)
|
|
1077
|
+
):
|
|
1078
|
+
raise ReportContractError(f"{label} 的 output_values 与来源行复算不一致(顺序敏感)。请检查字段、键序或省略手填结果后重跑。")
|
|
1079
|
+
return {**entry, "output_values": outputs, "method": {"type": operation, "expression": BUILTIN_FORMULAS[operation].format(*fields)}}
|
|
1080
|
+
|
|
1081
|
+
|
|
1082
|
+
def _trace_series_derived(
|
|
1083
|
+
chart_id: str,
|
|
1084
|
+
label: str,
|
|
1085
|
+
series_item: dict[str, Any],
|
|
1086
|
+
derivation: dict[str, Any],
|
|
1087
|
+
cat_values: list[Any] | None,
|
|
1088
|
+
cat_keys: list[Any] | None,
|
|
1089
|
+
data: list[Any],
|
|
1090
|
+
) -> None:
|
|
1091
|
+
"""Order-sensitive check of a derivation-backed series against its keys."""
|
|
1092
|
+
outputs = derivation["output_values"]
|
|
1093
|
+
keys = derivation["keys"]
|
|
1094
|
+
if len(data) != len(outputs):
|
|
1095
|
+
raise ReportContractError(
|
|
1096
|
+
"{label} 声明了派生记录 {derivation_id},但数据长度与 output_values 不一致。请逐项对齐后重跑。".format(
|
|
1097
|
+
label=label, derivation_id=derivation["derivation_id"]
|
|
1098
|
+
)
|
|
1099
|
+
)
|
|
1100
|
+
mismatched = _mismatch_indices(data, outputs)
|
|
1101
|
+
if mismatched:
|
|
1102
|
+
raise ReportContractError(
|
|
1103
|
+
"越源数值:{label} 与派生记录 {derivation_id} 的 output_values 在第 {mismatched} 项不一致(顺序敏感)。"
|
|
1104
|
+
"派生数据必须按 keys 顺序逐项使用,请回填后重跑。".format(label=label, derivation_id=derivation["derivation_id"], mismatched=mismatched)
|
|
1105
|
+
)
|
|
1106
|
+
reference_keys = cat_values if cat_values is not None else cat_keys
|
|
1107
|
+
if reference_keys is not None:
|
|
1108
|
+
if len(keys) != len(reference_keys):
|
|
1109
|
+
raise ReportContractError(
|
|
1110
|
+
"{label} 的派生记录 {derivation_id} keys 长度与图表类目不一致。请对齐后重跑。".format(
|
|
1111
|
+
label=label, derivation_id=derivation["derivation_id"]
|
|
1112
|
+
)
|
|
1113
|
+
)
|
|
1114
|
+
mismatched_keys = _mismatch_indices(keys, reference_keys)
|
|
1115
|
+
if mismatched_keys:
|
|
1116
|
+
raise ReportContractError(
|
|
1117
|
+
"{label} 的派生记录 {derivation_id} keys 与图表类目在第 {mismatched_keys} 项不一致(顺序敏感)。"
|
|
1118
|
+
"派生数据的分组键必须与类目逐项对应后重跑。".format(
|
|
1119
|
+
label=label, derivation_id=derivation["derivation_id"], mismatched_keys=mismatched_keys
|
|
1120
|
+
)
|
|
1121
|
+
)
|
|
1122
|
+
|
|
1123
|
+
|
|
1124
|
+
def _trace_table(
|
|
1125
|
+
chart: dict[str, Any],
|
|
1126
|
+
card_id: str,
|
|
1127
|
+
index: dict[str, int],
|
|
1128
|
+
body_rows: list[list[Any]],
|
|
1129
|
+
derivations_by_id: dict[str, Any],
|
|
1130
|
+
used_columns: list[str],
|
|
1131
|
+
) -> None:
|
|
1132
|
+
"""Row-tuple tracing for table charts with per-column field binding."""
|
|
1133
|
+
chart_id = chart["chart_id"]
|
|
1134
|
+
columns = chart["columns"]
|
|
1135
|
+
field_indices: list[int | None] = []
|
|
1136
|
+
deriv_positions: set[int] = set()
|
|
1137
|
+
for position, column in enumerate(columns):
|
|
1138
|
+
label = f"图表 {chart_id} 列『{column['header']}』"
|
|
1139
|
+
derivation = _resolve_derivation(column, label, chart_id, derivations_by_id, used_columns)
|
|
1140
|
+
if derivation is None:
|
|
1141
|
+
field_indices.append(_column_index(column, index, label + " 的 columns", card_id))
|
|
1142
|
+
continue
|
|
1143
|
+
# 派生列按文档可省略 field:占位即可,取值由下方键列与 output_values 校验完成。
|
|
1144
|
+
field_indices.append(None)
|
|
1145
|
+
deriv_positions.add(position)
|
|
1146
|
+
if derivation["key_card_id"] != card_id:
|
|
1147
|
+
raise ReportContractError(
|
|
1148
|
+
f"{label} 引用的派生记录 {derivation['derivation_id']} 的 key_card_id 不是本图来源卡,"
|
|
1149
|
+
"行级对齐要求引用派生的图表与分组键所在卡同源(见 references/derivation-log.md 的 key_card_id 契约)。"
|
|
1150
|
+
"请调整派生记录的 key_card_id 或图表 source_card_id 后重跑。"
|
|
1151
|
+
)
|
|
1152
|
+
if deriv_positions:
|
|
1153
|
+
# 每个派生记录独立解析自己的键列位置:不同 key_field 的派生共用首个键列,
|
|
1154
|
+
# 会把未对齐的派生值挂到错误行(评审复现:渠道派生 + 月份派生、仅提供渠道键列时仍被放行)。
|
|
1155
|
+
key_position_by_derivation: dict[str, int] = {}
|
|
1156
|
+
for position in sorted(deriv_positions):
|
|
1157
|
+
label = f"图表 {chart_id} 列『{columns[position]['header']}』"
|
|
1158
|
+
derivation = derivations_by_id[columns[position]["derivation_id"]]
|
|
1159
|
+
derivation_id = derivation["derivation_id"]
|
|
1160
|
+
if derivation_id in key_position_by_derivation:
|
|
1161
|
+
continue
|
|
1162
|
+
key_column_position = next(
|
|
1163
|
+
(k for k, other in enumerate(columns) if other.get("field") == derivation["key_field"]),
|
|
1164
|
+
None,
|
|
1165
|
+
)
|
|
1166
|
+
if key_column_position is None:
|
|
1167
|
+
raise ReportContractError(
|
|
1168
|
+
f"{label} 使用派生记录 {derivation_id}(分组键 {derivation['key_field']}),"
|
|
1169
|
+
f"但表格没有 field={derivation['key_field']} 的键列可对齐行序。"
|
|
1170
|
+
"请为该派生的分组键单独增加一列后重跑。"
|
|
1171
|
+
)
|
|
1172
|
+
key_position_by_derivation[derivation_id] = key_column_position
|
|
1173
|
+
validated_key_orders: set[str] = set()
|
|
1174
|
+
for position in sorted(deriv_positions):
|
|
1175
|
+
label = f"图表 {chart_id} 列『{columns[position]['header']}』"
|
|
1176
|
+
entry = derivations_by_id[columns[position]["derivation_id"]]
|
|
1177
|
+
derivation_id = entry["derivation_id"]
|
|
1178
|
+
if derivation_id not in validated_key_orders:
|
|
1179
|
+
key_values = [row[key_position_by_derivation[derivation_id]] for row in chart["rows"]]
|
|
1180
|
+
mismatched_keys = _mismatch_indices(key_values, entry["keys"])
|
|
1181
|
+
if mismatched_keys:
|
|
1182
|
+
raise ReportContractError(
|
|
1183
|
+
f"图表 {chart_id} 键列与派生记录 {derivation_id} 的 keys 在第 {mismatched_keys} 行不一致(顺序敏感)。请对齐后重跑。"
|
|
1184
|
+
)
|
|
1185
|
+
validated_key_orders.add(derivation_id)
|
|
1186
|
+
cells = [row[position] for row in chart["rows"]]
|
|
1187
|
+
if len(cells) != len(entry["output_values"]):
|
|
1188
|
+
raise ReportContractError(f"{label} 数据长度与派生记录 {derivation_id} 的 output_values 不一致。请逐行对齐后重跑。")
|
|
1189
|
+
mismatched = _mismatch_indices(cells, entry["output_values"])
|
|
1190
|
+
if mismatched:
|
|
1191
|
+
raise ReportContractError(
|
|
1192
|
+
f"越源数值:{label} 与派生记录 {derivation_id} 的 output_values 在第 {mismatched} 行不一致(顺序敏感)。请回填后重跑。"
|
|
1193
|
+
)
|
|
1194
|
+
for row_number, chart_row in enumerate(chart["rows"], start=1):
|
|
1195
|
+
found = any(
|
|
1196
|
+
all(
|
|
1197
|
+
chart_row[k] is None or (k in deriv_positions) or _same_value(card_row[field_indices[k]], chart_row[k])
|
|
1198
|
+
for k in range(len(field_indices))
|
|
1199
|
+
)
|
|
1200
|
+
for card_row in body_rows
|
|
1201
|
+
)
|
|
1202
|
+
if not found:
|
|
1203
|
+
raise ReportContractError(
|
|
1204
|
+
f"越源行:图表 {chart_id} 第 {row_number} 行的绑定列取值组合未在来源卡 {card_id} 的任何同一行出现。"
|
|
1205
|
+
"表格明细必须逐行来自来源卡 payload,请按行复制后重跑。"
|
|
1206
|
+
)
|
|
1207
|
+
|
|
1208
|
+
|
|
1209
|
+
def _header_index(card: dict[str, Any], label: str) -> dict[str, int]:
|
|
1210
|
+
"""Map header names to column positions; reject duplicates loudly."""
|
|
1211
|
+
index: dict[str, int] = {}
|
|
1212
|
+
for position, cell in enumerate(card["payload_rows"][0]):
|
|
1213
|
+
name = str(cell)
|
|
1214
|
+
if name in index:
|
|
1215
|
+
raise ReportContractError(
|
|
1216
|
+
f"{label} 表头存在重名列表头 {name!r},字段级溯源无法定位唯一列。"
|
|
1217
|
+
"请先在账本里为重名列起唯一别名(并同步修改引用它的 charts field)后重跑。"
|
|
1218
|
+
)
|
|
1219
|
+
index[name] = position
|
|
1220
|
+
return index
|
|
1221
|
+
|
|
1222
|
+
|
|
1223
|
+
def _column_index(holder: dict[str, Any], index: dict[str, int], label: str, card_id: str) -> int:
|
|
1224
|
+
"""Resolve a bound source column; missing binding is a hard error."""
|
|
1225
|
+
field = holder.get("field")
|
|
1226
|
+
if not isinstance(field, str) or not field:
|
|
1227
|
+
raise ReportContractError(
|
|
1228
|
+
f"{label} 缺少 field 列绑定:字段级溯源要求每个直接取值的类目/系列/表格列都声明来源表头名。"
|
|
1229
|
+
"请从来源卡 payload_rows 首行回填对应列名后重跑。"
|
|
1230
|
+
)
|
|
1231
|
+
if field not in index:
|
|
1232
|
+
raise ReportContractError(
|
|
1233
|
+
f"{label} 绑定的 field {field!r} 不在来源卡 {card_id} 表头里(可用列:{sorted(index)})。请改用 payload_rows 首行的原列名后重跑。"
|
|
1234
|
+
)
|
|
1235
|
+
return index[field]
|
|
1236
|
+
|
|
1237
|
+
|
|
1238
|
+
def _resolve_derivation(
|
|
1239
|
+
holder: dict[str, Any],
|
|
1240
|
+
label: str,
|
|
1241
|
+
chart_id: str,
|
|
1242
|
+
derivations_by_id: dict[str, dict[str, Any]],
|
|
1243
|
+
used_columns: list[str],
|
|
1244
|
+
) -> dict[str, Any] | None:
|
|
1245
|
+
"""Resolve an optional derivation_id declaration; track consumed columns."""
|
|
1246
|
+
derivation_id = holder.get("derivation_id")
|
|
1247
|
+
if not derivation_id:
|
|
1248
|
+
return None
|
|
1249
|
+
derivation = derivations_by_id.get(derivation_id)
|
|
1250
|
+
if derivation is None:
|
|
1251
|
+
raise ReportContractError(
|
|
1252
|
+
f"{label} 声明了派生记录 {derivation_id},但 derivations 里没有这条记录。"
|
|
1253
|
+
"请补齐该派生记录(九键格式见 references/derivation-log.md)后重跑。"
|
|
1254
|
+
)
|
|
1255
|
+
column = derivation["output_column"]
|
|
1256
|
+
if column not in used_columns:
|
|
1257
|
+
used_columns.append(column)
|
|
1258
|
+
return derivation
|
|
1259
|
+
|
|
1260
|
+
|
|
1261
|
+
def _same_value(left: Any, right: Any) -> bool:
|
|
1262
|
+
"""Compare ledger cells with plotted values; numbers compare numerically.
|
|
1263
|
+
|
|
1264
|
+
Integers compare exactly (no 2**53 float blurring); floats allow a tight
|
|
1265
|
+
relative tolerance so payload noise like 0.1 + 0.2 does not false-reject,
|
|
1266
|
+
while any material difference is still caught.
|
|
1267
|
+
"""
|
|
1268
|
+
if isinstance(left, bool) != isinstance(right, bool):
|
|
1269
|
+
return False
|
|
1270
|
+
if isinstance(left, int) and isinstance(right, int):
|
|
1271
|
+
return left == right
|
|
1272
|
+
if isinstance(left, (int, float)) and isinstance(right, (int, float)):
|
|
1273
|
+
return math.isclose(float(left), float(right), rel_tol=1e-9, abs_tol=1e-12)
|
|
1274
|
+
if left is None or right is None:
|
|
1275
|
+
return left is None and right is None
|
|
1276
|
+
return left == right
|
|
1277
|
+
|
|
1278
|
+
|
|
1279
|
+
def _mismatch_indices(left: list[Any], right: list[Any]) -> list[int]:
|
|
1280
|
+
"""1-based positions where two order-sensitive lists differ, using ledger-cell comparison."""
|
|
1281
|
+
return [i + 1 for i, (a, b) in enumerate(zip(left, right)) if not _same_value(a, b)]
|
|
1282
|
+
|
|
1283
|
+
|
|
1284
|
+
def _row_tuple_exists(body_rows: list[list[Any]], bindings: list[tuple[str, Any, int]]) -> bool:
|
|
1285
|
+
"""Whether all named-column (field, value, column) bindings coexist in a single payload row."""
|
|
1286
|
+
return any(all(_same_value(row[column], value) for _, value, column in bindings) for row in body_rows)
|
|
1287
|
+
|
|
1288
|
+
|
|
1289
|
+
def _validate_chart_shape(chart: dict[str, Any], seen_ids: set[str]) -> None:
|
|
1290
|
+
"""Enforce per-chart-type structural rules before tracing and rendering."""
|
|
1291
|
+
chart_type = chart.get("chart_type")
|
|
1292
|
+
if chart_type not in SUPPORTED_CHART_TYPES:
|
|
1293
|
+
supported = "/".join(SUPPORTED_CHART_TYPES)
|
|
1294
|
+
raise ReportContractError(
|
|
1295
|
+
f"图表 {chart.get('chart_id', '?')} 的 chart_type {chart_type!r} 不支持;可选值:{supported}。"
|
|
1296
|
+
"选型依据见 references/html-template.md,调整后重跑。"
|
|
1297
|
+
)
|
|
1298
|
+
chart_id = _require_text(chart.get("chart_id"), "charts[].chart_id")
|
|
1299
|
+
if chart_id in seen_ids:
|
|
1300
|
+
raise ReportContractError(f"图表 ID 重复:{chart_id} 出现两次,DOM 挂载点会冲突。请改名其中一个后重跑。")
|
|
1301
|
+
_require_text(chart.get("title"), f"图表 {chart_id} 的 title")
|
|
1302
|
+
_require_text(chart.get("interpretation"), f"图表 {chart_id} 的 interpretation")
|
|
1303
|
+
evidence_role = chart.get("evidence_role")
|
|
1304
|
+
if evidence_role not in SUPPORTED_EVIDENCE_ROLES:
|
|
1305
|
+
raise ReportContractError(
|
|
1306
|
+
f"图表 {chart_id} 缺少合法的 evidence_role(可选值:{'/'.join(SUPPORTED_EVIDENCE_ROLES)})。"
|
|
1307
|
+
"每张图都必须声明它在证据链中的角色:primary 主证据 / comparator 对比基准 / diagnostic 拆解诊断 / validation 交叉验证。请按已批准的 chapterEvidencePlan 回填后重跑。"
|
|
1308
|
+
)
|
|
1309
|
+
if not isinstance(chart.get("source_card_id"), str) or not chart["source_card_id"]:
|
|
1310
|
+
raise ReportContractError(f"图表 {chart_id} 缺少 source_card_id:每张图必须声明主来源卡用于脚注与溯源。请回填账本中的卡 ID 后重跑。")
|
|
1311
|
+
if chart_type == "table":
|
|
1312
|
+
_validate_table_shape(chart, chart_id)
|
|
1313
|
+
return
|
|
1314
|
+
categories = chart.get("categories")
|
|
1315
|
+
if chart_type == "scatter" and not categories:
|
|
1316
|
+
categories = None
|
|
1317
|
+
if categories is None:
|
|
1318
|
+
if chart_type != "scatter":
|
|
1319
|
+
raise ReportContractError(
|
|
1320
|
+
f"图表 {chart_id} 需要 categories.values 作为类目轴/占比标签,当前缺失。请从来源卡 payload 提取该维度列后重跑。"
|
|
1321
|
+
)
|
|
1322
|
+
length = 0
|
|
1323
|
+
else:
|
|
1324
|
+
if not isinstance(categories, dict) or not isinstance(categories.get("values"), list) or not categories["values"]:
|
|
1325
|
+
raise ReportContractError(
|
|
1326
|
+
f"图表 {chart_id} 需要 categories.values 作为类目轴/占比标签,当前缺失。请从来源卡 payload 提取该维度列后重跑。"
|
|
1327
|
+
)
|
|
1328
|
+
if not categories.get("derivation_id") and (not isinstance(categories.get("field"), str) or not categories["field"]):
|
|
1329
|
+
raise ReportContractError(
|
|
1330
|
+
f"图表 {chart_id} 的 categories 缺少 field 列绑定:字段级溯源要求类目轴声明来源表头名(payload_rows 首行原列名)。请回填后重跑。"
|
|
1331
|
+
)
|
|
1332
|
+
length = len(categories["values"])
|
|
1333
|
+
series_items = chart.get("series")
|
|
1334
|
+
if not isinstance(series_items, list) or not series_items:
|
|
1335
|
+
raise ReportContractError(f"图表 {chart_id} 至少需要一个系列数据。请从对应卡片的 payload 提取数据列后重跑。")
|
|
1336
|
+
if chart_type == "pie" and len(series_items) > 1:
|
|
1337
|
+
raise ReportContractError(
|
|
1338
|
+
f"饼图 {chart_id} 只支持一个系列(当前 {len(series_items)} 个);类别过多时建议改横向条形图,选型依据见 references/html-template.md。"
|
|
1339
|
+
)
|
|
1340
|
+
if chart_type == "pie" and length > MAX_PIE_CATEGORIES:
|
|
1341
|
+
raise ReportContractError(
|
|
1342
|
+
f"饼图 {chart_id} 有 {length} 个类别,超过 {MAX_PIE_CATEGORIES} 个上限(references/html-template.md 的选型约定)。"
|
|
1343
|
+
"请把尾部类别合并为「其他」并以 derivation 记账,或改用横向条形图后重跑。"
|
|
1344
|
+
)
|
|
1345
|
+
if chart_type == "scatter" and len(series_items) != 2:
|
|
1346
|
+
raise ReportContractError(f"散点图 {chart_id} 需要恰好 2 个系列分别作为 X/Y 轴(当前 {len(series_items)} 个)。请拆分或合并数据序列后重跑。")
|
|
1347
|
+
names: list[Any] = []
|
|
1348
|
+
for series_item in series_items:
|
|
1349
|
+
if not isinstance(series_item, dict):
|
|
1350
|
+
raise ReportContractError(f"图表 {chart_id} 的每个系列都应是对象(含 name 与 data 字段)。")
|
|
1351
|
+
name = series_item.get("name")
|
|
1352
|
+
names.append(name)
|
|
1353
|
+
data = series_item.get("data")
|
|
1354
|
+
if not isinstance(data, list) or (length and len(data) != length):
|
|
1355
|
+
shown = name if name else "(未命名系列)"
|
|
1356
|
+
raise ReportContractError(f"图表 {chart_id} 系列『{shown}』的数据长度与类目轴({length} 项)不一致。请保持每个系列与类目一一对应后重跑。")
|
|
1357
|
+
if any(not isinstance(name, str) or not name for name in names):
|
|
1358
|
+
raise ReportContractError(f"图表 {chart_id} 的每个系列都需要非空 name 以供图例与脚注引用。请补全后重跑。")
|
|
1359
|
+
for series_item in series_items:
|
|
1360
|
+
if not series_item.get("derivation_id") and (not isinstance(series_item.get("field"), str) or not series_item["field"]):
|
|
1361
|
+
raise ReportContractError(
|
|
1362
|
+
f"图表 {chart_id} 系列『{series_item.get('name', '(未命名)')}』缺少 series field 列绑定:"
|
|
1363
|
+
"字段级溯源要求系列声明来源表头名(payload_rows 首行原列名)。请回填后重跑。"
|
|
1364
|
+
)
|
|
1365
|
+
if len(set(names)) != len(names):
|
|
1366
|
+
raise ReportContractError(f"图表 {chart_id} 存在同名的多个系列,图例无法区分。请为每列起不同名称后重跑。")
|
|
1367
|
+
for series_item in series_items:
|
|
1368
|
+
shown = series_item.get("name", "(未命名)")
|
|
1369
|
+
declared_type = series_item.get("type")
|
|
1370
|
+
if declared_type is not None:
|
|
1371
|
+
if chart_type not in ("bar", "line") or declared_type not in SUPPORTED_SERIES_TYPES:
|
|
1372
|
+
raise ReportContractError(
|
|
1373
|
+
f"图表 {chart_id} 系列『{shown}』声明的 type {declared_type!r} 不可用:只有 bar/line 图允许系列级 type 覆盖(用于量率混合图)。请移除该键或修正取值后重跑。"
|
|
1374
|
+
)
|
|
1375
|
+
y_axis = series_item.get("y_axis")
|
|
1376
|
+
if y_axis is not None and (chart_type not in ("bar", "line") or y_axis not in SUPPORTED_Y_AXES):
|
|
1377
|
+
raise ReportContractError(
|
|
1378
|
+
f"图表 {chart_id} 系列『{shown}』声明的 y_axis {y_axis!r} 不可用:只有 bar/line 图允许声明 left/right 值轴。请移除该键或修正取值后重跑。"
|
|
1379
|
+
)
|
|
1380
|
+
value_format = series_item.get("value_format")
|
|
1381
|
+
if value_format is not None and value_format not in SUPPORTED_VALUE_FORMATS:
|
|
1382
|
+
raise ReportContractError(
|
|
1383
|
+
f"图表 {chart_id} 系列『{shown}』的 value_format 只接受 {'/'.join(SUPPORTED_VALUE_FORMATS)},当前为 {value_format!r}。请修正后重跑。"
|
|
1384
|
+
)
|
|
1385
|
+
if series_item.get("stack") is not None and (
|
|
1386
|
+
chart_type not in ("bar", "line") or not isinstance(series_item["stack"], str) or not series_item["stack"]
|
|
1387
|
+
):
|
|
1388
|
+
raise ReportContractError(
|
|
1389
|
+
f"图表 {chart_id} 系列『{shown}』的 stack 必须是非空字符串(堆积组名),且仅 bar/line 图支持堆积。请修正后重跑。"
|
|
1390
|
+
)
|
|
1391
|
+
|
|
1392
|
+
|
|
1393
|
+
def _validate_table_shape(chart: dict[str, Any], chart_id: str) -> None:
|
|
1394
|
+
"""Structural rules specific to table charts."""
|
|
1395
|
+
columns = chart.get("columns")
|
|
1396
|
+
if not isinstance(columns, list) or not columns:
|
|
1397
|
+
raise ReportContractError(f"表格图 {chart_id} 缺少非空 columns 数组。请按 references/html-template.md 的字段说明补齐后重跑。")
|
|
1398
|
+
headers: list[Any] = []
|
|
1399
|
+
for column in columns:
|
|
1400
|
+
if not isinstance(column, dict) or not isinstance(column.get("header"), str) or not column["header"]:
|
|
1401
|
+
raise ReportContractError(f"表格图 {chart_id} 的每一列都需要非空字符串 header。请补齐列名后重跑。")
|
|
1402
|
+
if not column.get("derivation_id") and (not isinstance(column.get("field"), str) or not column["field"]):
|
|
1403
|
+
raise ReportContractError(
|
|
1404
|
+
f"表格图 {chart_id} 列『{column['header']}』缺少 field 列绑定:字段级溯源要求每列声明来源表头名。请回填后重跑。"
|
|
1405
|
+
)
|
|
1406
|
+
headers.append(column["header"])
|
|
1407
|
+
rows = chart.get("rows")
|
|
1408
|
+
if not isinstance(rows, list) or not rows:
|
|
1409
|
+
raise ReportContractError(f"表格图 {chart_id} 缺少非空 rows 数组。至少保留一行明细数据后重跑。")
|
|
1410
|
+
mismatched = [position for position, row in enumerate(rows, start=1) if not isinstance(row, list) or len(row) != len(columns)]
|
|
1411
|
+
if mismatched:
|
|
1412
|
+
expected = f"columns 共 {len(columns)} 列"
|
|
1413
|
+
raise ReportContractError(f"表格图 {chart_id} 第 {mismatched} 行的列数与表头不一致({expected})。请对齐每行列数或删去多余空列后重跑。")
|
|
1414
|
+
|
|
1415
|
+
|
|
1416
|
+
def _executive_section_html(executive_summary: dict[str, Any], t: dict[str, str]) -> str:
|
|
1417
|
+
"""Emit the leading total block: global summary plus recommendations."""
|
|
1418
|
+
summary = escape(executive_summary["summary"])
|
|
1419
|
+
items = "".join("<li>" + escape(str(item)) + "</li>" for item in executive_summary["recommendations"])
|
|
1420
|
+
return (
|
|
1421
|
+
'<section class="executive-summary">\n<h2>'
|
|
1422
|
+
+ t["summary_title"]
|
|
1423
|
+
+ "</h2>\n"
|
|
1424
|
+
+ '<p class="summary">'
|
|
1425
|
+
+ summary
|
|
1426
|
+
+ '</p>\n<p class="recommendations-title">'
|
|
1427
|
+
+ t["recommendations"]
|
|
1428
|
+
+ '</p>\n<ol class="recommendations">'
|
|
1429
|
+
+ items
|
|
1430
|
+
+ "</ol>\n</section>"
|
|
1431
|
+
)
|
|
1432
|
+
|
|
1433
|
+
|
|
1434
|
+
def _toc_html(chapters: list[dict[str, Any]], t: dict[str, str]) -> str:
|
|
1435
|
+
"""Emit a linked table of contents when the report has multiple chapters."""
|
|
1436
|
+
items = "".join(
|
|
1437
|
+
'<li><a href="#chapter-' + escape(chapter["chapter_id"], quote=True) + '">' + escape(chapter["title"]) + "</a></li>" for chapter in chapters
|
|
1438
|
+
)
|
|
1439
|
+
return '<nav class="toc">\n<h2>' + t["toc_title"] + "</h2>\n<ol>" + items + "</ol>\n</nav>"
|
|
1440
|
+
|
|
1441
|
+
|
|
1442
|
+
def _chapter_section_html(chapter: dict[str, Any], chapter_sections: list[str], t: dict[str, str]) -> str:
|
|
1443
|
+
"""Emit one part block: anchor, heading, decision question, digest, then charts."""
|
|
1444
|
+
anchor = escape(chapter["chapter_id"], quote=True)
|
|
1445
|
+
heading = escape(chapter["title"])
|
|
1446
|
+
purpose = escape(chapter["purpose"])
|
|
1447
|
+
digest = escape(chapter["digest"])
|
|
1448
|
+
return (
|
|
1449
|
+
'<section class="chapter" id="chapter-'
|
|
1450
|
+
+ anchor
|
|
1451
|
+
+ '">\n<h2>'
|
|
1452
|
+
+ heading
|
|
1453
|
+
+ '</h2>\n<p class="purpose"><strong>'
|
|
1454
|
+
+ escape(t["purpose_label"])
|
|
1455
|
+
+ "</strong>"
|
|
1456
|
+
+ purpose
|
|
1457
|
+
+ '</p>\n<p class="digest">'
|
|
1458
|
+
+ digest
|
|
1459
|
+
+ "</p>\n"
|
|
1460
|
+
+ "\n".join(chapter_sections)
|
|
1461
|
+
+ "\n</section>"
|
|
1462
|
+
)
|
|
1463
|
+
|
|
1464
|
+
|
|
1465
|
+
def _chart_section_html(chart: dict[str, Any], footnote: str, t: dict[str, str]) -> str:
|
|
1466
|
+
"""Emit one report block: heading with evidence-role badge, body, reading, footnote."""
|
|
1467
|
+
escaped_id = escape(chart["chart_id"], quote=True)
|
|
1468
|
+
heading = escape(chart["title"])
|
|
1469
|
+
role = chart["evidence_role"]
|
|
1470
|
+
role_badge = '<span class="role-badge role-' + role + '">' + escape(t["role_" + role]) + "</span>"
|
|
1471
|
+
if chart["chart_type"] == "table":
|
|
1472
|
+
body = _table_html(chart, t)
|
|
1473
|
+
else:
|
|
1474
|
+
body = '<div id="chart-' + escaped_id + '" class="chart-canvas"></div>'
|
|
1475
|
+
interpretation = escape(chart["interpretation"])
|
|
1476
|
+
footnote_line = escape(footnote)
|
|
1477
|
+
return (
|
|
1478
|
+
'<section class="chart-block">\n'
|
|
1479
|
+
"<h2>"
|
|
1480
|
+
+ heading
|
|
1481
|
+
+ role_badge
|
|
1482
|
+
+ "</h2>\n"
|
|
1483
|
+
+ body
|
|
1484
|
+
+ '\n<p class="interpretation">'
|
|
1485
|
+
+ interpretation
|
|
1486
|
+
+ '</p>\n<p class="footnote">'
|
|
1487
|
+
+ footnote_line
|
|
1488
|
+
+ "</p>\n</section>"
|
|
1489
|
+
)
|
|
1490
|
+
|
|
1491
|
+
|
|
1492
|
+
def _table_html(chart: dict[str, Any], t: dict[str, str]) -> str:
|
|
1493
|
+
"""Render a table chart as a static styled HTML table (numbers formatted)."""
|
|
1494
|
+
header_cells = "".join("<th>" + escape(str(column["header"])) + "</th>" for column in chart["columns"])
|
|
1495
|
+
body_rows = "".join(
|
|
1496
|
+
"<tr>" + "".join("<td>" + escape(_cell_text(cell, t, format_numbers=True)) + "</td>" for cell in row) + "</tr>" for row in chart["rows"]
|
|
1497
|
+
)
|
|
1498
|
+
return '<table class="data-table"><thead><tr>' + header_cells + "</tr></thead><tbody>" + body_rows + "</tbody></table>"
|
|
1499
|
+
|
|
1500
|
+
|
|
1501
|
+
def _appendix_section_html(
|
|
1502
|
+
cards: list[dict[str, Any]],
|
|
1503
|
+
derivations_by_id: dict[str, Any],
|
|
1504
|
+
excluded_paths: Any,
|
|
1505
|
+
execution_meta: dict[str, Any] | None,
|
|
1506
|
+
t: dict[str, str],
|
|
1507
|
+
) -> tuple[str, list[dict[str, Any]]]:
|
|
1508
|
+
"""Build appendix A as downloadable cards, B, C, optional D; export raw card payloads."""
|
|
1509
|
+
parts = ['<section class="appendix"><h2>' + t["appendix"] + "</h2>", "<h3>" + t["appendix_a"] + "</h3>"]
|
|
1510
|
+
appendix_cards: list[dict[str, Any]] = []
|
|
1511
|
+
for position, card in enumerate(cards):
|
|
1512
|
+
header_row = card["payload_rows"][0]
|
|
1513
|
+
header_cells = "".join("<th>" + escape(_cell_text(cell, t)) + "</th>" for cell in header_row)
|
|
1514
|
+
body_rows = "".join(
|
|
1515
|
+
"<tr>" + "".join("<td>" + escape(_cell_text(cell, t)) + "</td>" for cell in row) + "</tr>" for row in card["payload_rows"][1:]
|
|
1516
|
+
)
|
|
1517
|
+
row_count = len(card["payload_rows"]) - 1
|
|
1518
|
+
escaped_card_id = escape(card["card_id"])
|
|
1519
|
+
meta_line = (
|
|
1520
|
+
t["query_label"]
|
|
1521
|
+
+ "“"
|
|
1522
|
+
+ escape(card["question"])
|
|
1523
|
+
+ "”"
|
|
1524
|
+
+ t["fetched_at_label"]
|
|
1525
|
+
+ escape(card["fetched_at"])
|
|
1526
|
+
+ t["rows_label"].format(n=row_count)
|
|
1527
|
+
)
|
|
1528
|
+
button = (
|
|
1529
|
+
'<button class="download-btn" type="button" onclick="event.preventDefault();VIZ_DOWNLOAD_CSV('
|
|
1530
|
+
+ str(len(appendix_cards))
|
|
1531
|
+
+ ')">'
|
|
1532
|
+
+ t["download_csv"]
|
|
1533
|
+
+ "</button>"
|
|
1534
|
+
)
|
|
1535
|
+
parts.append(
|
|
1536
|
+
'<details class="appendix-card">\n<summary>\n'
|
|
1537
|
+
+ f'<span class="appendix-summary-title">A.{position + 1} {t["card_word"]} {escaped_card_id}</span>\n'
|
|
1538
|
+
+ '<span class="appendix-summary-meta">· '
|
|
1539
|
+
+ escape(_truncate_text(card["question"]))
|
|
1540
|
+
+ t["rows_label"].format(n=row_count)
|
|
1541
|
+
+ "</span>\n"
|
|
1542
|
+
+ button
|
|
1543
|
+
+ "\n</summary>\n"
|
|
1544
|
+
+ '<p class="deriv-meta">'
|
|
1545
|
+
+ meta_line
|
|
1546
|
+
+ "</p>\n"
|
|
1547
|
+
+ '<table class="data-table"><thead><tr>'
|
|
1548
|
+
+ header_cells
|
|
1549
|
+
+ "</tr></thead><tbody>"
|
|
1550
|
+
+ body_rows
|
|
1551
|
+
+ "</tbody></table>\n</details>"
|
|
1552
|
+
)
|
|
1553
|
+
appendix_cards.append({"cardId": card["card_id"], "rows": card["payload_rows"]})
|
|
1554
|
+
if derivations_by_id:
|
|
1555
|
+
parts.append("<h3>" + t["appendix_b"] + "</h3>")
|
|
1556
|
+
for position, (derivation_id, entry) in enumerate(derivations_by_id.items(), start=1):
|
|
1557
|
+
sources = "、".join(entry["source_card_ids"])
|
|
1558
|
+
fields = "、".join(str(field) for field in entry["input_fields"])
|
|
1559
|
+
outputs = "、".join(_display_value(item, t) for item in entry["output_values"])
|
|
1560
|
+
parts.append(
|
|
1561
|
+
f"<p>B.{position} 【{escape(entry['output_column'])}】"
|
|
1562
|
+
+ t["deriv_based"].format(sources=escape(sources), fields=escape(fields))
|
|
1563
|
+
+ '<code class="deriv-expression">'
|
|
1564
|
+
+ escape(entry["method"]["expression"])
|
|
1565
|
+
+ '</code><span class="deriv-meta">'
|
|
1566
|
+
+ t["outputs_label"]
|
|
1567
|
+
+ escape(outputs)
|
|
1568
|
+
+ t["deriv_id_suffix"].format(did=escape(derivation_id))
|
|
1569
|
+
+ " · "
|
|
1570
|
+
+ t["recomputed" if entry["method"]["type"] in BUILTIN_FORMULAS else "custom_calculation"]
|
|
1571
|
+
+ "</span></p>"
|
|
1572
|
+
)
|
|
1573
|
+
if excluded_paths:
|
|
1574
|
+
parts.append("<h3>" + t["appendix_c"] + "</h3>")
|
|
1575
|
+
items: list[str] = []
|
|
1576
|
+
for position, item in enumerate(excluded_paths, start=1):
|
|
1577
|
+
_require_mapping(item, f"excluded_paths 第 {position} 条")
|
|
1578
|
+
question = _require_text(item.get("question"), f"excluded_paths 第 {position} 条的 question")
|
|
1579
|
+
reason = _require_text(item.get("reason"), f"excluded_paths 第 {position} 条的 reason")
|
|
1580
|
+
items.append('<li class="excluded-item">' + escape(t["excluded_intro"].format(q=question, reason=reason)) + "</li>")
|
|
1581
|
+
parts.append("<ul>" + "".join(items) + "</ul>")
|
|
1582
|
+
if execution_meta:
|
|
1583
|
+
parts.append("<h3>" + t["appendix_d"] + "</h3>")
|
|
1584
|
+
meta_rows = "".join(
|
|
1585
|
+
"<tr><th>" + escape(str(meta_key)) + "</th><td>" + escape(str(meta_value)) + "</td></tr>"
|
|
1586
|
+
for meta_key, meta_value in execution_meta.items()
|
|
1587
|
+
)
|
|
1588
|
+
parts.append('<table class="data-table"><tbody>' + meta_rows + "</tbody></table>")
|
|
1589
|
+
parts.append("</section>")
|
|
1590
|
+
return "\n".join(parts), appendix_cards
|
|
1591
|
+
|
|
1592
|
+
|
|
1593
|
+
def _document_html(
|
|
1594
|
+
title: str,
|
|
1595
|
+
workspace_name: str,
|
|
1596
|
+
generated_at: Any,
|
|
1597
|
+
output_language: str,
|
|
1598
|
+
t: dict[str, str],
|
|
1599
|
+
body_blocks: list[str],
|
|
1600
|
+
appendix_html: str,
|
|
1601
|
+
echarts_library: str,
|
|
1602
|
+
interactive_specs: list[dict[str, Any]],
|
|
1603
|
+
appendix_cards: list[dict[str, Any]],
|
|
1604
|
+
) -> str:
|
|
1605
|
+
"""Assemble the final single-file document from validated fragments."""
|
|
1606
|
+
generated_line = t["generated_at_label"] + escape(str(generated_at)) if generated_at else ""
|
|
1607
|
+
escaped_title = escape(title)
|
|
1608
|
+
escaped_workspace = escape(workspace_name)
|
|
1609
|
+
report_data_json = _script_json(interactive_specs)
|
|
1610
|
+
appendix_cards_json = _script_json(appendix_cards)
|
|
1611
|
+
lang_tag = output_language.replace("_", "-")
|
|
1612
|
+
head = (
|
|
1613
|
+
'<!DOCTYPE html>\n<html lang="' + lang_tag + '">\n<head>\n<meta charset="utf-8">\n'
|
|
1614
|
+
'<meta name="viewport" content="width=device-width, initial-scale=1">\n<title>'
|
|
1615
|
+
+ escaped_title
|
|
1616
|
+
+ "</title>\n<style>"
|
|
1617
|
+
+ _CSS
|
|
1618
|
+
+ "</style>\n</head>\n<body>\n"
|
|
1619
|
+
'<header class="report-header"><h1>'
|
|
1620
|
+
+ escaped_title
|
|
1621
|
+
+ '</h1><p class="meta">'
|
|
1622
|
+
+ t["workspace_label"]
|
|
1623
|
+
+ escaped_workspace
|
|
1624
|
+
+ generated_line
|
|
1625
|
+
+ "</p></header>\n<main>\n"
|
|
1626
|
+
)
|
|
1627
|
+
tail = (
|
|
1628
|
+
"\n</main>\n"
|
|
1629
|
+
+ appendix_html
|
|
1630
|
+
+ '\n<footer class="report-footer">'
|
|
1631
|
+
+ t["footer"]
|
|
1632
|
+
+ "</footer>\n"
|
|
1633
|
+
+ "<script>"
|
|
1634
|
+
+ echarts_library
|
|
1635
|
+
+ "</script>\n<script>window.VIZ_REPORT_DATA="
|
|
1636
|
+
+ report_data_json
|
|
1637
|
+
+ ";window.VIZ_APPENDIX_CARDS="
|
|
1638
|
+
+ appendix_cards_json
|
|
1639
|
+
+ ";"
|
|
1640
|
+
+ _BOOTSTRAP_JS.replace("__VIZ_LOAD_FAIL__", _script_json(t["load_fail"]))
|
|
1641
|
+
+ "</script>\n</body>\n</html>\n"
|
|
1642
|
+
)
|
|
1643
|
+
return head + "\n".join(body_blocks) + tail
|
|
1644
|
+
|
|
1645
|
+
|
|
1646
|
+
def _script_json(value: Any) -> str:
|
|
1647
|
+
"""Serialize inline JSON that cannot break out of a <script> element."""
|
|
1648
|
+
return json.dumps(value, ensure_ascii=False).replace("<" + "/", "<\\/").replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")
|
|
1649
|
+
|
|
1650
|
+
|
|
1651
|
+
def _display_value(value: Any, t: dict[str, str]) -> str:
|
|
1652
|
+
"""Stable textual rendering of appendix B outputs."""
|
|
1653
|
+
if value is None:
|
|
1654
|
+
return t["missing"]
|
|
1655
|
+
if isinstance(value, float):
|
|
1656
|
+
return repr(value)
|
|
1657
|
+
return str(value)
|
|
1658
|
+
|
|
1659
|
+
|
|
1660
|
+
def _truncate_text(value: Any, limit: int = 40) -> str:
|
|
1661
|
+
"""Shorten a long question for the collapsed appendix summary line."""
|
|
1662
|
+
text = _require_text(value, "cards[].question")
|
|
1663
|
+
return text if len(text) <= limit else text[: limit - 1] + "…"
|
|
1664
|
+
|
|
1665
|
+
|
|
1666
|
+
def _cell_text(cell: Any, t: dict[str, str], format_numbers: bool = False) -> str:
|
|
1667
|
+
"""Convert a ledger cell to cell text; missing stays explicitly labeled.
|
|
1668
|
+
|
|
1669
|
+
format_numbers=True 仅用于正文图表表格的展示层千分位(值不变);
|
|
1670
|
+
附录A 账本保持原始写法,逐字可核对。
|
|
1671
|
+
"""
|
|
1672
|
+
if cell is None:
|
|
1673
|
+
return t["missing"]
|
|
1674
|
+
if format_numbers and isinstance(cell, (int, float)) and not isinstance(cell, bool):
|
|
1675
|
+
return _format_number(cell)
|
|
1676
|
+
return str(cell)
|
|
1677
|
+
|
|
1678
|
+
|
|
1679
|
+
def _format_number(value: int | float) -> str:
|
|
1680
|
+
"""Thousand-separated display of a numeric cell; trailing zeros trimmed."""
|
|
1681
|
+
if isinstance(value, int):
|
|
1682
|
+
return f"{value:,}"
|
|
1683
|
+
return f"{value:,.4f}".rstrip("0").rstrip(".")
|
|
1684
|
+
|
|
1685
|
+
|
|
1686
|
+
def _require_text(value: Any, field: str) -> str:
|
|
1687
|
+
"""Accept only meaningful strings for identity fields."""
|
|
1688
|
+
if not isinstance(value, str) or not value.strip():
|
|
1689
|
+
raise ReportContractError(f"字段 {field} 必须是非空字符串,当前不符合。请回填后重跑组装命令。")
|
|
1690
|
+
return value
|
|
1691
|
+
|
|
1692
|
+
|
|
1693
|
+
def _require_list(value: Any, field: str) -> None:
|
|
1694
|
+
"""Accept only arrays for the ledger containers."""
|
|
1695
|
+
if not isinstance(value, list):
|
|
1696
|
+
raise ReportContractError(
|
|
1697
|
+
f"字段 {field} 必须是 JSON 数组。仅 derivations/excluded_paths 可为空列表,cards 与 charts 不得缺席。请修正顶层结构后重跑。"
|
|
1698
|
+
)
|
|
1699
|
+
|
|
1700
|
+
|
|
1701
|
+
def _require_mapping(value: Any, field: str) -> None:
|
|
1702
|
+
"""Accept only objects for ledger entries."""
|
|
1703
|
+
if not isinstance(value, dict):
|
|
1704
|
+
raise ReportContractError(f"{field} 应是 JSON 对象,当前不符合。请对照 references/derivation-log.md 的示例结构后重跑。")
|
|
1705
|
+
|
|
1706
|
+
|
|
1707
|
+
if __name__ == "__main__":
|
|
1708
|
+
sys.exit(main())
|