File size: 6,537 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
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
"""Test pass 2 overlap and contamination checks. Reads only the id and image columns of the test manifests (no label text).

1. exact id and exact image-path overlap of each test set with every frozen_mix_v1 training manifest and with the training
   sequence actually read by the models (seq/mix_v1_seq.tsv, all 6,000,000 rows; M1 read rows 0..1,310,591);
2. the report-only duplicate check of 21 Nov (build_logs/dedupe_all_dropped.tsv: training images byte-identical to, or within
   pHash distance of, a validation or test image): pairs whose partner is one of our test sets, per training manifest and reason;
3. RUKOPYS: any training row whose id, image path or source mentions rukopys; the raw folder's test metadata annotation_source
   census (values only);
4. TurkishOCR-Bench: any training row whose image path mentions turkishocr; print_real_train source values that mention dergipark
   and whether any equals a TurkishOCR-Bench document id (belge).

usage: tp2_overlap.py --out JSON
"""
import argparse
import collections
import csv
import glob
import json
import os
import re
import time

csv.field_size_limit(1 << 30)
DATA = "/path/to/TURKIC_OCR_DATA"
R5 = DATA + "/data/processed/r5"
SETS = ["az_localdoc_test", "rukopys_test", "hkr_test1", "hkr_test2", "chd_test", "school_test", "synth_hand_test", "synth_typed_test"]


def rows(path, cols):
    with open(path, encoding="utf-8", newline="") as f:
        rd = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
        for r in rd:
            yield {c: r.get(c, "") for c in cols}


ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True)
a = ap.parse_args()
t0 = time.time()
reg = {e["name"]: e for e in json.load(open(R5 + "/evalsets.json", encoding="utf-8"))["sets"]}
test_ids, test_imgs = {}, {}
for s in SETS:
    ids, imgs = set(), set()
    for r in rows(reg[s]["manifest"], ("id", "image")):
        ids.add(r["id"])
        imgs.add(r["image"])
        imgs.add(os.path.realpath(r["image"]))
    test_ids[s], test_imgs[s] = ids, imgs
out = {"generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "test_sets": {s: {"ids": len(test_ids[s])} for s in SETS}}

rk = re.compile(r"(?i)rukopys")
tob = re.compile(r"(?i)turkishocr")
train = {}
for p in sorted(glob.glob(R5 + "/frozen_mix_v1/*.tsv")):
    if p.endswith(".meta.tsv"):
        continue
    nm = os.path.basename(p)[:-4]
    ov_id = collections.Counter()
    ov_img = collections.Counter()
    n = n_rk = n_tob = 0
    for r in rows(p, ("id", "image", "source")):
        n += 1
        if rk.search(r["id"]) or rk.search(r["image"]) or rk.search(r["source"]):
            n_rk += 1
        if tob.search(r["image"]) or tob.search(r["source"]):
            n_tob += 1
        for s in SETS:
            if r["id"] in test_ids[s]:
                ov_id[s] += 1
            if r["image"] in test_imgs[s]:
                ov_img[s] += 1
    train[nm] = {"rows": n, "id_overlap": dict(ov_id), "image_path_overlap": dict(ov_img), "rows_mentioning_rukopys": n_rk,
                 "rows_mentioning_turkishocr": n_tob}
out["frozen_mix_v1"] = train

seq = R5 + "/seq/mix_v1_seq.tsv"
ov_id = collections.Counter()
ov_img = collections.Counter()
ov_id_m1 = collections.Counter()
n = n_rk = n_tob = 0
uniq = set()
for r in rows(seq, ("row", "id", "image", "source")):
    n += 1
    uniq.add(r["id"])
    try:
        ri = int(r["row"])
    except ValueError:
        ri = -1
    if rk.search(r["id"]) or rk.search(r["image"]) or rk.search(r["source"]):
        n_rk += 1
    if tob.search(r["image"]) or tob.search(r["source"]):
        n_tob += 1
    for s in SETS:
        hit = r["id"] in test_ids[s]
        if hit:
            ov_id[s] += 1
            if 0 <= ri < 1310592:
                ov_id_m1[s] += 1
        if r["image"] in test_imgs[s]:
            ov_img[s] += 1
out["training_sequence"] = {"path": seq, "rows": n, "unique_ids": len(uniq), "id_overlap_rows": dict(ov_id),
                            "id_overlap_rows_within_M1_rows_0_1310591": dict(ov_id_m1), "image_path_overlap_rows": dict(ov_img),
                            "rows_mentioning_rukopys": n_rk, "rows_mentioning_turkishocr": n_tob}

dd = R5 + "/build_logs/dedupe_all_dropped.tsv"
pairs = collections.defaultdict(collections.Counter)
test_rows_with_partner = collections.defaultdict(set)
for r in rows(dd, ("train_id", "manifest", "kind", "reason", "partner_id", "partner_manifest", "same_label")):
    if r["partner_manifest"] in SETS:
        pairs[r["partner_manifest"]]["%s | %s | same_label=%s" % (r["manifest"], r["reason"], r["same_label"])] += 1
        test_rows_with_partner[r["partner_manifest"]].add(r["partner_id"])
out["dedupe_all_pairs_with_our_test_sets"] = {s: dict(pairs[s]) for s in SETS}
out["dedupe_all_test_rows_with_a_training_partner"] = {s: sorted(test_rows_with_partner[s]) for s in SETS}
out["dedupe_all_note"] = ("build_logs/stage_dedupe_all.json says 'report only: no manifest is rewritten', so these training rows may "
                          "still be in frozen_mix_v1; the ids listed are test-row ids (no label text)")

meta = DATA + "/data/raw/rukopys_test/test/metadata.jsonl"
asrc = collections.Counter()
pages = 0
if os.path.exists(meta):
    for line in open(meta, encoding="utf-8"):
        if line.strip():
            d = json.loads(line)
            pages += 1
            asrc[str(d.get("annotation_source"))] += 1
out["rukopys_raw_test_metadata"] = {"path": meta, "pages": pages, "annotation_source": dict(asrc)}
out["raw_rukopys_folders"] = sorted(glob.glob(DATA + "/data/raw/*rukopys*"))

tob_docs = set()
tmeta = DATA + "/data/raw/turkishocr_bench/metadata.jsonl"
for line in open(tmeta, encoding="utf-8"):
    if line.strip():
        d = json.loads(line)
        b = str(d.get("belge", ""))
        tob_docs.add(b)
        tob_docs.add(b.split(":")[-1])
dp = collections.Counter()
dp_match = set()
for r in rows(R5 + "/frozen_mix_v1/print_real_train.tsv", ("source", "group")):
    for v in (r["source"], r["group"]):
        if re.search(r"(?i)dergipark", v):
            dp[v[:80]] += 1
        for tok in re.findall(r"\d{5,8}", v):
            if tok in tob_docs:
                dp_match.add(v[:120])
out["print_real_train_dergipark_sources"] = {"distinct": len(dp), "rows": sum(dp.values())}
out["print_real_train_values_with_a_tob_document_number"] = sorted(dp_match)[:50]
out["seconds"] = round(time.time() - t0, 1)
json.dump(out, open(a.out, "w", encoding="utf-8"), indent=1, ensure_ascii=False)
print("done", a.out, out["seconds"], "s")