#!/usr/bin/env python3 """Fetch earthquakes from the USGS ComCat FDSN event service as CSV, one file per calendar year. python3 -I fetch_comcat.py [] Standard library only. Query: format=csv, eventtype=earthquake, minmagnitude as given, orderby=time-asc, from 1 January of each year to 1 January of the next (or to the end date given for the last year). Each reply is saved as sent; fetch-log.jsonl gets the URL, size, SHA-256 and time. """ import datetime as dt import hashlib import json import pathlib import sys import time import urllib.request UA = "factchecked-research/1.0" BASE = "https://earthquake.usgs.gov/fdsnws/event/1/query" def main(): outdir = pathlib.Path(sys.argv[1]) y0, y1, mmin = int(sys.argv[2]), int(sys.argv[3]), sys.argv[4] last_end = sys.argv[5] if len(sys.argv) > 5 else None outdir.mkdir(parents=True, exist_ok=True) for year in range(y0, y1 + 1): start = f"{year}-01-01" end = last_end if (year == y1 and last_end) else f"{year + 1}-01-01" url = (f"{BASE}?format=csv&starttime={start}&endtime={end}&minmagnitude={mmin}" "&eventtype=earthquake&orderby=time-asc") name = f"comcat-m{mmin}-{start}-{end}.csv" if (outdir / name).exists(): continue for attempt in range(4): try: req = urllib.request.Request(url, headers={"User-Agent": UA}) with urllib.request.urlopen(req, timeout=300) as r: data = r.read() break except Exception as e: # network hiccup: wait and retry print("retry", year, e, flush=True) time.sleep(10 * (attempt + 1)) else: raise SystemExit(f"failed: {url}") if not data.startswith(b"time,"): raise SystemExit(f"unexpected reply for {year}: {data[:300]!r}") (outdir / name).write_bytes(data) rec = {"file": name, "url": url, "bytes": len(data), "rows": data.count(b"\n") - 1, "sha256": hashlib.sha256(data).hexdigest(), "fetched_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")} with (outdir / "fetch-log.jsonl").open("a", encoding="utf-8", newline="\n") as f: f.write(json.dumps(rec) + "\n") print(name, rec["rows"], "rows", flush=True) time.sleep(1) if __name__ == "__main__": main()