"""Nghiệm thu các tình huống công dân độc lập với nhãn PAKN lịch sử.""" from __future__ import annotations import argparse import re import time from typing import Any, Dict, List from ..common.config import load_config from ..common.io_utils import atomic_save_json, iter_jsonl, write_jsonl from ..common.logging_utils import get_logger from ..inference.pipeline import CivicPipeline LOG = get_logger("eval_acceptance") UNSAFE = re.compile( r"(?:(?:tôi|chúng tôi|hệ thống|trợ lý)[^.!?\n]{0,40}(?:đã|sẽ)\s+" r"(?:gửi|chuyển|tiếp nhận|tra soát|giải quyết)|" r"(?:phản ánh|thông tin|hồ sơ|vụ việc)(?:\s+của\s+bạn)?\s+" r"(?:đã|sẽ)\s+(?:được\s+)?(?:gửi|chuyển|tiếp nhận|tra soát|giải quyết))", re.I, ) LEGAL_ACTIONS = {"PROVIDE_LEGAL_BASIS", "PROVIDE_PROCEDURE_GUIDE"} def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--limit", type=int, default=None) parser.add_argument("--device", default="cpu") args = parser.parse_args() cfg = load_config("civic_nlu") path = f"{cfg['splits']['dir']}/citizen_acceptance.jsonl" cases = list(iter_jsonl(path, limit=args.limit)) pipe = CivicPipeline(cfg, device=args.device) rows: List[Dict[str, Any]] = [] started = time.time() for index, case in enumerate(cases, 1): response = pipe.run(case["question"], trace=True) item = {**case, **response.to_dict(include_trace=True)} item["intent_ok"] = response.intent == case.get("expected_intent") item["domain_ok"] = (not case.get("expected_domain") or response.domain == case["expected_domain"]) item["no_fake_handoff"] = not bool(UNSAFE.search(response.answer)) item["grounded_if_legal"] = not ( response.can_answer_directly and response.next_action in LEGAL_ACTIONS and not response.evidence) keywords = [str(word).lower() for word in case.get("answer_keywords", [])] item["answer_relevant"] = bool( not keywords or response.reason_code or not response.can_answer_directly or any(word in response.answer.lower() for word in keywords)) item["passed"] = all(item[key] for key in ( "intent_ok", "domain_ok", "no_fake_handoff", "grounded_if_legal", "answer_relevant")) rows.append(item) LOG.info("%d/%d %-22s intent=%s domain=%s pass=%s", index, len(cases), case["id"], response.intent, response.domain, item["passed"]) total = len(rows) or 1 summary = { "n": len(rows), "intent_accuracy": round(sum(r["intent_ok"] for r in rows) / total, 4), "domain_accuracy": round(sum(r["domain_ok"] for r in rows) / total, 4), "fake_handoff_count": sum(not r["no_fake_handoff"] for r in rows), "ungrounded_legal_count": sum(not r["grounded_if_legal"] for r in rows), "irrelevant_answer_count": sum(not r["answer_relevant"] for r in rows), "pass_rate": round(sum(r["passed"] for r in rows) / total, 4), "elapsed_s": round(time.time() - started, 1), "failed_ids": [r["id"] for r in rows if not r["passed"]], } write_jsonl(f"{cfg['reports']['dir']}/acceptance_predictions.jsonl", rows) atomic_save_json(f"{cfg['reports']['dir']}/acceptance_summary.json", summary) LOG.info("ACCEPTANCE %s", summary) if __name__ == "__main__": main()