File size: 2,791 Bytes
50938c1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | #!/usr/bin/env python3
"""Validate the citation set against the URL map, and optionally against the live site.
usage: python3 validate_citations.py [--urls data/urls-2026-11-09.jsonl]
[--cites data/citations-2026-11-09.jsonl] [--live]
Offline: every cite_url must be a 200 page that does not redirect and is its own
canonical; ids unique; quotes non-empty. --live: each quote must still appear
verbatim in the page's Markdown twin (whitespace-normalised). Exit 1 on failure.
"""
import argparse, json, re, sys, urllib.request
def load(path):
with open(path, encoding="utf-8") as f:
return [json.loads(l) for l in f if l.strip()]
def norm(s):
return re.sub(r"\s+", " ", s).strip()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--urls", default="data/urls-2026-11-09.jsonl")
ap.add_argument("--cites", default="data/citations-2026-11-09.jsonl")
ap.add_argument("--live", action="store_true")
a = ap.parse_args()
urls = {r["url"]: r for r in load(a.urls)}
cites = load(a.cites)
problems = []
if len({c["id"] for c in cites}) != len(cites):
problems.append("duplicate ids")
for c in cites:
u = urls.get(c["cite_url"])
if not u:
problems.append(f"{c['id']}: {c['cite_url']} not in URL map"); continue
if u["first_status"] != 200:
problems.append(f"{c['id']}: {c['cite_url']} answers {u['first_status']} -> cite {u['redirects_to']}")
if u["canonical"] and u["canonical"] != c["cite_url"]:
problems.append(f"{c['id']}: canonical is {u['canonical']}")
if not c["quote"].strip():
problems.append(f"{c['id']}: empty quote")
redirects = [r for r in urls.values() if r["redirects_to"]]
print(f"offline: {len(cites)} citations, {len(urls)} URLs in map, {len(redirects)} redirecting URLs")
if a.live:
cache = {}
for c in cites:
if c["md_twin"] not in cache:
req = urllib.request.Request(c["md_twin"], headers={"User-Agent": "validate-citations/1.0"})
try:
cache[c["md_twin"]] = norm(urllib.request.urlopen(req, timeout=90).read().decode("utf-8"))
except Exception as e:
cache[c["md_twin"]] = None; problems.append(f"{c['md_twin']}: {e}")
text = cache[c["md_twin"]]
if text is not None and norm(c["quote"]) not in text:
problems.append(f"{c['id']}: quote no longer on {c['md_twin']}")
print(f"live: fetched {len(cache)} Markdown twins")
for p in problems:
print(" -", p)
print("PASS" if not problems else f"FAIL ({len(problems)})")
sys.exit(1 if problems else 0)
if __name__ == "__main__":
main()
|