File size: 6,109 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""R5 FREEZE: decision of 21 Nov 2026 ~02:05 UTC (option B extended). From the FROZEN synthetic train copies only, drop
  (a) near_dup_same_label: the synthetic train rows that DATA's duplicate check (build_logs/dedupe_all_dropped.tsv, run 01:58:30 UTC)
      pairs with a synthetic val/test row by near pHash (distance <= 4) AND the same non-empty label;
  (b) text_leak_ge20: every synthetic train row whose label equals the label of a synthetic val/test LINE of at least 20 characters
      (same definition as AUDIT's data_audit.py lines 278-286: unit == line, len(text) >= 20, whitespace collapsed).
Val/test labels are read from the read-only copies in frozen_eval_v1/ and are never printed or written; outputs hold ids only.
Non-synthetic train rows that match (b) are counted and listed (ids), not dropped (the decision covers synthetic rows only).
Writes into OUT_DIR: synth_hand_train.tsv, synth_typed_train.tsv and their .meta.tsv sidecars without the dropped rows (raw lines
copied byte for byte), dropped_rows.tsv (id, manifest, reason, matched_valtest_id, matched_valtest_manifest, detail), drop_report.json.
usage: python -I drop_rows.py FROZEN_TRAIN_DIR FROZEN_EVAL_DIR DEDUPE_DROPPED_TSV OUT_DIR PREDROP_DIR
(the two synthetic train manifests and their sidecars are read from PREDROP_DIR, the copies made before any drop)
"""
import collections
import csv
import hashlib
import json
import os
import sys

csv.field_size_limit(10 ** 9)
fz, fe, ddt, out, pre = sys.argv[1:6]
os.makedirs(out, exist_ok=True)
SYN = ["synth_hand_train", "synth_typed_train"]
TRAIN = ["kohtd_train", "hkr_train", "chd_train", "school_train", "synth_hand_train", "synth_typed_train", "print_real_train", "synth_clutter_train"]
VALTEST = ["synth_hand_val", "synth_hand_test", "synth_typed_val", "synth_typed_test", "synth_clutter_val", "synth_clutter_test",
           "synth_pages_val", "synth_pages_test"]


def norm(t):
    return " ".join(t.split())


def sha(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            h.update(b)
    return h.hexdigest()


def rows(p):
    with open(p, encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))


drops = []  # (id, manifest, reason, matched id, matched manifest, detail)
# (a)
with open(ddt, encoding="utf-8", newline="") as f:
    for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE):
        if r["manifest"] in SYN and r["partner_manifest"] in VALTEST and r["same_label"] == "True" and r["kind"] != "clutter":
            drops.append((r["train_id"], r["manifest"], "near_dup_same_label", r["partner_id"], r["partner_manifest"], r["reason"]))
n_a = len(drops)
# (b)
vt = collections.defaultdict(list)
vt_n = {}
for m in VALTEST:
    n = 0
    for r in rows(os.path.join(fe, m + ".tsv")):
        if r["unit"] == "line" and len(r["text"]) >= 20:
            vt[norm(r["text"])].append((r["id"], m))
            n += 1
    vt_n[m] = n
matched_vt = set()
nonsyn = collections.Counter()
nonsyn_ids = []
train_rows = {}
for m in TRAIN:
    rs = rows(os.path.join(pre if m in SYN else fz, m + ".tsv"))
    train_rows[m] = len(rs)
    for r in rs:
        k = norm(r["text"])
        if k in vt:
            for vid, vm in vt[k]:
                matched_vt.add((vid, vm))
                if m in SYN:
                    drops.append((r["id"], m, "text_leak_ge20", vid, vm, "exact label of a val/test line >= 20 chars"))
                else:
                    nonsyn[m] += 1
                    nonsyn_ids.append([r["id"], m, vid, vm])
drop_ids = {m: {d[0] for d in drops if d[1] == m} for m in SYN}
# filtered copies (raw lines, byte for byte)
written = {}
for m in SYN:
    for fn in (m + ".tsv", m + ".meta.tsv"):
        src, dst = os.path.join(pre, fn), os.path.join(out, fn)
        kept = dropped = 0
        with open(src, "rb") as fi, open(dst, "wb") as fo:
            fo.write(fi.readline())
            for line in fi:
                rid = line.split(b"\t", 1)[0].decode("utf-8")
                if rid in drop_ids[m]:
                    dropped += 1
                    continue
                fo.write(line)
                kept += 1
        written[fn] = {"source": src, "source_sha256": sha(src), "out": dst, "out_sha256": sha(dst), "rows_kept": kept, "rows_dropped": dropped}
        if dropped != len(drop_ids[m]):
            raise SystemExit("%s: dropped %d lines but %d ids are listed" % (fn, dropped, len(drop_ids[m])))
with open(os.path.join(out, "dropped_rows.tsv"), "w", encoding="utf-8", newline="") as f:
    f.write("id\tmanifest\treason\tmatched_valtest_id\tmatched_valtest_manifest\tdetail\n")
    for d in sorted(drops):
        f.write("\t".join(d) + "\n")
rep = {"decision": "decision of 21 Nov 2026 ~02:05 UTC, option B extended (near-duplicate same-label rows + text leak of val/test lines >= 20 chars), synthetic train rows only, frozen copies only; manifests/ unchanged",
       "pairs_a_near_dup_same_label": n_a,
       "pairs_b_text_leak": len(drops) - n_a,
       "unique_rows_dropped": {m: len(v) for m, v in drop_ids.items()},
       "unique_rows_dropped_total": sum(len(v) for v in drop_ids.values()),
       "unique_rows_dropped_by_reason": {r: len({(d[0], d[1]) for d in drops if d[2] == r}) for r in ("near_dup_same_label", "text_leak_ge20")},
       "rows_in_both_reasons": len({(d[0], d[1]) for d in drops if d[2] == "near_dup_same_label"} & {(d[0], d[1]) for d in drops if d[2] == "text_leak_ge20"}),
       "valtest_lines_ge20": vt_n, "valtest_lines_ge20_matched_by_any_train_row": len(matched_vt),
       "valtest_lines_ge20_matched_by_manifest": dict(collections.Counter(vm for _, vm in matched_vt)),
       "nonsynthetic_train_rows_matching_b_not_dropped": dict(nonsyn), "nonsynthetic_matches": nonsyn_ids[:200],
       "train_rows_before": train_rows, "files": written}
json.dump(rep, open(os.path.join(out, "drop_report.json"), "w", encoding="utf-8"), indent=1)
print(json.dumps({k: v for k, v in rep.items() if k not in ("files", "nonsynthetic_matches")}, indent=1))