eval_modeling.py 23.7 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 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
"""AI 建模评测:用一份业务文档 + 一个业务数据源跑一遍建模流水线,出一张**确定性**的质量评分卡。

系统是通用的,每份文档都只是一个评测样例:改了流水线,就在几个样例上各跑一遍、对比评分卡,
样例之间都变好才算改动是通用的。评分只看能机器判断的事实(绑没绑上、能不能算、测试过没过、
流程卡有没有错、文档条目覆盖了多少),不看 AI 自己报的「可信度」。

用法:
    python scripts/eval_modeling.py cases                      # 列出样例
    python scripts/eval_modeling.py prep inv                   # 为样例建一个干净的克隆库 ai_ontology_eval_inv
    python scripts/eval_modeling.py run inv --tag v14          # 在克隆库里跑一遍,存 mydocs/建模评测/inv/v14.{json,md}
    python scripts/eval_modeling.py resume inv --tag v14 --run mr_xxx     # 接着跑一次中断 / 出错的运行
    python scripts/eval_modeling.py score inv --tag v13 --db ai_ontology_9101 --run mr_xxx   # 给已有的一次运行打分(只读)
    python scripts/eval_modeling.py compare inv                # 把这个样例历次评分卡并排对比

新样例:在 CASES 里加一行(文档路径、从哪个库复制数据源、数据源 id)。
"""
from __future__ import annotations

import argparse
import json
import os
import re
import subprocess
import sys
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "mydocs" / "建模评测"

CASES: dict[str, dict] = {
    "inv": {"title": "库存补货业务手册", "doc": r"D:\code\onto_query_demo_8103\docs\demo\库存补货业务手册.md",
            "src_db": "ai_ontology_v10", "ds_name": "库存业务库"},
    "4s": {"title": "4S 店配件库存与缺件处理业务手册", "doc": str(ROOT / "docs" / "demo2_4S" / "4S店配件库存与缺件处理业务手册.md"),
           "src_db": "ai_ontology_v10", "ds_name": "配件业务库"},
}
# 克隆时复制的系统表:系统设置(模型、密钥)、数据源和它内省出来的表 / 列 / 关联。不带本体、草案、角色、建模记录。
CONFIG_TABLES = ["otlg_config"]


def _db_name(case: str) -> str:
    return f"ai_ontology_eval_{case}"


def _use_db(db: str, data_dir: str | None = None) -> None:
    """设好库名再 import app(配置在 import 时读环境变量)。"""
    os.environ["DB_NAME"] = db
    os.environ["DATA_DIR"] = data_dir or str(OUT / "_data" / db)
    os.chdir(ROOT)
    # EVAL_CODE_ROOT:用一份代码快照跑(跑基线时主目录里的代码还在改,模块是懒加载的,不能混着用)
    sys.path.insert(0, os.environ.get("EVAL_CODE_ROOT") or str(ROOT))


