File size: 5,855 Bytes
d4bd8c8 | 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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | #!/usr/bin/env python3
"""Derive articles.jsonl from the Constitution 2.0 Core. Standard library only.
python3 build_articles.py # verify the committed articles.jsonl
python3 build_articles.py --write # regenerate it
The dataset rows are DERIVED. The canonical artifact is the Core markdown, byte for
byte, at ./constitution-v2.0-core.md. This script exists so that the
derivation is reproducible by a stranger rather than trusted: regenerate, and the
bytes must be identical to what is committed.
Three refusals, each of which has bitten this corpus before:
1. The Core is hash-checked BEFORE parsing. Parsing an unverified source and then
reporting the result would attest to whatever happened to be on disk.
2. Exactly 47 articles or the build fails. A silently short corpus is worse than no
corpus, because it looks complete.
3. Every emitted `text` must be a byte-exact substring of the Core. A `####`
sub-heading is NOT an article boundary -- treating it as one truncated Article 36
to nothing in an earlier build of a different tool, and the check below is what
would have caught it.
"""
import argparse
import hashlib
import json
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
CORE = os.path.join(HERE, "constitution-v2.0-core.md")
OUT = os.path.join(HERE, "data", "articles.jsonl")
CORE_SHA256 = "7e6d12e1025a46cc3a860d6147d79e2362c4d88cb727ce9423854b5008be4c82"
EXPECTED_ARTICLES = 47
# An article opens at a level-3 heading. A boundary is any heading of level 1 to 3 --
# and specifically NOT level 4, which is a sub-heading inside an article's own body.
ARTICLE_OPEN = re.compile(r"^### +Article +([0-9]+[A-Z]?) *: *(.*)$")
BOUNDARY = re.compile(r"^#{1,3}(?!#)\s+\S")
PART = re.compile(r"^## +(PART [IVX]+: .*)$")
def parse(core_text):
lines = core_text.split("\n")
part = None
articles = []
i = 0
while i < len(lines):
part_match = PART.match(lines[i])
if part_match:
part = part_match.group(1).strip()
open_match = ARTICLE_OPEN.match(lines[i])
if not open_match:
i += 1
continue
start = i
j = i + 1
while j < len(lines) and not BOUNDARY.match(lines[j]):
j += 1
block = "\n".join(lines[start:j]).rstrip("\n")
heading = lines[start]
body = "\n".join(lines[start + 1:j]).strip("\n")
title = open_match.group(2).strip()
spine = "[SPINE" in heading
articles.append({
"article_id": open_match.group(1),
"title": re.sub(r"\s*\[SPINE.*?\]\s*$", "", title).strip(),
"heading": heading,
"part": part,
"spine": spine,
"text": block,
"body": body,
})
i = j
return articles
def build():
with open(CORE, "rb") as handle:
raw = handle.read()
actual = hashlib.sha256(raw).hexdigest()
if actual != CORE_SHA256:
raise SystemExit(
"REFUSED: the Core does not match its pinned digest.\n"
" expected %s\n actual %s\n"
"Parsing an unverified source would attest to whatever is on disk."
% (CORE_SHA256, actual))
core_text = raw.decode("utf-8")
articles = parse(core_text)
if len(articles) != EXPECTED_ARTICLES:
raise SystemExit("REFUSED: found %d articles, expected %d. A short corpus that "
"looks complete is worse than no corpus."
% (len(articles), EXPECTED_ARTICLES))
ids = [a["article_id"] for a in articles]
if len(set(ids)) != len(ids):
raise SystemExit("REFUSED: duplicate article ids: %s" % ids)
for a in articles:
for field in ("heading", "text", "body"):
if a[field] and a[field] not in core_text:
raise SystemExit(
"REFUSED: article %s field %r is not a byte-exact substring of the "
"Core. The dataset must quote, never paraphrase."
% (a["article_id"], field))
for a in articles:
a["source_url"] = "https://article11.ai/constitution-v2.0-core.md"
a["source_sha256"] = CORE_SHA256
a["license"] = "CC0-1.0"
lines = [json.dumps(a, ensure_ascii=False, sort_keys=True) for a in articles]
return ("\n".join(lines) + "\n").encode("utf-8"), articles
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--write", action="store_true",
help="regenerate data/articles.jsonl")
args = parser.parse_args()
payload, articles = build()
digest = hashlib.sha256(payload).hexdigest()
spine = sum(1 for a in articles if a["spine"])
if args.write:
os.makedirs(os.path.dirname(OUT), exist_ok=True)
with open(OUT, "wb") as handle:
handle.write(payload)
print("wrote %s" % OUT)
else:
if not os.path.exists(OUT):
print("data/articles.jsonl is absent; run with --write")
return 1
with open(OUT, "rb") as handle:
committed = handle.read()
if committed != payload:
print("MISMATCH: the committed articles.jsonl is not what this script "
"derives from the Core.")
print(" committed %s" % hashlib.sha256(committed).hexdigest())
print(" derived %s" % digest)
return 1
print("committed articles.jsonl matches a fresh derivation")
print(" articles : %d" % len(articles))
print(" spine articles: %d" % spine)
print(" bytes : %d" % len(payload))
print(" sha256 : %s" % digest)
print(" every field verified as a byte-exact substring of the Core")
return 0
if __name__ == "__main__":
sys.exit(main())
|