edgar_segmenter_artifacts / scripts /15_caption_split.py
arthrod's picture
Add files using upload-large-folder tool
a1d579a verified
Raw
History Blame Contribute Delete
10.4 kB
"""Split a caption from its body (Arthur, 2026-09-25: "i think we should always split, even when in the same paragraph ...
5. Bananas You told me I love bananas (pay attention where there isnt a period but there is an extra space or something,
like a capitzalized item) ... mark all unreviewed"). Supersedes 1-ce-5 rubric fork F5 (A: caption + unmarked paragraph
one record); follows F12 (B) and "1. Bananas." / "I love bananas" -> 1 / 1-paragraph.
A content row splits in two when its SOT text opens with a marker and a caption:
marker "5.", "5.1", "(a)", "Section 5", "Article IV", "A." ...
caption 1 to 16 words right after the marker, title case or capitals (short words of / and / the ... allowed inside),
ending at the first of: a word ending with "." or ":" (not an abbreviation: U.S., Inc., No., Co. ...), a line break
or 2+ spaces in the source, or a word that opens a sentence (The, This, Each, If, You, Such, Subject ...) when the
caption already has a word; never a caption that itself opens with such a word ("5. The Company shall ...")
body at least 4 words, starting with a capital, a quote or a bracket
The caption row keeps the row (its marker, level, id); the body row is new: full_marker "<marker>-paragraph", the same level
(markers.py: "2-paragraph -> 1"), row_id "<row_id>#body". Both lose their review and get code_edit {what: caption_split}
(the viewer's "caption split by code" flag, heinous, until reviewed). Ranges are cut where the caption's last word ends in
the source; a row whose SOT text and source text disagree before that point is not split: it gets caption_check (the
viewer's "caption glued to its body" flag) for Arthur to split by hand.
Writes a backup (/tmp/sot_provisioned.before_caption_split.jsonl) before changing claude_run/NEW/sot_provisioned.jsonl.
Usage: uv run python claude_run/NEW/scripts/15_caption_split.py [--dry-run] [--show N]
"""
import argparse
import copy
import json
import re
import shutil
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
MARKER = re.compile(r"^\s*((?:section|article)\s+[0-9IVXLCivxlc]+(?:\.\d+)*[.:]?|\(?[0-9]{1,3}(?:\.[0-9]+)*[.)]|\(?[A-Za-z]{1,2}[.)]|\([0-9A-Za-z]{1,5}\)|[IVXLC]{1,6}\.)(?=\s)", re.I)
SMALL = {"of", "and", "the", "to", "in", "for", "on", "or", "a", "an", "with", "by", "&", "-", "–", "—", "/", "under", "upon", "from", "at", "as", "its", "their", "no"}
OPENERS = {"The", "This", "These", "That", "Those", "Each", "Any", "All", "If", "In", "On", "Upon", "Subject", "Notwithstanding", "Except", "For", "Such",
"It", "You", "We", "Our", "Your", "I", "Unless", "Within", "During", "Without", "At", "By", "To", "As", "When", "Where", "There", "Neither",
"Nothing", "Either", "Both", "Following", "Prior", "After", "Before", "From", "Following", "Company", "Executive", "Employee", "Employer",
"Borrower", "Lender", "Seller", "Buyer", "Purchaser", "Consultant", "Participant", "Licensee", "Licensor", "Tenant", "Landlord", "He", "She", "They",
"Should", "Shall", "May", "Will", "Whereas"}
# a capitalised word that always opens a sentence, even inside what looked like a caption ("G. Bankruptcy If Tenant ...")
ALWAYS = {"The", "This", "These", "That", "Each", "If", "Subject", "Notwithstanding", "Except", "It", "You", "We", "Unless", "During",
"Neither", "Nothing", "Such", "When", "Where", "There", "Should", "Shall", "May", "Will", "Whereas"} # not Without / In / Upon: "Termination Without Cause"
ABBREV = re.compile(r"^(?:[A-Z]\.){1,3}$|^(?:U\.S\.|Inc\.|No\.|Co\.|Corp\.|Ltd\.|L\.P\.|LLC\.|Mr\.|Ms\.|Dr\.|St\.|vs\.|v\.|etc\.|Sec\.|Art\.)$")
TRANS = str.maketrans({"“": '"', "”": '"', "‘": "'", "’": "'", " ": " "})
def caption_cut(text):
"""(number of words, marker included, that make marker + caption) or None, on text as the source has it."""
m = MARKER.match(text)
if not m: return None
words = [(w.group(), w.start(), w.end()) for w in re.finditer(r"\S+", text)]
nm = len(re.findall(r"\S+", m.group(1))) # words of the marker itself ("Section 5" is two)
if len(words) < nm + 5: return None
def caption_like(k):
bare = words[k][0].strip("\"'()[]*,;.:")
return bool(bare) and (bare[:1].isupper() or bare[:1].isdigit() or bare.lower() in SMALL)
def runs_to_period(k):
"""a caption that goes on past k (a line break, extra space or colon inside it): the words after k up to a
period within 8 words are all caption-like -> the index of the word the caption ends with, else None"""
for j in range(k + 1, min(len(words), k + 9)):
w = words[j][0]
if w in (".", ":"): return j
if not caption_like(j): return None
if w.endswith(".") and not ABBREV.match(w): return j
return None
def opens_sentence(k): # "Company shall", "The Executive": an opener followed by a lower-case word that is not a short word
bare = words[k][0].strip("\"'()[]*,;")
nxt = words[k + 1][0].strip("\"'()[]*,;") if k + 1 < len(words) else ""
return bare in OPENERS and (bare in ALWAYS or (nxt[:1].islower() and nxt.lower() not in SMALL))
cap = []; k = nm
while k < len(words):
w, s, e = words[k]; bare = w.strip("\"'()[]*,;")
if w in (".", ":") and cap: cap.append(k); break # "Cause ." : a period after a space ends the caption
if not bare: return None
if not cap and (opens_sentence(k) or w.startswith(('"', "“"))): return None # a sentence or a defined term, no caption
if cap and (bare in ALWAYS or (opens_sentence(k) and k + 1 < len(words) and words[k + 1][0][:1].islower())): break # a sentence opens here
if not caption_like(k): return None
cap.append(k)
if len(cap) > 16: return None
gap = text[e:words[k + 1][1]] if k + 1 < len(words) else ""
ends = (w.endswith((".", ":")) and not ABBREV.match(w)) or "\n" in gap or " " in gap.replace("\t", " ")
if ends:
more = runs_to_period(k) if (w.endswith(":") or not w.endswith(".")) else None
if more is None: break
cap += list(range(k + 1, more + 1)); k = more; break
k += 1
else:
return None
if len(cap) > 17: return None
last = cap[-1]
if last + 1 >= len(words): return None
body = words[last + 1:]
if len(body) < 4 or not re.match(r"[A-Z\"'“(\[]", body[0][0]): return None
capw = [x for x in (words[k][0].strip("\"'()[]*,;.:") for k in cap) if x]
if not capw or capw[-1].lower() in SMALL: return None # "Should the" / "Underwriter and the": a sentence, not a caption
big = [w for w in capw if w.lower() not in SMALL]
if not big or sum(1 for w in big if w[:1].isupper() or w[:1].isdigit()) < len(big): return None
return last + 1 # words 0..last are marker + caption
def words_of(s):
return [w.translate(TRANS) for w in re.findall(r"\S+", s)]
def main():
ap = argparse.ArgumentParser(); ap.add_argument("--dry-run", action="store_true"); ap.add_argument("--show", type=int, default=0); a = ap.parse_args()
path = ROOT / "sot_provisioned.jsonl"; texts = json.loads((ROOT / "viewer/data/texts.json").read_text())
rows = [json.loads(l) for l in path.open() if l.strip()]
at = datetime.now(timezone.utc).isoformat(timespec="seconds"); stats = Counter(); shown = 0; out = []; by_doc = defaultdict(list)
for r in rows:
if r.get("is_garbage") or not r.get("segment_text") or str(r.get("full_marker") or "").endswith("paragraph"): out.append(r); continue
n = caption_cut(r["segment_text"])
if n is None: out.append(r); continue
t = texts.get(r["document_id"]); a0, b0 = r["source"]["ranges"][0]["start"], r["source"]["ranges"][-1]["end"]
src = t[a0:b0] if t else ""
cw = words_of(r["segment_text"]); cap_c = "".join(cw[:n])
pos = [i for i, ch in enumerate(src) if not ch.isspace()]; src_c = "".join(src[i] for i in pos).translate(TRANS)
if not src_c.startswith(cap_c) or len(src_c) <= len(cap_c):
r = copy.deepcopy(r); r["caption_check"] = {"caption": " ".join(cw[:n]), "why": "caption found in the SOT text, but the source text differs before it: split by hand", "at": at}
out.append(r); stats["flagged"] += 1; continue
cap_end = a0 + pos[len(cap_c) - 1] + 1; body_start = a0 + pos[len(cap_c)]
sm = list(re.finditer(r"\S+", r["segment_text"])); s_cap = r["segment_text"][:sm[n - 1].end()]; s_body = r["segment_text"][sm[n].start():]
old = {k: r.get(k) for k in ("segment_text", "full_marker", "level")} | {"ranges": r["source"]["ranges"]}
edit = {"what": "caption_split", "at": at, "why": "a caption is always its own unit (Arthur, 2026-09-25)", "old": old}
c = copy.deepcopy(r); c.pop("review", None); c.pop("caption_check", None)
c["segment_text"] = s_cap; c["literal"] = t[a0:cap_end]; c["source"] = {**c["source"], "ranges": [{"start": a0, "end": cap_end}]}
c["code_edit"] = (c.get("code_edit") or []) + [edit]
body = copy.deepcopy(c); body["row_id"] = f"{r['row_id']}#body"; body["segment_text"] = s_body; body["literal"] = t[body_start:b0]
body["source"] = {**body["source"], "ranges": [{"start": body_start, "end": b0}]}
fm = r.get("full_marker"); body["full_marker"] = f"{fm}-paragraph" if fm else None
if body.get("path_id"): body["path_id"] = f"{body['path_id']}-paragraph"
out += [c, body]; stats["split"] += 1
if shown < a.show: print(f"{r['row_id']:18s} [{fm}] {s_cap!r} || {' '.join(s_body.split())[:70]!r}"); shown += 1
for r in out: by_doc[r["document_id"]].append(r)
final = []
for d in by_doc: # the new body rows sit right after their caption: renumber each document's order
seq = by_doc[d]
for k, r in enumerate(seq): r["order"] = k
final += seq
print(dict(stats), "rows before", len(rows), "after", len(final))
if a.dry_run: return
shutil.copy2(path, "/tmp/sot_provisioned.before_caption_split.jsonl")
path.write_text("\n".join(json.dumps(r, ensure_ascii=False) for r in final) + "\n")
print("written; backup /tmp/sot_provisioned.before_caption_split.jsonl")
if __name__ == "__main__":
main()