modeling_world.py
12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""AI 建模的「草案世界」:把这次还没采纳的草案叠在已发布本体上,拿真实业务数据试一试。
以前草案好不好只能看 AI 自己报的「可信度」。这里直接算:
- 计算属性 / 状态:在业务库里算一遍,给出分布(「1240 条里 37 条为是」)和几条样例;
- 指标:按定义取一次数,给出当前值;
- 定时监控:按今天的数据扫一遍,会命中几条;
- 流程卡:试运行(不写数据、不发通知、审批视为通过)。
人看到的是「在你的数据上会怎样」,而不是一个说不清来由的分数。只读,不改业务库。
"""
from __future__ import annotations
import contextlib
import logging
from typing import Any, Iterator
from fastapi import HTTPException
from . import schema, service
from .sqlutil import ident
log = logging.getLogger(__name__)
def _concept(it: dict) -> dict | None:
p = it.get("payload") or {}
kind = p.get("kind")
spec = dict(p.get("spec") or {})
if kind not in ("object_type", "link_type", "function", "action") or (kind == "action" and spec.get("_stub")):
return None
try:
spec = schema.normalize_spec(kind, spec) # 运行时代码按规整后的形状读(参数的可选值、默认值……)
except schema.SpecError:
pass
cid = f"draft:{it['id']}"
return {"id": cid, "kind": kind, "name": p.get("name") or "", "display_name": "",
"category": spec.get("category", "") if kind == "function" else "",
"object_type": (spec.get("object_type") or spec.get("target_type") or "") if kind in ("function", "action") else "",
"description": p.get("description") or "", "synonyms": list(p.get("synonyms") or []),
"spec": spec, "status": "draft", "version": 0, "origin": "modeling",
"bindings": [{"id": 0, "concept_id": cid, "ds_id": int(b.get("ds_id") or 0), "target_kind": b.get("target_kind"),
"ref": b.get("ref") or {}} for b in p.get("bindings") or [] if b.get("target_kind")]}
def concepts(items: list[dict]) -> list[dict]:
return [c for c in (_concept(it) for it in items) if c]
@contextlib.contextmanager
def world(items: list[dict]) -> Iterator[None]:
"""items:这次建模还没决定的草案(review 条目)。块里的运行时 = 工作副本 + 这些草案。"""
with service.draft_runtime(extra=concepts(items)):
yield
def sample_values(ds_id: int, table: str, column: str, limit: int = 500) -> list[str]:
"""业务表某一列的不同取值(抽样)。读不到就返回空,不影响调用方。"""
from ..text2sql import executor, semantic
from .sqlutil import to_dialect
try:
ds = semantic.get_datasource(ds_id) or {}
dialect = ds.get("ds_type") or "mysql"
out = executor.execute(ds_id, to_dialect(f"SELECT DISTINCT {ident(column)} FROM {ident(table)} LIMIT {int(limit)}",
dialect), dialect, policy="catalog")
except Exception: # noqa: BLE001
return []
if not out.ok or out.result is None:
return []
return [str(r[0]) for r in out.result.rows if r and r[0] not in (None, "")]
# ---------------- 计算属性 ----------------
def _fmt(v: Any) -> str:
if isinstance(v, float):
return f"{v:.2f}".rstrip("0").rstrip(".")
return "空" if v is None else str(v)
def property_trial(obj_name: str, props: list[str]) -> dict[str, dict]:
"""在 world() 里调用。每个属性:{ok, error, summary, total, dist|stats, samples}。"""
from . import objects
ot = service.rt_find(obj_name, "object_type")
if ot is None:
return {p: {"ok": False, "error": f"找不到对象「{obj_name}」"} for p in props}
try:
b = objects.table_binding(ot)
plan = objects._plan(ot, b["ref"])
ds_id, sub = objects.source_sql(ot)
except HTTPException as e:
return {p: {"ok": False, "error": str(e.detail)} for p in props}
except Exception as e: # noqa: BLE001
return {p: {"ok": False, "error": str(e)[:200]} for p in props}
pmap = {p["name"]: p for p in (ot.get("spec") or {}).get("properties") or []}
out: dict[str, dict] = {}
samples: list[dict] = []
try:
res = objects.query(ot["id"], limit=5)
samples = [{"label": x.get("label"), **{p: (x.get("properties") or {}).get(p) for p in props}} for x in res["items"]]
except Exception: # noqa: BLE001
pass
for name in props:
if name in plan["errors"]:
out[name] = {"ok": False, "error": plan["errors"][name]}
continue
if name not in plan["exprs"] and name not in (b["ref"].get("columns") or {}):
out[name] = {"ok": False, "error": f"「{obj_name}」没有属性「{name}」"}
continue
col = f"q.{ident(name)}" if name in plan["exprs"] else f"q.{ident(b['ref']['columns'][name])}"
dt = (pmap.get(name) or {}).get("data_type") or "number"
try:
if dt in ("boolean", "string", "enum", "date", "datetime", "text"):
_, rows = objects._run(ds_id, f"SELECT {col} AS v, COUNT(*) AS n FROM {sub} AS q GROUP BY {col} "
f"ORDER BY n DESC LIMIT 8")
total = sum(int(r[1] or 0) for r in rows)
if dt == "boolean":
yes = sum(int(r[1] or 0) for r in rows if r[0] not in (None, 0, "0", False))
summary = f"共 {total} 条,是 {yes} 条,否 {total - yes} 条"
else:
summary = f"共 {total} 条,最多的取值:" + "、".join(f"{_fmt(r[0])}({r[1]})" for r in rows[:5])
out[name] = {"ok": True, "total": total, "dist": [[r[0], int(r[1] or 0)] for r in rows], "summary": summary}
else:
_, rows = objects._run(ds_id, f"SELECT COUNT(*), SUM(CASE WHEN {col} IS NULL THEN 1 ELSE 0 END), "
f"MIN({col}), MAX({col}), AVG({col}), "
f"SUM(CASE WHEN {col} <> 0 THEN 1 ELSE 0 END) FROM {sub} AS q")
n, nulls, lo, hi, avg, nz = (rows[0] + [None] * 6)[:6] if rows else (0, 0, None, None, None, 0)
summary = (f"共 {n} 条,最小 {_fmt(lo)}、最大 {_fmt(hi)}、平均 {_fmt(float(avg) if avg is not None else None)},"
f"不为 0 的 {nz or 0} 条" + (f",算不出(空){nulls} 条" if nulls else ""))
out[name] = {"ok": True, "total": int(n or 0), "stats": {"min": lo, "max": hi, "avg": avg, "nonzero": nz,
"nulls": nulls}, "summary": summary}
except HTTPException as e:
out[name] = {"ok": False, "error": str(e.detail)[:300]}
except Exception as e: # noqa: BLE001
out[name] = {"ok": False, "error": str(e)[:300]}
if out[name].get("ok"):
out[name]["samples"] = [{"label": s["label"], "value": s.get(name)} for s in samples]
return out
# ---------------- 指标 ----------------
def metric_trial(concept: dict) -> dict:
"""在 world() 里调用。按定义取一次数:{ok, value, summary, sql} 或 {ok: False, error}。"""
from . import metrics
try:
res = metrics.query(concept, question=f"[建模试算] {concept['name']}")
except HTTPException as e:
return {"ok": False, "error": str(e.detail)[:300]}
except Exception as e: # noqa: BLE001
return {"ok": False, "error": str(e)[:300]}
unit = (concept.get("spec") or {}).get("unit") or ""
return {"ok": True, "value": res.get("value"), "sql": res.get("sql"),
"summary": f"按现在的数据算出来是 {_fmt(res.get('value'))}{unit}"}
# ---------------- 规则 ----------------
def rule_trial(concept: dict, limit: int = 500) -> dict:
"""在 world() 里调用。规则的输入都能对上它那类对象的属性时,拿真实数据逐条算一遍:
判定类给「多少条为是」,计算类给范围。要额外输入的规则返回空(没法直接试)。"""
from . import objects, rules
from .modeling_grade import input_property
spec = concept.get("spec") or {}
obj = spec.get("object_type") or ""
ot = service.rt_find(obj, "object_type") if obj else None
if ot is None or not spec.get("expression"):
return {}
props = {p["name"] for p in (ot.get("spec") or {}).get("properties") or []}
mapping = {}
for i in spec.get("inputs") or []:
prop = input_property(i) or (i["name"] if i["name"] in props else "")
if not prop or prop not in props:
return {}
mapping[i["name"]] = prop
try:
res = objects.query(ot["id"], limit=limit)
except HTTPException as e:
return {"ok": False, "error": str(e.detail)[:300]}
vals, errs = [], 0
for x in res["items"]:
row = x.get("properties") or {}
try:
vals.append(rules.evaluate(spec["expression"], {k: row.get(v) for k, v in mapping.items()}))
except Exception: # noqa: BLE001 某一行数据缺值,算不出就跳过
errs += 1
n = len(res["items"])
tail = f"({errs} 条缺数据算不出)" if errs else ""
if vals and all(isinstance(v, bool) for v in vals):
yes = sum(1 for v in vals if v)
return {"ok": True, "summary": f"{n} 条「{obj}」里 {yes} 条为是{tail}", "yes": yes, "total": n}
nums = [v for v in vals if isinstance(v, (int, float))]
if nums:
return {"ok": True, "summary": f"{n} 条「{obj}」:最小 {_fmt(min(nums))}、最大 {_fmt(max(nums))}{tail}", "total": n}
return {"ok": True, "summary": f"{n} 条「{obj}」都算过了{tail}", "total": n}
# ---------------- 定时监控 ----------------
def watch_trial(body: dict) -> dict:
"""在 world() 里调用。按今天的数据扫一遍:{ok, scanned, hits, summary, samples}。"""
from . import rules
from ..watch import engine
src = body.get("source") or {}
if src.get("kind") == "sop":
return {"ok": True, "scanned": 0, "hits": 0, "summary": "到点就跑流程卡,不看数据"}
try:
rows, scanned = engine.scan_rows(src)
except HTTPException as e:
return {"ok": False, "error": str(e.detail)[:300]}
except Exception as e: # noqa: BLE001
return {"ok": False, "error": str(e)[:300]}
cond = body.get("condition") or ""
hits = []
for row in rows:
try:
if not cond or rules.evaluate(cond, row):
hits.append(row)
except rules.RuleError as e:
return {"ok": False, "error": f"条件求值失败:{e}"}
return {"ok": True, "scanned": scanned, "hits": len(hits),
"samples": [str(h.get("label") or h.get("key") or "") for h in hits[:5]],
"summary": f"按今天的数据看了 {scanned} 条,会命中 {len(hits)} 条"}
# ---------------- 流程卡 ----------------
def sop_trial(sop_id: str, params: dict | None = None) -> dict:
"""在 world() 里调用。试运行这张流程卡草稿:不写数据、不发通知,审批视为通过,人工任务填模拟值。
返回 {ok, status, steps:[{title, status, note}], summary}。"""
from ..sop import engine
try:
run = engine.start(sop_id, params or {}, mode="dry_run", trigger="dry_run", wait=True)
run = engine.get_run(run["id"], rows=True)
except HTTPException as e:
return {"ok": False, "error": str(e.detail)[:400]}
except Exception as e: # noqa: BLE001
log.warning("流程卡试运行失败", exc_info=True)
return {"ok": False, "error": str(e)[:400]}
steps = [{"title": s.get("title") or s.get("step_id"), "status": s.get("status"),
"note": str(s.get("note") or s.get("error") or "")[:200]}
for s in run.get("steps") or []]
bad = [s for s in steps if s["status"] in ("failed", "error")]
# 逐条处理的各行在后台接着跑,主流程这时是「等待中」:走到这里没出错就算通过
ok = run.get("status") == "done" or (run.get("status") == "waiting" and not bad)
return {"ok": ok and not bad, "status": run.get("status"), "steps": steps[:40],
"error": run.get("error") or "", "run_id": run.get("id"),
"summary": (f"试运行走完了 {len(steps)} 步" if ok and not bad
else f"试运行停在了「{(bad[0]['title'] if bad else run.get('status'))}」:{(bad[0]['note'] if bad else run.get('error') or '')}")}