fullerene-data / scripts /profile.py
Karan2599's picture
The training set's and 41 benchmarks' manifests, and the data report
35a8678 verified
Raw History Blame Contribute Delete
26.2 kB
"""Measure what is inside each downloaded phase 1 source.
usage: python data/profile.py [--root DIR] [--only NAME ...]
Writes data/reports/phase1/profile/<name>.json: counts (pages, lines, words,
characters), the character set and its Unicode scripts, line geometry, layout
labels, PDF text-layer coverage, font coverage, whatever applies to that
source. report.py turns these into the comparison report.
Big sources are sampled where reading everything adds nothing (PDF text is
read from up to SAMPLE_PDFS documents per source; every annotation file is
read whole). Each profile records what it sampled.
"""
import argparse
import collections
import gzip
import io
import json
import math
import re
import sys
import tarfile
import time
import zipfile
from pathlib import Path
from fontTools import unicodedata as fu
from fetch import DEFAULT_ROOT
from sources import BY_NAME, SOURCES
HERE = Path(__file__).resolve().parent
OUT = HERE / "reports" / "phase1" / "profile"
SAMPLE_PDFS = 1500
TEXT_SAMPLE_CHARS = 60_000_000 # per text file
# Letters the Latin group must render and read: Latin-1,
# Latin Extended-A diacritics, Vietnamese and Yoruba tone marks, ß/ẞ.
LATIN_TEST = {
"latin1": "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ",
"latin_ext_a": "ĀāĂ㥹ĆćČčĎďĐđĒēĖėĘęĚěĞğĪīĮįİıĽľŁłŃńŇňŐőŒœŘřŚśŞşŠšŢţŤťŮůŰűŸŹźŻżŽž",
"vietnamese": "ẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊịỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹƠơƯư",
"yoruba": "ẸẹỌọṢṣ",
"eszett": "ẞß",
}
def log(name, msg):
print(f"[{time.strftime('%H:%M:%S')}] {name}: {msg}", flush=True)
def pct(values, qs=(5, 50, 95)):
if not values:
return {}
v = sorted(values)
return {f"p{q}": round(v[min(len(v) - 1, int(q / 100 * len(v)))], 2) for q in qs}
class Chars:
"""Character statistics over a stream of strings."""
def __init__(self):
self.counts = collections.Counter()
self.strings = 0
self.lengths = []
def add(self, s):
if not s:
return
self.counts.update(s)
self.strings += 1
if len(self.lengths) < 200_000:
self.lengths.append(len(s))
def summary(self, top_scripts=8):
total = sum(self.counts.values())
if not total:
return {"characters": 0}
scripts = collections.Counter()
for ch, n in self.counts.items():
if not ch.isspace():
scripts[fu.script(ch)] += n
letters = sum(n for s, n in scripts.items() if s not in ("Zyyy", "Zinh", "Zzzz"))
ranked = [n for _, n in self.counts.most_common()]
cum, k999, k9999 = 0, None, None
for i, n in enumerate(ranked, 1):
cum += n
if k999 is None and cum >= 0.999 * total:
k999 = i
if k9999 is None and cum >= 0.9999 * total:
k9999 = i
break
return {
"strings": self.strings,
"characters": total,
"unique_characters": len(self.counts),
"chars_for_99.9pct": k999,
"chars_for_99.99pct": k9999,
"scripts": {s: round(n / max(letters, 1), 4) for s, n in scripts.most_common(top_scripts)
if s not in ("Zyyy", "Zinh", "Zzzz")},
"digits_share": round(sum(n for c, n in self.counts.items() if c.isdigit()) / total, 4),
"length": pct(self.lengths),
"latin_test_coverage": {k: round(sum(1 for c in v if c in self.counts) / len(v), 3)
for k, v in LATIN_TEST.items()},
"rarest_seen": "".join(c for c, _ in self.counts.most_common()[-40:] if not c.isspace()),
}
# ---------------------------------------------------------------------- fonts
def cmap_of(path):
from fontTools.ttLib import TTFont
try:
f = TTFont(path, fontNumber=0, lazy=True)
return set(f.getBestCmap() or {})
except Exception: # noqa: BLE001 (a broken font file)
return None
def font_coverage(cmaps):
out = {}
for k, chars in LATIN_TEST.items():
cps = {ord(c) for c in chars}
full = sum(1 for c in cmaps if cps <= c)
out[k] = round(full / max(len(cmaps), 1), 3)
return out
def profile_fonts_google(src, d):
fams = []
for meta in d.glob("*/*/METADATA.pb"):
t = meta.read_text(encoding="utf-8", errors="replace")
cat = re.search(r'category:\s*"([A-Z_]+)"', t)
subsets = re.findall(r'subsets:\s*"([\w-]+)"', t)
fonts = sorted(meta.parent.glob("*.ttf"))
regular = next((f for f in fonts if "Regular" in f.name), fonts[0] if fonts else None)
fams.append(dict(license_dir=meta.parent.parent.name, category=cat.group(1) if cat else "?",
subsets=subsets, files=len(fonts), regular=regular))
log(src["name"], f"{len(fams)} families; reading cmaps")
latin = [f for f in fams if "latin" in f["subsets"] and f["regular"]]
cm = {}
for f in latin:
c = cmap_of(f["regular"])
if c is not None:
cm[f["regular"]] = c
by_cat = collections.defaultdict(list)
for f in latin:
if f["regular"] in cm:
by_cat[f["category"]].append(cm[f["regular"]])
subsets = collections.Counter(s for f in fams for s in f["subsets"])
return {
"families": len(fams),
"font_files": sum(f["files"] for f in fams),
"by_license_dir": dict(collections.Counter(f["license_dir"] for f in fams)),
"by_category": dict(collections.Counter(f["category"] for f in fams)),
"subsets_top": dict(subsets.most_common(30)),
"latin_families_checked": len(cm),
"latin_full_coverage_share": font_coverage(list(cm.values())),
"latin_full_coverage_by_category": {k: font_coverage(v) for k, v in by_cat.items()},
"N_tilde_missing_in_display": sum(1 for c in by_cat.get("DISPLAY", []) if 0xD1 not in c),
}
def profile_fonts_noto(src, d):
files = [p for p in d.rglob("*.ttf") if "full" in p.parts or "hinted" in p.parts or "unhinted" in p.parts]
fams = collections.defaultdict(list)
for p in files:
fams[p.name.split("-")[0]].append(p)
scripts = collections.Counter()
for fam, ps in fams.items():
regular = next((p for p in ps if "Regular" in p.name), ps[0])
c = cmap_of(regular) or set()
sc = collections.Counter(fu.script(chr(u)) for u in c if 0x20 < u < 0x110000)
for s, _ in sc.most_common(1):
scripts[s] += 1
return {"families": len(fams), "font_files": len(files),
"main_script_of_family": dict(scripts.most_common(80)), "distinct_main_scripts": len(scripts)}
def profile_langdata(src, d):
langs = {}
for p in d.glob("*/*.training_text"):
langs.setdefault(p.parent.name, 0)
langs[p.parent.name] += p.stat().st_size
chars = Chars()
for lang in ("eng", "deu", "fra", "spa", "vie", "pol", "ces", "tur"):
p = d / lang / f"{lang}.training_text"
if p.exists():
chars.add(p.read_text(encoding="utf-8", errors="replace")[:5_000_000])
fonts = sum(1 for _ in d.glob("*/okfonts.txt"))
return {"languages_with_training_text": len(langs), "training_text_bytes": sum(langs.values()),
"largest": dict(sorted(langs.items(), key=lambda x: -x[1])[:10]), "font_lists": fonts,
"latin_sample_chars": chars.summary()}
# ----------------------------------------------------------------------- text
def profile_parquet_text(src, d):
import pyarrow.parquet as pq
out = {}
for p in sorted(d.rglob("*.parquet")):
pf = pq.ParquetFile(p)
chars, n, taken = Chars(), pf.metadata.num_rows, 0
total_chars = 0
for batch in pf.iter_batches(columns=["text"], batch_size=2000):
for t in batch.column(0).to_pylist():
t = t or ""
total_chars += len(t)
if taken < TEXT_SAMPLE_CHARS:
chars.add(t)
taken += len(t)
key = p.relative_to(d).as_posix()
out[key] = {"documents": n, "characters": total_chars, "sampled_characters": taken,
"chars": chars.summary()}
log(src["name"], f"{key}: {n} docs, {total_chars / 1e6:.0f} M chars")
return {"files": out, "documents": sum(v["documents"] for v in out.values()),
"characters": sum(v["characters"] for v in out.values())}
# ------------------------------------------------------------------ synthetic
def quad_geometry(q):
(x0, y0), (x1, y1), (x2, y2), (x3, y3) = q
width = math.hypot(x1 - x0, y1 - y0)
height = math.hypot(x3 - x0, y3 - y0)
angle = math.degrees(math.atan2(y1 - y0, x1 - x0))
return width, height, angle
def profile_nvidia(src, d):
import h5py
per_lang = {}
for p in sorted(d.rglob("*.h5")):
lang = p.relative_to(d).parts[0]
s = per_lang.setdefault(lang, dict(files=0, samples=0, lines=[], words=[], paras=[], heights=[],
angles=[], widths=[], dims=[], chars=Chars(), with_order=0))
s["files"] += 1
with h5py.File(p, "r") as f:
ann = f["annotations"]
dims = f["dimensions"][:]
n = len(ann)
s["samples"] += n
for i in range(n):
a = json.loads(ann[i])
lines = a.get("line_bboxes", [])
s["lines"].append(len(lines))
s["words"].append(len(a.get("word_bboxes", [])))
s["paras"].append(len(a.get("para_bboxes", [])))
s["with_order"] += bool(a.get("relation_graph"))
for ln in lines[:40]:
s["chars"].add(ln.get("text", ""))
if ln.get("quad"):
w, h, ang = quad_geometry(ln["quad"])
if len(s["heights"]) < 400_000:
s["heights"].append(h)
s["angles"].append(ang)
s["widths"].append(w)
if len(s["dims"]) < 50_000:
s["dims"].append(tuple(int(x) for x in dims[i][:2]))
log(src["name"], f"{p.name}: {n} samples")
out = {}
for lang, s in per_lang.items():
hs = [h for h, _ in s["dims"]]
ws = [w for _, w in s["dims"]]
rot = sum(1 for a in s["angles"] if abs(a) > 2)
out[lang] = {
"files": s["files"], "samples": s["samples"],
"lines_per_page": pct(s["lines"]), "words_per_page": pct(s["words"]),
"paragraphs_per_page": pct(s["paras"]), "lines_total": sum(s["lines"]),
"line_height_px": pct(s["heights"]), "line_width_px": pct(s["widths"]),
"lines_tilted_over_2deg_share": round(rot / max(len(s["angles"]), 1), 4),
"page_height_px": pct(hs), "page_width_px": pct(ws),
"with_reading_order_share": round(s["with_order"] / max(s["samples"], 1), 4),
"chars": s["chars"].summary(),
}
return out
# ------------------------------------------------------------------- layout
# the class ids of DocLayNet v1.2, from its dataset card
DOCLAYNET_LABELS = {1: "Caption", 2: "Footnote", 3: "Formula", 4: "List-item", 5: "Page-footer", 6: "Page-header",
7: "Picture", 8: "Section-header", 9: "Table", 10: "Text", 11: "Title"}
def profile_doclaynet(src, d):
import pyarrow.parquet as pq
files = sorted(d.rglob("*.parquet"))
schema = pq.ParquetFile(files[0]).schema_arrow
cols = [n for n in schema.names if n not in ("image", "images", "pdf")]
splits, cats, doc_cats, cells, texts = collections.Counter(), collections.Counter(), collections.Counter(), 0, Chars()
sizes = []
for p in files:
split = p.name.split("-")[0]
pf = pq.ParquetFile(p)
splits[split] += pf.metadata.num_rows
for batch in pf.iter_batches(columns=cols, batch_size=500):
for row in batch.to_pylist():
cats.update(DOCLAYNET_LABELS.get(x, str(x)) for x in row.get("category_id") or [])
meta = row.get("metadata") or {}
if isinstance(meta, str):
try:
meta = json.loads(meta)
except ValueError:
meta = {}
if isinstance(meta, dict):
if meta.get("doc_category"):
doc_cats[meta["doc_category"]] += 1
if meta.get("original_width") and len(sizes) < 50_000: # PDF points
sizes.append((meta["original_width"], meta["original_height"]))
# pdf_cells: one list per layout box, of the PDF text cells inside it
for box in row.get("pdf_cells") or []:
cells += len(box)
for c in box:
if isinstance(c.get("text"), str):
texts.add(c["text"])
log(src["name"], f"{p.name} done")
return {"pages_by_split": dict(splits), "pages": sum(splits.values()), "columns": schema.names,
"label_instances": dict(cats.most_common(30)), "doc_categories": dict(doc_cats),
"text_cells": cells, "cell_chars": texts.summary(),
"page_width_pt": pct([w for w, _ in sizes]), "page_height_pt": pct([h for _, h in sizes])}
# ---------------------------------------------------------- text in images
def profile_hiertext(src, d):
out = {}
for split in ("train", "validation", "test"):
p = d / f"{split}.jsonl.gz"
if not p.exists():
continue
data = json.loads(gzip.open(p, "rt", encoding="utf-8").read())
anns = data.get("annotations", [])
n = dict(images=len(anns), paragraphs=0, lines=0, words=0, illegible=0, handwritten=0, vertical=0)
chars, heights = Chars(), []
for a in anns:
for para in a.get("paragraphs", []):
n["paragraphs"] += 1
for ln in para.get("lines", []):
n["lines"] += 1
chars.add(ln.get("text", ""))
for w in ln.get("words", []):
n["words"] += 1
n["illegible"] += not w.get("legible", True)
n["handwritten"] += bool(w.get("handwritten"))
n["vertical"] += bool(w.get("vertical"))
v = w.get("vertices")
if v and len(heights) < 300_000:
ys = [pt[1] for pt in v]
heights.append(max(ys) - min(ys))
n.update(word_height_px=pct(heights), chars=chars.summary())
out[split] = n
for tgz in sorted(d.glob("*.tgz")):
with tarfile.open(tgz, "r:gz") as t:
out.setdefault("image_archives", {})[tgz.name] = sum(1 for m in t if m.isfile())
return out
def profile_textocr(src, d):
out = {}
for split in ("train", "val"):
p = d / f"TextOCR_0.1_{split}.json"
if not p.exists():
continue
data = json.loads(p.read_text(encoding="utf-8"))
anns = data["anns"].values()
chars, heights, illegible = Chars(), [], 0
for a in anns:
s = a.get("utf8_string", "")
if s == ".":
illegible += 1
continue
chars.add(s)
if a.get("bbox") and len(heights) < 300_000:
heights.append(a["bbox"][3])
out[split] = dict(images=len(data["imgs"]), words=len(data["anns"]), illegible=illegible,
word_height_px=pct(heights), chars=chars.summary())
z = d / "train_val_images.zip"
if z.exists():
with zipfile.ZipFile(z) as zf:
out["image_files"] = sum(1 for i in zf.infolist() if not i.is_dir())
return out
# ----------------------------------------------------------------- historical
def profile_gt4histocr(src, d):
out = {}
for outer in d.glob("*.tar"):
with tarfile.open(outer) as t:
for m in t:
if not m.isfile():
continue
f = t.extractfile(m)
if m.name.endswith((".tar.bz2", ".tar.gz", ".tar", ".tbz2")):
corpus = Path(m.name).name.split(".")[0]
stats = dict(lines=0, images=0, chars=Chars())
with tarfile.open(fileobj=f, mode="r|*") as inner:
for im in inner:
if im.name.endswith(".gt.txt"):
stats["lines"] += 1
stats["chars"].add(inner.extractfile(im).read().decode("utf-8", "replace").strip())
elif im.name.endswith((".png", ".tif", ".jpg", ".bin.png", ".nrm.png")):
stats["images"] += 1
out[corpus] = dict(lines=stats["lines"], images=stats["images"], chars=stats["chars"].summary())
log(src["name"], f"{corpus}: {stats['lines']} lines")
return {"corpora": out, "lines": sum(v["lines"] for v in out.values())}
# ------------------------------------------------------- generic HF parquet
def profile_hf_parquet(src, d):
import pyarrow.parquet as pq
out = {}
for p in sorted(d.rglob("*.parquet")):
pf = pq.ParquetFile(p)
schema = pf.schema_arrow
textcols = [n for n in schema.names if n in ("text", "transcription", "ground_truth", "label", "words", "tokens")]
chars = Chars()
if textcols:
for batch in pf.iter_batches(columns=textcols, batch_size=500):
for col in batch.columns:
for v in col.to_pylist():
if isinstance(v, str):
chars.add(v)
elif isinstance(v, list):
for x in v:
if isinstance(x, str):
chars.add(x)
out[p.relative_to(d).as_posix()] = dict(rows=pf.metadata.num_rows, columns=schema.names,
chars=chars.summary())
return {"files": out, "rows": sum(v["rows"] for v in out.values())}
# ------------------------------------------------------------------------ PDFs
def pdf_stats(data, pages_to_read=3):
import pypdfium2 as pdfium
doc = pdfium.PdfDocument(data)
n = len(doc)
chars, sizes = [], []
text = ""
for i in range(min(n, pages_to_read)):
page = doc[i]
w, h = page.get_size()
sizes.append((round(w), round(h)))
t = page.get_textpage().get_text_range()
chars.append(len(t.strip()))
text += t
return n, chars, sizes, text
def page_format(w, h):
w, h = sorted((w, h))
if abs(w - 612) < 8 and abs(h - 792) < 8:
return "Letter"
if abs(w - 595) < 8 and abs(h - 842) < 8:
return "A4"
return "other"
class PdfSet:
def __init__(self):
self.docs = self.failed = 0
self.pages, self.chars_per_page, self.formats = [], [], collections.Counter()
self.text_pages = self.empty_pages = 0
self.chars = Chars()
def add(self, data):
try:
n, chars, sizes, text = pdf_stats(data)
except Exception: # noqa: BLE001 (an encrypted or broken PDF)
self.failed += 1
return
self.docs += 1
self.pages.append(n)
for c in chars:
self.chars_per_page.append(c)
if c >= 50:
self.text_pages += 1
else:
self.empty_pages += 1
for w, h in sizes:
self.formats[page_format(w, h)] += 1
self.chars.add(text[:20000])
def summary(self):
read = self.text_pages + self.empty_pages
return {"documents_read": self.docs, "unreadable": self.failed, "pages_per_doc": pct(self.pages),
"pages_total_in_read_docs": sum(self.pages), "chars_per_page": pct(self.chars_per_page),
"pages_with_text_layer_share": round(self.text_pages / max(read, 1), 4),
"page_formats": dict(self.formats), "chars": self.chars.summary()}
def profile_pdf_dir(src, d):
s = PdfSet()
for p in sorted((d / "pdf").glob("*.pdf"))[:SAMPLE_PDFS]:
s.add(p.read_bytes())
lic = collections.Counter()
m = HERE / "manifests" / "phase1" / f"{src['name']}.json"
if m.exists():
for f in json.loads(m.read_text(encoding="utf-8"))["files"]:
lic[f.get("license")] += 1
return {"pdfs": len(list((d / "pdf").glob("*.pdf"))), "licenses": dict(lic), **s.summary()}
def profile_govdocs(src, d):
s, seen, exts = PdfSet(), 0, collections.Counter()
for part in sorted(d.rglob("*.tar.a?")):
try:
with tarfile.open(part, "r|") as t: # a stream: the piece ends mid-archive
for m in t:
if not m.isfile():
continue
seen += 1
exts[Path(m.name).suffix.lower()] += 1
if s.docs + s.failed < SAMPLE_PDFS and m.name.lower().endswith(".pdf"):
s.add(t.extractfile(m).read())
except (tarfile.ReadError, EOFError):
pass # the cut at the end of the piece
return {"files_in_piece": seen, "extensions": dict(exts.most_common(8)), **s.summary()}
def profile_pdfa(src, d):
s, docs, pages, lines, words = PdfSet(), 0, [], [], []
chars = Chars()
for shard in sorted(d.rglob("*.tar")):
with tarfile.open(shard) as t:
for m in t:
if not m.isfile():
continue
if m.name.endswith(".json"):
docs += 1
j = json.load(t.extractfile(m))
pg = j.get("pages", [])
pages.append(len(pg))
for p in pg[:5]:
ln = (p.get("lines") or {}).get("text") or []
wd = (p.get("words") or {}).get("text") or []
lines.append(len(ln))
words.append(len(wd))
for x in ln[:60]:
chars.add(x)
elif m.name.endswith(".pdf") and s.docs + s.failed < SAMPLE_PDFS:
s.add(t.extractfile(m).read())
log(src["name"], f"{shard.name}: {docs} documents so far")
return {"documents": docs, "pages_per_doc": pct(pages), "pages_total": sum(pages),
"lines_per_page": pct(lines), "words_per_page": pct(words), "label_chars": chars.summary(),
"pdf_sample": s.summary()}
# ----------------------------------------------------------------- eval sets
def profile_files(src, d):
exts = collections.Counter()
size = 0
for p in d.rglob("*"):
if p.is_file() and ".cache" not in p.parts:
exts[p.suffix.lower() or "-"] += 1
size += p.stat().st_size
out = {"files_by_type": dict(exts.most_common(10)), "bytes": size}
if src["name"] in ("iam-line", "funsd"):
out.update(profile_hf_parquet(src, d))
return out
PROFILERS = {
"fonts-google": profile_fonts_google, "fonts-noto": profile_fonts_noto, "langdata-lstm": profile_langdata,
"wikipedia": profile_parquet_text, "fineweb-2": profile_parquet_text, "finepdfs": profile_parquet_text,
"nvidia-ocr-synthetic": profile_nvidia, "doclaynet": profile_doclaynet, "hiertext": profile_hiertext,
"textocr": profile_textocr, "gt4histocr": profile_gt4histocr, "gnhk": profile_hf_parquet,
"govdocs1": profile_govdocs, "pdfa-eng": profile_pdfa, "pmc-oa": profile_pdf_dir, "arxiv": profile_pdf_dir,
"omni-parse-bench": profile_files, "omnidocbench": profile_files, "olmocr-bench": profile_files,
"iam-line": profile_files, "funsd": profile_files,
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--root", type=Path, default=DEFAULT_ROOT)
ap.add_argument("--only", nargs="*")
a = ap.parse_args()
for stream in (sys.stdout, sys.stderr): # errors can carry any script; see fetch.py
stream.reconfigure(encoding="utf-8", errors="replace")
OUT.mkdir(parents=True, exist_ok=True)
for src in [BY_NAME[n] for n in a.only] if a.only else SOURCES:
d = a.root / src["name"]
if not d.exists():
log(src["name"], "not downloaded; skipped")
continue
t0 = time.time()
try:
prof = PROFILERS[src["name"]](src, d)
err = None
except Exception as e: # noqa: BLE001 (record it and go on)
prof, err = {}, f"{type(e).__name__}: {e}"
(OUT / f"{src['name']}.json").write_text(json.dumps(
{"name": src["name"], "seconds": round(time.time() - t0), "error": err, "profile": prof},
indent=1, ensure_ascii=False, default=str), encoding="utf-8")
log(src["name"], f"profiled in {round(time.time() - t0)} s" + (f"; ERROR {err}" if err else ""))
if __name__ == "__main__":
sys.exit(main())