@arcticdata/dsh-datarc-assistant 26.39.0 → 26.39.1
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 +45 -10
- package/api-operations.js +404 -0
- package/client.js +452 -87
- package/cordis.patch.yml +4 -4
- package/entry/SKILL.md +34 -0
- package/icon.png +0 -0
- package/index.js +35 -47
- package/locale/en.json +6 -6
- package/locale/zh.json +6 -6
- package/native-api.mjs +326 -0
- package/native-contracts.js +195 -0
- package/native-execution.js +184 -0
- package/native-runner.mjs +107 -0
- package/native-state.js +67 -0
- package/native-tools.js +241 -0
- package/operations.js +1260 -0
- package/package.json +65 -51
- package/{skills → runtime}/datarc-access-permissions/SKILL.md +30 -30
- package/{skills → runtime}/datarc-access-permissions/references/api.md +31 -31
- package/{skills → runtime}/datarc-access-permissions/references/write-order.md +16 -16
- package/{skills → runtime}/datarc-analysis-report/SKILL.md +125 -125
- package/{skills → runtime}/datarc-analysis-report/agents/openai.yaml +6 -6
- package/{skills → runtime}/datarc-analysis-report/references/analyst-frameworks.md +215 -215
- package/{skills → runtime}/datarc-analysis-report/references/api-contracts.md +478 -478
- package/{skills → runtime}/datarc-analysis-report/references/direct-card-fallback-design.md +66 -66
- package/{skills → runtime}/datarc-analysis-report/references/human-in-the-loop.md +142 -142
- package/{skills → runtime}/datarc-analysis-report/references/loop-personalization-policy.md +138 -138
- package/{skills → runtime}/datarc-analysis-report/references/manifest-example.json +779 -779
- package/{skills → runtime}/datarc-analysis-report/references/narrative-schema.md +160 -160
- package/{skills → runtime}/datarc-analysis-report/references/question-syntax.md +151 -151
- package/{skills → runtime}/datarc-analysis-report/scripts/run_analysis_report.py +2225 -2225
- package/{skills → runtime}/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -1914
- package/{skills → runtime}/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -5295
- package/{skills → runtime}/datarc-data-search/SKILL.md +243 -243
- package/{skills → runtime}/datarc-data-search/scripts/calculate.py +116 -116
- package/{skills → runtime}/datarc-data-search/scripts/data-search.mjs +628 -628
- package/{skills/datarc-dataseek-search → runtime/datarc-data-search}/scripts/datarc-client.mjs +464 -464
- package/{skills → runtime}/datarc-data-search/scripts/search-result.mjs +211 -211
- package/{skills → runtime}/datarc-dataseek-batch-evaluation/SKILL.md +59 -59
- package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -36
- package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -30
- package/{skills/datarc-data-search → runtime/datarc-dataseek-batch-evaluation}/scripts/datarc-client.mjs +464 -464
- package/{skills → runtime}/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -1020
- package/{skills → runtime}/datarc-dataseek-search/SKILL.md +96 -96
- package/{skills/datarc-dataseek-batch-evaluation → runtime/datarc-dataseek-search}/scripts/datarc-client.mjs +464 -464
- package/{skills → runtime}/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -257
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/SKILL.md +44 -44
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -4
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/evals/evals.json +165 -165
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/dataset.md +77 -77
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -93
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/interventions.md +64 -64
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -47
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/rollback.md +11 -11
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -95
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -29
- package/{skills → runtime}/datarc-dataseek-testset-generation/SKILL.md +47 -47
- package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -464
- package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -526
- package/{skills → runtime}/datarc-datasource/SKILL.md +97 -97
- package/{skills → runtime}/datarc-oauth/SKILL.md +50 -50
- package/{skills → runtime}/datarc-oauth/scripts/auth.mjs +192 -192
- package/{skills → runtime}/datarc-oauth/scripts/credentials.mjs +237 -237
- package/{skills → runtime}/datarc-report-add-card/SKILL.md +90 -90
- package/{skills → runtime}/datarc-report-add-card/agents/openai.yaml +4 -4
- package/runtime/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
- package/{skills → runtime}/datarc-report-add-card/scripts/report-card.mjs +439 -439
- package/{skills → runtime}/datarc-semantic-alias/SKILL.md +20 -20
- package/{skills → runtime}/datarc-semantic-alias/scripts/alias-plan.mjs +422 -422
- package/{skills → runtime}/datarc-semantic-alias/scripts/alias.mjs +11 -11
- package/{skills → runtime}/datarc-semantic-calibration/SKILL.md +20 -20
- package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -683
- package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration.mjs +11 -11
- package/{skills → runtime}/datarc-semantic-core/SKILL.md +12 -12
- package/{skills → runtime}/datarc-semantic-core/scripts/artifact-journal.mjs +853 -830
- package/{skills → runtime}/datarc-semantic-core/scripts/canonical.mjs +48 -48
- package/{skills → runtime}/datarc-semantic-core/scripts/case-model.mjs +608 -608
- package/{skills → runtime}/datarc-semantic-core/scripts/cli.mjs +180 -180
- package/{skills → runtime}/datarc-semantic-core/scripts/datarc-client.mjs +180 -180
- package/{skills → runtime}/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -57
- package/{skills → runtime}/datarc-semantic-core/scripts/interventions.mjs +693 -693
- package/{skills → runtime}/datarc-semantic-core/scripts/live-resolution.mjs +305 -305
- package/{skills → runtime}/datarc-semantic-core/scripts/model-scope.mjs +49 -49
- package/{skills → runtime}/datarc-semantic-core/scripts/reproduction.mjs +330 -330
- package/{skills → runtime}/datarc-semantic-core/scripts/semantic-cli.mjs +799 -740
- package/{skills → runtime}/datarc-semantic-core/scripts/shared.mjs +312 -312
- package/{skills → runtime}/datarc-semantic-core/scripts/verification.mjs +1111 -1014
- package/{skills → runtime}/datarc-semantic-dataset/SKILL.md +20 -20
- package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -749
- package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -813
- package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset.mjs +11 -11
- package/{skills → runtime}/datarc-semantic-knowledge/SKILL.md +38 -38
- package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -61
- package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-generation.json +16 -16
- package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -347
- package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -848
- package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -31
- package/{skills → runtime}/datarc-semantic-prompt/SKILL.md +20 -20
- package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt-plan.mjs +598 -447
- package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt.mjs +15 -15
- package/{skills → runtime}/datarc-semantic-synonym/SKILL.md +20 -20
- package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -688
- package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym.mjs +11 -11
- package/{skills → runtime}/datarc-viz-analysis-report/SKILL.md +108 -108
- package/{skills → runtime}/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -8
- package/{skills → runtime}/datarc-viz-analysis-report/assets/echarts.min.js +45 -45
- package/{skills → runtime}/datarc-viz-analysis-report/references/api-contracts.md +163 -163
- package/{skills → runtime}/datarc-viz-analysis-report/references/derivation-log.md +157 -157
- package/{skills → runtime}/datarc-viz-analysis-report/references/evidence-framework.md +76 -76
- package/{skills → runtime}/datarc-viz-analysis-report/references/html-template.md +92 -92
- package/{skills → runtime}/datarc-viz-analysis-report/references/provenance-format.md +56 -56
- package/{skills → runtime}/datarc-viz-analysis-report/references/question-syntax.md +151 -151
- package/{skills → runtime}/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -1708
- package/{skills → runtime}/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -964
- package/{skills → runtime}/datarc-workspace-configuration/SKILL.md +59 -59
- package/{skills → runtime}/datarc-workspace-configuration/references/artifacts.md +75 -75
- package/{skills → runtime}/datarc-workspace-configuration/references/verification.md +20 -20
- package/{skills → runtime}/datarc-workspace-configuration/scripts/configuration.mjs +722 -662
- package/{skills → runtime}/datarc-workspace-context/SKILL.md +43 -43
- package/{skills → runtime}/datarc-workspace-context/agents/openai.yaml +4 -4
- package/{skills → runtime}/datarc-workspace-context/scripts/datarc-client.mjs +31 -31
- package/{skills → runtime}/datarc-workspace-context/scripts/query-display.mjs +114 -114
- package/{skills → runtime}/datarc-workspace-context/scripts/workspace-context.mjs +58 -58
- package/{skills → runtime}/datarc-workspace-custom-tables/SKILL.md +89 -89
- package/{skills → runtime}/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -165
- package/{skills → runtime}/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -601
- package/{skills → runtime}/datarc-workspace-keywords/SKILL.md +197 -197
- package/{skills → runtime}/datarc-workspace-keywords/agents/openai.yaml +4 -4
- package/{skills → runtime}/datarc-workspace-keywords/references/api-fields.md +79 -79
- package/{skills → runtime}/datarc-workspace-keywords/references/derived-measures.md +177 -177
- package/{skills → runtime}/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -145
- package/{skills → runtime}/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -2421
- package/{skills → runtime}/datarc-workspace-membership/SKILL.md +29 -29
- package/{skills → runtime}/datarc-workspace-membership/references/api.md +19 -19
- package/{skills → runtime}/datarc-workspace-modeling/SKILL.md +209 -209
- package/{skills → runtime}/datarc-workspace-modeling/agents/openai.yaml +4 -4
- package/{skills → runtime}/datarc-workspace-modeling/references/join-preview.md +38 -38
- package/{skills → runtime}/datarc-workspace-modeling/references/model-plan.md +300 -300
- package/{skills → runtime}/datarc-workspace-modeling/references/model-tags.md +95 -95
- package/{skills → runtime}/datarc-workspace-modeling/references/modeling-contract.json +29 -29
- package/{skills → runtime}/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -2423
- package/{skills → runtime}/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -137
- package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -238
- package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -1261
- package/skills-provider.js +51 -0
- package/workflow-index.json +434 -0
- package/icon.svg +0 -4
- package/skills/datarc-report-add-card/scripts/datarc-client.mjs +0 -464
- package/skills-index.json +0 -194
|
@@ -1,116 +1,116 @@
|
|
|
1
|
-
"""Calculate ad hoc shares and period growth from ordinary search result references."""
|
|
2
|
-
|
|
3
|
-
import argparse
|
|
4
|
-
import json
|
|
5
|
-
import subprocess
|
|
6
|
-
import sys
|
|
7
|
-
from decimal import Decimal, InvalidOperation
|
|
8
|
-
from pathlib import Path
|
|
9
|
-
|
|
10
|
-
SEARCH = Path(__file__).with_name("data-search.mjs")
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def load_series(result_file: str, workspace_id: str, series: int = 0, first: int | None = None) -> tuple[list, list]:
|
|
14
|
-
"""Read business columns and rows through the same credential and workspace checks as recall."""
|
|
15
|
-
command = ["node", str(SEARCH), "recall", "--workspace-id", workspace_id, "--from-result", result_file]
|
|
16
|
-
run = subprocess.run(command, capture_output=True, encoding="utf-8", check=False)
|
|
17
|
-
payload = json.loads(run.stdout)
|
|
18
|
-
if run.returncode or not payload.get("ok"):
|
|
19
|
-
raise ValueError(payload.get("error", {}).get("message") or "读取历史结果失败,请核对工作区和结果引用")
|
|
20
|
-
previews = payload["data"]["previews"]
|
|
21
|
-
if not 0 <= series < len(previews):
|
|
22
|
-
raise ValueError("结果中没有所选数据序列,请检查预览中的序列位置")
|
|
23
|
-
preview = previews[series]
|
|
24
|
-
if first is not None and first < 1:
|
|
25
|
-
raise ValueError("所需的前 N 行必须大于零,请核对对象数量")
|
|
26
|
-
data = preview["data"] if not preview.get("error") else None
|
|
27
|
-
covers_first = (
|
|
28
|
-
first is not None and preview.get("coverage") == "preview" and preview.get("offset", 0) == 0 and isinstance(data, list) and len(data) >= first
|
|
29
|
-
)
|
|
30
|
-
if preview.get("error") or (preview.get("coverage") != "complete" and not covers_first):
|
|
31
|
-
raise ValueError("所选序列取数失败或仅有部分预览,请补齐所需行或按所需粒度聚合后再计算")
|
|
32
|
-
columns, rows = preview["columns"], data
|
|
33
|
-
if not isinstance(rows, list):
|
|
34
|
-
rows = [[rows]]
|
|
35
|
-
if any(not isinstance(row, list) or len(row) != len(columns) for row in rows):
|
|
36
|
-
raise ValueError("数据行与业务列不匹配,请选择可用的表格序列")
|
|
37
|
-
return columns, rows[:first]
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
def percentage(current: object, base: object, operation: str) -> Decimal | None:
|
|
41
|
-
if operation not in ("share", "yoy", "mom"):
|
|
42
|
-
raise ValueError("请选择 share、yoy 或 mom")
|
|
43
|
-
if current is None or base is None:
|
|
44
|
-
return None
|
|
45
|
-
try:
|
|
46
|
-
current_value, base_value = Decimal(str(current)), Decimal(str(base))
|
|
47
|
-
except InvalidOperation as exc:
|
|
48
|
-
raise ValueError("指标含有非数值,请核对原始数值列后重试") from exc
|
|
49
|
-
if not current_value.is_finite() or not base_value.is_finite():
|
|
50
|
-
raise ValueError("指标含有非有限数值,请核对原始数值列后重试")
|
|
51
|
-
if base_value == 0:
|
|
52
|
-
return None
|
|
53
|
-
if operation == "share":
|
|
54
|
-
return current_value * 100 / base_value
|
|
55
|
-
return (current_value - base_value) * 100 / abs(base_value)
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
def values_by_key(table: tuple[list, list], metric: str, keys: list[str]) -> dict:
|
|
59
|
-
columns, rows = table
|
|
60
|
-
for name in [*keys, metric]:
|
|
61
|
-
if columns.count(name) != 1:
|
|
62
|
-
raise ValueError(f"列「{name}」缺失或重名,请按实际业务列名和序列选择输入")
|
|
63
|
-
indexes = [columns.index(key) for key in keys]
|
|
64
|
-
value_index = columns.index(metric)
|
|
65
|
-
values = {}
|
|
66
|
-
for row in rows:
|
|
67
|
-
# Time dimensions can use a composite cell such as [year, month].
|
|
68
|
-
key = tuple(tuple(row[i]) if isinstance(row[i], list) else row[i] for i in indexes)
|
|
69
|
-
if key in values:
|
|
70
|
-
raise ValueError("同一分组出现多行,请补齐分组键或先按正确粒度汇总")
|
|
71
|
-
values[key] = row[value_index]
|
|
72
|
-
return values
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
def main() -> None:
|
|
76
|
-
parser = argparse.ArgumentParser(description=__doc__)
|
|
77
|
-
parser.add_argument("operation", choices=("share", "yoy", "mom"))
|
|
78
|
-
parser.add_argument("--workspace-id", required=True)
|
|
79
|
-
parser.add_argument("--current", required=True)
|
|
80
|
-
parser.add_argument("--base", required=True)
|
|
81
|
-
parser.add_argument("--value", required=True)
|
|
82
|
-
parser.add_argument("--base-value", help="分母或基期指标列,默认同本期")
|
|
83
|
-
parser.add_argument("--by", action="append", default=[], help="业务分组列,可重复")
|
|
84
|
-
parser.add_argument("--total", action="store_true", help="占比使用单行总体分母")
|
|
85
|
-
parser.add_argument("--first", type=int, help="仅计算本期已确认排序的前 N 行")
|
|
86
|
-
parser.add_argument("--current-series", type=int, default=0)
|
|
87
|
-
parser.add_argument("--base-series", type=int, default=0)
|
|
88
|
-
args = parser.parse_args()
|
|
89
|
-
if args.total and args.operation != "share":
|
|
90
|
-
parser.error("--total 仅用于占比,增长率需要同口径的基期")
|
|
91
|
-
table = load_series(args.current, args.workspace_id, args.current_series, args.first)
|
|
92
|
-
base_table = (
|
|
93
|
-
table
|
|
94
|
-
if args.first is None and (args.current, args.current_series) == (args.base, args.base_series)
|
|
95
|
-
else load_series(args.base, args.workspace_id, args.base_series)
|
|
96
|
-
)
|
|
97
|
-
current = values_by_key(table, args.value, args.by)
|
|
98
|
-
base = values_by_key(base_table, args.base_value or args.value, [] if args.total else args.by)
|
|
99
|
-
rows = []
|
|
100
|
-
for key, value in current.items():
|
|
101
|
-
reference = base.get(() if args.total else key)
|
|
102
|
-
pct = percentage(value, reference, args.operation)
|
|
103
|
-
rows.append([*key, value, reference, None if pct is None else str(pct)])
|
|
104
|
-
label = {"share": "占比", "yoy": "同比增长率", "mom": "环比增长率"}[args.operation]
|
|
105
|
-
result = {"columns": [*args.by, "本期值", "分母" if args.operation == "share" else "基期值", label + "(%)"], "rows": rows}
|
|
106
|
-
json.dump(result, sys.stdout, ensure_ascii=False)
|
|
107
|
-
sys.stdout.write("\n")
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
if __name__ == "__main__":
|
|
111
|
-
sys.stdout.reconfigure(encoding="utf-8")
|
|
112
|
-
sys.stderr.reconfigure(encoding="utf-8")
|
|
113
|
-
try:
|
|
114
|
-
main()
|
|
115
|
-
except (ValueError, OSError) as exc:
|
|
116
|
-
sys.exit(f"计算未完成:{exc}")
|
|
1
|
+
"""Calculate ad hoc shares and period growth from ordinary search result references."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
from decimal import Decimal, InvalidOperation
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
SEARCH = Path(__file__).with_name("data-search.mjs")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def load_series(result_file: str, workspace_id: str, series: int = 0, first: int | None = None) -> tuple[list, list]:
|
|
14
|
+
"""Read business columns and rows through the same credential and workspace checks as recall."""
|
|
15
|
+
command = ["node", str(SEARCH), "recall", "--workspace-id", workspace_id, "--from-result", result_file]
|
|
16
|
+
run = subprocess.run(command, capture_output=True, encoding="utf-8", check=False)
|
|
17
|
+
payload = json.loads(run.stdout)
|
|
18
|
+
if run.returncode or not payload.get("ok"):
|
|
19
|
+
raise ValueError(payload.get("error", {}).get("message") or "读取历史结果失败,请核对工作区和结果引用")
|
|
20
|
+
previews = payload["data"]["previews"]
|
|
21
|
+
if not 0 <= series < len(previews):
|
|
22
|
+
raise ValueError("结果中没有所选数据序列,请检查预览中的序列位置")
|
|
23
|
+
preview = previews[series]
|
|
24
|
+
if first is not None and first < 1:
|
|
25
|
+
raise ValueError("所需的前 N 行必须大于零,请核对对象数量")
|
|
26
|
+
data = preview["data"] if not preview.get("error") else None
|
|
27
|
+
covers_first = (
|
|
28
|
+
first is not None and preview.get("coverage") == "preview" and preview.get("offset", 0) == 0 and isinstance(data, list) and len(data) >= first
|
|
29
|
+
)
|
|
30
|
+
if preview.get("error") or (preview.get("coverage") != "complete" and not covers_first):
|
|
31
|
+
raise ValueError("所选序列取数失败或仅有部分预览,请补齐所需行或按所需粒度聚合后再计算")
|
|
32
|
+
columns, rows = preview["columns"], data
|
|
33
|
+
if not isinstance(rows, list):
|
|
34
|
+
rows = [[rows]]
|
|
35
|
+
if any(not isinstance(row, list) or len(row) != len(columns) for row in rows):
|
|
36
|
+
raise ValueError("数据行与业务列不匹配,请选择可用的表格序列")
|
|
37
|
+
return columns, rows[:first]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def percentage(current: object, base: object, operation: str) -> Decimal | None:
|
|
41
|
+
if operation not in ("share", "yoy", "mom"):
|
|
42
|
+
raise ValueError("请选择 share、yoy 或 mom")
|
|
43
|
+
if current is None or base is None:
|
|
44
|
+
return None
|
|
45
|
+
try:
|
|
46
|
+
current_value, base_value = Decimal(str(current)), Decimal(str(base))
|
|
47
|
+
except InvalidOperation as exc:
|
|
48
|
+
raise ValueError("指标含有非数值,请核对原始数值列后重试") from exc
|
|
49
|
+
if not current_value.is_finite() or not base_value.is_finite():
|
|
50
|
+
raise ValueError("指标含有非有限数值,请核对原始数值列后重试")
|
|
51
|
+
if base_value == 0:
|
|
52
|
+
return None
|
|
53
|
+
if operation == "share":
|
|
54
|
+
return current_value * 100 / base_value
|
|
55
|
+
return (current_value - base_value) * 100 / abs(base_value)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def values_by_key(table: tuple[list, list], metric: str, keys: list[str]) -> dict:
|
|
59
|
+
columns, rows = table
|
|
60
|
+
for name in [*keys, metric]:
|
|
61
|
+
if columns.count(name) != 1:
|
|
62
|
+
raise ValueError(f"列「{name}」缺失或重名,请按实际业务列名和序列选择输入")
|
|
63
|
+
indexes = [columns.index(key) for key in keys]
|
|
64
|
+
value_index = columns.index(metric)
|
|
65
|
+
values = {}
|
|
66
|
+
for row in rows:
|
|
67
|
+
# Time dimensions can use a composite cell such as [year, month].
|
|
68
|
+
key = tuple(tuple(row[i]) if isinstance(row[i], list) else row[i] for i in indexes)
|
|
69
|
+
if key in values:
|
|
70
|
+
raise ValueError("同一分组出现多行,请补齐分组键或先按正确粒度汇总")
|
|
71
|
+
values[key] = row[value_index]
|
|
72
|
+
return values
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def main() -> None:
|
|
76
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
77
|
+
parser.add_argument("operation", choices=("share", "yoy", "mom"))
|
|
78
|
+
parser.add_argument("--workspace-id", required=True)
|
|
79
|
+
parser.add_argument("--current", required=True)
|
|
80
|
+
parser.add_argument("--base", required=True)
|
|
81
|
+
parser.add_argument("--value", required=True)
|
|
82
|
+
parser.add_argument("--base-value", help="分母或基期指标列,默认同本期")
|
|
83
|
+
parser.add_argument("--by", action="append", default=[], help="业务分组列,可重复")
|
|
84
|
+
parser.add_argument("--total", action="store_true", help="占比使用单行总体分母")
|
|
85
|
+
parser.add_argument("--first", type=int, help="仅计算本期已确认排序的前 N 行")
|
|
86
|
+
parser.add_argument("--current-series", type=int, default=0)
|
|
87
|
+
parser.add_argument("--base-series", type=int, default=0)
|
|
88
|
+
args = parser.parse_args()
|
|
89
|
+
if args.total and args.operation != "share":
|
|
90
|
+
parser.error("--total 仅用于占比,增长率需要同口径的基期")
|
|
91
|
+
table = load_series(args.current, args.workspace_id, args.current_series, args.first)
|
|
92
|
+
base_table = (
|
|
93
|
+
table
|
|
94
|
+
if args.first is None and (args.current, args.current_series) == (args.base, args.base_series)
|
|
95
|
+
else load_series(args.base, args.workspace_id, args.base_series)
|
|
96
|
+
)
|
|
97
|
+
current = values_by_key(table, args.value, args.by)
|
|
98
|
+
base = values_by_key(base_table, args.base_value or args.value, [] if args.total else args.by)
|
|
99
|
+
rows = []
|
|
100
|
+
for key, value in current.items():
|
|
101
|
+
reference = base.get(() if args.total else key)
|
|
102
|
+
pct = percentage(value, reference, args.operation)
|
|
103
|
+
rows.append([*key, value, reference, None if pct is None else str(pct)])
|
|
104
|
+
label = {"share": "占比", "yoy": "同比增长率", "mom": "环比增长率"}[args.operation]
|
|
105
|
+
result = {"columns": [*args.by, "本期值", "分母" if args.operation == "share" else "基期值", label + "(%)"], "rows": rows}
|
|
106
|
+
json.dump(result, sys.stdout, ensure_ascii=False)
|
|
107
|
+
sys.stdout.write("\n")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
112
|
+
sys.stderr.reconfigure(encoding="utf-8")
|
|
113
|
+
try:
|
|
114
|
+
main()
|
|
115
|
+
except (ValueError, OSError) as exc:
|
|
116
|
+
sys.exit(f"计算未完成:{exc}")
|