"""Fetch the public inputs of factchecked.science's check of S0 News's research note 010, by URL, under a plain client name, and compare each with the SHA-256 of the copy we used. Usage: python3 -I fetch_inputs.py --small files polar_pressure_check.py needs (~20 MB) python3 -I fetch_inputs.py --all also the reanalysis files (~520 MB, plus 793 JRA-55 files of 65 kB) for extract_fields.py and fixround_checks.py Standard library only. The list of files and our hashes is input_sha256.txt, next to this script. Several providers update their files (BAS's ASL and SAM indices, READER, GISTEMP, NOAA's CO2, Scripps's O2, ISD's latest year, PSL's R1 months), so a changed hash is reported, not treated as an error; results from changed files may differ slightly from ours. A file already present with our hash is not fetched again. Requests go one at a time; a refused request (HTTP 4xx) is reported and not retried. Terms: see DATA_TERMS.txt. The JRA-55 files come from JAMSTEC's Reanalysis Intercomparison Dataset (RID), "for research purposes only"; read its terms before using them. """ import hashlib import os import sys import time import urllib.error import urllib.request UA = "factchecked-research/1.0" PSL = "https://downloads.psl.noaa.gov/Datasets/" BASES = [ # (prefix of our relative path, URL prefix) ("psl-r1/", PSL + "ncep.reanalysis.derived/surface/"), ("psl-r1-gauss/", PSL + "ncep.reanalysis.derived/surface_gauss/"), ("psl-20crv3/", PSL + "20thC_ReanV3/Monthlies/sfcMO/"), ("jamstec-rid/JRA-55_sp_monthly/", "https://www.jamstec.go.jp/RID/thredds/fileServer/testAll/surface/common-grid/monthly/sp/JRA-55/"), ("bas-asl/", "https://files.bas.ac.uk/twins/asli/"), ("bas-sam/", "https://www.nerc-bas.ac.uk/public/icd/gjma/"), ("reader/", "https://legacy.bas.ac.uk/met/READER/surface/"), ("noaa-isd/isd-history.csv", "https://www.ncei.noaa.gov/pub/data/noaa/isd-history.csv"), ("scripps-o2/", "https://keelinglabsites.ucsd.edu/websitedatao2/"), ("noaa-gml-co2/", "https://gml.noaa.gov/webdata/ccgg/trends/co2/"), ("nasa-gistemp/", "https://data.giss.nasa.gov/gistemp/tabledata_v4/"), ] SMALL = ("bas-asl/", "bas-sam/", "reader/", "noaa-isd/eureka/", "noaa-isd/resolute/", "scripps-o2/", "noaa-gml-co2/", "nasa-gistemp/") def url_for(rel): if rel.startswith(("noaa-isd/eureka/", "noaa-isd/resolute/")): name = rel.rsplit("/", 1)[1] year = name.split("-")[2].split(".")[0] return f"https://www.ncei.noaa.gov/pub/data/noaa/{year}/{name}" for prefix, base in BASES: if rel == prefix or (prefix.endswith("/") and rel.startswith(prefix)): return base if not prefix.endswith("/") else base + rel[len(prefix):] raise ValueError(rel) def sha256(path): h = hashlib.sha256() with open(path, "rb") as fh: for chunk in iter(lambda: fh.read(1 << 20), b""): h.update(chunk) return h.hexdigest() def fetch(url, dest, tries=2): for k in range(tries): try: req = urllib.request.Request(url, headers={"User-Agent": UA}) with urllib.request.urlopen(req, timeout=300) as r, open(dest + ".part", "wb") as fh: while True: chunk = r.read(1 << 20) if not chunk: break fh.write(chunk) os.replace(dest + ".part", dest) return "ok" except urllib.error.HTTPError as e: return f"refused: HTTP {e.code}" except (urllib.error.URLError, OSError) as e: if k + 1 == tries: return f"failed: {e}" time.sleep(5) return "failed" def main(): if len(sys.argv) < 3 or sys.argv[2] not in ("--small", "--all"): sys.exit(__doc__) folder, mode = sys.argv[1], sys.argv[2] here = os.path.dirname(os.path.abspath(__file__)) rows = [] with open(os.path.join(here, "input_sha256.txt"), encoding="utf-8") as fh: for line in fh: if line.strip(): h, rel = line.split(None, 1) rows.append((h, rel.strip())) if mode == "--small": rows = [r for r in rows if r[1].startswith(SMALL) and r[1] != "reader/stationpt.html"] same = changed = bad = 0 for h, rel in rows: dest = os.path.join(folder, *rel.split("/")) os.makedirs(os.path.dirname(dest), exist_ok=True) if os.path.exists(dest) and sha256(dest) == h: same += 1 continue status = fetch(url_for(rel), dest) if status != "ok": bad += 1 print(f"{rel}: {status}") continue if sha256(dest) == h: same += 1 else: changed += 1 print(f"{rel}: fetched, but it differs from our copy (the provider has updated it)") print(f"{same} files match our copies, {changed} differ, {bad} not fetched") if __name__ == "__main__": main()