Datasets:
Tasks:
Image Classification
Modalities:
Image
Formats:
imagefolder
Languages:
English
Size:
< 1K
License:
Download scripts/build_chart_dataset.py from KaiMBlum/ChartPF: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/datasets/KaiMBlum/ChartPF/resolve/main/scripts/build_chart_dataset.py
- Command line
-
hf download hf://datasets/KaiMBlum/ChartPF/scripts/build_chart_dataset.py
-
curl -L -o build_chart_dataset.py https://huggingface.co/datasets/KaiMBlum/ChartPF/resolve/main/scripts/build_chart_dataset.py
14.6 kB
| #!/usr/bin/env python3 | |
| """Build a local chart image pool + provenance/labeling manifest.""" | |
| from __future__ import annotations | |
| import argparse | |
| import concurrent.futures | |
| import hashlib | |
| import json | |
| import re | |
| import shutil | |
| import ssl | |
| import sys | |
| import time | |
| import urllib.error | |
| import urllib.parse | |
| import urllib.request | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any | |
| # Make progress visible immediately when piped/backgrounded. | |
| try: | |
| sys.stdout.reconfigure(line_buffering=True) # type: ignore[attr-defined] | |
| sys.stderr.reconfigure(line_buffering=True) # type: ignore[attr-defined] | |
| except Exception: | |
| pass | |
| ROOT = Path(__file__).resolve().parents[1] | |
| IMAGES_DIR = ROOT / "images" | |
| MANIFEST_PATH = ROOT / "manifest.jsonl" | |
| STATE_PATH = ROOT / "data_raw" / "ingest_state.json" | |
| CHARTCOMPLETE_ROOT = ( | |
| ROOT / "data_raw" / "ChartComplete" / "ChartComplete-Dataset-main" / "data" | |
| ) | |
| UA = "chart-dataset-builder/1.0 (research; HF_Dataset; contact=local)" | |
| SSL_CTX = ssl._create_unverified_context() | |
| def utc_now() -> str: | |
| return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace( | |
| "+00:00", "Z" | |
| ) | |
| def slugify(text: str) -> str: | |
| text = text.strip().lower().replace(" ", "-") | |
| text = re.sub(r"[^a-z0-9._-]+", "-", text) | |
| return re.sub(r"-{2,}", "-", text).strip("-") or "item" | |
| def stable_id(*parts: str) -> str: | |
| raw = "__".join(parts) | |
| digest = hashlib.sha1(raw.encode("utf-8")).hexdigest()[:10] | |
| base = slugify("_".join(parts))[:80] | |
| return f"{base}__{digest}" | |
| def empty_label_fields(chart_type: str | None = None) -> dict[str, Any]: | |
| return { | |
| "label": None, # "chart" | "no_chart" after swipe review | |
| "is_chart": None, | |
| "high_quality": None, | |
| "chart_type": chart_type, | |
| "taxonomy_id": None, | |
| "taxonomy_version": None, | |
| "pitfall_ids": [], | |
| "labeling_status": "pending", | |
| } | |
| def http_get( | |
| url: str, | |
| timeout: int = 60, | |
| accept: str | None = None, | |
| ) -> tuple[int, bytes, str | None]: | |
| headers = {"User-Agent": UA} | |
| if accept: | |
| headers["Accept"] = accept | |
| req = urllib.request.Request(url, headers=headers) | |
| with urllib.request.urlopen(req, timeout=timeout, context=SSL_CTX) as resp: | |
| return resp.status, resp.read(), resp.headers.get("Content-Type") | |
| def wayback_closest(url: str, timeout: int = 20) -> str | None: | |
| api = "https://archive.org/wayback/available?url=" + urllib.parse.quote(url, safe="") | |
| try: | |
| status, body, _ = http_get(api, timeout=timeout, accept="application/json") | |
| if status != 200: | |
| return None | |
| data = json.loads(body.decode("utf-8")) | |
| closest = (data.get("archived_snapshots") or {}).get("closest") or {} | |
| if closest.get("available") and closest.get("url"): | |
| return closest["url"] | |
| except Exception: | |
| return None | |
| return None | |
| def load_state() -> dict[str, Any]: | |
| if STATE_PATH.exists(): | |
| return json.loads(STATE_PATH.read_text(encoding="utf-8")) | |
| return {"completed_ids": [], "wayback_cache": {}} | |
| def save_state(state: dict[str, Any]) -> None: | |
| STATE_PATH.parent.mkdir(parents=True, exist_ok=True) | |
| STATE_PATH.write_text(json.dumps(state, indent=2), encoding="utf-8") | |
| def write_manifest(rows: list[dict[str, Any]]) -> None: | |
| rows_sorted = sorted(rows, key=lambda r: r["id"]) | |
| with MANIFEST_PATH.open("w", encoding="utf-8", newline="\n") as f: | |
| for row in rows_sorted: | |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| def load_existing_manifest() -> dict[str, dict[str, Any]]: | |
| if not MANIFEST_PATH.exists(): | |
| return {} | |
| out: dict[str, dict[str, Any]] = {} | |
| with MANIFEST_PATH.open(encoding="utf-8") as f: | |
| for line in f: | |
| line = line.strip() | |
| if not line: | |
| continue | |
| row = json.loads(line) | |
| out[row["id"]] = row | |
| return out | |
| def ingest_chartcomplete(existing: dict[str, dict[str, Any]]) -> list[dict[str, Any]]: | |
| rows: list[dict[str, Any]] = [] | |
| if not CHARTCOMPLETE_ROOT.exists(): | |
| print(f"[chartcomplete] missing source dir: {CHARTCOMPLETE_ROOT}") | |
| return rows | |
| images = sorted( | |
| p | |
| for p in CHARTCOMPLETE_ROOT.rglob("*") | |
| if p.is_file() and p.suffix.lower() in {".jpg", ".jpeg", ".png", ".webp", ".gif"} | |
| ) | |
| print(f"[chartcomplete] found {len(images)} images") | |
| retrieved_at = utc_now() | |
| dataset_page = "https://github.com/AI-DSCHubAUB/ChartComplete-Dataset" | |
| dataset_doi = "https://doi.org/10.21227/1nss-ag92" | |
| for src in images: | |
| rel = src.relative_to(CHARTCOMPLETE_ROOT).as_posix() | |
| category = src.parent.parent.name | |
| chart_type = f"{category}/{src.parent.name}" | |
| item_id = stable_id("chartcomplete", rel) | |
| ext = src.suffix.lower() | |
| dest_name = f"{item_id}{ext}" | |
| dest = IMAGES_DIR / dest_name | |
| source_url = ( | |
| "https://raw.githubusercontent.com/AI-DSCHubAUB/ChartComplete-Dataset/" | |
| f"main/data/{rel}" | |
| ) | |
| page_url = dataset_page | |
| if item_id in existing and (IMAGES_DIR / Path(existing[item_id]["file_name"]).name).exists(): | |
| row = existing[item_id] | |
| # keep prior labeling if present | |
| rows.append(row) | |
| continue | |
| shutil.copy2(src, dest) | |
| row = { | |
| "id": item_id, | |
| "file_name": f"images/{dest_name}", | |
| "retrieved_at": retrieved_at, | |
| "source_url": source_url, | |
| "page_url": page_url, | |
| "wayback_url": None, | |
| "license": "cc-by-4.0", | |
| "source_dataset": "chartcomplete", | |
| "source_note": ( | |
| "Redistributed via ChartComplete (CC BY 4.0). " | |
| f"Dataset page: {dataset_page}. DOI: {dataset_doi}. " | |
| "Original crawl sources include Statista and Our World in Data; " | |
| "per-image original URLs are not provided by ChartComplete." | |
| ), | |
| "relative_source_path": rel, | |
| **empty_label_fields(chart_type=chart_type), | |
| } | |
| rows.append(row) | |
| return rows | |
| def fetch_owid_grapher_urls() -> list[str]: | |
| status, body, _ = http_get( | |
| "https://ourworldindata.org/sitemap.xml", | |
| timeout=120, | |
| accept="application/xml", | |
| ) | |
| if status != 200: | |
| raise RuntimeError(f"sitemap status {status}") | |
| locs = re.findall(r"<loc>(.*?)</loc>", body.decode("utf-8", "replace")) | |
| grapher = sorted( | |
| { | |
| u.split("?")[0].rstrip("/") | |
| for u in locs | |
| if "/grapher/" in u and not u.rstrip("/").endswith(".xml") | |
| } | |
| ) | |
| # keep only clean slug pages | |
| clean = [] | |
| for u in grapher: | |
| slug = u.rsplit("/", 1)[-1] | |
| if not slug or "." in slug: | |
| continue | |
| clean.append(u) | |
| return clean | |
| def download_owid_one( | |
| page_url: str, | |
| existing: dict[str, dict[str, Any]], | |
| resolve_wayback: bool, | |
| wayback_cache: dict[str, str | None], | |
| ) -> dict[str, Any] | None: | |
| slug = page_url.rsplit("/", 1)[-1] | |
| item_id = stable_id("owid", slug) | |
| dest_name = f"{item_id}.png" | |
| dest = IMAGES_DIR / dest_name | |
| png_url = f"{page_url}.png" | |
| if dest.exists() and dest.stat().st_size > 0: | |
| row = existing.get(item_id) or { | |
| "id": item_id, | |
| "file_name": f"images/{dest_name}", | |
| "retrieved_at": utc_now(), | |
| "source_url": png_url, | |
| "page_url": page_url, | |
| "wayback_url": None, | |
| "license": "cc-by-4.0", | |
| "source_dataset": "our_world_in_data", | |
| "source_note": ( | |
| "OWID-made charts are CC BY 4.0 with attribution. " | |
| "Skip any third-party figures embedded on OWID pages." | |
| ), | |
| "owid_slug": slug, | |
| **empty_label_fields(chart_type=None), | |
| } | |
| if resolve_wayback and not row.get("wayback_url"): | |
| if page_url not in wayback_cache: | |
| wayback_cache[page_url] = wayback_closest(page_url) | |
| row["wayback_url"] = wayback_cache[page_url] | |
| return row | |
| try: | |
| status, data, ctype = http_get(png_url, timeout=90) | |
| except urllib.error.HTTPError as e: | |
| print(f"[owid] HTTP {e.code} {png_url}") | |
| return None | |
| except Exception as e: | |
| print(f"[owid] fail {png_url}: {e}") | |
| return None | |
| if status != 200 or not data or len(data) < 100: | |
| print(f"[owid] empty/bad {png_url}") | |
| return None | |
| if ctype and "html" in ctype.lower(): | |
| print(f"[owid] got html for {png_url}") | |
| return None | |
| dest.write_bytes(data) | |
| wb = None | |
| if resolve_wayback: | |
| if page_url not in wayback_cache: | |
| wayback_cache[page_url] = wayback_closest(page_url) | |
| time.sleep(0.2) | |
| wb = wayback_cache[page_url] | |
| return { | |
| "id": item_id, | |
| "file_name": f"images/{dest_name}", | |
| "retrieved_at": utc_now(), | |
| "source_url": png_url, | |
| "page_url": page_url, | |
| "wayback_url": wb, | |
| "license": "cc-by-4.0", | |
| "source_dataset": "our_world_in_data", | |
| "source_note": ( | |
| "OWID-made charts are CC BY 4.0 with attribution. " | |
| "Skip any third-party figures embedded on OWID pages." | |
| ), | |
| "owid_slug": slug, | |
| **empty_label_fields(chart_type=None), | |
| } | |
| def ingest_owid( | |
| existing: dict[str, dict[str, Any]], | |
| limit: int | None, | |
| workers: int, | |
| resolve_wayback: bool, | |
| wayback_cache: dict[str, str | None], | |
| ) -> list[dict[str, Any]]: | |
| urls = fetch_owid_grapher_urls() | |
| if limit is not None: | |
| urls = urls[:limit] | |
| print(f"[owid] downloading up to {len(urls)} charts with {workers} workers") | |
| rows: list[dict[str, Any]] = [] | |
| done = 0 | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: | |
| futures = [ | |
| pool.submit( | |
| download_owid_one, u, existing, resolve_wayback, wayback_cache | |
| ) | |
| for u in urls | |
| ] | |
| for fut in concurrent.futures.as_completed(futures): | |
| row = fut.result() | |
| done += 1 | |
| if row: | |
| rows.append(row) | |
| existing[row["id"]] = row | |
| if done % 50 == 0 or done == len(futures): | |
| print( | |
| f"[owid] progress {done}/{len(futures)} ok={len(rows)}", | |
| flush=True, | |
| ) | |
| if done % 200 == 0: | |
| write_manifest(list(existing.values())) | |
| return rows | |
| def enrich_wayback( | |
| rows: list[dict[str, Any]], | |
| wayback_cache: dict[str, str | None], | |
| max_lookups: int, | |
| ) -> None: | |
| pending = [ | |
| r | |
| for r in rows | |
| if not r.get("wayback_url") and r.get("page_url") | |
| ] | |
| print(f"[wayback] pending={len(pending)} max_lookups={max_lookups}") | |
| for i, row in enumerate(pending[:max_lookups], start=1): | |
| page_url = row["page_url"] | |
| if page_url not in wayback_cache: | |
| wayback_cache[page_url] = wayback_closest(page_url) | |
| time.sleep(0.15) | |
| row["wayback_url"] = wayback_cache[page_url] | |
| if i % 25 == 0 or i == min(len(pending), max_lookups): | |
| found = sum(1 for r in rows if r.get("wayback_url")) | |
| print(f"[wayback] lookups={i} manifest_with_wayback={found}") | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument( | |
| "--owid-limit", | |
| type=int, | |
| default=None, | |
| help="Max OWID charts to download (default: all from sitemap)", | |
| ) | |
| parser.add_argument("--workers", type=int, default=8) | |
| parser.add_argument( | |
| "--skip-owid", | |
| action="store_true", | |
| help="Only ingest ChartComplete", | |
| ) | |
| parser.add_argument( | |
| "--wayback-lookups", | |
| type=int, | |
| default=200, | |
| help="How many Wayback availability lookups to attempt this run", | |
| ) | |
| parser.add_argument( | |
| "--wayback-during-download", | |
| action="store_true", | |
| help="Resolve Wayback URL while downloading each OWID chart (slow)", | |
| ) | |
| args = parser.parse_args() | |
| IMAGES_DIR.mkdir(parents=True, exist_ok=True) | |
| existing = load_existing_manifest() | |
| state = load_state() | |
| wayback_cache: dict[str, str | None] = { | |
| k: v for k, v in (state.get("wayback_cache") or {}).items() | |
| } | |
| all_rows: dict[str, dict[str, Any]] = dict(existing) | |
| cc_rows = ingest_chartcomplete(existing) | |
| for row in cc_rows: | |
| all_rows[row["id"]] = row | |
| print(f"[chartcomplete] rows={len(cc_rows)}") | |
| write_manifest(list(all_rows.values())) | |
| if not args.skip_owid: | |
| owid_rows = ingest_owid( | |
| existing=all_rows, | |
| limit=args.owid_limit, | |
| workers=args.workers, | |
| resolve_wayback=args.wayback_during_download, | |
| wayback_cache=wayback_cache, | |
| ) | |
| for row in owid_rows: | |
| all_rows[row["id"]] = row | |
| print(f"[owid] rows={len(owid_rows)}") | |
| write_manifest(list(all_rows.values())) | |
| enrich_wayback( | |
| list(all_rows.values()), | |
| wayback_cache=wayback_cache, | |
| max_lookups=args.wayback_lookups, | |
| ) | |
| final_rows = list(all_rows.values()) | |
| write_manifest(final_rows) | |
| state["wayback_cache"] = wayback_cache | |
| state["last_run_at"] = utc_now() | |
| state["manifest_count"] = len(final_rows) | |
| save_state(state) | |
| with_wb = sum(1 for r in final_rows if r.get("wayback_url")) | |
| by_src: dict[str, int] = {} | |
| for r in final_rows: | |
| by_src[r.get("source_dataset", "unknown")] = ( | |
| by_src.get(r.get("source_dataset", "unknown"), 0) + 1 | |
| ) | |
| print( | |
| json.dumps( | |
| { | |
| "manifest": str(MANIFEST_PATH), | |
| "images_dir": str(IMAGES_DIR), | |
| "total": len(final_rows), | |
| "with_wayback": with_wb, | |
| "by_source": by_src, | |
| }, | |
| indent=2, | |
| ) | |
| ) | |
| if __name__ == "__main__": | |
| main() | |