# ---------------- 建克隆库 ----------------
def prep(case: str) -> None:
    c = CASES[case]
    db = _db_name(case)
    _use_db("ai_ontology_dev")
    from sqlalchemy import create_engine, text
    from app.core.config import get_settings
    st = get_settings()
    eng = create_engine(st.url_for(st.db_name), future=True)
    with eng.begin() as x:
        x.execute(text(f"DROP DATABASE IF EXISTS `{db}`"))
        x.execute(text(f"CREATE DATABASE `{db}` DEFAULT CHARACTER SET utf8mb4"))
    env = {**os.environ, "DB_NAME": db, "DATA_DIR": str(OUT / "_data" / db)}
    subprocess.run([sys.executable, "-c", "from app.core import db; db.init_db(); "
                    "from app.governance import users; users.seed(); print('init ok')"], cwd=ROOT, env=env, check=True)
    src = c["src_db"]
    with eng.connect() as x:     # 按名字找数据源:重建源库后 id 会变
        ds = int(c.get("ds_id") or x.execute(text(f"SELECT id FROM `{src}`.otlg_datasource WHERE name = :n"),
                                             {"n": c["ds_name"]}).scalar())

    def cols(x, schema: str, t: str) -> list[str]:
        return [r[0] for r in x.execute(text("SELECT column_name FROM information_schema.columns WHERE table_schema = :s "
                                             "AND table_name = :t ORDER BY ordinal_position"), {"s": schema, "t": t})]

    def copy(x, t: str, where: str = "", alias: str = "s") -> None:
        """两边表结构可能差几列(老库没跑过新迁移):只复制共有的列。"""
        have = set(cols(x, src, t))
        common = [k for k in cols(x, db, t) if k in have]
        # 新库多出来、又不许为空的列补个空值
        extra = [(k, "0" if typ in ("int", "bigint", "tinyint", "smallint", "decimal", "double", "float") else "''")
                 for k, typ in x.execute(text("SELECT column_name, data_type FROM information_schema.columns WHERE table_schema = :s "
                                              "AND table_name = :t AND is_nullable = 'NO' AND column_default IS NULL"),
                                         {"s": db, "t": t}) if k not in have]
        names = ", ".join(f"`{k}`" for k in common + [k for k, _ in extra])
        vals = ", ".join([f"{alias}.`{k}`" for k in common] + [v for _, v in extra])
        x.execute(text(f"INSERT INTO `{db}`.`{t}` ({names}) SELECT {vals} FROM `{src}`.`{t}` {alias} {where}"), {"d": ds})

    with eng.begin() as x:
        for t in CONFIG_TABLES:
            x.execute(text(f"DELETE FROM `{db}`.`{t}`"))
            copy(x, t)
        x.execute(text(f"DELETE FROM `{db}`.otlg_datasource"))
        copy(x, "otlg_datasource", "WHERE s.id = :d")
        x.execute(text(f"UPDATE `{db}`.otlg_datasource SET workspace = 'default'"))
        copy(x, "otlg_sm_model", "WHERE s.ds_id = :d")
        copy(x, "otlg_sm_column", f"JOIN `{src}`.otlg_sm_model m ON m.id = s.model_id WHERE m.ds_id = :d")
        copy(x, "otlg_sm_relation", "WHERE s.ds_id = :d")
        n = {t: x.execute(text(f"SELECT COUNT(*) FROM `{db}`.`{t}`")).scalar()
             for t in ("otlg_datasource", "otlg_sm_model", "otlg_sm_column", "otlg_sm_relation")}
    print(case, db, n)


def _clone_ds(c: dict) -> int:
    """克隆库里那个业务数据源的 id(复制时保留了源库的 id,按名字找)。"""
    from sqlalchemy import create_engine, text
    from app.core.config import get_settings
    st = get_settings()
    with create_engine(st.url_for(st.db_name), future=True).connect() as x:
        return int(c.get("ds_id") or x.execute(text("SELECT id FROM otlg_datasource WHERE name = :n"),
                                               {"n": c["ds_name"]}).scalar())


# ---------------- 跑一遍 ----------------
def run(case: str, tag: str, adopt: bool) -> Path:
    c = CASES[case]
    _use_db(_db_name(case))
    import app.main  # noqa: F401  注册系统工具、审核处理器、发布闸门(真实服务启动时会做)
    from app.kernel import modeling
    raw = Path(c["doc"]).read_bytes()
    t0 = time.time()
    r = modeling.create(f"评测 {case} {tag}", files=[(Path(c["doc"]).name, raw)], ds_ids=[_clone_ds(c)])
    rid = r["id"]
    print("run", rid, flush=True)
    last = ""
    for ev in modeling.execute(rid):
        m = f"{ev.get('stage')} {ev.get('progress')} {ev.get('message', '')}"
        if m != last:
            print(time.strftime("%H:%M:%S"), m, flush=True)
            last = m
    wall = round(time.time() - t0, 1)
    return _save(case, tag, rid, wall=wall, adopt=adopt)


def resume(case: str, tag: str, rid: str, adopt: bool, from_stage: str = "") -> Path:
    """接着跑一次中断 / 出错的运行(从没跑完的那一步继续);from_stage 给了就从那一步起重跑。"""
    _use_db(_db_name(case))
    import app.main  # noqa: F401
    from app.core.dbx import jdump, jload, session
    from app.kernel import modeling
    from app.kernel.models import ModelRun
    if from_stage:
        again = modeling.ORDER[modeling.ORDER.index(from_stage):]
        with session() as s:
            row = s.get(ModelRun, rid)
            rows = modeling._stage_rows(jload(row.stages_json, []) or [])
            for x in rows:
                if x["key"] in again and x["status"] != "skipped":
                    x["status"] = "pending"
            row.stages_json = jdump(rows)
            s.commit()
    t0 = time.time()
    last = ""
    for ev in modeling.execute(rid):
        m = f"{ev.get('stage')} {ev.get('progress')} {ev.get('message', '')}"
        if m != last:
            print(time.strftime("%H:%M:%S"), m, flush=True)
            last = m
    return _save(case, tag, rid, wall=round(time.time() - t0, 1), adopt=adopt)


