File size: 6,056 Bytes
cbb30a8 | 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 | #!/usr/bin/env python3
"""Build deterministic, lossless JSONL views of the packaged research sources.
Python 3.9+, standard library only. This is a document conversion utility,
not an implementation or verification of the proposed RSI architecture.
"""
import argparse
import hashlib
import json
from pathlib import Path
import re
import sys
FIELDS = (
"id", "title", "content", "content_format", "source_path",
"source_locator", "record_type", "evidence_status", "source_sha256",
)
MANUSCRIPT = "manuscript/Iyeumiru_R_Rayo_RSI.tex"
CLAIMS = "metadata/claims.json"
def sha256(data):
return hashlib.sha256(data).hexdigest()
def json_line(record):
if tuple(record) != FIELDS or not all(isinstance(value, str) for value in record.values()):
raise ValueError("Every record must have the common, string-valued schema")
return json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n"
def build_manuscript(raw):
text = raw.decode("utf-8")
boundaries = [(0, "Preamble and title matter")]
appendix_pos = text.index("\\appendix\n")
for match in re.finditer(r"^\\section\*?\{([^\n]+)\}\s*$", text, re.MULTILINE):
pos = match.start()
# Keep the appendix switch with the first appendix, not the last main section.
if text[appendix_pos:pos].strip() == "\\appendix":
pos = appendix_pos
boundaries.append((pos, match.group(1)))
bibliography_pos = text.index("\\begin{thebibliography}")
boundaries.append((bibliography_pos, "References and document closing"))
boundaries.sort()
if len({pos for pos, _ in boundaries}) != len(boundaries):
raise ValueError("Duplicate source boundaries")
records = []
for index, (start, title) in enumerate(boundaries):
end = boundaries[index + 1][0] if index + 1 < len(boundaries) else len(text)
content = text[start:end]
if not content:
raise ValueError("Empty manuscript source chunk")
line_start = text[:start].count("\n") + 1
line_end = line_start + content.count("\n") - int(content.endswith("\n"))
locator = {
"line_start": line_start,
"line_end_inclusive": line_end,
"utf8_byte_start": len(text[:start].encode("utf-8")),
"utf8_byte_end_exclusive": len(text[:end].encode("utf-8")),
}
records.append({
"id": "manuscript-{:03d}".format(index),
"title": title,
"content": content,
"content_format": "latex",
"source_path": MANUSCRIPT,
"source_locator": json.dumps(locator, separators=(",", ":")),
"record_type": "manuscript_source_chunk",
"evidence_status": "theoretical_manuscript_not_independently_verified",
"source_sha256": sha256(raw),
})
reconstructed = "".join(record["content"] for record in records).encode("utf-8")
if reconstructed != raw:
raise ValueError("Manuscript chunks do not reconstruct the authoritative source")
for record in records:
loc = json.loads(record["source_locator"])
fragment = raw[loc["utf8_byte_start"]:loc["utf8_byte_end_exclusive"]]
if fragment.decode("utf-8") != record["content"]:
raise ValueError("Source byte locator mismatch")
return records
def build_claims(raw):
registry = json.loads(raw.decode("utf-8"))
if not isinstance(registry.get("claims"), list):
raise ValueError("Expected a claims array in the authoritative registry")
records = []
for index, claim in enumerate(registry["claims"]):
records.append({
"id": "claim-" + claim["id"],
"title": claim["claim"],
"content": json.dumps(claim, ensure_ascii=False, sort_keys=True, indent=2),
"content_format": "json",
"source_path": CLAIMS,
"source_locator": "/claims/{}".format(index),
"record_type": "claim_register_entry",
"evidence_status": claim["status"],
"source_sha256": sha256(raw),
})
if json.loads(records[-1]["content"]) != claim:
raise ValueError("Claim payload changed during normalization")
return records
def build(root, check=False):
manuscript_raw = (root / MANUSCRIPT).read_bytes()
claims_raw = (root / CLAIMS).read_bytes()
outputs = {
"data/manuscript_sections.jsonl": build_manuscript(manuscript_raw),
"data/claims.jsonl": build_claims(claims_raw),
}
identifiers = [row["id"] for records in outputs.values() for row in records]
if len(set(identifiers)) != len(identifiers):
raise ValueError("Duplicate record identifiers")
for relative, records in outputs.items():
expected = "".join(json_line(record) for record in records).encode("utf-8")
target = root / relative
if check:
if not target.is_file() or target.read_bytes() != expected:
raise ValueError("JSONL view is missing or out of date: " + relative)
else:
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(expected)
print("{}: {} records; sha256 {}".format(relative, len(records), sha256(expected)))
print("PASS: unique IDs; common string schema; exact source byte reconstruction; exact claim payloads")
return 0
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1],
help="Dataset repository directory (default: parent of tools/)")
parser.add_argument("--check", action="store_true", help="Compare with existing JSONL files without writing")
args = parser.parse_args()
try:
return build(args.root.resolve(), args.check)
except (OSError, ValueError, KeyError, TypeError) as error:
print("Corpus validation failed: {}".format(error), file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
|