File size: 3,115 Bytes
6a6ce4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
clean_train_data.py — Deterministic sanitizer for sandhi-boundary JSONL data.

Guarantees for every row that passes:
  - seq is a non-empty string (SLP1, may contain spaces per base convention)
  - bnd is a strictly-increasing list of ints, each in [0, len(seq)-2]
    (i.e. every piece is non-empty and the final piece is non-empty)
  - no duplicate boundaries (a duplicate creates a zero-length word)
  - pieces partition seq exactly (''.join(pieces) == seq)

Rows that violate any invariant are DROPPED (never silently fixed), and the
reason is counted. Writing is atomic (temp file + rename).

Usage:
    python clean_train_data.py --in data/train_V2_fixed.jsonl --out data/train_V2_fixed_clean.jsonl
    python clean_train_data.py --in data/train_V2_targeted.jsonl --out data/train_V2_targeted_clean.jsonl
"""

import argparse
import json
import os
import sys
import tempfile
from collections import Counter


def validate_row(seq, bnd):
    """Return (ok, reason) for one row. bnd = list of 0-based last-char indices."""
    if not isinstance(seq, str) or not seq:
        return False, "empty-seq"
    if not isinstance(bnd, list):
        return False, "bnd-not-list"
    for b in bnd:
        if not isinstance(b, int) or isinstance(b, bool):
            return False, "bnd-not-int"
    if any(b < 0 or b >= len(seq) - 1 for b in bnd):
        return False, "bnd-out-of-range"  # bnd must leave >=1 char for next word
    if len(set(bnd)) != len(bnd):
        return False, "duplicate-bnd"
    if any(b1 >= b2 for b1, b2 in zip(bnd, bnd[1:])):
        return False, "bnd-not-increasing"
    return True, "ok"


def clean_file(inp: str, out: str):
    kept = 0
    reasons = Counter()
    tmp_fd, tmp_path = tempfile.mkstemp(
        prefix=os.path.basename(out) + ".", dir=os.path.dirname(out) or ".")
    with os.fdopen(tmp_fd, "w", encoding="utf-8") as fout, \
            open(inp, encoding="utf-8") as fin:
        for line in fin:
            line = line.strip()
            if not line:
                continue
            try:
                d = json.loads(line)
            except json.JSONDecodeError:
                reasons["json-parse-error"] += 1
                continue
            ok, reason = validate_row(d.get("seq", ""), d.get("bnd", []))
            if not ok:
                reasons[reason] += 1
                continue
            fout.write(json.dumps(d, ensure_ascii=False) + "\n")
            kept += 1
    os.replace(tmp_path, out)
    return kept, reasons


def main():
    ap = argparse.ArgumentParser(description="Sanitize boundary JSONL dataset")
    ap.add_argument("--in", dest="inp", required=True)
    ap.add_argument("--out", dest="out", required=True)
    args = ap.parse_args()

    kept, reasons = clean_file(args.inp, args.out)
    print(f"input : {args.inp}")
    print(f"output: {args.out}")
    print(f"rows kept: {kept}")
    dropped = sum(reasons.values())
    print(f"rows dropped: {dropped}")
    for reason, n in reasons.most_common():
        print(f"  - {reason}: {n}")
    if dropped:
        sys.exit(2)


if __name__ == "__main__":
    main()