def _save(case: str, tag: str, rid: str, *, wall: float | None = None, adopt: bool = False) -> Path:
    from app.kernel import modeling
    g = modeling.get(rid)
    calls = modeling.calls(rid)
    card = scorecard(g, calls)
    card["wall_s"] = wall
    if adopt and g["status"] == "done":          # 没跑完的不采纳(否则接着跑时草案已经都上线了)
        card["adopt"] = _adopt_all(rid, g)
    d = OUT / case
    d.mkdir(parents=True, exist_ok=True)
    (d / f"{tag}.json").write_text(json.dumps({"case": case, "tag": tag, "run_id": rid, "card": card, "run": g, "calls": calls},
                                              ensure_ascii=False, indent=1, default=str), encoding="utf-8")
    md = render(case, tag, rid, card)
    (d / f"{tag}.md").write_text(md, encoding="utf-8")
    print(md)
    return d / f"{tag}.md"


def _adopt_all(rid: str, g: dict) -> dict:
    """全部采纳上线,看有多少能真正落地(只在克隆库里做)。"""
    from app.kernel import modeling
    ids = [it["id"] for v in g["items"].values() for it in v if it["status"] == "pending"]
    sids = [s["id"] for s in g["sops"] if not s["current_version"]]
    wids = [w["id"] for w in g["watches"] if w.get("status") == "pending"]
    try:
        ad = modeling.adopt(rid, ids, sids, wids)
    except BaseException as e:  # noqa: BLE001
        return {"error": str(e)[:300]}
    return {"accepted": len(ad["accepted"]), "failed": len(ad["failed"]), "published": ad["published"],
            "held": len(ad["held"]), "held_why": list(ad["held"].values())[:8],
            "sops_ok": sum(1 for v in ad["sops"].values() if not v), "sops_failed": [v for v in ad["sops"].values() if v][:4],
            "watches_ok": sum(1 for v in (ad.get("watches") or {}).values() if not v)}


# ---------------- 评分 ----------------
def _sample_values(ds_id: int, table: str, column: str) -> list[str]:
    from app.text2sql import executor, semantic
    from app.kernel.sqlutil import ident, to_dialect
    ds = semantic.get_datasource(ds_id) or {}
    dialect = ds.get("ds_type") or "mysql"
    sql = to_dialect(f"SELECT DISTINCT {ident(column)} FROM {ident(table)} LIMIT 500", dialect)
    out = executor.execute(ds_id, sql, dialect, policy="catalog")
    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] is not None]


def _ready(it: dict) -> tuple[bool, str]:
    """草案能不能直接用。评测自己判,不用流水线报的结果(各版本口径要一样):
    规则要能解析、只用自己的输入、有测试用例且都过了。"""
    p = it.get("payload") or {}
    sp = p.get("spec") or {}
    binds = [b.get("target_kind") for b in p.get("bindings") or []]
    kind, cat = p.get("kind"), sp.get("category")
    if [g for g in p.get("schema_gaps") or [] if not g.get("resolved")]:
        return False, "数据缺口"
    if p.get("test_failures"):
        return False, "测试没过"
    if kind == "object_type" and "table" not in binds:
        return False, "没绑表"
    if kind == "link_type" and "join" not in binds:
        return False, "没有关联列"
    if kind == "action" and sp.get("_stub"):
        return False, "动作没补全"
    if kind == "function":
        if cat == "aggregate" and "metric_expr" not in binds:
            return False, "指标没取数"
        if cat == "rule":
            if not sp.get("expression"):
                return False, "规则没公式"
            from app.kernel import rules as rule_engine
            try:
                used = set(rule_engine.free_names(sp["expression"]))
            except Exception:  # noqa: BLE001
                return False, "公式写法有误"
            have = {i.get("name") for i in sp.get("inputs") or []} | {str(x) for x in sp.get("params") or [] if isinstance(x, str)}
            if used - have - {"today"}:
                return False, f"公式用了没声明的 {'、'.join(sorted(used - have - {'today'}))}"
            if not sp.get("tests"):
                return False, "规则没有测试用例"
        if cat == "decision" and not sp.get("rows"):
            return False, "决策表空"
    return True, ""


