File size: 3,845 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 | """R5 DATA (extra, beyond the plan): fetch the open Azerbaijani handwriting benchmark LocalDoc/azerbaijani-htr-benchmark
(CC BY 4.0, 442 human-annotated line crops from 29 pages, test-sized) and write a test-only manifest.
Plain public downloads, no login, no token, no special headers. The files are untrusted data: parquet is read with pyarrow only, nothing is executed.
Run on a ZEN4 node: python -I r5_fetch_az_htr.py fetch | manifest
"""
import hashlib
import io
import json
import sys
import time
import urllib.request
from pathlib import Path
DATA = Path("/path/to/TURKIC_OCR_DATA")
RAW = DATA / "data/raw/localdoc_az_htr"
R5 = DATA / "data/processed/r5"
REPO = "LocalDoc/azerbaijani-htr-benchmark"
API = f"https://huggingface.co/api/datasets/{REPO}"
HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"]
def sha256_file(p):
h = hashlib.sha256()
with open(p, "rb") as f:
for c in iter(lambda: f.read(1 << 20), b""):
h.update(c)
return h.hexdigest()
def fetch():
RAW.mkdir(parents=True, exist_ok=True)
meta = json.load(urllib.request.urlopen(API, timeout=60))
json.dump(meta, open(RAW / "api_record.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
sib = [s["rfilename"] for s in meta.get("siblings", [])]
log = {"repo": REPO, "licence_field": (meta.get("cardData") or {}).get("license"), "files": {}, "fetched_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
for name in sib:
if name.endswith(".parquet") or name == "README.md" or name == ".gitattributes":
dst = RAW / name
dst.parent.mkdir(parents=True, exist_ok=True)
url = f"https://huggingface.co/datasets/{REPO}/resolve/main/{name}"
data = urllib.request.urlopen(url, timeout=300).read()
dst.write_bytes(data)
log["files"][name] = {"bytes": len(data), "sha256": sha256_file(dst)}
json.dump(log, open(RAW / "fetch_log.json", "w", encoding="utf-8"), indent=1)
print(json.dumps(log)[:1500])
def manifest():
import unicodedata
import pyarrow.parquet as pq
cands = sorted(RAW.rglob("*.parquet"))
print("parquet files:", [str(c.relative_to(RAW)) for c in cands])
lines = [c for c in cands if "line" in str(c).lower()]
assert lines, "no lines parquet found"
pf = pq.ParquetFile(lines[0])
print("schema:", pf.schema_arrow)
tbl = pf.read()
cols = tbl.column_names
img_col = next(c for c in cols if "image" in c.lower())
txt_col = next(c for c in cols if c.lower() in ("text", "label", "transcription", "ground_truth", "gt"))
page_col = next((c for c in cols if "page" in c.lower() or "source" in c.lower()), None)
out_dir = R5 / "images/az_localdoc_htr"
out_dir.mkdir(parents=True, exist_ok=True)
rows = []
for i in range(tbl.num_rows):
im = tbl.column(img_col)[i].as_py()
data = im["bytes"] if isinstance(im, dict) else im
text = unicodedata.normalize("NFC", str(tbl.column(txt_col)[i].as_py())).strip()
for ch in ("\t", "\r", "\n"):
text = text.replace(ch, " ")
dst = out_dir / f"{i:04d}.png"
from PIL import Image
Image.open(io.BytesIO(data)).convert("RGB").save(dst)
grp = "az_page_" + str(tbl.column(page_col)[i].as_py()) if page_col else "az_page_unknown"
rows.append([f"az_localdoc:{i:04d}", str(dst), text, "az", "Latn", "hand_real", "localdoc_az_htr", "test", grp, "line"])
mp = R5 / "manifests/az_localdoc_test.tsv"
with open(mp, "w", encoding="utf-8", newline="") as f:
f.write("\t".join(HDR) + "\n")
for r in rows:
f.write("\t".join(r) + "\n")
print("wrote", mp, len(rows), "columns", cols)
if __name__ == "__main__":
{"fetch": fetch, "manifest": manifest}[sys.argv[1]]()
|