modeling_grade.py
7.85 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
"""AI 建模:草案体检。代替以前的「可信度」—— 那是 AI 自己报的分数,说不清来由,还会被环节的先后顺序弄错
(动作和指标同时跑,打分时指标还没写完,五个实跑通过的指标全被打成了低)。
这里只看事实,每条草案给一张检查清单:
- 对象:对上了数据表;每个计算属性在业务数据上算得出(附分布);
- 关系:对上了关联列;
- 指标:取数方式在业务库里跑通了(附当前值);
- 规则:有公式、只用自己的输入、有测试用例且都通过(能对上对象的,附在数据上的命中情况);
- 决策表:有行、测试通过;
- 动作:参数和效果补全了、校验通过。
清单里必须项都过了 = 能直接用。在最后「汇总草案」这一步统一跑,编辑、按对账修改之后也会重跑。
"""
from __future__ import annotations
import re
from typing import Any, Callable
from ..governance import review
from . import modeling, modeling_world
def _prop_label(x: dict) -> str:
return x.get("display_name") or x["name"]
def readiness(p: dict) -> dict:
"""{ready, checks:[{ok, text, must}]}。must=False 的只是提示,不影响「能直接用」。"""
kind = p.get("kind")
spec = p.get("spec") or {}
binds = {b.get("target_kind"): b for b in p.get("bindings") or []}
checks: list[dict] = []
def add(ok: bool, text: str, must: bool = True) -> None:
checks.append({"ok": bool(ok), "text": text, "must": must})
if kind == "object_type":
add("table" in binds, "对上了数据表" if "table" in binds else "还没对上数据表")
trials = p.get("prop_trials") or {}
for x in spec.get("properties") or []:
if x.get("expression"):
t = trials.get(x["name"])
if t is None:
continue
add(t.get("ok"), f"计算属性「{_prop_label(x)}」{':' + t['summary'] if t.get('ok') else '算不出:' + str(t.get('error'))}")
elif x.get("storage") == "ontology":
add(True, f"「{_prop_label(x)}」业务表里没有这一列,值由本系统保存", must=False)
elif kind == "link_type":
add("join" in binds, "对上了关联列" if "join" in binds else "表里没找到这两类对象之间的关联列")
elif kind == "function":
cat = spec.get("category") or "rule"
t = p.get("trial") or {}
if cat == "aggregate":
ok = "metric_expr" in binds and t.get("ok", True)
add(ok, ("取数方式在业务库里跑通了" + (f":{t['summary']}" if t.get("summary") else "")) if ok
else ("还没有取数方式" if "metric_expr" not in binds else f"取数失败:{t.get('error')}"))
for c in p.get("calibre_conflicts") or []:
add(False, f"口径可能重复:{c.get('note') or c.get('column')}", must=False)
elif cat == "rule":
add(bool(spec.get("expression")), "写成了公式" if spec.get("expression") else "还没写成公式")
if spec.get("expression"):
probs = modeling._rule_problems(spec)
add(not probs, "公式只用了自己的输入" if not probs else probs[0])
n = len(spec.get("tests") or [])
fails = p.get("test_failures") or []
add(n > 0 and not fails, f"{n} 个测试用例都通过" if n and not fails
else ("没有测试用例" if not n else f"测试没过:{fails[0]}"))
if t.get("summary"):
add(t.get("ok", True), f"在数据上试了:{t['summary']}" if t.get("ok", True) else f"在数据上试算失败:{t.get('error')}",
must=False)
elif cat == "decision":
add(bool(spec.get("rows")), f"决策表 {len(spec.get('rows') or [])} 行" if spec.get("rows") else "决策表还是空的")
fails = p.get("test_failures") or []
n = len(spec.get("tests") or [])
if n or fails:
add(not fails, f"{n} 个测试用例都通过" if not fails else f"测试没过:{fails[0]}")
elif kind == "action":
add(not spec.get("_stub"), "参数、前置条件和效果都补全了" if not spec.get("_stub") else "只有说明,参数和效果还没补全")
for g in p.get("schema_gaps") or []:
if not g.get("resolved"):
add(False, f"{g.get('object_type') or ''}缺「{g.get('need')}」,业务表里没有地方存")
for prob in p.get("problems") or []:
add(False, prob)
if not p.get("evidence"):
add(True, "没有原文出处(从数据表推出来的)", must=False)
return {"ready": all(c["ok"] for c in checks if c["must"]), "checks": checks}
def _concept(it: dict) -> dict | None:
return modeling_world._concept(it)
def trial_item(it: dict) -> dict:
"""在 world() 里调用:给一条草案做真实数据上的试算,返回要写进 payload 的字段。"""
p = it.get("payload") or {}
spec = p.get("spec") or {}
out: dict[str, Any] = {}
if p.get("kind") == "object_type":
names = [x["name"] for x in spec.get("properties") or [] if x.get("expression")]
if names and any(b.get("target_kind") == "table" for b in p.get("bindings") or []):
out["prop_trials"] = modeling_world.property_trial(p["name"], names)
elif p.get("kind") == "function" and spec.get("category") == "aggregate":
if any(b.get("target_kind") == "metric_expr" for b in p.get("bindings") or []):
c = _concept(it)
if c:
out["trial"] = modeling_world.metric_trial(c)
elif p.get("kind") == "function" and spec.get("category") == "rule" and spec.get("expression"):
c = _concept(it)
if c:
tr = modeling_world.rule_trial(c)
if tr:
out["trial"] = tr
return out
def grade_all(run_id: str, note: Callable[[str], None] | None = None) -> dict:
"""全部待定草案试算 + 体检,结果写回草案(confidence 只是兼容老页面:能直接用 = 1,否则 0.5)。"""
items = modeling._pending(run_id)
trials: dict[str, dict] = {}
with modeling_world.world(items):
for it in items:
try:
trials[it["id"]] = trial_item(it)
except Exception as e: # noqa: BLE001 一条试算出错不影响别的
trials[it["id"]] = {"trial": {"ok": False, "error": str(e)[:200]}}
ready = 0
for it in items:
p = {**(it["payload"] or {}), **trials.get(it["id"], {})}
p["readiness"] = readiness(p)
ready += 1 if p["readiness"]["ready"] else 0
review.update_payload(it["id"], p, confidence=1.0 if p["readiness"]["ready"] else 0.5)
if note and not p["readiness"]["ready"]:
miss = next((c["text"] for c in p["readiness"]["checks"] if c["must"] and not c["ok"]), "")
note(f"「{p.get('name')}」还差:{miss}")
_grade_watches(run_id, items)
return {"total": len(items), "ready": ready}
def _grade_watches(run_id: str, items: list[dict]) -> None:
drafts = modeling._inputs(run_id).get("watch_drafts") or []
todo = [d for d in drafts if d.get("status") == "pending"]
if not todo:
return
res: dict[str, dict] = {}
with modeling_world.world(items):
for d in todo:
res[d["id"]] = modeling_world.watch_trial(d.get("body") or {})
def keep(inp: dict) -> None:
for d in inp.get("watch_drafts") or []:
if d["id"] in res:
d["trial"] = res[d["id"]]
modeling._patch_inputs(run_id, keep)
_PROP = re.compile(r"对应属性\s*([A-Za-z_][\w]*)")
def input_property(i: dict) -> str:
"""规则的一个输入对应对象的哪个属性(AI 写规则时记在说明里)。"""
m = _PROP.search(str(i.get("description") or ""))
return m.group(1) if m else ""