def scorecard(g: dict, calls: list[dict]) -> dict:
    items = g["items"]
    objs, links, fns, acts = (items.get(k) or [] for k in ("object_type", "link_type", "function", "action"))
    card: dict = {"status": g["status"], "elapsed_min": round((g.get("elapsed_ms") or 0) / 60000, 1)}

    # 对象
    inst_syn, table_syn, label_is_key, comp_props = [], [], 0, 0
    for it in objs:
        p = it["payload"] or {}
        props = (p.get("spec") or {}).get("properties") or []
        comp_props += sum(1 for x in props if x.get("expression"))
        tb = next((b for b in p.get("bindings") or [] if b.get("target_kind") == "table"), None)
        syn = [s for s in p.get("synonyms") or [] if s != p.get("name")]
        table_syn += [s for s in syn if re.fullmatch(r"[A-Za-z0-9_]+", s) and "_" in s]
        if not tb:
            continue
        ref = tb.get("ref") or {}
        if ref.get("label_column") and ref.get("label_column") == ref.get("key_column"):
            label_is_key += 1
        try:
            vals = _sample_values(int(tb["ds_id"]), ref["table"], ref.get("label_column") or ref["key_column"])
        except Exception:  # noqa: BLE001
            vals = []
        for s in syn:
            if len(s) >= 2 and not re.fullmatch(r"[A-Za-z0-9_]+", s) and any(s in v for v in vals):
                inst_syn.append(f"{p.get('name')}:{s}")
    ready = {k: sum(1 for it in (items.get(k) or []) if _ready(it)[0]) for k in ("object_type", "link_type", "function", "action")}
    not_ready = [f"{(it['payload'] or {}).get('name')}({_ready(it)[1]})"
                 for k in ("object_type", "link_type", "function", "action") for it in items.get(k) or [] if not _ready(it)[0]]
    card["objects"] = {"n": len(objs), "bound": sum(1 for it in objs if any(b.get("target_kind") == "table" for b in (it["payload"] or {}).get("bindings") or [])),
                       "computed_props": comp_props, "instance_synonyms": inst_syn, "table_synonyms": table_syn,
                       "label_is_key": label_is_key}
    card["links"] = {"n": len(links), "bound": sum(1 for it in links if (it["payload"] or {}).get("bindings")),
                     "with_inverse": sum(1 for it in links if ((it["payload"] or {}).get("spec") or {}).get("inverse_name"))}

    # 函数
    def cat(it: dict) -> str:
        return ((it["payload"] or {}).get("spec") or {}).get("category") or "rule"
    rules = [it for it in fns if cat(it) == "rule"]
    decs = [it for it in fns if cat(it) == "decision"]
    mets = [it for it in fns if cat(it) == "aggregate"]
    tests_all = sum(len(((it["payload"] or {}).get("spec") or {}).get("tests") or []) for it in fns)
    tests_bad = sum(len((it["payload"] or {}).get("test_failures") or []) for it in fns)
    card["functions"] = {"n": len(fns), "rules": len(rules),
                         "rules_computable": sum(1 for it in rules if ((it["payload"] or {}).get("spec") or {}).get("expression")),
                         "rules_tested": sum(1 for it in rules if ((it["payload"] or {}).get("spec") or {}).get("tests")),
                         "decisions": len(decs), "decisions_ok": sum(1 for it in decs if ((it["payload"] or {}).get("spec") or {}).get("rows")),
                         "metrics": len(mets),
                         "metrics_bound": sum(1 for it in mets if any(b.get("target_kind") == "metric_expr" for b in (it["payload"] or {}).get("bindings") or [])),
                         "tests": tests_all, "tests_failed": tests_bad,
                         "calibre_conflicts": sum(len((it["payload"] or {}).get("calibre_conflicts") or []) for it in fns)}
    card["actions"] = {"n": len(acts), "complete": sum(1 for it in acts if not ((it["payload"] or {}).get("spec") or {}).get("_stub")),
                       "schema_gaps": sum(len((it["payload"] or {}).get("schema_gaps") or []) for it in acts)}
    total = len(objs) + len(links) + len(fns) + len(acts)
    card["ready"] = {"n": sum(ready.values()), "of": total, "ratio": round(sum(ready.values()) / total, 2) if total else 0,
                     "by_kind": ready, "not_ready": not_ready}

    # 流程卡
    sops = g.get("sops") or []
    card["sops"] = {"n": len(sops), "steps": [s.get("step_count") for s in sops],
                    "errors": sum(len((s.get("validation") or {}).get("errors") or []) for s in sops),
                    "warnings": sum(len((s.get("validation") or {}).get("warnings") or []) for s in sops),
                    "with_errors": sum(1 for s in sops if (s.get("validation") or {}).get("errors")),
                    "req_steps_covered": sum((s.get("coverage") or {}).get("covered", 0) for s in sops),
                    "req_steps_total": sum((s.get("coverage") or {}).get("total", 0) for s in sops),
                    "dry_run_ok": sum(1 for s in sops if (s.get("dry_run") or {}).get("ok"))}
    ws = g.get("watches") or []
    card["watches"] = {"n": len(ws), "with_issue": sum(1 for w in ws if w.get("issue") or w.get("weak")),
                       "issues": [w.get("issue") for w in ws if w.get("issue")][:6]}

    # 对账 / 条目覆盖
    chk = g.get("check") or {}
    card["check"] = {"summary": chk.get("summary") or {}, "items": len(chk.get("items") or [])}
    citems = [x for x in chk.get("items") or [] if x.get("id") and x.get("status") != "na"]
    if citems:
        card["reqs"] = {"n": len(citems), "covered": sum(1 for x in citems if x["status"] in ("covered", "builtin")),
                        "builtin": sum(1 for x in citems if x["status"] == "builtin")}
    card["fixes"] = len(g.get("fixes") or [])

    # 成本
    card["llm"] = {"calls": len(calls), "failed": sum(1 for c in calls if c.get("status") != "done"),
                   "prompt_k": round(sum(c.get("prompt_tokens") or 0 for c in calls) / 1000, 1),
                   "output_k": round(sum(c.get("output_tokens") or 0 for c in calls) / 1000, 1),
                   "reasoning_k": round(sum(c.get("reasoning_tokens") or 0 for c in calls) / 1000, 1)}
    return card


