File size: 7,548 Bytes
cf29045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d50bd61
 
cf29045
 
 
 
 
 
 
 
d50bd61
cf29045
d50bd61
 
 
cf29045
 
 
 
 
 
 
d50bd61
 
 
 
 
 
 
 
cf29045
d50bd61
 
 
cf29045
 
 
 
d50bd61
cf29045
 
 
 
 
 
 
 
 
 
d50bd61
cf29045
 
 
 
 
 
 
d50bd61
 
cf29045
 
 
 
 
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
#!/usr/bin/env python3
"""Chấm bộ regression HÀNH VI (data/splits/regression_behavior.jsonl).

Không so câu chữ — so hành vi: trạng thái cuối, có hỏi lại đúng/sai thông tin không,
có dùng đúng/nhầm thủ tục không, có nói điều bị cấm không.

    python3 scripts/eval_regression.py                 # gọi API đang chạy (127.0.0.1:8000)
    python3 scripts/eval_regression.py --in-process    # tự dựng pipeline (không cần server)

Kết quả: reports/regression_results.json + reports/regression_results.md
"""
from __future__ import annotations

import argparse
import json
import sys
import time
import urllib.request
from pathlib import Path
from typing import Any, Dict, List

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

SLOT_WORDS = {"application_id": ["mã hồ sơ"], "procedure_name": ["tên thủ tục"],
              "agency": ["cơ quan đã tiếp nhận", "cơ quan tiếp nhận hồ sơ"],
              "province": ["tỉnh", "thành phố"]}


