File size: 14,118 Bytes
1e5748d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
"""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  # noqa: E402

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                      # the other kind: nested, stays in its item
        if i == want: run.append(m); want += 1; continue
        # a single letter that is also a roman numeral ("(i)", "(v)") may be nested in a letter run
        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                                       # sequence broken: the run ends here
    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:  # renumber as 06_cut_enums_exhibits.py
                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                        # nested runs: cut again next pass
        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:  # the cut that made it: undo it whole (every #s row of that parent, and deeper cuts below them)
        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}:  # renumber the document's order densely, keeping its sequence
            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()