def render(case: str, tag: str, rid: str, c: dict) -> str:
    o, l, f, a, s, w, r = c["objects"], c["links"], c["functions"], c["actions"], c["sops"], c["watches"], c["ready"]
    rows = [
        ("能直接用的元素", f"{r['n']}/{r['of']}({int(r['ratio'] * 100)}%)"),
        ("对象 绑表 / 计算属性", f"{o['bound']}/{o['n']} · {o['computed_props']}"),
        ("实例值误当别名", f"{len(o['instance_synonyms'])} {o['instance_synonyms'][:6] or ''}"),
        ("表名当别名 / 显示列是主键", f"{len(o['table_synonyms'])} · {o['label_is_key']}"),
        ("关系 有关联列 / 有反向名", f"{l['bound']}/{l['n']} · {l['with_inverse']}"),
        ("规则 可算 / 有测试", f"{f['rules_computable']}/{f['rules']} · {f['rules_tested']}"),
        ("决策表 有行", f"{f['decisions_ok']}/{f['decisions']}"),
        ("指标 实跑通过", f"{f['metrics_bound']}/{f['metrics']}"),
        ("测试用例 失败/总数", f"{f['tests_failed']}/{f['tests']}"),
        ("口径冲突", f"{f['calibre_conflicts']}"),
        ("动作 补全 / 数据缺口", f"{a['complete']}/{a['n']} · {a['schema_gaps']}"),
        ("流程卡 张数 / 步数 / 错误", f"{s['n']} · {s['steps']} · {s['errors']}"),
        ("流程卡 覆盖文档步骤 / 试运行通过", f"{s['req_steps_covered']}/{s['req_steps_total']} · {s['dry_run_ok']}/{s['n']}"),
        ("定时 有问题/总数", f"{w['with_issue']}/{w['n']}"),
        ("对账", json.dumps(c["check"]["summary"], ensure_ascii=False)),
    ]
    if c.get("reqs"):
        rq = c["reqs"]
        rows.append(("文档条目覆盖", f"{rq['covered']}/{rq['n']}(平台已具备 {rq['builtin']})"))
    rows.append(("按对账修改", str(c.get("fixes", 0))))
    rows.append(("AI 调用 / token(k) 入·出·思考", f"{c['llm']['calls']}(失败 {c['llm']['failed']})· {c['llm']['prompt_k']}·{c['llm']['output_k']}·{c['llm']['reasoning_k']}"))
    rows.append(("耗时", f"{c['elapsed_min']} 分钟"))
    if c.get("adopt"):
        ad = c["adopt"]
        rows.append(("全部采纳后上线", f"上线 {ad.get('published')},留草稿 {ad.get('held')},流程卡 {ad.get('sops_ok')},定时 {ad.get('watches_ok')}"
                     + (f";{ad.get('error')}" if ad.get("error") else "")))
    out = [f"# 建模评测 · {CASES.get(case, {}).get('title', case)} · {tag}", "", f"run `{rid}` · 状态 {c['status']}", "",
           "| 项 | 结果 |", "|---|---|"] + [f"| {k} | {v} |" for k, v in rows]
    if r["not_ready"]:
        out += ["", "**还不能直接用:** " + "、".join(r["not_ready"])]
    if w["issues"]:
        out += ["", "**定时问题:** " + ";".join(w["issues"])]
    if c.get("adopt", {}).get("held_why"):
        out += ["", "**采纳后没上线的原因:** " + ";".join(str(x)[:120] for x in c["adopt"]["held_why"])]
    return "\n".join(out) + "\n"


