| """Segment, by code only, the content rows the viewer already flags for splitting (Arthur, 2026-09-24: |
| "try segmenting the content whenever it was flagged already, use code only"; his example, doc-0035#28 |
| `6(a)`: "(a) Except ... (i) control ..., (ii) provide ..., ... (vii) have ...", which 08 skipped because |
| its own leading "(a)" was taken for a one-item run). |
| |
| Rows: unreviewed, not garbage, with a level and a marker (no toc / title / signature block), flagged |
| enum_merged, enum_heading, enum_runs_on, under_old_spans or model_miss "split" (viewer/dump_flags.ts), |
| and every row this script creates (passes repeat until nothing changes, so nested runs are cut too). |
| Enumerators: "(a)" "(A)" "(i)" "(I)" "(1)" standing alone (06_cut_enums_exhibits.py's TOKEN and its |
| cross-reference filters: "Section 5(a)", "(a) above", "sixty (60)" are not enumerators). |
| sibling split: the row opens with its own enumerator (s) and the same kind continues in sequence |
| in its text ("(i) control ..., (ii) provide ..."): the row keeps its first item, each further |
| item becomes a row right after it at the SAME level, marker = the row's marker with its last |
| "(s)" replaced ("6(a)(i)" -> "6(a)(ii)"); only when the marker ends with "(s)". |
| child split: otherwise, the row's own leading enumerator set aside, the earliest run that starts |
| at a first value (a / A / i / I / 1) or at (x), with 2+ items in sequence; the row keeps its |
| lead-in, items become children at level + 1, marker = parent + item in the 2026-09-24 |
| convention ("6(a)" + (i) -> "6(a)(i)", "5" + (1) -> "5.1"). |
| A run stops where its kind breaks sequence (a restart stays inside the last item). An item of the |
| other kind inside a run (a roman (i) inside (a)..(c)) stays in its item and is cut in a later pass. |
| Refused (listed): lead-in under 10 characters in a child split, an item under 20 characters, a |
| marker that already exists in the document. |
| Every row changed or created gets code_edit (heinous in the viewer until reviewed). Then run |
| 03_place_annotations.py; cuts whose rows it cannot place are undone and each cut row's literal is |
| refreshed from its placed range (--finish does both). |
| Usage: python claude_run/NEW/scripts/09_split_flagged.py --flags /tmp/flags.json [--dry-run] |
| python claude_run/NEW/scripts/09_split_flagged.py --finish |
| """ |
| import argparse |
| import copy |
| import datetime |
| import importlib.util |
| import json |
| import re |
| import subprocess |
| import sys |
| from collections import Counter, defaultdict |
| from pathlib import Path |
|
|
| ROOT = Path(__file__).resolve().parents[1] |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| from markers import _roman, canon, strip_path |
|
|
| spec = importlib.util.spec_from_file_location("cut06", Path(__file__).resolve().parent / "06_cut_enums_exhibits.py") |
| c6 = importlib.util.module_from_spec(spec); spec.loader.exec_module(c6) |
| NOW = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds") |
| SPLIT_FLAGS = {"enum_merged", "enum_heading", "enum_runs_on", "under_old_spans"} |
| KINDS = ("la", "lr", "ua", "ur", "d") |
| TAG = "split_flagged" |
|
|
|
|
| def index(v: str, kind: str) -> int | None: |
| """0-based position of v in the kind's sequence, None when v is not of that kind.""" |
| if kind == "d": return int(v) - 1 if v.isdigit() else None |
| if kind == "la": return ord(v) - 97 if len(v) == 1 and v.islower() else None |
| if kind == "ua": return ord(v) - 65 if len(v) == 1 and v.isupper() else None |
| if kind == "lr": return _roman(v) - 1 if v.islower() and _roman(v) else None |
| return _roman(v) - 1 if v.isupper() and _roman(v) else None |
|
|
|
|
| def tokens(t: str): |
| return [m for m in c6.TOKEN.finditer(t) if not c6.XREF_BEFORE.search(t[: m.start()]) and not c6.XREF_AFTER.match(t[m.end():]) |
| and not (m.group(1).isdigit() and c6.NUMWORD.search(t[: m.start()]))] |
|
|
|
|
| def run_from(toks, k0, kind): |
| run = [toks[k0]]; want = index(toks[k0].group(1), kind) + 1 |
| for m in toks[k0 + 1:]: |
| i = index(m.group(1), kind) |
| if i is None: continue |
| if i == want: run.append(m); want += 1; continue |
| |
| if kind in ("la", "ua") and index(m.group(1), "lr" if kind == "la" else "ur") is not None and len(m.group(1)) == 1 and i != want: continue |
| break |
| return run |
|
|
|
|
| def find(t: str): |
| """('sibling' | 'child', kind, run, own) or (None, why).""" |
| toks = tokens(t) |
| own = toks[0] if toks and not t[: toks[0].start()].strip(" \"'“") else None |
| if own: |
| best = max(((kind, run_from(toks, 0, kind)) for kind in KINDS if index(own.group(1), kind) is not None), key=lambda x: len(x[1]), default=None) |
| if best and len(best[1]) >= 2: return "sibling", best[0], best[1], own |
| rest = toks[1:] if own else toks |
| for k, m in enumerate(rest): |
| for kind in KINDS: |
| i = index(m.group(1), kind) |
| if i == 0 or (kind == "la" and m.group(1) == "x"): |
| run = run_from(rest, k, kind) |
| if len(run) >= 2: return "child", kind, run, own |
| return None, "no run of 2+ items" |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser(); ap.add_argument("--flags"); ap.add_argument("--dry-run", action="store_true"); ap.add_argument("--finish", action="store_true"); a = ap.parse_args() |
| if a.finish: return finish() |
| rows = [json.loads(line) for line in (ROOT / "sot_provisioned.jsonl").open() if line.strip()] |
| flags = json.loads(Path(a.flags).read_text()) |
| by = defaultdict(list) |
| for r in rows: by[r["document_id"]].append(r) |
| queue = [] |
| for r in rows: |
| f = set(flags.get(r["row_id"], [])) |
| if f & SPLIT_FLAGS or ("model_miss" in f and (r.get("model_miss") or {}).get("kind") == "split"): queue.append(r) |
| log = {"cuts": [], "skipped": []}; passes = 0 |
| while queue: |
| passes += 1; nxt = [] |
| for r in queue: |
| if r.get("is_garbage") or r.get("review"): continue |
| t = r.get("segment_text") or ""; pm = (r.get("full_marker") or "").strip(); did = r["document_id"] |
| if r.get("level") is None or not pm or strip_path(pm).lower() in c6.SKIP_MARKERS: |
| log["skipped"].append({"row_id": r["row_id"], "why": "no level / marker, or toc / title / signature block", "text": " ".join(t.split())[:90]}); continue |
| got = find(t) |
| if got[0] is None: |
| if passes == 1: log["skipped"].append({"row_id": r["row_id"], "why": got[1], "text": " ".join(t.split())[:90]}) |
| continue |
| mode, kind, run, own = got |
| markers = {x.get("full_marker") for x in by[did]} |
| if mode == "sibling": |
| s = own.group(1) |
| if not pm.endswith(f"({s})") and not pm.endswith(f".{s}"): |
| log["skipped"].append({"row_id": r["row_id"], "why": f"sibling run but the marker {pm!r} does not end with its own ({s})", "text": " ".join(t.split())[:90]}); continue |
| base = pm[: -len(f"({s})")] if pm.endswith(f"({s})") else pm[: -len(f".{s}")] |
| mk = lambda v: canon(f"{base}({v})") or f"{base}({v})"; lvl = int(r["level"]) |
| keep, items = t[: run[1].start()], run[1:] |
| else: |
| mk = lambda v: canon(f"{pm}-({v})" if pm.endswith("-paragraph") else f"{pm}({v})") or f"{pm}({v})"; lvl = int(r["level"]) + 1 |
| keep, items = t[: run[0].start()], run |
| cuts = [m.start() for m in items] + [len(t)] |
| texts = [t[cuts[k]: cuts[k + 1]] for k in range(len(items))] |
| news = [mk(m.group(1)) for m in items] |
| why = ("lead-in under 10 characters" if mode == "child" and len(keep.strip()) < 10 else |
| "an item under 20 characters (a reference?)" if min(len(x.strip()) for x in texts + [keep]) < 20 else |
| f"{next(n for n in news if n in markers)!r} already exists" if any(n in markers for n in news) else None) |
| if why: |
| log["skipped"].append({"row_id": r["row_id"], "why": why, "text": " ".join(t.split())[:90]}); continue |
| r.setdefault("code_edit", []).append({"what": f"{TAG}_{mode}_parent" if mode == "child" else f"{TAG}_first_sibling", "at": NOW, "old": {"segment_text": t}}) |
| r["segment_text"] = keep.strip() |
| kids = [] |
| for k, (m, text, new) in enumerate(zip(items, texts, news)): |
| c = copy.deepcopy(r); c.pop("review", None); c.pop("model_miss", None) |
| c["row_id"] = f"{r['row_id']}#s{k + 1}"; c["segment_text"] = text.strip(); c["level"] = lvl; c["full_marker"] = new |
| c["code_edit"] = [{"what": f"{TAG}_{'child' if mode == 'child' else 'sibling'}", "at": NOW, "old": {"from_row": r["row_id"]}}] |
| if mode == "child" or r.get("classification") == "strict-enumerated": c["classification"] = "strict-enumerated" |
| kids.append(c) |
| n = len(kids); rr = by[did] |
| for x in rr: |
| if x is r: continue |
| if int(x["order"]) > int(r["order"]): x["order"] = int(x["order"]) + n |
| if x.get("sot_order") is not None and r.get("sot_order") is not None and int(x["sot_order"]) > int(r["sot_order"]): x["sot_order"] = int(x["sot_order"]) + n |
| for x in sorted([x for x in rr if int(x["order"]) > int(r["order"]) + n], key=lambda x: int(x["order"])): |
| if x.get("sot_item_id") in (0, None): break |
| x["sot_item_id"] = int(x["sot_item_id"]) + n |
| for k, c in enumerate(kids): |
| c["order"] = int(r["order"]) + k + 1 |
| if r.get("sot_order") is not None: c["sot_order"] = int(r["sot_order"]) + k + 1 |
| if r.get("sot_item_id") is not None: c["sot_item_id"] = int(r["sot_item_id"]) + k + 1 |
| at = rows.index(r) + 1; rows[at:at] = kids; rr.extend(kids) |
| log["cuts"].append({"row_id": r["row_id"], "mode": mode, "marker": pm, "new": news, "pass": passes}) |
| nxt += [r] + kids |
| queue = nxt |
| for x in log["cuts"]: print(f"{x['mode']:8} p{x['pass']} {x['row_id']:26} {x['marker']!r} -> {x['new']}") |
| print(json.dumps({"cuts": len(log["cuts"]), "by_mode": dict(Counter(x["mode"] for x in log["cuts"])), "rows_created": sum(len(x["new"]) for x in log["cuts"]), "passes": passes, |
| "skipped": dict(Counter(x["why"].split(" ->")[0] if "already" not in x["why"] else "marker already exists" for x in log["skipped"]))}), |
| "(dry run)" if a.dry_run else "(written)") |
| (ROOT / "results/09_split_flagged.log.json").write_text(json.dumps(log, ensure_ascii=False, indent=1)) |
| if a.dry_run: return |
| write(rows) |
| with (ROOT / "viewer/edits.log.jsonl").open("a") as fh: |
| fh.write(json.dumps({"at": NOW, "by": "Claude, at Arthur's request (09_split_flagged.py: flagged rows segmented by code; every row marked code_edit)", "changes": log}, ensure_ascii=False) + "\n") |
|
|
|
|
| def write(rows): |
| 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") |
|
|
|
|
| def finish(): |
| """Place; undo every cut with a row 03 cannot place; place again; refresh the cut rows' literal.""" |
| py = str(ROOT.parents[1] / ".venv/bin/python"); place = lambda: subprocess.run([py, str(ROOT / "scripts/03_place_annotations.py")], check=True, capture_output=True, text=True).stdout.strip().splitlines()[-1] |
| print("placed:", place()) |
| rep = json.loads((ROOT / "sot_annotated.report.json").read_text()) |
| cut_parents = {x["row_id"] for x in json.loads((ROOT / "results/09_split_flagged.log.json").read_text())["cuts"]} |
| lost = {x["row_id"] for x in rep.get("not_found", []) + rep.get("leftover_copies", []) if "#s" in x.get("row_id", "") or x.get("row_id") in cut_parents} |
| rows = [json.loads(line) for line in (ROOT / "sot_provisioned.jsonl").open() if line.strip()] |
| parents = set() |
| for rid in lost: |
| parents.add(rid if rid in cut_parents else rid.rsplit("#s", 1)[0]) |
| if parents: |
| drop = {r["row_id"] for r in rows if any(r["row_id"].startswith(p + "#s") for p in parents)} |
| by = defaultdict(list) |
| for r in rows: by[r["document_id"]].append(r) |
| for r in rows: |
| if r["row_id"] not in parents: continue |
| ce = [x for x in r["code_edit"] if x["what"].startswith(TAG) and "segment_text" in x.get("old", {})][-1] |
| r["segment_text"] = " ".join(ce["old"]["segment_text"].split()); r["code_edit"].remove(ce) |
| if not r["code_edit"]: del r["code_edit"] |
| rows = [r for r in rows if r["row_id"] not in drop] |
| for did in {p.split("#")[0] for p in parents}: |
| rr = sorted([r for r in rows if r["document_id"] == did], key=lambda r: int(r["order"])) |
| for k, r in enumerate(rr): r["order"] = k |
| print(f"undone: {len(parents)} cuts ({len(drop)} rows) whose rows 03 could not place: {sorted(parents)}") |
| write(rows); print("placed:", place()) |
| ann = {json.loads(x)["row_id"]: json.loads(x) for x in (ROOT / "sot_annotated.jsonl").open()} |
| texts = json.loads((ROOT / "viewer/data/texts.json").read_text()); n = 0 |
| for r in rows: |
| if not any(x["what"].startswith(("enum_cut", TAG)) for x in (r.get("code_edit") or [])) or r["row_id"] not in ann: continue |
| lit = "".join(texts[r["document_id"]][x["start"]:x["end"]] for x in ann[r["row_id"]]["source"]["ranges"]) |
| if r.get("literal") != lit: r["literal"] = lit; n += 1 |
| write(rows); print("literal refreshed:", n) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|