Download src/preprocessing/build_retrieval_eval.py from khiemdztv/civic-backup: direct link, hf CLI and curl.
- Browser
- Download file 4.46 kB
-
https://huggingface.co/khiemdztv/civic-backup/resolve/main/src/preprocessing/build_retrieval_eval.py
- Command line
-
hf download hf://khiemdztv/civic-backup/src/preprocessing/build_retrieval_eval.py
-
curl -L -o build_retrieval_eval.py https://huggingface.co/khiemdztv/civic-backup/resolve/main/src/preprocessing/build_retrieval_eval.py
4.46 kB
| """T-44 — Benchmark truy xuất với gold CÓ THẬT. | |
| (a) TTHC: truy vấn tổng hợp từ tiêu đề + mô tả; gold = chunk cùng doc_id. | |
| (b) PAKN: câu hỏi của dân làm truy vấn; gold = chunk VBPL có số hiệu được viện dẫn | |
| trong câu trả lời chính thức. Đo thật: chỉ 3,1% câu trả lời có viện dẫn số hiệu | |
| (3.582 mẫu) — vẫn đủ cho một benchmark nghiêm túc, và con số này được ghi rõ. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import random | |
| import re | |
| from collections import Counter, defaultdict | |
| from typing import Any, Dict, List, Set | |
| from ..common.config import add_config_args, load_config | |
| from ..common.io_utils import iter_jsonl_gz, iter_parquet_batches, write_jsonl | |
| from ..common.logging_utils import Timer, get_logger | |
| from .text_norm import normalize, truncate_chars | |
| LOG = get_logger("build_retrieval_eval") | |
| CIT = re.compile(r"\b\d{1,4}\s*/\s*\d{4}\s*/\s*[A-ZĐ][A-ZĐ\-]{1,12}\b") | |
| CIT2 = re.compile(r"\b\d{1,4}/[A-ZĐ]{2,6}-[A-ZĐ]{2,8}\b") | |
| def build_tthc_queries(cfg, limit: int, rng: random.Random) -> List[Dict[str, Any]]: | |
| by_doc: Dict[str, List[str]] = defaultdict(list) | |
| titles: Dict[str, str] = {} | |
| for batch in iter_parquet_batches(cfg["data_clean"]["tthc_chunks"], | |
| ["chunk_id", "doc_id", "title", "section"], 16384): | |
| for cid, did, ti, sec in zip(batch["chunk_id"], batch["doc_id"], | |
| batch["title"], batch["section"]): | |
| by_doc[did].append(cid) | |
| titles.setdefault(did, ti or "") | |
| docs = [d for d, c in by_doc.items() if len(c) >= 2 and titles.get(d)] | |
| rng.shuffle(docs) | |
| out = [] | |
| for d in docs[:limit]: | |
| t = normalize(titles[d]) | |
| out.append({"qid": f"tthc:{d}", "query": f"Thủ tục {t} thực hiện như thế nào?", | |
| "gold_chunk_ids": by_doc[d], "gold_doc_ids": [d], | |
| "route": "TTHC", "origin": "tthc_title"}) | |
| return out | |
| def build_pakn_queries(cfg, limit: int, rng: random.Random) -> List[Dict[str, Any]]: | |
| LOG.info("Lập chỉ mục số hiệu -> chunk_id trên VBPL …") | |
| by_sohieu: Dict[str, List[str]] = defaultdict(list) | |
| for path in (cfg["data_clean"]["vbpl_chunks"], cfg["data_clean"]["vbpldp_chunks"]): | |
| for batch in iter_parquet_batches(path, ["chunk_id", "so_hieu", "con_hieu_luc"], 32768): | |
| for cid, sh, eff in zip(batch["chunk_id"], batch["so_hieu"], batch["con_hieu_luc"]): | |
| if sh and eff and len(by_sohieu[sh.strip()]) < 40: | |
| by_sohieu[sh.strip()].append(cid) | |
| out: List[Dict[str, Any]] = [] | |
| n_scanned = n_cited = 0 | |
| for d in iter_jsonl_gz(cfg["data_clean"]["pakn_docs"]): | |
| n_scanned += 1 | |
| ans = d.get("answer") or "" | |
| cits = {c.replace(" ", "") for c in CIT.findall(ans)} | set(CIT2.findall(ans)) | |
| if not cits: | |
| continue | |
| n_cited += 1 | |
| gold: List[str] = [] | |
| for c in cits: | |
| gold.extend(by_sohieu.get(c, [])) | |
| if not gold: | |
| continue | |
| q = normalize(d.get("question") or "") | |
| if len(q) < 40: | |
| continue | |
| out.append({"qid": f"pakn:{d['doc_id']}", "query": truncate_chars(q, 700), | |
| "gold_chunk_ids": gold[:60], "gold_doc_ids": sorted(cits), | |
| "route": "VBPL", "origin": "pakn_citation", | |
| "send_date": d.get("send_date")}) | |
| LOG.info("PAKN: quét %d, có viện dẫn số hiệu %d (%.1f%%), khớp được gold %d", | |
| n_scanned, n_cited, 100 * n_cited / max(1, n_scanned), len(out)) | |
| rng.shuffle(out) | |
| return out[:limit] | |
| def main() -> None: | |
| ap = argparse.ArgumentParser(description="T-44 dựng benchmark truy xuất") | |
| ap.add_argument("--n-tthc", type=int, default=800) | |
| ap.add_argument("--n-pakn", type=int, default=800) | |
| add_config_args(ap) | |
| args = ap.parse_args() | |
| cfg = load_config("paths", args.overrides) | |
| rng = random.Random(42) | |
| with Timer(LOG, "build_retrieval_eval"): | |
| rows = build_tthc_queries(cfg, args.n_tthc, rng) + build_pakn_queries(cfg, args.n_pakn, rng) | |
| rng.shuffle(rows) | |
| out = cfg["splits"]["retrieval_eval"] | |
| write_jsonl(out, rows) | |
| LOG.info("Đã ghi %d truy vấn -> %s | theo nguồn: %s", len(rows), out, | |
| dict(Counter(r["origin"] for r in rows))) | |
| if __name__ == "__main__": | |
| main() | |