File size: 3,848 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
"""T-11 — Chia train/dev/test THEO THỜI GIAN.

Cấm chia ngẫu nhiên: dữ liệu trải 2024→2026, chia ngẫu nhiên gây rò rỉ thông tin
tương lai và thổi phồng kết quả. Đồng thời bảo đảm không tập nào dùng chung
`dup_group` (chống rò rỉ qua văn bản gần trùng).
"""
from __future__ import annotations

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

from ..common.config import add_config_args, load_config
from ..common.io_utils import atomic_save_json, iter_jsonl_gz
from ..common.logging_utils import Timer, get_logger

LOG = get_logger("temporal_split")

DEFAULT_TRAIN_END = "2026-01-09"   # phân vị 80% của send_date (đo thật)
DEFAULT_DEV_END = "2026-03-23"     # phân vị 90%


def assign_split(send_date: Optional[str], train_end: str, dev_end: str) -> str:
    d = (send_date or "")[:10]
    if not d or len(d) < 10:
        return "train"                 # thiếu ngày -> để ở train, không làm bẩn test
    if d <= train_end:
        return "train"
    if d <= dev_end:
        return "dev"
    return "test"


def build(cfg, train_end: str, dev_end: str) -> Dict[str, Any]:
    """Quét 2 lượt: lượt 1 quyết định split theo ngày, lượt 2 xử lý xung đột dup_group."""
    doc_split: Dict[str, str] = {}
    doc_group: Dict[str, str] = {}
    group_splits: Dict[str, Counter] = {}
    years = Counter()

    for d in iter_jsonl_gz(cfg["data_clean"]["pakn_docs"]):
        doc_id = str(d.get("doc_id", ""))
        if not doc_id:
            continue
        sp = assign_split(d.get("send_date"), train_end, dev_end)
        grp = d.get("dup_group") or doc_id
        doc_split[doc_id] = sp
        doc_group[doc_id] = grp
        group_splits.setdefault(grp, Counter())[sp] += 1
        years[(d.get("send_date") or "????")[:4]] += 1

    # Một dup_group nằm ở nhiều tập -> dồn hết về tập SỚM NHẤT (ưu tiên train)
    order = {"train": 0, "dev": 1, "test": 2}
    conflicts = 0
    group_final: Dict[str, str] = {}
    for grp, c in group_splits.items():
        if len(c) > 1:
            conflicts += 1
        group_final[grp] = min(c.keys(), key=lambda s: order[s])
    for doc_id, grp in doc_group.items():
        doc_split[doc_id] = group_final[grp]

    counts = Counter(doc_split.values())
    total = sum(counts.values()) or 1
    manifest = {
        "strategy": "temporal",
        "train_end": train_end,
        "dev_end": dev_end,
        "counts": dict(counts),
        "ratio": {k: round(v / total, 4) for k, v in counts.items()},
        "total": total,
        "dup_group_conflicts_resolved": conflicts,
        "years": dict(sorted(years.items())),
        "assignment": doc_split,
    }
    return manifest


def main() -> None:
    ap = argparse.ArgumentParser(description="T-11 temporal split")
    ap.add_argument("--train-end", default=DEFAULT_TRAIN_END)
    ap.add_argument("--dev-end", default=DEFAULT_DEV_END)
    add_config_args(ap)
    args = ap.parse_args()
    cfg = load_config("paths", args.overrides)

    with Timer(LOG, "temporal_split"):
        man = build(cfg, args.train_end, args.dev_end)
    atomic_save_json(cfg["splits"]["manifest"], man)
    LOG.info("Tỉ lệ: %s", man["ratio"])
    LOG.info("Số dup_group phải hoà giải: %d", man["dup_group_conflicts_resolved"])
    LOG.info("Manifest -> %s", cfg["splits"]["manifest"])


def load_assignment(cfg) -> Dict[str, str]:
    from ..common.io_utils import load_json
    man = load_json(cfg["splits"]["manifest"], default=None)
    if not man:
        raise FileNotFoundError(
            f"Chưa có {cfg['splits']['manifest']} — hãy chạy: python -m src.preprocessing.temporal_split"
        )
    return man["assignment"]


if __name__ == "__main__":
    main()