"""Normalize the full_marker of a document built of "Article N:" headings and "N.M" sections to Arthur's article style (Arthur, 2026-09-24, doc-0518: "yes plz for normalization"): "article-4", "article-4-4.1", "article-4-4.3(1)", "article-3-3.1(3)(A)", "article-4-paragraph", "article-4-paragraph-(1)" (as in his other documents: article-4-4.1, article-40-paragraph). The provisioner's markers there carry noise ("Article 2.2" for section 2.2, "ARTICLE 2 Article 3" for article 3, "8" for "Article 8: ..."), so each content row's marker is rebuilt from the label its own text starts with, inside the current article: "Article N: ..." -> article-N (starts article N) "N.M ..." -> article--N.M (only when N is the current article) "(k) ..." -> (k), or
-paragraph-(k) after an article's lead-in "A. ..." after an "(k)" item -> (A) a "paragraph" row right after an article heading -> article--paragraph Rows whose text starts with no such label (title, preamble, parts, signature blocks, other paragraphs) keep their marker, spelled by markers.normalize() ("signature block" -> "signature-block"). A rebuilt marker whose last part disagrees with the old marker's last part is not written and is reported instead. Levels are not touched. Every change is marked code_edit (heinous in the viewer) and logged to viewer/edits.log.jsonl. Usage: uv run python claude_run/NEW/scripts/07_normalize_articles.py doc-0518 [--dry-run] """ import argparse import datetime import json import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(Path(__file__).resolve().parent)) from markers import normalize # noqa: E402 NOW = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds") ART = re.compile(r"^\s*article\s+(\d+)\s*[:.]", re.I) SEC = re.compile(r"^\s*(\d+)\.(\d+(?:\.\d+)*)\s") ITEM = re.compile(r"^\s*\((\d+|[a-z]|[ivx]+)\)\s") LETTER = re.compile(r"^\s*([A-Z])\.\s") def tail(m: str) -> str: """The last label of a marker: "3.1(3)(A)" -> "A", "Article 2.3 2.4" -> "2.4", "Article 4" -> "4".""" p = re.findall(r"\(([^()]+)\)\s*$", m) return p[0] if p else re.split(r"[\s-]+", m.strip())[-1] def main(): ap = argparse.ArgumentParser(); ap.add_argument("doc"); ap.add_argument("--dry-run", action="store_true"); a = ap.parse_args() rows = [json.loads(line) for line in (ROOT / "sot_provisioned.jsonl").open() if line.strip()] rr = sorted([r for r in rows if r["document_id"] == a.doc], key=lambda r: int(r["order"])) cur = sec = item = None; after_heading = False; changes, refused = [], [] for r in rr: if r.get("is_garbage"): continue old = r.get("full_marker") or ""; t = " ".join((r.get("segment_text") or "").split()); new = None if (m := ART.match(t)): cur, sec, item = m.group(1), None, None; new = f"article-{cur}"; after_heading = True elif cur and (m := SEC.match(t)) and m.group(1) == cur: sec = f"article-{cur}-{m.group(1)}.{m.group(2)}"; item = None; new = sec; after_heading = False elif cur and (m := ITEM.match(t)): base = sec or f"article-{cur}-paragraph"; item = f"{base}({m.group(1)})" if sec else f"{base}-({m.group(1)})"; new = item elif cur and item and (m := LETTER.match(t)): new = f"{item}({m.group(1)})" elif cur and after_heading and old.strip().lower().endswith("paragraph"): new = f"article-{cur}-paragraph"; after_heading = False else: new = normalize(old) if old else old if ART.match(t) is None and old.strip().lower().startswith("part"): cur = sec = item = None if new is None or new == old: continue if old and tail(old).lower() != tail(new).lower() and old.strip().lower() not in ("paragraph", "signature block") and not (ART.match(t) and tail(old) == ""): if not (ART.match(t) and re.fullmatch(r"\d+", tail(old)) and tail(old) != tail(new)): refused.append({"order": r["order"], "old": old, "new": new, "text": t[:70]}); continue changes.append({"document_id": a.doc, "row_id": r["row_id"], "order": r["order"], "level": r.get("level"), "old": old, "new": new}) r.setdefault("code_edit", []).append({"what": "article_normalize", "at": NOW, "old": {"full_marker": old}}); r["full_marker"] = new for c in changes: print(f"#{c['order']:>4} L{c['level']!s:4} {c['old']!r:32} -> {c['new']!r}") for x in refused: print(f"NOT WRITTEN #{x['order']:>4} {x['old']!r} -> {x['new']!r} (last part disagrees) | {x['text']}") print(f"{len(changes)} markers normalized, {len(refused)} not written ({'dry run' 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": NOW, "by": f"Claude, at Arthur's request (07_normalize_articles.py {a.doc}: article style; marked code_edit)", "field": "full_marker", "changes": changes, "not_written": refused}, ensure_ascii=False) + "\n") if __name__ == "__main__": main()