File size: 7,561 Bytes
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""T-10 — Kiểm toán toàn bộ data_clean bằng streaming (RAM đỉnh < 6 GB).

Đầu ra: reports/data_audit.md + artifacts/audit_stats.json
"""
from __future__ import annotations

import argparse
from collections import Counter
from typing import Any, Dict, List

from ..common.config import add_config_args, load_config
from ..common.io_utils import (atomic_save_json, iter_jsonl_gz,
                               iter_parquet_batches, parquet_num_rows)
from ..common.logging_utils import Timer, get_logger, log_resources, ram_gb
from .text_norm import looks_mojibake

LOG = get_logger("audit_data")
CHUNK_COLS = ["source", "section", "linh_vuc", "loai_van_ban", "co_quan_ban_hanh",
              "con_hieu_luc", "n_tokens_est", "so_hieu", "dup_group"]


def _pct(a: int, b: int) -> str:
    return f"{(a / b * 100):.1f}%" if b else "0.0%"


def audit_chunks(path: str, name: str) -> Dict[str, Any]:
    LOG.info("Kiểm toán %s …", name)
    total = parquet_num_rows(path)
    eff = Counter(); lv = Counter(); lvb = Counter(); sec = Counter(); cq = Counter()
    toks: List[int] = []
    mojibake = 0
    sohieu = set()
    for batch in iter_parquet_batches(path, CHUNK_COLS, 16384):
        eff.update(batch["con_hieu_luc"])
        lv.update(x for x in batch["linh_vuc"] if x)
        lvb.update(x for x in batch["loai_van_ban"] if x)
        sec.update(batch["section"])
        cq.update(x for x in batch["co_quan_ban_hanh"] if x)
        toks.extend(int(t or 0) for t in batch["n_tokens_est"])
        for x in batch["loai_van_ban"]:
            if x and looks_mojibake(x):
                mojibake += 1
        sohieu.update(x for x in batch["so_hieu"] if x)
    toks.sort()
    def q(p: float) -> int:
        return toks[min(len(toks) - 1, int(p * len(toks)))] if toks else 0
    return {
        "rows": total,
        "con_hieu_luc_true": eff.get(True, 0),
        "con_hieu_luc_false": eff.get(False, 0),
        "n_linh_vuc": len(lv),
        "n_so_hieu": len(sohieu),
        "mojibake_rows": mojibake,
        "tokens": {"mean": round(sum(toks) / max(1, len(toks)), 1),
                   "p50": q(0.50), "p95": q(0.95), "p99": q(0.99), "max": toks[-1] if toks else 0},
        "top_loai_van_ban": lvb.most_common(10),
        "top_linh_vuc": lv.most_common(10),
        "top_section": sec.most_common(10),
        "top_co_quan": cq.most_common(10),
    }


def audit_pakn(path: str) -> Dict[str, Any]:
    LOG.info("Kiểm toán pakn_docs …")
    n = 0; has_ans = 0; pii = Counter(); years = Counter(); dup = Counter()
    toks: List[int] = []
    for d in iter_jsonl_gz(path):
        n += 1
        if d.get("has_answer"):
            has_ans += 1
        for k, v in (d.get("pii_kinds") or {}).items():
            pii[k] += int(v)
        years[(d.get("send_date") or "????")[:4]] += 1
        toks.append(int(d.get("n_tokens_est") or 0))
        dup[d.get("dup_group", "")] += 1
    toks.sort()
    def q(p: float) -> int:
        return toks[min(len(toks) - 1, int(p * len(toks)))] if toks else 0
    over256 = sum(1 for t in toks if t > 256)
    return {
        "docs": n,
        "has_answer": has_ans,
        "pii_kinds": dict(pii.most_common()),
        "years": dict(sorted(years.items())),
        "tokens": {"mean": round(sum(toks) / max(1, len(toks)), 1),
                   "p50": q(0.50), "p95": q(0.95), "p99": q(0.99)},
        "over_256_tokens": over256,
        "over_256_ratio": round(over256 / max(1, n), 4),
        "n_dup_groups": len(dup),
    }


def render(stats: Dict[str, Any]) -> str:
    p = stats["pakn"]
    L: List[str] = [
        "# Báo cáo Kiểm toán Dữ liệu (T-10)", "",
        f"_Sinh tự động bởi `src/preprocessing/audit_data.py` — RAM đỉnh {stats['peak_ram_gb']:.1f} GB._", "",
        "## 1. Phản ánh – Kiến nghị (PAKN)", "",
        f"- Tổng số phản ánh: **{p['docs']:,}**",
        f"- Có câu trả lời chính thức của cơ quan: **{p['has_answer']:,}** ({_pct(p['has_answer'], p['docs'])}) "
        "— đây là nguồn thông tin đặc quyền cho Tầng 2 (chưng cất nhãn).",
        f"- Phân bố theo năm gửi: {p['years']}",
        f"- Độ dài (token ước tính): trung bình {p['tokens']['mean']}, p50 {p['tokens']['p50']}, "
        f"**p95 {p['tokens']['p95']}**, p99 {p['tokens']['p99']}",
        f"- **Vượt trần 256 token: {p['over_256_tokens']:,} mẫu ({_pct(p['over_256_tokens'], p['docs'])})** "
        "→ Sliding-Window (W=224, S=32) là bắt buộc, không phải tuỳ chọn.",
        f"- Thẻ PII đã khử: {p['pii_kinds']}", "",
    ]
    L += ["## 2. Kho tri thức (chunks)", "",
          "| Nguồn | Số chunk | Còn hiệu lực | Hết hiệu lực | Số hiệu VB | Lĩnh vực | Mojibake | p95 token |",
          "|---|---:|---:|---:|---:|---:|---:|---:|"]
    for name in ("tthc", "vbpl", "vbpldp", "pakn_chunks"):
        s = stats["chunks"].get(name)
        if not s:
            continue
        L.append(
            f"| `{name}` | {s['rows']:,} | {s['con_hieu_luc_true']:,} | {s['con_hieu_luc_false']:,} | "
            f"{s['n_so_hieu']:,} | {s['n_linh_vuc']:,} | {s['mojibake_rows']:,} | {s['tokens']['p95']:,} |"
        )
    v = stats["chunks"].get("vbpl", {})
    if v:
        share = _pct(v["con_hieu_luc_false"], v["rows"])
        L += ["", f"> **Cảnh báo pháp lý**: {v['con_hieu_luc_false']:,} chunk VBPL đã **HẾT HIỆU LỰC** "
              f"({share} corpus). Không lọc `con_hieu_luc` là trích dẫn sai luật. "
              "Đồng thời đây là nguồn `INSUFFICIENT` tự nhiên cho Model B.", ""]
    for name in ("tthc", "vbpl"):
        s = stats["chunks"].get(name)
        if not s:
            continue
        L += [f"### Chi tiết `{name}`", "",
              f"- Loại văn bản: {s['top_loai_van_ban'][:6]}",
              f"- Section: {s['top_section'][:8]}",
              f"- Cơ quan ban hành (top): {[c for c, _ in s['top_co_quan'][:6]]}", ""]
    L += ["## 3. Kết luận cho khâu thiết kế", "",
          "1. Bắt buộc streaming `iter_batches` — không `read_parquet()` toàn file (RAM 15 GB).",
          "2. Bắt buộc lọc `con_hieu_luc == True` cho mọi trích dẫn pháp lý.",
          "3. Bắt buộc Sliding-Window cho Model A.",
          "4. Bắt buộc sửa mojibake trước khi dựng index BM25.",
          "5. Temporal split theo `send_date` (dữ liệu trải 2024→2026), cấm chia ngẫu nhiên.", ""]
    return "\n".join(L)


def main() -> None:
    ap = argparse.ArgumentParser(description="T-10 kiểm toán dữ liệu")
    add_config_args(ap)
    args = ap.parse_args()
    cfg = load_config("paths", args.overrides)
    dc = cfg["data_clean"]

    with Timer(LOG, "audit_data"):
        stats: Dict[str, Any] = {"chunks": {}}
        stats["pakn"] = audit_pakn(dc["pakn_docs"])
        log_resources(LOG, "sau PAKN | ")
        for name, path in (("tthc", dc["tthc_chunks"]), ("vbpl", dc["vbpl_chunks"]),
                           ("vbpldp", dc["vbpldp_chunks"]), ("pakn_chunks", dc["pakn_chunks"])):
            stats["chunks"][name] = audit_chunks(path, name)
            log_resources(LOG, f"sau {name} | ")
        stats["peak_ram_gb"] = ram_gb()

    atomic_save_json(cfg["artifacts"]["audit_stats"], stats)
    out = f"{cfg['reports']['dir']}/data_audit.md"
    with open(out, "w", encoding="utf-8") as f:
        f.write(render(stats))
    LOG.info("Đã ghi %s và %s", out, cfg["artifacts"]["audit_stats"])


if __name__ == "__main__":
    main()