Datasets:
Tasks:
Image Classification
Modalities:
Image
Formats:
imagefolder
Languages:
English
Size:
< 1K
License:
File size: 14,601 Bytes
16c3bac | 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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 | #!/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()
|