#!/usr/bin/env python3 # /// script # requires-python = ">=3.8" # dependencies = [ # "requests", # "tqdm", # ] # /// from __future__ import annotations import contextlib import datetime as dt import json import queue import sqlite3 import threading from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple from concurrent.futures import ThreadPoolExecutor, as_completed import time as _time import requests from requests import Session from tqdm import tqdm def build_query(start_date: dt.date, end_date: dt.date) -> str: assert start_date <= end_date start_iso = start_date.isoformat() end_iso = end_date.isoformat() return ( 'mediatype:(texts) ' 'AND (language:eng OR language:"English") ' f'AND (date:[{start_iso} TO {end_iso}] OR year:[{start_date.year} TO {end_date.year}]) ' # 'AND downloads:[5 TO *] ' 'AND format:("Full Text" OR "txt" OR "text")' ) def http_get_json( session: Session, url: str, params: Sequence[Tuple[str, Any]], timeout_seconds: float, retries: int, ) -> Dict[str, Any]: print(f"\nRequesting from {url} {params}") backoff = 1.0 for attempt in range(retries + 1): try: resp = session.get(url, params=params, timeout=timeout_seconds) resp.raise_for_status() return resp.json() except requests.exceptions.Timeout as e: print(f"Exception: {e}, {url=} {params=}") if attempt == retries: raise _time.sleep(backoff) backoff *= 2.0 except requests.exceptions.ConnectionError as e: print(f"Exception: {e}, {url=} {params=}") if attempt == retries: raise _time.sleep(backoff) backoff *= 2.0 except requests.exceptions.HTTPError as e: print(f"Exception: {e}, {url=} {params=}") code = e.response.status_code if e.response is not None else None if code is not None and 500 <= code < 600 and attempt < retries: _time.sleep(backoff) backoff *= 2.0 continue raise except json.JSONDecodeError as e: print(f"Exception: {e}, {url=} {params=}") if attempt == retries: raise _time.sleep(backoff) backoff *= 2.0 raise RuntimeError("unreachable") def scrape_total_only( session: Session, endpoint: str, query: str, timeout_seconds: float, retries: int, ) -> int: params: List[Tuple[str, Any]] = [ ("q", query), ("total_only", "true"), # count is optional when total_only=true; include to be explicit and satisfy min constraint. ("count", 100), ] data = http_get_json(session, endpoint, params, timeout_seconds, retries) total = int(data.get("total", 0)) assert total >= 0 return total def month_ranges(start_date: dt.date, end_date: dt.date) -> List[Tuple[dt.date, dt.date]]: assert start_date <= end_date ranges: List[Tuple[dt.date, dt.date]] = [] y, m = start_date.year, start_date.month end_ym = (end_date.year, end_date.month) while (y, m) <= end_ym: first = dt.date(y, m, 1) if m == 12: next_month = dt.date(y + 1, 1, 1) else: next_month = dt.date(y, m + 1, 1) last = min(next_month - dt.timedelta(days=1), end_date) if first < start_date: first = start_date ranges.append((first, last)) if m == 12: y, m = y + 1, 1 else: m += 1 return ranges def ensure_schema(connection: sqlite3.Connection) -> None: connection.execute( """ CREATE TABLE IF NOT EXISTS items ( identifier TEXT PRIMARY KEY, title TEXT, creator TEXT, date TEXT, downloads INTEGER, item_size INTEGER, subject TEXT ) """ ) connection.commit() def coerce_str(value: Any) -> Optional[str]: if value is None: return None if isinstance(value, list): return "; ".join(str(x) for x in value if x is not None) return str(value) def coerce_int(value: Any) -> Optional[int]: if value is None: return None try: return int(value) except (ValueError, TypeError): return None def docs_to_rows(docs: Iterable[Dict[str, Any]]) -> List[Tuple]: rows: List[Tuple] = [] for d in docs: identifier = coerce_str(d.get("identifier")) if not identifier: continue title = coerce_str(d.get("title")) creator = coerce_str(d.get("creator")) date_val = coerce_str(d.get("date")) subject = coerce_str(d.get("subject")) downloads = coerce_int(d.get("downloads")) item_size = coerce_int(d.get("item_size")) rows.append((identifier, title, creator, date_val, downloads, item_size, subject)) return rows def writer_loop( database_path: str, input_queue: "queue.Queue[Optional[List[Tuple]]]", commit_batch_size: int, ) -> None: with contextlib.closing(sqlite3.connect(database_path, timeout=30.0)) as conn: ensure_schema(conn) pending: List[Tuple] = [] while True: item = input_queue.get() if item is None: if pending: conn.executemany( "INSERT OR REPLACE INTO items(identifier, title, creator, date, downloads, item_size, subject) VALUES(?,?,?,?,?,?,?)", pending, ) conn.commit() break pending.extend(item) if len(pending) >= commit_batch_size: conn.executemany( "INSERT OR REPLACE INTO items(identifier, title, creator, date, downloads, item_size, subject) VALUES(?,?,?,?,?,?,?)", pending, ) conn.commit() pending.clear() def scrape_month_cursor_loop( session: Session, endpoint: str, query: str, fields: Sequence[str], batch_count: int, timeout_seconds: float, retries: int, rows_out: "queue.Queue[Optional[List[Tuple]]]", items_bar: tqdm, ) -> None: print(f"\nRequesting {batch_count} from {endpoint} {query}") params_base: Dict[str, Any] = { "q": query, "fields": ",".join(fields), "count": batch_count, } params = list(params_base.items()) try: data = http_get_json(session, endpoint, params, timeout_seconds, retries) except (requests.exceptions.RequestException, json.JSONDecodeError): return while True: docs = data.get("items", []) if docs: rows = docs_to_rows(docs) if rows: rows_out.put(rows) items_bar.update(len(docs)) # items_bar.set_description(f"items ({docs.get('date')})") cursor = data.get("cursor") if not cursor: break params = list(params_base.items()) + [("cursor", cursor)] try: data = http_get_json(session, endpoint, params, timeout_seconds, retries) except (requests.exceptions.RequestException, json.JSONDecodeError): break def run() -> None: database_path = "data/archive-dot-org/archive.org.1900s.db" endpoint = "https://archive.org/services/search/v1/scrape" start_date = dt.date(1900, 1, 1) end_date = dt.date(1950, 1, 1) batch_count = 10000 # scraping API requires count >= 100 request_timeout_seconds = 20.0 request_retries = 5 writer_commit_batch_size = 500 max_workers = 8 fields = ["creator", "date", "downloads", "identifier", "item_size", "subject", "title"] session = requests.Session() # Plan monthly queries and totals monthly_queries: List[Tuple[str, int]] = [] months = month_ranges(start_date, end_date) with tqdm(desc="planning-months", total=len(months), unit="month") as plan_bar: for m_start, m_end in months: q = build_query(m_start, m_end) try: total = scrape_total_only(session, endpoint, q, request_timeout_seconds, request_retries) except (requests.exceptions.RequestException, json.JSONDecodeError): total = 0 monthly_queries.append((q, total)) plan_bar.update(1) total_items = sum(t for _, t in monthly_queries) rows_queue: "queue.Queue[Optional[List[Tuple]]]" = queue.Queue(maxsize=max_workers * 4) writer_thread = threading.Thread( target=writer_loop, args=(database_path, rows_queue, writer_commit_batch_size), daemon=True, ) writer_thread.start() with tqdm(total=total_items if total_items > 0 else None, desc="items", unit="it") as items_bar, \ ThreadPoolExecutor(max_workers=max_workers) as pool: futures = [] for q, total in monthly_queries: futures.append( pool.submit( scrape_month_cursor_loop, session, endpoint, q, fields, batch_count, request_timeout_seconds, request_retries, rows_queue, items_bar, ) ) for f in as_completed(futures): try: # f.get(timeout=None) f.result() except Exception: raise rows_queue.put(None) writer_thread.join() if __name__ == "__main__": run()