edgar_segmenter_artifacts / scripts /05_normalize_markers.py
arthrod's picture
Add files using upload-large-folder tool
a1d579a verified
Raw History Blame Contribute Delete
4.74 kB
"""Normalize full_marker to Arthur's style in the documents he is annotating (Arthur, 2026-09-23:
"try to normalize the full_mark of all items that I'm annotating, favoring when I annotated").
Documents: every document with a reviewed row or a row whose full_marker Arthur changed (against
the viewer's first snapshot .given/sot_provisioned.jsonl). Every content row gets the format of
markers.normalize() (2026-09-23, Arthur: "2.1.7 1 ... should be 2.1.7.1 when normalized", also on
his own rows): only the spelling changes, never what the marker says; his rows get nothing else.
The container prefixes he wrote in the document ("exhibit-a", "APPENDIX-1") win over the default
casing, and where he writes a container's items in parentheses ("APPENDIX-1-(2)(ii)") the others
follow. On the other rows only, a bare "paragraph" becomes "<unit>-paragraph" when the
numbered unit it continues is the nearest earlier content row at the SAME level (his closing
paragraph convention, "2-paragraph"); otherwise it stays "paragraph". Garbage rows are not touched.
Writes sot_provisioned.jsonl (the viewer's file; each change logged to viewer/edits.log.jsonl
with the old and new marker) unless --dry-run; prints every change.
Usage: uv run python claude_run/NEW/scripts/05_normalize_markers.py [--dry-run] [--all-docs]
"""
import argparse
import datetime
import json
import re
import sys
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(Path(__file__).resolve().parent))
from markers import marker_depth, normalize # noqa: E402
def main():
ap = argparse.ArgumentParser(); ap.add_argument("--dry-run", action="store_true"); ap.add_argument("--all-docs", action="store_true"); a = ap.parse_args()
rows = [json.loads(line) for line in (ROOT / "sot_provisioned.jsonl").open() if line.strip()]
first = {}
for line in (ROOT / ".given/sot_provisioned.jsonl").open():
r = json.loads(line); first[r["row_id"]] = r.get("full_marker")
his = lambda r: bool(r.get("review")) or (r["row_id"] in first and first[r["row_id"]] != r.get("full_marker")) or r["row_id"] not in first
docs = {r["document_id"] for r in rows if his(r)} if not a.all_docs else {r["document_id"] for r in rows}
by = defaultdict(list)
for r in rows: by[r["document_id"]].append(r)
lvl = lambda r: int(r["level"]) if r.get("level") is not None and str(r["level"]).lstrip("-").isdigit() else None
changes = []
for did in sorted(docs):
rr = sorted(by[did], key=lambda r: int(r["order"]))
forms = {}; paren = any(his(r) and re.match(r"^[A-Za-z]+-[^-()]+-\(", r.get("full_marker") or "") for r in rr)
for r in rr: # container prefixes as Arthur wrote them in this document
m = r.get("full_marker") or ""
if his(r) and "-" in m and m.split("-")[0].lower() in ("exhibit", "annex", "schedule", "appendix", "attachment", "article", "addendum", "rider"):
pre = "-".join(m.split("-")[:2]); forms.setdefault(pre.lower(), pre)
content = [r for r in rr if not r.get("is_garbage")]
for i, r in enumerate(content):
old = r.get("full_marker"); new = normalize(old, forms, paren)
if not his(r) and (new or "").strip().lower() == "paragraph" and lvl(r) is not None:
unit = next((x for x in reversed(content[:i]) if lvl(x) is not None and lvl(x) <= lvl(r) and marker_depth(x.get("full_marker"))), None)
if unit is not None and lvl(unit) == lvl(r): new = f"{unit['full_marker']}-paragraph"
if new != old:
changes.append({"document_id": did, "row_id": r["row_id"], "order": r["order"], "level": r.get("level"), "old": old, "new": new})
r["full_marker"] = new
for c in changes: print(f"{c['document_id']} #{c['order']:>4} L{c['level']!s:4} {c['old']!r:40} -> {c['new']!r}")
print(f"{len(changes)} markers normalized in {len(docs)} documents ({'dry run, nothing written' if a.dry_run else 'written'})")
if a.dry_run or not changes: return
tmp = ROOT / "sot_provisioned.jsonl.tmp"
with tmp.open("w") as fh:
for r in rows: fh.write(json.dumps(r, ensure_ascii=False) + "\n")
tmp.replace(ROOT / "sot_provisioned.jsonl")
with (ROOT / "viewer/edits.log.jsonl").open("a") as fh:
fh.write(json.dumps({"at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
"by": "Claude, at Arthur's request (normalize full_marker to his style; on his own rows only the spelling)",
"field": "full_marker", "changes": changes}, ensure_ascii=False) + "\n")
if __name__ == "__main__":
main()