#!/usr/bin/env python # /// script # requires-python = ">=3.10" # dependencies = [ # "tqdm", # ] # /// """ Chronicling America OCR dump downloader (no options, no deps). Run: uv run chronicling_dl_simple.py """ import os import json import tarfile import urllib.request from pathlib import Path import tqdm CATALOG_URL = "https://chroniclingamerica.loc.gov/ocr.json" DEST_ROOT = Path("data/chronicling-america") ARCHIVES_DIR = DEST_ROOT / "_archives" def remove_non_txt_files(root: Path) -> None: deleted = 0 for p in root.rglob("*"): if p.is_file() and p.suffix.lower() != ".txt": p.unlink() deleted += 1 print(f"deleted {deleted} non-txt files in {root}") def main() -> None: DEST_ROOT.mkdir(parents=True, exist_ok=True) ARCHIVES_DIR.mkdir(parents=True, exist_ok=True) with urllib.request.urlopen(CATALOG_URL) as r: catalog = json.load(r) for entry in tqdm.tqdm(catalog["ocr"]): url = entry["url"] name = entry["name"] archive_path = ARCHIVES_DIR / name out_dir = DEST_ROOT / name.removesuffix(".tar.bz2") if out_dir.exists(): print(f"Directory exists, skipping {out_dir}") continue else: if not archive_path.exists(): print(f"downloading {name}") urllib.request.urlretrieve(url, archive_path) print(f"extracting {name}") with tarfile.open(archive_path, "r:bz2") as tar: tar.extractall(out_dir) # simple, unsafe but short remove_non_txt_files(out_dir) os.remove(archive_path) print("done") if __name__ == "__main__": main()