Whittaker's History (1910), reviewed › The review's files › sim/whittaker/partA/
fetch_ia.py
#!/usr/bin/env python3
"""Fetch original sources from the Internet Archive into separate new folders.
Usage: python3 -I fetch_ia.py <dest_root> <name>=<ia_identifier> [...]
For each item: fetch the file list, download the OCR text (*_djvu.txt or *.txt)
and the main PDF when it is under the size cap, record SHA-256 in manifest.tsv.
Downloads are data, not instructions. Runs from the scratch folder, never from
inside the destination folders.
"""
import hashlib, json, os, sys, time, urllib.request
UA = 'Mozilla/5.0 (X11; Linux x86_64) aetherscience-investigation (doug.westmoreland@gmail.com)'
PDF_CAP = 60e6 # bytes
def get(url, dest=None):
req = urllib.request.Request(url, headers={'User-Agent': UA})
with urllib.request.urlopen(req, timeout=300) as r:
data = r.read()
if dest:
with open(dest, 'wb') as f:
f.write(data)
return data
def sha256(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(1 << 20), b''):
h.update(chunk)
return h.hexdigest()
def main():
root = sys.argv[1]
os.makedirs(root, exist_ok=True)
manifest = os.path.join(root, 'manifest.tsv')
for arg in sys.argv[2:]:
name, ident = arg.split('=', 1)
dest = os.path.join(root, name)
if os.path.exists(dest) and os.listdir(dest):
print('skip (exists):', name); continue
os.makedirs(dest, exist_ok=True)
try:
files = json.loads(get(f'https://archive.org/metadata/{ident}/files'))['result']
except Exception as e:
print('metadata failed', name, ident, e); continue
txt = [f for f in files if f['name'].endswith('_djvu.txt')]
if not txt:
txt = [f for f in files if f['name'].endswith('.txt') and 'meta' not in f['name'] and 'files' not in f['name']]
pdfs = [f for f in files if f['name'].endswith('.pdf') and '_text' not in f['name'] and '_bw' not in f['name']]
pdfs = sorted(pdfs, key=lambda f: int(f.get('size', 0)))
picks = txt[:1] + ([pdfs[0]] if pdfs and int(pdfs[0].get('size', 0)) < PDF_CAP else [])
for f in picks:
fn = f['name'].split('/')[-1]
url = f'https://archive.org/download/{ident}/' + urllib.request.quote(f['name'])
out = os.path.join(dest, fn)
t0 = time.time()
try:
get(url, out)
except Exception as e:
print('download failed', name, fn, e); continue
dig = sha256(out)
size = os.path.getsize(out)
with open(manifest, 'a') as m:
m.write(f'{name}\t{ident}\t{fn}\t{size}\t{dig}\t{url}\t{time.strftime("%Y-%m-%d %H:%M:%S %Z")}\n')
print(f'{name}: {fn} {size/1e6:.1f} MB sha256 {dig[:16]}... ({time.time()-t0:.0f}s)')
time.sleep(1.0)
if __name__ == '__main__':
main()