def check(case: Dict[str, Any], r: Dict[str, Any]) -> List[str]:
    exp, fails = case["expected"], []
    answer = (r.get("answer") or "").lower()
    ev = r.get("evidence") or []
    titles = " || ".join((e.get("title") or "") + " " + (e.get("citation") or "") for e in ev).lower()
    if exp.get("allowed_final_states") and r.get("final_state") not in exp["allowed_final_states"]:
        fails.append(f"final_state={r.get('final_state')} (cần {exp['allowed_final_states']})")
    for key in ("domain", "intent"):
        if exp.get(key) and r.get(key) not in exp[key]:
            fails.append(f"{key}={r.get(key)} (cần {exp[key]})")
    if r.get("intent") in exp.get("forbidden_intent", []):
        fails.append(f"intent bị cấm: {r.get('intent')}")
    missing = r.get("missing_slots") or []
    ask_zone = answer.split("để tôi hỗ trợ")[-1] if "để tôi hỗ trợ" in answer else ""
    for slot in exp.get("must_not_ask", []):
        # Hỏi lại = nằm trong missing_slots hoặc câu hỏi lại cuối câu trả lời.
        if slot in missing and r.get("final_state") != "ANSWER":
            fails.append(f"hỏi lại {slot} (không được hỏi)")
        elif any(w in ask_zone for w in SLOT_WORDS.get(slot, [])):
            fails.append(f"câu hỏi lại nhắc tới {slot}")
    for slot in exp.get("must_ask", []):
        if slot not in missing and not any(w in answer for w in SLOT_WORDS.get(slot, [])):
            fails.append(f"không hỏi {slot}")
    if exp.get("expected_procedure_title") and not any(
            t.lower() in titles for t in exp["expected_procedure_title"]):
        fails.append(f"không dùng thủ tục chứa {exp['expected_procedure_title']}")
    for t in exp.get("forbidden_procedure_title", []):
        if t.lower() in titles:
            fails.append(f"dùng thủ tục bị cấm: {t}")
    for t in exp.get("answer_must_contain", []):
        if t.lower() not in answer:
            fails.append(f"câu trả lời thiếu “{t}”")
    for t in exp.get("answer_must_not_contain", []):
        if t.lower() in answer:
            fails.append(f"câu trả lời chứa điều bị cấm “{t}”")
    if "max_evidence" in exp and len(ev) > exp["max_evidence"]:
        fails.append(f"có {len(ev)} nguồn (tối đa {exp['max_evidence']})")
    for k, v in (exp.get("known_slot") or {}).items():
        if (r.get("known_slots") or {}).get(k) != v:
            fails.append(f"known_slots.{k}={(r.get('known_slots') or {}).get(k)!r} (cần {v!r})")
    return fails


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--api", default="http://127.0.0.1:8000/v1/civic/analyze")
    ap.add_argument("--in-process", action="store_true")
    ap.add_argument("--device", default="cuda")
    ap.add_argument("--file", default=str(ROOT / "data/splits/regression_behavior.jsonl"))
    ap.add_argument("--out", default="regression_results",
                    help="tên tệp kết quả trong reports/ (không kèm đuôi)")
    args = ap.parse_args()
    cases = [json.loads(l) for l in open(args.file, encoding="utf-8") if l.strip()]

    if args.in_process:
        from src.common.config import load_config, load_env_file
        from src.inference.pipeline import CivicPipeline
        load_env_file()
        pipe = CivicPipeline(load_config("civic_nlu"), device=args.device)
        ask = lambda q, history=None: pipe.run(q, history=history).to_dict()
    else:
        def ask(q: str, history=None) -> Dict[str, Any]:
            body = {"query": q, **({"history": history} if history else {})}
            req = urllib.request.Request(args.api, data=json.dumps(body).encode(),
                                         headers={"Content-Type": "application/json"})
            with urllib.request.urlopen(req, timeout=400) as resp:
                return json.load(resp)

    rows, started = [], time.time()
    for case in cases:
        t0 = time.time()
        # Ca hội thoại: hỏi lần lượt các câu trước trong cùng phiên, rồi mới hỏi câu cần chấm.
        history: List[Dict[str, Any]] = []
        for prev in case.get("history", []):
            pr = ask(prev, history or None)
            history.append({"query": prev,
                            "standalone_query": (pr.get("context") or {}).get("standalone_query") or prev,
                            "known_slots": pr.get("known_slots") or {}})
        r = ask(case["query"], history or None)
        fails = check(case, r)
        ctx = r.get("context") or {}
        if "expect_follow_up" in case and bool(ctx.get("follow_up")) != case["expect_follow_up"]:
            fails.append(f"follow_up={bool(ctx.get('follow_up'))} (cần {case['expect_follow_up']})")
        rows.append({"id": case["id"], "query": case["query"], "passed": not fails,
                     "fails": fails, "final_state": r.get("final_state"),
                     "engine": r.get("engine"), "intent": r.get("intent"),
                     "domain": r.get("domain"), "seconds": round(time.time() - t0, 1),
                     "standalone_query": ctx.get("standalone_query"),
                     "answer": r.get("answer")})
        mark = "PASS" if not fails else "FAIL"
        print(f"{mark} {case['id']:<34} {r.get('final_state') or '-':<17} "
              f"engine={r.get('engine')}  {'; '.join(fails)}")

    n_pass = sum(r["passed"] for r in rows)
    summary = {"n": len(rows), "passed": n_pass, "pass_rate": round(n_pass / max(1, len(rows)), 4),
               "engines": sorted({r["engine"] or "-" for r in rows}),
               "elapsed_s": round(time.time() - started, 1)}
    out = ROOT / "reports"
    (out / f"{args.out}.json").write_text(
        json.dumps({"summary": summary, "rows": rows}, ensure_ascii=False, indent=2),
        encoding="utf-8")
    md = ["# Regression hành vi", "",
          f"{n_pass}/{len(rows)} ca đạt · engine: {', '.join(summary['engines'])}", "",
          "| Ca | Kết quả | Trạng thái cuối | Lỗi |", "|---|---|---|---|"]
    md += [f"| `{r['id']}` | {'✅' if r['passed'] else '❌'} | {r['final_state']} | "
           f"{'; '.join(r['fails']) or '—'} |" for r in rows]
    (out / f"{args.out}.md").write_text("\n".join(md) + "\n", encoding="utf-8")
    print(f"\n{n_pass}/{len(rows)} đạt ({summary['elapsed_s']}s) -> reports/{args.out}.md")
    return 0 if n_pass == len(rows) else 1


if __name__ == "__main__":
    raise SystemExit(main())