File size: 7,879 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 152 153 154 155 156 157 158 159 160 161 | """R5 DATA: count what is on disk for every data source held on the cluster.
Writes DATA/outputs/r5/disk_counts.json: for each source the counts and the exact files or folders that were counted.
Read-only. Usage: python -I r5_disk_counts.py
"""
import collections
import json
import os
import time
import zipfile
from pathlib import Path
import pyarrow.parquet as pq
DATA = Path("/path/to/TURKIC_OCR_DATA")
RAW = DATA / "data/raw"
PROC = DATA / "data/processed"
OUT = DATA / "outputs/r5/disk_counts.json"
res = {}
def zip_count(zp, skip_macosx=True):
z = zipfile.ZipFile(zp)
names = [i for i in z.infolist() if not i.is_dir()]
if skip_macosx:
names = [i for i in names if not i.filename.startswith("__MACOSX")]
ext = collections.Counter(os.path.splitext(i.filename)[1].lower() for i in names)
return {"files": len(names), "by_extension": dict(ext), "uncompressed_bytes": sum(i.file_size for i in names),
"zip_bytes": os.path.getsize(zp), "counted_file": str(zp)}
def n_files(d, pattern_ext=None):
n = 0
total = 0
for e in os.scandir(d):
if e.is_file() and (pattern_ext is None or e.name.lower().endswith(pattern_ext)):
n += 1
total += e.stat().st_size
return n, total
def lines(p):
n = 0
b = 0
with open(p, "rb") as f:
for line in f:
n += 1
b += len(line)
return n, b
# KOHTD
img_dir = PROC / "kohtd_words_raw/KOHTD_dataset/HK_dataset/img"
ann_dir = PROC / "kohtd_words_raw/KOHTD_dataset/HK_dataset/ann"
ni, bi = n_files(img_dir, ".jpg")
na, _ = n_files(ann_dir, ".json")
res["kohtd_words"] = {"word_crop_images": ni, "annotation_files": na, "bytes_images": bi, "counted_folder": str(img_dir)}
sheets = RAW / "kohtd/forms_sheets_extracted/20200929_Examination_sheets_cleaned"
ns, bs = n_files(sheets, ".jpg")
res["kohtd_sheets"] = {"sheet_scans": ns, "bytes": bs, "counted_folder": str(sheets)}
sp = {}
for name in ("train", "validation", "test"):
n, _ = lines(PROC / f"kohtd_split_v1/{name}.tsv")
sp[name] = n - 1
res["kohtd_split_v1_rows"] = {"rows": sp, "counted_folder": str(PROC / "kohtd_split_v1")}
# HKR
res["hkr_words"] = zip_count(RAW / "hkr_words_kaggle_scispecai/hkr_dat.zip")
# CHD
chd = zip_count(RAW / "chd/archive.zip")
z = zipfile.ZipFile(RAW / "chd/archive.zip")
chd["train_tsv_rows"] = sum(1 for l in z.read("train.tsv").decode("utf-8").split("\n") if l.strip())
chd["test_tsv_rows"] = sum(1 for l in z.read("test.tsv").decode("utf-8").split("\n") if l.strip())
res["chd"] = chd
# Sheriyeva isolated letters
sh = {}
for s in ("train", "val", "test"):
c = zip_count(RAW / f"sheriyeva/{s}.zip")
sh[s] = c
res["sheriyeva_letters"] = sh
# Turkish and Azerbaijani character sets
for key, zp, member in (("yasiradoan_hw_tr_en_hu", "yasiradoan_hw_tr_en_hu/yasiradoan_hw_tr_en_hu.zip", "version7.csv"),
("yasiradoan_tr_csv", "yasiradoan_tr_csv/yasiradoan_tr_csv.zip", "Turkish_special_characters_2.csv"),
("azemnist", "azemnist/azemnist.zip", "AzEMNIST.csv")):
zf = zipfile.ZipFile(RAW / zp)
n = 0
classes = collections.Counter()
with zf.open(member) as f:
for line in f:
n += 1
# label is the last column for yasiradoan files and the first column for AzEMNIST
parts = line.decode("utf-8", "replace").rstrip("\r\n").split(",")
classes[parts[0] if key == "azemnist" else parts[-1]] += 1
res[key] = {"rows": n, "distinct_label_values": len(classes), "counted_file": str(RAW / zp) + "::" + member}
res["muhammeterem_tr_en_chars"] = zip_count(RAW / "muhammeterem_tr_en_chars/muhammeterem_tr_en_chars.zip")
# school notebooks
base = RAW / "school_notebooks_ru"
sn = {}
for s in ("train", "val", "test"):
d = json.load(open(base / f"annotations_{s}.json", encoding="utf-8"))
cats = collections.Counter(a["category_id"] for a in d["annotations"])
withtext = collections.Counter(a["category_id"] for a in d["annotations"] if ((a.get("attributes") or {}).get("translation") or "").strip())
sn[s] = {"pages": len(d["images"]), "annotations_by_category_id": dict(cats), "annotations_with_text_by_category_id": dict(withtext),
"counted_file": str(base / f"annotations_{s}.json")}
sn["category_names"] = {"0": "pupil_text (word polygons with text)", "1": "pupil_comment", "2": "teacher_comment", "3": "paper", "4": "text_line (polygon, no text)"}
res["school_notebooks_ru"] = sn
# RUKOPYS test
rows = [json.loads(l) for l in open(RAW / "rukopys_test/test/metadata.jsonl", encoding="utf-8")]
types = collections.Counter(r2["type"] for r in rows for r2 in r["regions"])
res["rukopys_test"] = {"pages": len(rows), "regions_by_type": dict(types),
"handwritten_uk_legible": sum(1 for r in rows for r2 in r["regions"] if r2["type"] == "handwritten" and r2["language"] == "uk" and r2["legibility"] == "legible"),
"pages_by_source": dict(collections.Counter(r["source"] for r in rows)),
"counted_file": str(RAW / "rukopys_test/test/metadata.jsonl")}
# TurkishOCR-Bench
rows = [json.loads(l) for l in open(RAW / "turkishocr_bench/metadata.jsonl", encoding="utf-8")]
res["turkishocr_bench"] = {"pages": len(rows), "by_category": dict(collections.Counter(r["kategori"] for r in rows)),
"by_licence_field": dict(collections.Counter(r.get("lisans", "") for r in rows)),
"counted_file": str(RAW / "turkishocr_bench/metadata.jsonl")}
# NAF
naf = RAW / "naf/extracted_images"
nn, _ = n_files(naf)
res["naf"] = {"extracted_files": nn, "counted_folder": str(naf),
"note": "findings record NEW_NAF: 863 labelled form images (train 708, valid 78, test 77)"}
# DocLayNet v1.2 test parquet
tot = 0
files = sorted((RAW / "doclaynet_v1_2_test/data").glob("*.parquet"))
for f in files:
tot += pq.ParquetFile(f).metadata.num_rows
res["doclaynet_v1_2_test"] = {"pages": tot, "parquet_files": len(files), "counted_folder": str(RAW / "doclaynet_v1_2_test/data")}
# ailabykt Sakha monolingual corpus
sak = RAW / "ailabykt_sakha_mono/data"
cnt = collections.Counter()
tot = 0
for f in sorted(sak.glob("*.parquet")):
pf = pq.ParquetFile(f)
tot += pf.metadata.num_rows
if "source" in pf.schema_arrow.names:
col = pf.read(columns=["source"]).column(0).to_pylist()
cnt.update(col)
res["ailabykt_sakha_mono"] = {"documents": tot, "documents_by_source": dict(cnt), "counted_folder": str(sak)}
# generator text per language
pt = {}
for lang in ("kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"):
p = PROC / f"pagesynth_text/{lang}/sentences.tsv"
n, b = lines(p)
lw = json.load(open(PROC / f"pagesynth_text/{lang}/label_words.json", encoding="utf-8"))
pt[lang] = {"sentences_file_lines": n, "bytes": b, "label_words": ({k: len(v) for k, v in lw.items() if isinstance(v, list)} if isinstance(lw, dict) else len(lw)), "counted_file": str(p)}
res["pagesynth_text"] = pt
# fonts: raw folder and generator assets
fonts = {}
for d in sorted(os.scandir(RAW / "fonts"), key=lambda e: e.name):
if d.is_dir():
fonts[d.name] = sorted(x.name for x in os.scandir(d.path))
res["fonts_raw_folder"] = {"families": len(fonts), "files_by_family": fonts, "counted_folder": str(RAW / "fonts")}
ga = Path("/path/to/TURKIC_OCR_CODE/src/pagesynth/assets/fonts")
res["fonts_generator_assets"] = {"files": sorted(x.name for x in os.scandir(ga) if x.is_file()), "counted_folder": str(ga),
"licence_files": sorted(x.name for x in os.scandir(ga / "licences"))}
res["generated_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
OUT.parent.mkdir(parents=True, exist_ok=True)
json.dump(res, open(OUT, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print("written", OUT)
|