"""TẦNG 1 — Gán nhãn yếu bằng luật. Độ phủ đo thật trên 114.813 phản ánh: domain 69,1% | next_action 24,7%. => Luật KHÔNG đủ cho head next_action; phần còn lại do llm_label.py (Tầng 2) đảm nhiệm. NGUYÊN TẮC BẤT DI BẤT DỊCH: nhãn nào không luật nào bắt được thì để None (mask), tuyệt đối không gán bừa. Đó chính là lý do tồn tại của Masked Multi-Task Loss. """ from __future__ import annotations import re from typing import Any, Dict, List, Optional, Tuple import yaml from ..common.config import CONFIG_DIR from ..common.io_utils import load_json from ..common.registry import get_registry from ..common.schema import NLUSample, Slot from .pii import TAG_TO_SLOT, has_slot_tag from .slot_tagger_rules import extract_slots from .text_norm import normalize _RULES: Optional[Dict[str, Any]] = None _COMPILED: Optional[Dict[str, List[Tuple[str, int, str, List["re.Pattern[str]"]]]]] = None _LV2DOM: Optional[Dict[str, str]] = None def _load() -> None: global _RULES, _COMPILED if _COMPILED is not None: return with open(CONFIG_DIR / "weak_rules.yaml", "r", encoding="utf-8") as f: _RULES = yaml.safe_load(f) _COMPILED = {} for key in ("intent_rules", "problem_rules", "next_action_rules"): _COMPILED[key] = [ (r["label"], int(r.get("priority", 0)), r.get("field", "both"), [re.compile(p, re.IGNORECASE) for p in r["any_regex"]]) for r in _RULES.get(key, []) ] def _linhvuc_map(artifacts_dir: Optional[str] = None) -> Dict[str, str]: global _LV2DOM if _LV2DOM is None: from ..common.config import load_config cfg = load_config("paths") gz = load_json(f"{artifacts_dir or cfg['artifacts']['dir']}/gazetteers.json", default={}) or {} _LV2DOM = gz.get("linhvuc2domain", {}) return _LV2DOM def _pick_field(question: str, answer: str, title: str, field: str) -> str: if field == "question": return f"{title} {question}" if field == "answer": return answer return f"{title} {question} {answer}" def _best_match(key: str, question: str, answer: str, title: str) -> Tuple[Optional[str], Optional[str]]: """Trả (label, rule_id) của luật ưu tiên cao nhất khớp được, hoặc (None, None).""" _load() best: Optional[Tuple[int, str, str]] = None for label, prio, field, pats in _COMPILED[key]: blob = _pick_field(question, answer, title, field) for i, pat in enumerate(pats): if pat.search(blob): cand = (prio, label, f"{key}:{label}#{i}") if best is None or cand[0] > best[0]: best = cand break return (best[1], best[2]) if best else (None, None) def label_domain(title: str, question: str, answer: str) -> Tuple[Optional[str], Optional[str]]: _load() blob = f"{title} {question} {answer}".lower() # Chấm điểm = priority + độ dài từ khoá. Từ khoá dài mang nhiều thông tin hơn: # "giấy chứng nhận quyền sử dụng đất" (LAND_ADMIN) phải thắng "tư pháp" (JUSTICE). best: Optional[Tuple[float, str, str]] = None for r in _RULES.get("domain_rules", []): prio = float(r.get("priority", 0)) for kw in r.get("any", []): if kw in blob: cand = (prio + 0.8 * len(kw), r["label"], f"domain:{r['label']}:{kw}") if best is None or cand[0] > best[0]: best = cand return (best[1], best[2]) if best else (None, None) def label_routes(intent: Optional[str]) -> Optional[List[str]]: _load() if intent is None: return None routes = [r for r, intents in _RULES.get("route_rules", {}).items() if intent in intents] return routes or ["TTHC"] def _required_slots_for(intent: Optional[str], policy: Dict[str, Any]) -> List[str]: if intent is None: return [] for p in policy.get("policies", []): if p.get("intent") == intent: return list(p.get("required_slots", [])) return [] _POLICY: Optional[Dict[str, Any]] = None def _policy() -> Dict[str, Any]: global _POLICY if _POLICY is None: with open(CONFIG_DIR / "action_policy.yaml", "r", encoding="utf-8") as f: _POLICY = yaml.safe_load(f) return _POLICY def compute_missing_slots(intent: Optional[str], text: str, slots: List[Slot]) -> Optional[List[str]]: """Slot bắt buộc theo intent mà công dân KHÔNG cung cấp.""" if intent is None: return None reg = get_registry() required = _required_slots_for(intent, _policy()) present = {s.slot_type for s in slots} for kind, slot_type in TAG_TO_SLOT.items(): if has_slot_tag(text, kind): present.add(slot_type) missing = [s for s in required if s not in present and s in reg.missing_slot.label2id] return missing def annotate(doc: Dict[str, Any], use_answer: bool = True) -> NLUSample: """Gán nhãn một phản ánh. `use_answer=True` khi CHUẨN BỊ DỮ LIỆU (được đọc câu trả lời chính thức — thông tin hậu nghiệm). Lúc SUY LUẬN luôn là False. """ title = normalize(doc.get("title", "")) question = normalize(doc.get("question", "")) answer = normalize(doc.get("answer", "")) if use_answer else "" text = f"{title}. {question}".strip() if title else question domain, r_dom = label_domain(title, question, answer) intent, r_int = _best_match("intent_rules", question, answer, title) problem, r_prb = _best_match("problem_rules", question, answer, title) action, r_act = (_best_match("next_action_rules", question, answer, title) if use_answer else (None, None)) slots = extract_slots(text) missing = compute_missing_slots(intent, text, slots) routes = label_routes(intent) can_answer = None if intent is None else (not missing) label_source: Dict[str, str] = {} rule_ids: Dict[str, str] = {} for head, val, rid in (("domain", domain, r_dom), ("intent", intent, r_int), ("problem_type", problem, r_prb), ("next_action", action, r_act)): if val is not None: label_source[head] = "rule" if rid: rule_ids[head] = rid if slots: label_source["slots"] = "rule" if missing is not None: label_source["missing_slots"] = "rule" if routes is not None: label_source["retrieval_routes"] = "rule" if can_answer is not None: label_source["can_answer"] = "rule" return NLUSample( doc_id=str(doc.get("doc_id", "")), text=text, send_date=doc.get("send_date"), domain=domain, intent=intent, problem_type=problem, next_action=action, can_answer=can_answer, retrieval_routes=routes, missing_slots=missing, slots=slots, label_source=label_source, rule_ids=rule_ids, ) def domain_from_linhvuc(linh_vuc: str) -> Optional[str]: """Ánh xạ trực tiếp khi biết lĩnh vực (dùng cho chunk TTHC/VBPL).""" d = _linhvuc_map().get(linh_vuc or "") return None if d in (None, "OTHER") else d def _annotate_worker(doc: Dict[str, Any]) -> NLUSample: """Hàm top-level để multiprocessing pickle được.""" return annotate(doc, use_answer=True) # ---------------------------------------------------------------- CLI (T-21) def _run_cli() -> None: import argparse from collections import Counter from ..common.config import add_config_args, load_config from ..common.io_utils import iter_jsonl_gz, write_jsonl from ..common.logging_utils import Timer, get_logger from .word_segment import commit_cache, init_cache log = get_logger("weak_label") ap = argparse.ArgumentParser(description="T-21 — gán nhãn yếu Tầng 1 (luật)") ap.add_argument("--limit", type=int, default=None, help="chỉ xử lý N mẫu đầu (để thử)") ap.add_argument("--no-segment", action="store_true", default=True, help="bỏ qua word-segment ở tầng này (mặc định bật; " "build_nlu_dataset.py sẽ segment đúng tập được chọn)") ap.add_argument("--segment", dest="no_segment", action="store_false", help="bật word-segment ngay tại tầng 1 (chậm hơn ~30x)") ap.add_argument("--workers", type=int, default=4, help="số tiến trình song song (máy có 4 vCPU)") add_config_args(ap) args = ap.parse_args() cfg = load_config("paths", args.overrides) init_cache(cfg["artifacts"]["seg_cache"]) heads = ["domain", "intent", "problem_type", "next_action", "can_answer", "retrieval_routes", "missing_slots", "slots"] cover: Counter = Counter() dist: dict = {h: Counter() for h in ("domain", "intent", "problem_type", "next_action")} n = 0 def _iter_samples(): """Sinh NLUSample, dùng multiprocessing khi workers > 1.""" docs = iter_jsonl_gz(cfg["data_clean"]["pakn_docs"], limit=args.limit) if args.workers > 1 and args.no_segment: import multiprocessing as mp with mp.Pool(args.workers) as pool: for s in pool.imap(_annotate_worker, docs, chunksize=256): yield s else: from .word_segment import segment for doc in docs: s = annotate(doc, use_answer=True) if not args.no_segment: s.text_seg = segment(s.text) yield s def rows(): nonlocal n for s in _iter_samples(): n += 1 for h in heads: v = getattr(s, h, None) if v is not None and v != []: cover[h] += 1 for h in dist: v = getattr(s, h) if v is not None: dist[h][v] += 1 if n % 20000 == 0: log.info("… %d mẫu", n) commit_cache() yield s.to_dict() out = cfg["splits"]["rule_labels"] with Timer(log, "weak_label"): written = write_jsonl(out, rows()) commit_cache() log.info("Đã ghi %d mẫu -> %s", written, out) log.info("--- ĐỘ PHỦ NHÃN (Tầng 1 - luật) ---") for h in heads: log.info(" %-18s %7d / %d (%5.1f%%)", h, cover[h], n, 100 * cover[h] / max(1, n)) for h, c in dist.items(): log.info(" phân bố %-14s %s", h, c.most_common(6)) if __name__ == "__main__": _run_cli()