beyarkay commited on
Commit
3aa142c
·
1 Parent(s): 9682b79

add scraper to download txt files from archive.org

Browse files
Files changed (1) hide show
  1. src/download_txt_archive_dot_org.py +267 -0
src/download_txt_archive_dot_org.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # requires-python = ">=3.8"
4
+ # dependencies = [
5
+ # "requests",
6
+ # "tqdm",
7
+ # ]
8
+ # ///
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import re
14
+ import sqlite3
15
+ import threading
16
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
17
+ from concurrent.futures import ThreadPoolExecutor, as_completed
18
+
19
+ import requests
20
+ from requests import Session
21
+ from tqdm import tqdm
22
+
23
+
24
+ # ----------------------------
25
+ # CONFIG (intentionally globals)
26
+ # ----------------------------
27
+ DB_PATH: str = "archive.org.db"
28
+ DOWNLOAD_DIR: str = "./data/archive-dot-org" # target download folder
29
+ MIN_DOWNLOADS: int = 1000 # only download items with downloads >= this
30
+ DATE_START: int = 1880 # inclusive year
31
+ DATE_END: int = 1882 # inclusive year
32
+ EXTRA_WHERE: str = (
33
+ # example: require "science", exclude "religion"
34
+ # "AND lower(subject) LIKE '%science%' AND lower(subject) NOT LIKE '%religion%'"
35
+ # Exclude religious texts
36
+ "AND LOWER(subject) NOT LIKE '%baptist%' "
37
+ "AND LOWER(subject) NOT LIKE '%church%' "
38
+ "AND LOWER(subject) NOT LIKE '%congregation%'"
39
+ "AND LOWER(subject) NOT LIKE '%methodis%'"
40
+ "AND LOWER(subject) NOT LIKE '%religio%'"
41
+ "AND LOWER(subject) NOT LIKE '%christ%'"
42
+ "AND LOWER(subject) NOT LIKE '%protestant%'"
43
+ "AND LOWER(subject) NOT LIKE '%evangelical%'"
44
+ "AND LOWER(subject) NOT LIKE '%bible%'"
45
+ "AND LOWER(subject) NOT LIKE '%theology%'"
46
+ "AND LOWER(subject) NOT LIKE '%hymn%'"
47
+ "AND LOWER(subject) NOT LIKE '%theism%'"
48
+ # Exclude newspapers, periodicals, etc
49
+ "AND LOWER(subject) NOT LIKE '%newspaper%'"
50
+ "AND LOWER(subject) NOT LIKE '%tribune%'"
51
+ "AND LOWER(subject) NOT LIKE '%herald%'"
52
+
53
+ )
54
+ LIMIT_ITEMS: int = 10_000 # hard cap to avoid runaway
55
+ MAX_WORKERS: int = 2 # parallel downloads
56
+ REQUEST_TIMEOUT_S: float = 30.0 # per HTTP request
57
+ REQUEST_RETRIES: int = 3 # retry on transient errors
58
+
59
+ def build_sql_query(
60
+ min_downloads: int,
61
+ year_start: int,
62
+ year_end: int,
63
+ extra_where_sql: str,
64
+ limit_items: int,
65
+ ) -> Tuple[str, Tuple]:
66
+ assert year_start <= year_end
67
+ # Extract first 4 digits from `date` safely; skip rows without a 4-digit year.
68
+ base_where = (
69
+ "WHERE downloads >= ? "
70
+ "AND date IS NOT NULL "
71
+ "AND substr(date,1,4) GLOB '[0-9][0-9][0-9][0-9]' "
72
+ "AND CAST(substr(date,1,4) AS INTEGER) BETWEEN ? AND ? "
73
+ )
74
+ params: Tuple = (min_downloads, year_start, year_end)
75
+ # Extra WHERE is injected as a trusted constant by the user (not parameterized).
76
+ where_clause = base_where + (f" {extra_where_sql} " if extra_where_sql.strip() else "")
77
+ sql = (
78
+ "SELECT identifier FROM items "
79
+ + where_clause
80
+ + "ORDER BY downloads DESC, identifier ASC "
81
+ + "LIMIT ?"
82
+ )
83
+ params = params + (limit_items,)
84
+ return sql, params
85
+
86
+
87
+ def list_identifiers(
88
+ db_path: str,
89
+ min_downloads: int,
90
+ year_start: int,
91
+ year_end: int,
92
+ extra_where_sql: str,
93
+ limit_items: int,
94
+ ) -> List[str]:
95
+ sql, params = build_sql_query(min_downloads, year_start, year_end, extra_where_sql, limit_items)
96
+ with sqlite3.connect(db_path) as conn:
97
+ conn.row_factory = lambda cur, row: row[0]
98
+ rows: List[str] = conn.execute(sql, params).fetchall()
99
+ return rows
100
+
101
+
102
+ def http_get_json_with_retries(
103
+ session: Session,
104
+ url: str,
105
+ params: Optional[Sequence[Tuple[str, Any]]] = None,
106
+ timeout_s: float = REQUEST_TIMEOUT_S,
107
+ retries: int = REQUEST_RETRIES,
108
+ ) -> Dict[str, Any]:
109
+ attempt = 0
110
+ backoff = 1.0
111
+ while True:
112
+ try:
113
+ resp = session.get(url, params=params, timeout=timeout_s, verify=True)
114
+ resp.raise_for_status()
115
+ return resp.json()
116
+ except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.HTTPError):
117
+ attempt += 1
118
+ if attempt > retries:
119
+ raise
120
+ _sleep(backoff)
121
+ backoff *= 2.0
122
+
123
+
124
+ def http_stream_download(
125
+ session: Session,
126
+ url: str,
127
+ dest_path: str,
128
+ timeout_s: float = REQUEST_TIMEOUT_S,
129
+ retries: int = REQUEST_RETRIES,
130
+ ) -> None:
131
+ # Stream to temp file; atomic rename at end.
132
+ tmp_path = dest_path + ".part"
133
+ attempt = 0
134
+ backoff = 1.0
135
+ while True:
136
+ try:
137
+ with session.get(url, stream=True, timeout=timeout_s, verify=True) as r:
138
+ r.raise_for_status()
139
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
140
+ with open(tmp_path, "wb") as f:
141
+ for chunk in r.iter_content(chunk_size=1024 * 1024):
142
+ if chunk:
143
+ f.write(chunk)
144
+ os.replace(tmp_path, dest_path)
145
+ return
146
+ except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.HTTPError):
147
+ attempt += 1
148
+ if attempt > retries:
149
+ # Clean partial
150
+ with _suppress():
151
+ os.remove(tmp_path)
152
+ raise
153
+ _sleep(backoff)
154
+ backoff *= 2.0
155
+
156
+
157
+ def choose_txt_file(files: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
158
+ # Prefer the largest .txt file; fall back to any .txt.
159
+ txts = [f for f in files if isinstance(f.get("name"), str) and f["name"].lower().endswith(".txt")]
160
+ if not txts:
161
+ return None
162
+ def file_size(f: Dict[str, Any]) -> int:
163
+ try:
164
+ return int(f.get("size", 0))
165
+ except Exception:
166
+ return 0
167
+ txts.sort(key=file_size, reverse=True)
168
+ return txts[0]
169
+
170
+
171
+ def fetch_txt_for_identifier(session: Session, identifier: str) -> Optional[Tuple[str, str]]:
172
+ # Return (filename, download_url) or None.
173
+ meta_url = f"https://archive.org/metadata/{identifier}"
174
+ data = http_get_json_with_retries(session, meta_url)
175
+ meta = data.get('metadata', {})
176
+ date = meta.get('date', 'undated')
177
+ if type(date) is list:
178
+ date = str(sorted(date)[0])
179
+ print(f"Fetched metadata for `{meta.get('title')}` by `{meta.get('creator')}`")
180
+ files = data.get("files", [])
181
+ if not isinstance(files, list):
182
+ return None
183
+ chosen = choose_txt_file(files)
184
+ if not chosen:
185
+ return None
186
+ name = chosen["name"]
187
+ # Prefer canonical /download URL
188
+ url = f"https://archive.org/download/{identifier}/{name}"
189
+ return name, url, date
190
+
191
+
192
+ def sanitize_identifier(identifier: str) -> str:
193
+ # Keep filesystem safe
194
+ return re.sub(r"[^A-Za-z0-9._-]+", "_", identifier)
195
+
196
+
197
+ def download_one(session: Session, base_dir: str, identifier: str) -> Tuple[str, bool, Optional[str]]:
198
+ try:
199
+ # subdir = os.path.join(base_dir, sanitize_identifier(identifier))
200
+ # os.makedirs(subdir, exist_ok=True)
201
+ meta = fetch_txt_for_identifier(session, identifier)
202
+ if not meta:
203
+ return identifier, None, False, "no .txt file found"
204
+ filename, url, date = meta
205
+ dest = os.path.join(base_dir, str(date)[:4], filename)
206
+ if os.path.exists(dest) and os.path.getsize(dest) > 0:
207
+ return identifier, None, True, "exists"
208
+ http_stream_download(session, url, dest)
209
+ # print(f"\nDownloaded {url}")
210
+ return identifier, date, True, None
211
+ except Exception as e:
212
+ return identifier, None, False, str(e)
213
+
214
+
215
+ def _sleep(seconds: float) -> None:
216
+ import time as _t
217
+ _t.sleep(seconds)
218
+
219
+
220
+ class _suppress:
221
+ def __enter__(self):
222
+ return self
223
+ def __exit__(self, exc_type, exc, tb):
224
+ return True
225
+
226
+
227
+ def run() -> None:
228
+ identifiers = list_identifiers(
229
+ DB_PATH,
230
+ MIN_DOWNLOADS,
231
+ DATE_START,
232
+ DATE_END,
233
+ EXTRA_WHERE,
234
+ LIMIT_ITEMS,
235
+ )
236
+ if not identifiers:
237
+ print("No identifiers match the filters.")
238
+ return
239
+
240
+ session = requests.Session()
241
+ lock = threading.Lock()
242
+ success_count = 0
243
+ skip_count = 0
244
+ fail_count = 0
245
+
246
+ with ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool, tqdm(total=len(identifiers), desc="download", unit=" item") as bar:
247
+ futures = [pool.submit(download_one, session, DOWNLOAD_DIR, ident) for ident in identifiers]
248
+ for f in as_completed(futures):
249
+ ident, date, ok, msg = f.result()
250
+ bar.set_description(f"[{date}] downloaded {ident} {ok=} {msg=}")
251
+ with lock:
252
+ if ok and msg == "exists":
253
+ skip_count += 1
254
+ elif ok:
255
+ success_count += 1
256
+ else:
257
+ fail_count += 1
258
+ bar.update(1)
259
+ if not ok and msg:
260
+ bar.write(f"[FAIL] {ident}: {msg}")
261
+
262
+ print(f"done: success={success_count} skipped={skip_count} failed={fail_count}")
263
+
264
+
265
+ if __name__ == "__main__":
266
+ run()
267
+