"""Chấm truy xuất VBPL theo VĂN BẢN, trên kho hợp nhất với cờ hiệu lực hiện hành. Bộ câu hỏi: - pakn : data/splits/retrieval_eval_vbpl.jsonl (python -m src.preprocessing.build_vbpl_eval) - manual : data/splits/retrieval_eval_vbpl_manual.jsonl — câu soát tay, đáp án là văn bản ĐANG áp dụng (có thể khác văn bản cán bộ từng trích). Cách dựng truy vấn (--modes): - raw : nguyên văn câu hỏi (như bộ chấm cũ); - base : build_retrieval_query(câu hỏi) — truy vấn gốc pipeline luôn chạy kèm; - gemini : search_queries từ plan_query của Gemini (đúng lời gọi pipeline dùng) + base, gộp theo điểm rerank cao nhất mỗi chunk, loại văn bản đã có văn bản thay thế trong kết quả — như `_gather_sources`. Kết quả Gemini lưu cache, chạy lại không tốn hạn mức; - gemini_raw : như gemini nhưng truy vấn cuối là nguyên văn câu hỏi thay cho base. Xếp hạng văn bản = thứ tự lần đầu văn bản xuất hiện trong danh sách chunk đã rerank. python -m src.evaluation.eval_vbpl --modes raw base gemini --local """ from __future__ import annotations import argparse import gc import hashlib import json import threading import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Tuple from ..common.config import add_config_args, load_config, load_env_file from ..common.io_utils import atomic_save_json, iter_jsonl, write_jsonl from ..common.logging_utils import Timer, get_logger from ..preprocessing.build_vbpl_eval import norm_sohieu from ..preprocessing.word_segment import init_cache LOG = get_logger("eval_vbpl") KS = (1, 3, 5, 10) LONG_CHARS = 300 # câu hỏi dài: từ 300 ký tự (~60 từ) trở lên # ------------------------------------------------------------------ truy vấn Gemini def _key(q: Dict[str, Any]) -> str: return hashlib.sha1(q["query"].encode("utf-8")).hexdigest()[:16] def prepare_gemini(queries: Sequence[Dict[str, Any]], cache_path: Path, workers: int) -> Dict[str, List[str]]: """Gọi plan_query cho các câu chưa có trong cache (song song), trả {khoá: [truy vấn]}.""" from ..common.registry import get_registry from ..generation import gemini_reasoner cache: Dict[str, List[str]] = {} if cache_path.exists(): for r in iter_jsonl(str(cache_path)): cache[r["key"]] = r["search_queries"] todo = [q for q in queries if _key(q) not in cache] if not todo: return cache load_env_file() rcfg = dict(load_config("generation").get("reasoner") or {}) # Chỉ các mô hình Flash-Lite pipeline dùng cho lượt plan: gói miễn phí giới hạn theo PHÚT, # nên chờ hết cửa sổ rồi gọi lại thay vì rơi xuống mô hình khác (gemini-2.5-flash-lite # hiện trả 404 và làm hỏng cả câu). light = list(rcfg.get("light_models") or [])[:2] rcfg.update(light_models=light, fallback_models=light, model=light[0] if light else rcfg["model"]) rs = gemini_reasoner.build_from_env(rcfg) if rs is None: raise SystemExit("Chế độ gemini cần GEMINI_API_KEY (.env).") reg = get_registry() labels = {"domain": reg.domain.labels, "intent": reg.intent.labels, "problem": reg.problem.labels} lock = threading.Lock() LOG.info("Gemini plan_query cho %d câu (cache có %d) …", len(todo), len(cache)) def one(q: Dict[str, Any]) -> None: errors = 0 for _ in range(30): try: plan = rs.plan_query(q["query"], {}, labels, {}) break except gemini_reasoner.QuotaExceeded as exc: wait = exc.until - time.time() if wait > 600: # hết hạn mức NGÀY raise time.sleep(max(5.0, wait)) except Exception as exc: # pragma: no cover LOG.warning("plan_query lỗi %s: %s", q["qid"], str(exc)[:120]) errors += 1 if errors >= 3: return time.sleep(5) else: return sq = [str(x) for x in (plan.get("search_queries") or []) if isinstance(x, str)] rec = {"key": _key(q), "qid": q["qid"], "search_queries": sq, "model": rs.client.last_model} with lock: cache[rec["key"]] = sq with open(cache_path, "a", encoding="utf-8") as f: f.write(json.dumps(rec, ensure_ascii=False) + "\n") with ThreadPoolExecutor(workers) as ex: for i, _ in enumerate(ex.map(one, todo), 1): if i % 50 == 0: LOG.info(" Gemini %d/%d", i, len(todo)) return cache def query_list(q: Dict[str, Any], mode: str, plans: Dict[str, List[str]]) -> List[str]: from ..retrieval.query_builder import build_retrieval_query base = build_retrieval_query(q["query"]) if mode == "raw": return [q["query"]] if mode == "base": return [base] sq = [s for s in plans.get(_key(q), []) if len(s) >= 6][:3] if mode == "gemini_raw": # thử nghiệm: thay base bằng nguyên văn câu hỏi return sq + [q["query"]] return sq + [base] # như pipeline: queries[:3] + [base] # ------------------------------------------------------------------ tra cứu def ranked_docs(r, cfg, queries: List[str], question: str, local: bool, topk: int) -> List[Dict[str, Any]]: pool: Dict[str, Any] = {} for qs in queries: for e in r.search(qs, ["VBPL"], None, topk=topk)["evidence"]: old = pool.get(e.chunk_id) if old is None or e.rerank_score > old.rerank_score: pool[e.chunk_id] = e items = list(pool.values()) if local and r.legal() is not None: from ..common.provinces import resolve_province place = resolve_province(question) if place is not None: extra = r.search_legal(queries[-1], "hybrid", None, scope=("local", tuple(place.search_olds))) rr = r.reranker() items += rr.rerank(queries[-1], extra, topk=3) if rr is not None else extra[:3] if (cfg.get("legal_priors") or {}).get("drop_superseded", False): from ..retrieval.legal_store import mark_superseded mark_superseded(items, cfg) present = {e.so_hieu for e in items if not e.superseded_by} items = [e for e in items if not (e.superseded_full and e.superseded_by in present)] items.sort(key=lambda e: -e.rerank_score) seen, out = set(), [] for e in items: k = norm_sohieu(e.so_hieu) or e.doc_id if k in seen: continue seen.add(k) out.append({"so_hieu": k, "score": round(float(e.rerank_score), 4), "title": (e.title or "")[:100], "valid": bool(e.con_hieu_luc)}) return out # ------------------------------------------------------------------ chỉ số def score_one(docs: List[str], gold: Sequence[str], outdated: Sequence[str]) -> Dict[str, float]: gold_s, old_s = set(gold), set(outdated) first = next((i for i, d in enumerate(docs[:10], 1) if d in gold_s), None) m = {f"hit@{k}": float(first is not None and first <= k) for k in KS} m["mrr@10"] = 1.0 / first if first else 0.0 m["cover@5"] = len(set(docs[:5]) & gold_s) / max(1, len(gold_s)) m["outdated@5"] = float(bool(set(docs[:5]) & old_s)) return m def aggregate(rows: List[Dict[str, float]]) -> Dict[str, float]: n = len(rows) if not n: return {"n": 0} out = {k: round(sum(r[k] for r in rows) / n, 4) for k in rows[0]} out["n"] = n return out def subsets(q: Dict[str, Any]) -> List[str]: tags = ["all", "long" if len(q["query"]) >= LONG_CHARS else "short"] scope = q.get("gold_scope") or {} if scope and all(s != "central" for s in scope.values()): tags.append("local_only") return tags def render(res: Dict[str, Dict[str, Dict[str, Dict[str, float]]]], note: str) -> str: names = {"all": "Tất cả", "short": f"Câu ngắn (< {LONG_CHARS} ký tự)", "long": f"Câu dài (≥ {LONG_CHARS} ký tự)", "local_only": "Gold chỉ có VB địa phương"} L = ["# Truy xuất VBPL — chấm theo văn bản", "", note, ""] for set_name, by_mode in res.items(): L += [f"## Bộ `{set_name}`", ""] parts = [p for p in ("all", "short", "long", "local_only") if any(p in v for v in by_mode.values())] for p in parts: n = next(v[p]["n"] for v in by_mode.values() if p in v) L += [f"### {names[p]} ({n} câu)", "", "| Truy vấn | Hit@1 | Hit@3 | Hit@5 | Hit@10 | MRR@10 | Phủ gold@5 | VB cũ trong top 5 |", "|---|---:|---:|---:|---:|---:|---:|---:|"] for mode, parts_res in by_mode.items(): a = parts_res.get(p) if a and a["n"]: L.append(f"| `{mode}` | {a['hit@1']:.3f} | {a['hit@3']:.3f} | {a['hit@5']:.3f} | " f"{a['hit@10']:.3f} | {a['mrr@10']:.3f} | {a['cover@5']:.3f} | " f"{a['outdated@5']:.3f} |") L.append("") L += ["## Đọc bảng", "", "- **Hit@k**: có ít nhất một văn bản gold trong k văn bản đầu (đã gộp chunk theo số hiệu).", "- **Phủ gold@5**: tỉ lệ văn bản gold nằm trong top 5 (câu có nhiều văn bản gold).", "- **VB cũ trong top 5**: tỉ lệ câu có văn bản cán bộ từng trích nhưng nay đã hết hiệu lực " "lọt vào top 5. Kho lọc hiệu lực trước khi xếp hạng, nên con số khác 0 chỉ đến từ văn bản " "dữ liệu còn ghi nhầm 'Còn hiệu lực' (STALE_VALID trong build_vbpl_eval), tức lỗi cờ cần sửa ở dữ liệu.", "- Bộ `pakn`: gold = văn bản cán bộ trích, còn hiệu lực theo cờ mới, đã bỏ văn bản thủ tục chung. " "Bộ `manual`: gold = văn bản đang áp dụng, soát tay.", ""] return "\n".join(L) def rescore(sets: Dict[str, List[Dict[str, Any]]], base: str) -> None: """Chấm lại dự đoán đã lưu (top 10 văn bản mỗi câu) theo gold hiện tại của các bộ câu hỏi.""" by_id = {(s, q["qid"]): q for s, qs in sets.items() for q in qs} rows = list(iter_jsonl(base + ".preds.jsonl")) res: Dict[str, Dict[str, Dict[str, Dict[str, float]]]] = {} per: Dict[Tuple[str, str], Dict[str, List[Dict[str, float]]]] = {} kept = [] for d in rows: q = by_id.get((d["set"], d["qid"])) if q is None: continue ids: List[str] = [] for t in d["top"]: t["so_hieu"] = norm_sohieu(t["so_hieu"]) or t["so_hieu"] if t["so_hieu"] not in ids: ids.append(t["so_hieu"]) m = score_one(ids, q["gold_docs"], q.get("outdated_cited") or []) d.update(gold=q["gold_docs"], **m) kept.append(d) for t in subsets(q): per.setdefault((d["set"], d["mode"]), {}).setdefault(t, []).append(m) for (set_name, mode), parts in per.items(): res.setdefault(set_name, {})[mode] = {t: aggregate(v) for t, v in parts.items()} a = res[set_name][mode]["all"] LOG.info("%-7s %-10s Hit@1=%.3f Hit@5=%.3f Hit@10=%.3f MRR=%.3f", set_name, mode, a["hit@1"], a["hit@5"], a["hit@10"], a["mrr@10"]) atomic_save_json(base + ".json", res) write_jsonl(base + ".preds.jsonl", kept) note = ("Kho hợp nhất, cờ hiệu lực hiện hành, lọc hiệu lực tại hôm nay trước khi xếp hạng. " "Chấm lại từ dự đoán đã lưu theo gold hiện tại (--rescore).") with open(base + ".md", "w", encoding="utf-8") as f: f.write(render(res, note)) LOG.info("-> %s.md", base) def main() -> None: ap = argparse.ArgumentParser(description="Chấm truy xuất VBPL theo văn bản") ap.add_argument("--sets", nargs="*", default=["pakn", "manual"]) ap.add_argument("--modes", nargs="*", default=["raw", "base", "gemini", "gemini_raw"]) ap.add_argument("--limit", type=int, default=None) ap.add_argument("--local", action="store_true", help="câu nêu tỉnh: tra thêm văn bản địa phương như pipeline thật") ap.add_argument("--topk", type=int, default=30, help="số chunk lấy mỗi truy vấn trước khi gộp") ap.add_argument("--workers", type=int, default=4, help="số luồng gọi Gemini") ap.add_argument("--device", default="cuda") ap.add_argument("--tag", default="") ap.add_argument("--plans-only", action="store_true", help="chỉ gọi Gemini lấy truy vấn, không chấm") ap.add_argument("--rescore", action="store_true", help="chấm lại từ reports/retrieval_vbpl..preds.jsonl theo gold hiện tại, " "không tra cứu lại (dùng sau khi sửa gold)") add_config_args(ap) args = ap.parse_args() cfg = load_config("retrieval", args.overrides) init_cache(cfg["artifacts"]["seg_cache"]) split_dir = Path(cfg["splits"]["retrieval_eval"]).parent files = {"pakn": split_dir / "retrieval_eval_vbpl.jsonl", "manual": split_dir / "retrieval_eval_vbpl_manual.jsonl"} sets: Dict[str, List[Dict[str, Any]]] = {} for s in args.sets: if not files[s].exists(): raise SystemExit(f"Thiếu {files[s]}. Chạy: python -m src.preprocessing.build_vbpl_eval") sets[s] = list(iter_jsonl(str(files[s]), limit=args.limit)) LOG.info("Bộ %s: %d câu", s, len(sets[s])) base = f"{cfg['reports']['dir']}/retrieval_vbpl" + (f".{args.tag}" if args.tag else "") if args.rescore: rescore(sets, base) return plans: Dict[str, List[str]] = {} if any(m.startswith("gemini") for m in args.modes): plans = prepare_gemini([q for v in sets.values() for q in v], split_dir / "retrieval_eval_vbpl_plans.jsonl", args.workers) if args.plans_only: LOG.info("Đã có truy vấn Gemini cho %d câu.", len(plans)) return from ..retrieval.retriever import HybridRetriever r = HybridRetriever(cfg, device=args.device) res: Dict[str, Dict[str, Dict[str, Dict[str, float]]]] = {} dump: List[Dict[str, Any]] = [] for set_name, queries in sets.items(): res[set_name] = {} for mode in args.modes: per: Dict[str, List[Dict[str, float]]] = {} with Timer(LOG, f"{set_name}/{mode}"): for i, q in enumerate(queries, 1): qs = query_list(q, mode, plans) docs = ranked_docs(r, cfg, qs, q["query"], args.local, args.topk) ids = [d["so_hieu"] for d in docs] m = score_one(ids, q["gold_docs"], q.get("outdated_cited") or []) for t in subsets(q): per.setdefault(t, []).append(m) dump.append({"set": set_name, "mode": mode, "qid": q["qid"], "queries": qs, "gold": q["gold_docs"], "top": docs[:10], **m}) if i % 100 == 0: LOG.info(" [%s/%s] %d/%d", set_name, mode, i, len(queries)) res[set_name][mode] = {t: aggregate(v) for t, v in per.items()} a = res[set_name][mode]["all"] LOG.info("%-7s %-7s Hit@1=%.3f Hit@5=%.3f Hit@10=%.3f MRR=%.3f", set_name, mode, a["hit@1"], a["hit@5"], a["hit@10"], a["mrr@10"]) del r gc.collect() note = ("Kho hợp nhất, cờ hiệu lực hiện hành, lọc hiệu lực tại hôm nay trước khi xếp hạng" + ("; câu nêu tỉnh tra thêm văn bản địa phương" if args.local else "") + f". Mỗi truy vấn lấy {args.topk} chunk đã rerank, gộp theo số hiệu văn bản.") atomic_save_json(base + ".json", res) write_jsonl(base + ".preds.jsonl", dump) with open(base + ".md", "w", encoding="utf-8") as f: f.write(render(res, note)) LOG.info("-> %s.md", base) if __name__ == "__main__": main()