def compare(case: str) -> None:
    d = OUT / case
    cards = []
    for p in sorted(d.glob("*.json")):
        j = json.loads(p.read_text(encoding="utf-8"))
        cards.append((j["tag"], j["card"]))
    if not cards:
        print("还没有评分卡")
        return
    keys = [("能直接用", lambda c: f"{c['ready']['n']}/{c['ready']['of']}"),
            ("计算属性", lambda c: c["objects"]["computed_props"]),
            ("实例当别名", lambda c: len(c["objects"]["instance_synonyms"])),
            ("规则可算", lambda c: f"{c['functions']['rules_computable']}/{c['functions']['rules']}"),
            ("指标实跑", lambda c: f"{c['functions']['metrics_bound']}/{c['functions']['metrics']}"),
            ("动作补全", lambda c: f"{c['actions']['complete']}/{c['actions']['n']}"),
            ("流程卡错误", lambda c: c["sops"]["errors"]),
            ("流程卡覆盖步骤", lambda c: f"{c['sops']['req_steps_covered']}/{c['sops']['req_steps_total']}"),
            ("定时有问题", lambda c: f"{c['watches']['with_issue']}/{c['watches']['n']}"),
            ("条目覆盖", lambda c: f"{c['reqs']['covered']}/{c['reqs']['n']}" if c.get("reqs") else "-"),
            ("耗时(分)", lambda c: c["elapsed_min"]),
            ("调用", lambda c: c["llm"]["calls"])]
    print("| 项 | " + " | ".join(t for t, _ in cards) + " |")
    print("|---|" + "---|" * len(cards))
    for name, fn in keys:
        print(f"| {name} | " + " | ".join(str(fn(c)) for _, c in cards) + " |")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["cases", "prep", "run", "resume", "score", "compare"])
    ap.add_argument("case", nargs="?")
    ap.add_argument("--tag", default=time.strftime("%m%d_%H%M"))
    ap.add_argument("--db", default="")
    ap.add_argument("--run", default="")
    ap.add_argument("--no-adopt", action="store_true")
    ap.add_argument("--from", dest="from_stage", default="")
    a = ap.parse_args()
    sys.stdout.reconfigure(encoding="utf-8")
    if a.cmd == "cases":
        for k, v in CASES.items():
            print(k, v)
        return
    if a.case not in CASES:
        ap.error(f"样例只能是 {list(CASES)}")
    if a.cmd == "prep":
        prep(a.case)
    elif a.cmd == "run":
        run(a.case, a.tag, adopt=not a.no_adopt)
    elif a.cmd == "resume":
        resume(a.case, a.tag, a.run, adopt=not a.no_adopt, from_stage=a.from_stage)
    elif a.cmd == "score":
        _use_db(a.db or _db_name(a.case))
        _save(a.case, a.tag, a.run, adopt=False)
    else:
        compare(a.case)


if __name__ == "__main__":
    main()