File size: 4,802 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
"""LOOPGUARD seal check, part 2 (School Notebooks test pages). Part 1 (lg_seal_scan.py) searched 'school_test_<n>', a form no
School test item uses: the crop manifest builder (scripts/r5/r5_build_real.py stage_school) names crops 'school:test_<stem>_<k>'
with group 'school_page_<stem>' and crop images under .../school/test/<stem>/, and page originals live under
val_test_images/test/<stem>.jpg. This scan looks for those forms. Prints and writes paths and counts only (no text).

Per file it counts:
  orig_path   'val_test_images/test/'                       (a path to a test photograph: page level if a model output)
  crop_id     'school:test_'                                (a crop-level item id)
  crop_img    '/school/test/<stem>/'                        (a crop image path)
  group       'school_page_<stem>' for a TEST stem          (group id of crop rows; ambiguous only if the stem is also a val/train stem)
  bare_name   '<test stem>.<ext>' not preceded by 'val_test_images/test/' (a test photograph's file name elsewhere)
The 150 test stems come from a listing of val_test_images/test (names only); val stems from val_test_images/val, train stems
from the images.zip name list; stem collisions are reported.

usage: lg_seal_scan2.py --root DATA --out JSON [--workers 16]
"""
import argparse
import json
import os
import re
import time
import zipfile
from multiprocessing import Pool

ap = argparse.ArgumentParser()
ap.add_argument("--root", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--workers", type=int, default=16)
a = ap.parse_args()

SCAN_DIRS = ["outputs", "data/processed", "logs", "checksums", "release"]
EXT = (".json", ".jsonl", ".tsv", ".txt", ".out", ".csv", ".log", ".sha256", ".md", ".py", ".sh", ".sbatch")
SCHOOL = os.path.join(a.root, "data/raw/school_notebooks_ru")


def stems(folder):
    return {os.path.splitext(n)[0]: n for n in os.listdir(folder)} if os.path.isdir(folder) else {}


TEST = stems(os.path.join(SCHOOL, "val_test_images/test"))
VAL = stems(os.path.join(SCHOOL, "val_test_images/val"))
with zipfile.ZipFile(os.path.join(SCHOOL, "images.zip")) as z:
    TRAIN = {os.path.splitext(os.path.basename(n))[0] for n in z.namelist() if not n.startswith("__MACOSX") and not n.endswith("/")}
COLL = {"test_and_val": sorted(set(TEST) & set(VAL)), "test_and_train": sorted(set(TEST) & TRAIN)}
alt = b"|".join(re.escape(s.encode()) for s in sorted(TEST, key=len, reverse=True))
PATS = {
    "orig_path": re.compile(rb"val_test_images/test/"),
    "crop_id": re.compile(rb"school:test_"),
    "crop_img": re.compile(rb"/school/test/(?:" + alt + rb")/"),
    "group": re.compile(rb"school_page_(?:" + alt + rb")(?![0-9A-Za-z_])"),
    "bare_name": re.compile(rb"(?<![0-9A-Za-z_/])(?:" + alt + rb")\.(?:jpg|JPG|jpeg|JPEG|png|PNG)"),
}


def scan(path):
    res = {k: 0 for k in PATS}
    try:
        with open(path, "rb") as f:
            carry = b""
            while True:
                chunk = f.read(64 << 20)
                buf = carry + chunk
                if chunk:
                    nl = buf.rfind(b"\n")
                    if nl < 0 or len(buf) - nl > (1 << 20):
                        carry, buf = buf[-512:], buf[:-512]
                    else:
                        carry, buf = buf[nl + 1:], buf[:nl + 1]
                else:
                    carry = b""
                for k, p in PATS.items():
                    res[k] += len(p.findall(buf))      # bare_name excludes names after a '/', so paths are not counted twice
                if not chunk:
                    break
    except OSError as e:
        res["error"] = str(e)
    return path, res


if __name__ == "__main__":
    t0 = time.time()
    files = []
    for sd in SCAN_DIRS:
        for dp, dns, fns in os.walk(os.path.join(a.root, sd)):
            for fn in fns:
                if fn.lower().endswith(EXT):
                    files.append(os.path.join(dp, fn))
    with Pool(a.workers) as pool:
        out = pool.map(scan, files, chunksize=8)
    hits = {os.path.relpath(p, a.root): r for p, r in out if r.get("error") or any(r[k] for k in PATS)}
    rep = {"root": a.root, "scan_dirs": SCAN_DIRS, "extensions": EXT, "n_files_scanned": len(files),
           "n_test_stems": len(TEST), "n_val_stems": len(VAL), "n_train_stems": len(TRAIN), "stem_collisions": COLL,
           "patterns": {k: p.pattern[:80].decode("ascii", "replace") for k, p in PATS.items()},
           "n_files_with_hits": len(hits), "hits": hits, "seconds": round(time.time() - t0, 1)}
    with open(a.out, "w", encoding="utf-8") as f:
        json.dump(rep, f, indent=1)
    print("files", len(files), "test stems", len(TEST), "collisions", {k: len(v) for k, v in COLL.items()},
          "files with hits", len(hits), "seconds", rep["seconds"], flush=True)