#!/usr/bin/env python3
"""Turn archived copies of SSGEOS's home page into a list of dated forecasts.
python3 -I extract_forecasts.py
.html>
Standard library only. For every archived copy (Wayback Machine, raw "id_" form) it reads the forecast block:
the forecast text and its "updated" stamp, the MAGNITUDE PROBABILITY table and its own "updated" stamp, the
named forecast window ("Earthquake Forecast 8-11 June 2022", "Latest Earthquake Forecast 9-18 July 2024",
"Forecast 10-19 November 2026"...) and the date span of the SSGI graph shown with it. Copies with the same
table stamp are one forecast; the earliest copy is kept and the others are listed.
Stamps without a year, or with a year that puts them after the copy was archived or more than 60 days before
it, get the year that puts them closest before the archive time (flagged "year inferred" or "year corrected").
Times are UTC, as the page gives them. Nothing here looks at earthquakes.
"""
import datetime as dt
import glob
import gzip
import json
import os
import re
import sys
from html.parser import HTMLParser
MONTHS = {m: i for i, m in enumerate(["january", "february", "march", "april", "may", "june", "july", "august",
"september", "october", "november", "december"], 1)}
BLOCK = {"p", "div", "br", "li", "tr", "h1", "h2", "h3", "h4", "h5", "h6", "table", "section", "td", "th",
"figcaption", "figure", "header", "footer", "span"}
STOP = ("support ssgeos", "we need your support", "recent earthquakes", "50 latest earthquakes",
"validity of earthquake forecasting")
STAMP = re.compile(r"^updated (\d{1,2}) ([A-Za-z]+)(?: (\d{4}))?,? (\d{1,2}):(\d{2}) UTC$")
BIN_RANGE = re.compile(r"^(?:M\s*)?(\d\.\d)\s*-\s*(\d\.\d)$")
BIN_OPEN = re.compile(r"^(?:M\s*)?(\d\.\d)\+$|^[≥>]=?\s*(\d\.\d)$")
PCT = re.compile(r"^(\d{1,3})%$")
WINDOW = re.compile(r"^(?:Latest )?(?:Earthquake )?(?:Forecast|Warning)\b\s*-?\s*(.*)$", re.I)
GRAPH = re.compile(r"^SSGI COMMON graph(?: overview)? (.*)$", re.I)
SKIP_TEXT = ("also check out", "potential regions", ">> refresh", "magnitude probability")
HEADLINES = ("EARTHQUAKE WARNING", "QUAKE WATCH", "MEGA-THRUST EARTHQUAKE WARNING", "EARTHQUAKE FORECAST")
class T(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.out, self.skip = [], 0
def handle_starttag(self, tag, attrs):
if tag in ("script", "style", "noscript"):
self.skip += 1
if tag in BLOCK:
self.out.append("\n")
if tag == "img":
self.out.append("\n{img}\n")
def handle_endtag(self, tag):
if tag in ("script", "style", "noscript") and self.skip:
self.skip -= 1
if tag in BLOCK:
self.out.append("\n")
def handle_data(self, data):
if not self.skip:
self.out.append(data)
def page_lines(path):
b = open(path, "rb").read()
if b[:2] == b"\x1f\x8b":
b = gzip.decompress(b)
raw = re.sub(r"", " ", b.decode("utf-8", errors="replace"), flags=re.S)
p = T()
p.feed(raw)
lines = [" ".join(l.split()) for l in "".join(p.out).splitlines()]
return [l for l in lines if l and l != "{img}"]
def block(lines):
start = next((i for i, l in enumerate(lines)
if re.search(r"EARTHQUAKE FORECAST|EARTHQUAKE WARNING|QUAKE WATCH|Refresh the page", l)), None)
if start is None:
start = next((max(0, i - 1) for i, l in enumerate(lines) if STAMP.match(l)), None)
if start is None:
return []
out = []
for l in lines[start:]:
if any(s in l.lower() for s in STOP):
break
out.append(l)
return out
def stamp_time(m, capture):
"""Datetime for an 'updated' stamp; returns (datetime, flag).
A stamp without a year gets the year that puts it closest to the archive time, at most 3 days after it.
A stamp whose year puts it more than 3 days after the archive time or more than 60 days before it is
treated as a typo and gets that year instead. A stamp up to 3 days after the archive time is kept as
written and flagged (the page's own clock or a typo; such a stamp is never used to start a window
before the copy existed: see score_forecasts.py)."""
day, mon, year, hh, mm = int(m.group(1)), MONTHS[m.group(2).lower()], m.group(3), int(m.group(4)), int(m.group(5))
cands = []
for y in (capture.year - 1, capture.year, capture.year + 1):
try:
cands.append(dt.datetime(y, mon, day, hh, mm, tzinfo=dt.timezone.utc))
except ValueError:
pass
ok = [c for c in cands if c <= capture + dt.timedelta(days=3)]
best = min(ok, key=lambda c: abs(capture - c), default=None)
if year is None:
t, flag = best, "year inferred"
else:
t = dt.datetime(int(year), mon, day, hh, mm, tzinfo=dt.timezone.utc)
flag = None
if t > capture + dt.timedelta(days=3) or capture - t > dt.timedelta(days=60):
t, flag = best, f"year corrected from {year}"
if t is not None and t > capture:
flag = (flag + "; " if flag else "") + "stamp later than the archive time"
return t, flag
def parse_range(s, ref):
"""Parse '8-11 June 2022', '24 July - 4 August 2022', '28 December 2022 - 3 January 2023' (and the page's
'25 September - 3 October September 2022') into (first day, last day). Returns None if no range."""
s = s.replace("—", "-").replace("–", "-")
m = re.search(r"(\d{1,2})(?:\s+([A-Za-z]+))?(?:\s+(\d{4}))?\s*-\s*(\d{1,2})\s+([A-Za-z]+)(?:\s+[A-Za-z]+)?\s+(\d{4})", s)
if not m:
return None
d1, m1, y1, d2, m2, y2 = m.groups()
if m2.lower() not in MONTHS or (m1 and m1.lower() not in MONTHS):
return None
y2 = int(y2)
mon2 = MONTHS[m2.lower()]
mon1 = MONTHS[m1.lower()] if m1 else mon2
y1 = int(y1) if y1 else (y2 - 1 if mon1 > mon2 else y2)
return dt.date(y1, mon1, int(d1)), dt.date(y2, mon2, int(d2))
def served_times(folder):
"""The Wayback Machine sometimes serves a nearby copy instead of the one asked for; FETCHLOG.tsv records
the final URL, whose timestamp is the copy actually saved."""
out = {}
log = os.path.join(folder, "FETCHLOG.tsv")
for line in open(log, encoding="utf-8").read().splitlines()[1:]:
f = line.split("\t")
m = re.search(r"/web/(\d{14})", f[2])
if m and f[3] == "200":
out[f[1]] = m.group(1)
return out
def parse_capture(path, served):
asked = re.search(r"home-(\d{14})", path).group(1)
ts = served.get(os.path.basename(path), asked)
capture = dt.datetime.strptime(ts, "%Y%m%d%H%M%S").replace(tzinfo=dt.timezone.utc)
lines = block(page_lines(path))
rec = {"capture": ts, "capture_utc": capture.isoformat(), "file": os.path.basename(path), "flags": []}
if ts != asked:
rec["flags"].append(f"asked for the copy of {asked}; the archive served {ts}")
try:
k = next(i for i, l in enumerate(lines) if l.upper() == "MAGNITUDE PROBABILITY")
except StopIteration:
k = None
head = lines if k is None else lines[:k]
# forecast text and its stamp
text_stamp, text, headline = None, [], []
for l in head:
m = STAMP.match(l)
if m and text_stamp is None:
t, flag = stamp_time(m, capture)
text_stamp = t
if flag:
rec["flags"].append("text stamp " + flag)
continue
if l.upper() in HEADLINES:
headline.append(l.upper())
continue
if any(l.lower().startswith(s) for s in SKIP_TEXT) or WINDOW.match(l) or GRAPH.match(l):
continue
if text_stamp is not None:
text.append(l)
rec["text_stamp_utc"] = text_stamp.isoformat() if text_stamp else None
rec["headline"] = headline
rec["text"] = text
# the table
bins, pcts, table_stamp = [], [], None
if k is not None:
for l in lines[k + 1:]:
m = STAMP.match(l)
if m and table_stamp is None:
t, flag = stamp_time(m, capture)
table_stamp = t
if flag:
rec["flags"].append("table stamp " + flag)
continue
mr, mo, mp = BIN_RANGE.match(l), BIN_OPEN.match(l), PCT.match(l)
if mr:
bins.append({"label": l, "lo": float(mr.group(1)), "hi": float(mr.group(2))})
elif mo:
bins.append({"label": l, "lo": float(mo.group(1) or mo.group(2)), "hi": None})
elif mp:
pcts.append(int(mp.group(1)) / 100)
if bins and len(bins) == len(pcts):
for b, p in zip(bins, pcts):
b["p"] = p
rec["bins"] = bins
else:
rec["bins"] = []
if bins or pcts:
rec["flags"].append(f"table unreadable ({len(bins)} bins, {len(pcts)} percentages)")
rec["table_stamp_utc"] = table_stamp.isoformat() if table_stamp else None
# windows
named, graph = None, None
for l in lines:
mw, mg = WINDOW.match(l), GRAPH.match(l)
if mw and named is None and l.upper() not in HEADLINES:
r = parse_range(mw.group(1), capture)
if r:
named = {"label": l, "first_day": r[0].isoformat(), "last_day": r[1].isoformat()}
if mg and graph is None:
r = parse_range(mg.group(1), capture)
if r:
graph = {"label": l, "first_day": r[0].isoformat(), "last_day": r[1].isoformat()}
rec["named_window"], rec["graph_window"] = named, graph
return rec
def main():
files = sorted(glob.glob(os.path.join(sys.argv[1], "home-*.html")))
served = served_times(sys.argv[1])
caps = sorted((parse_capture(f, served) for f in files), key=lambda c: c["capture"])
forecasts, by_stamp = [], {}
for c in caps:
if not c["bins"] or not c["table_stamp_utc"]:
continue
key = c["table_stamp_utc"]
if key in by_stamp:
f = by_stamp[key]
f["also_archived"].append(c["capture_utc"])
if [b["p"] for b in c["bins"]] != [b["p"] for b in f["bins"]]:
f["flags"].append(f"copy {c['capture']} shows other probabilities under the same stamp")
continue
f = dict(c)
f["also_archived"] = []
by_stamp[key] = f
forecasts.append(f)
forecasts.sort(key=lambda f: f["table_stamp_utc"])
for i, f in enumerate(forecasts, 1):
f["id"] = f"F{i:03d}"
out = {"source": "Wayback Machine copies of https://www.ssgeos.org/ (raw id_ form), saved in downloads/wayback-home/",
"copies_read": len(caps), "copies_without_table": sum(1 for c in caps if not c["bins"]),
"forecasts": forecasts}
with open(sys.argv[2], "w", encoding="utf-8", newline="\n") as fh:
json.dump(out, fh, ensure_ascii=False, indent=1)
sys.stdout.reconfigure(encoding="utf-8")
print(f"{len(caps)} copies, {len(forecasts)} distinct tables")
for f in forecasts:
print(f["id"], f["table_stamp_utc"][:16], "cap", f["capture"], [f"{b['label']}:{b['p']:.0%}" for b in f["bins"]],
"named", (f["named_window"] or {}).get("first_day"), (f["named_window"] or {}).get("last_day"),
"graph", (f["graph_window"] or {}).get("first_day"), (f["graph_window"] or {}).get("last_day"),
"|".join(f["flags"]))
if __name__ == "__main__":
main()