File size: 1,702 Bytes
3fffd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
9269662
3fffd0e
 
 
 
 
 
 
 
 
 
1462867
 
 
 
 
 
 
 
3fffd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
2abde28
3fffd0e
2abde28
3fffd0e
 
 
 
 
 
1462867
9269662
3fffd0e
 
 
 
 
 
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
#!/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()