Datasets:
Download tools/export_track.py from comradev7/Scenic-Font-Analysis: direct link, hf CLI and curl.
- Browser
- Download file 6.02 kB
-
https://huggingface.co/datasets/comradev7/Scenic-Font-Analysis/resolve/main/tools/export_track.py
- Command line
-
hf download hf://datasets/comradev7/Scenic-Font-Analysis/tools/export_track.py
-
curl -L -o export_track.py https://huggingface.co/datasets/comradev7/Scenic-Font-Analysis/resolve/main/tools/export_track.py
6.02 kB
| """Stage a single track into the shared dataset layout. | |
| Given a directory of images and a ground-truth CSV, this produces: | |
| <out>/track_<letter>/ | |
| ground_truth.csv # schema-normalized, adds style_unified | |
| manifest.json # counts + checksums for integrity checks | |
| images.tar.gz # images archived by basename (HF: <=10k files/dir) | |
| Images are stored as a single archive because Hugging Face repositories reject | |
| any directory with more than 10,000 files. Teammates upload <out> with | |
| tools/push_repo.py. | |
| """ | |
| import os | |
| import sys | |
| import json | |
| import tarfile | |
| import hashlib | |
| import argparse | |
| from datetime import datetime, timezone | |
| import pandas as pd | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from taxonomy import add_unified_column, UNIFIED_STYLE_CLASSES # noqa: E402 | |
| REQUIRED_COLUMNS = [ | |
| "image_filename", "language", "font_family", "font_style", | |
| "style_unified", "split", "is_clean", "text", | |
| ] | |
| ALLOWED_SPLITS = {"train", "val", "test"} | |
| STYLE_SET = set(UNIFIED_STYLE_CLASSES) | |
| IMAGE_SUFFIXES = (".jpg", ".jpeg", ".png", ".bmp", ".webp") | |
| def sha256(path): | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for chunk in iter(lambda: f.read(1 << 20), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def build_archive(src_dir, archive_path, compression): | |
| mode = "w:gz" if compression == "gz" else "w" | |
| members = 0 | |
| with tarfile.open(archive_path, mode) as tar: | |
| for name in sorted(os.listdir(src_dir)): | |
| src = os.path.join(src_dir, name) | |
| if os.path.isfile(src) and name.lower().endswith(IMAGE_SUFFIXES): | |
| tar.add(src, arcname=name) | |
| members += 1 | |
| return members | |
| def main(): | |
| ap = argparse.ArgumentParser(description="Stage a track into the shared layout.") | |
| ap.add_argument("--track", required=True, help="Track letter, e.g. a") | |
| ap.add_argument("--images", required=True, help="Directory of image files.") | |
| ap.add_argument("--ground-truth", required=True, dest="gt", help="Raw ground-truth CSV.") | |
| ap.add_argument("--out", default="staging", help="Staging root (default: staging).") | |
| ap.add_argument("--archive", choices=["tar", "tar.gz", "none"], default="tar.gz", | |
| help="Image archive format (default tar.gz; 'none' stages loose files).") | |
| ap.add_argument("--no-images", action="store_true", help="Stage metadata only.") | |
| ap.add_argument("--backfill-local", action="store_true", | |
| help="Also rewrite the input CSV with the style_unified column.") | |
| args = ap.parse_args() | |
| track = args.track.strip().lower() | |
| track_dir = os.path.join(args.out, f"track_{track}") | |
| os.makedirs(track_dir, exist_ok=True) | |
| df = pd.read_csv(args.gt) | |
| add_unified_column(df) | |
| missing_cols = [c for c in REQUIRED_COLUMNS if c not in df.columns] | |
| if missing_cols: | |
| raise SystemExit(f"[ERROR] missing columns: {missing_cols}") | |
| bad_styles = sorted(set(df["style_unified"]) - STYLE_SET) | |
| if bad_styles: | |
| raise SystemExit(f"[ERROR] invalid style_unified values: {bad_styles}") | |
| bad_splits = sorted(set(df["split"]) - ALLOWED_SPLITS) | |
| if bad_splits: | |
| raise SystemExit(f"[ERROR] invalid split values: {bad_splits}") | |
| gt_out = os.path.join(track_dir, "ground_truth.csv") | |
| df.to_csv(gt_out, index=False) | |
| manifest = { | |
| "schema_version": "1.0", | |
| "track": f"track_{track}", | |
| "created_utc": datetime.now(timezone.utc).isoformat(), | |
| "image_count": int(len(df)), | |
| "columns": REQUIRED_COLUMNS, | |
| "style_unified_counts": {k: int(v) for k, v in df["style_unified"].value_counts().items()}, | |
| "split_counts": {k: int(v) for k, v in df["split"].value_counts().items()}, | |
| "language_counts": {k: int(v) for k, v in df["language"].value_counts().items()}, | |
| "ground_truth_sha256": sha256(gt_out), | |
| } | |
| if not args.no_images: | |
| available = {n for n in os.listdir(args.images) | |
| if os.path.isfile(os.path.join(args.images, n)) | |
| and n.lower().endswith(IMAGE_SUFFIXES)} | |
| referenced = set(df["image_filename"]) | |
| missing = sorted(referenced - available) | |
| if missing: | |
| raise SystemExit(f"[ERROR] {len(missing)} referenced images missing " | |
| f"(e.g. {missing[:3]})") | |
| if args.archive == "none": | |
| images_dir = os.path.join(track_dir, "images") | |
| os.makedirs(images_dir, exist_ok=True) | |
| import shutil | |
| for name in referenced: | |
| dst = os.path.join(images_dir, name) | |
| if not os.path.exists(dst): | |
| try: | |
| os.link(os.path.join(args.images, name), dst) | |
| except OSError: | |
| shutil.copy2(os.path.join(args.images, name), dst) | |
| manifest["image_layout"] = "images/<image_filename>" | |
| else: | |
| compression = "gz" if args.archive == "tar.gz" else "" | |
| archive_name = f"images.{args.archive}" | |
| archive_path = os.path.join(track_dir, archive_name) | |
| members = build_archive(args.images, archive_path, compression) | |
| if members < len(referenced): | |
| raise SystemExit(f"[ERROR] archive has {members} members, " | |
| f"expected at least {len(referenced)}") | |
| manifest["image_layout"] = archive_name | |
| manifest["images_archive_sha256"] = sha256(archive_path) | |
| manifest["images_archive_members"] = int(members) | |
| with open(os.path.join(track_dir, "manifest.json"), "w", encoding="utf-8") as f: | |
| json.dump(manifest, f, indent=2) | |
| if args.backfill_local: | |
| df.to_csv(args.gt, index=False) | |
| print(f"[backfill] rewrote {args.gt} with style_unified") | |
| print(json.dumps(manifest, indent=2)) | |
| print(f"[ok] staged track_{track} -> {track_dir}") | |
| if __name__ == "__main__": | |
| main() | |