Download scripts/12_path_ids.py from arthrod/edgar_segmenter_artifacts: direct link, hf CLI and curl.
- Browser
- Download file 8.39 kB
-
https://huggingface.co/datasets/arthrod/edgar_segmenter_artifacts/resolve/main/scripts/12_path_ids.py
- Command line
-
hf download hf://datasets/arthrod/edgar_segmenter_artifacts/scripts/12_path_ids.py
-
curl -L -o 12_path_ids.py https://huggingface.co/datasets/arthrod/edgar_segmenter_artifacts/resolve/main/scripts/12_path_ids.py
8.39 kB
| """Bracketed addresses for repeated markers (Arthur, 2026-09-24: "Let's do the brackets solution to all | |
| repeated items, but flag for my review"). | |
| What a marker says is the drafter's label, or the unit it inherits plus the kind ("5-paragraph"). When two | |
| or more content rows of a document say the same, each gets a unique address computed here, written into | |
| BOTH full_marker and path_id (Arthur, 2026-09-24: "path_id and full_marker the same except when absolutely | |
| indicated. I also only annotate full marker"); readers take the label through markers.strip_path: | |
| definition definition["Affiliate"]: the first quoted term in the row's first 150 characters | |
| (an ordinal when none is found or the term repeats) | |
| signature-block signature-block["TPG Pace Holdings Corp."]: the text before the first "By:" | |
| (3-80 characters, after any "IN WITNESS WHEREOF ... written above."; else an ordinal) | |
| anything else <marker>[n], n = 0, 1, 2, ... in document order ("5-paragraph[0]", "whereas[3]"); 0-based | |
| (Arthur, 2026-09-24: "Normalize the data, so we start with [0] whenever we have more than 1") | |
| descendants a row whose marker extends a repeated marker ("paragraph-(i)" under "paragraph") | |
| takes the path_id of the nearest earlier row with that marker ("paragraph[2]-(i)"); | |
| still repeated after that -> an ordinal too | |
| A repeated PRINTED label (a marker with a depth that is not a paragraph, "10.7" twice) gets its ordinal | |
| and the reason "duplicate printed label: likely an annotation error". | |
| A row that gets a path_id for the first time gets code_edit {"what": "path_id", "why": ...} (the viewer flags it | |
| until it is reviewed). Rerunning renumbers every repeated group in document order, reviewed rows included (the | |
| numbers only; the viewer's split pushes later numbers the same way), and removes a path_id whose marker no longer | |
| repeats in its document. | |
| Usage: python claude_run/NEW/scripts/12_path_ids.py [--dry-run] | |
| """ | |
| import argparse | |
| import datetime | |
| import json | |
| import re | |
| 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 marker_depth, strip_path # noqa: E402 | |
| NOW = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds") | |
| TERM = re.compile(r"[“\"]\s*([^”\"]{1,80}?)\s*[”\"]") | |
| def key_of(r, marker): | |
| t = " ".join((r.get("segment_text") or "").split()) | |
| if marker.endswith("definition"): | |
| m = TERM.search(t[:150]) | |
| return m.group(1).strip() if m else None | |
| if marker.endswith("signature-block"): | |
| t = re.sub(r"^IN WITNESS WHEREOF.*?(written|first above written|date first written above|hereinabove)\.?\s*", "", t, flags=re.I) | |
| m = re.match(r"(.{3,80}?)\s*By\s*:", t) | |
| return m.group(1).strip(" ,:") if m else None | |
| return None | |
| def base_of(r) -> str: | |
| """What the marker says, without any address brackets (markers.strip_path): full_marker carries the address.""" | |
| return strip_path(r.get("full_marker")) | |
| def reviewed_after_path(r): | |
| ce = [x for x in (r.get("code_edit") or []) if x.get("what") == "path_id"] | |
| return bool(ce) and bool(r.get("review", {}).get("at")) and str(r["review"]["at"]) > str(ce[-1]["at"]) | |
| def main(): | |
| ap = argparse.ArgumentParser(); 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()] | |
| by = defaultdict(list) | |
| for r in rows: by[r["document_id"]].append(r) | |
| out, why_count = [], Counter() | |
| for did, rr in by.items(): | |
| c = [r for r in sorted(rr, key=lambda r: int(r["order"])) if not r.get("is_garbage") and base_of(r)] | |
| count = Counter(base_of(r) for r in c) | |
| repeated = {m for m, n in count.items() if n > 1} | |
| path, seen_path, ordinal = {}, Counter(), Counter() | |
| # keys (definition terms, signature parties) usable only when unique within their marker group | |
| keys = defaultdict(Counter) | |
| for r in c: | |
| m = base_of(r) | |
| if m in repeated and (k := key_of(r, m)): keys[m][k] += 1 | |
| for i, r in enumerate(c): | |
| m = base_of(r); pid, why = m, None | |
| # a descendant of a repeated marker: the longest repeated prefix that this marker extends | |
| cands = [p for p in repeated if p != m and m.startswith(p) and m[len(p):len(p) + 1] in ("-", "(", ".")] | |
| if cands: | |
| p = max(cands, key=len) | |
| parent = next((x for x in reversed(c[:i]) if base_of(x) == p), None) | |
| if parent is not None and parent["row_id"] in path: | |
| pid = path[parent["row_id"]] + m[len(p):]; why = f"descendant of repeated {p!r}" | |
| if m in repeated and pid == m: # a descendant resolved through its parent is unique already (the collision pass checks) | |
| k = key_of(r, m) | |
| if k and keys[m][k] == 1: pid = f'{m}["{k}"]'; why = "repeated marker, keyed by " + ("defined term" if m.endswith("definition") else "party") | |
| else: | |
| pid = f"{m}[{ordinal[m]}]"; ordinal[m] += 1 | |
| d = marker_depth(m) | |
| why = ("duplicate printed label: likely an annotation error" if d is not None and not m.endswith("paragraph") and "paragraph" not in m | |
| else "repeated marker, numbered in document order") | |
| seen_path[pid] += 1 | |
| path[r["row_id"]] = pid | |
| if pid != m: out.append((r, pid, why)) | |
| # still colliding after prefixes (two descendants resolved to the same address): ordinal them | |
| dup = {p for p, n in seen_path.items() if n > 1} | |
| if dup: | |
| k2 = Counter() | |
| for idx, (r, pid, why) in enumerate(out): | |
| if r["document_id"] == did and pid in dup: out[idx] = (r, f"{pid}[{k2[pid]}]", (why or "") + "; still repeated, numbered"); k2[pid] += 1 | |
| for r in c: | |
| if path[r["row_id"]] in dup and not any(x[0] is r for x in out): p0 = path[r["row_id"]]; out.append((r, f"{p0}[{k2[p0]}]", "still repeated, numbered")); k2[p0] += 1 | |
| changed = renumbered = removed = 0 | |
| has = {id(r) for r, _, _ in out} | |
| for r in rows: # an address on a marker that no longer repeats: gone, from both fields | |
| if id(r) in has or r.get("is_garbage"): continue | |
| if r.get("path_id"): del r["path_id"]; removed += 1 | |
| if (r.get("full_marker") or "").strip() != base_of(r) and base_of(r): r["full_marker"] = base_of(r); removed += 1 | |
| for r, pid, why in out: | |
| why_count[why.split(";")[0] if why else "?"] += 1 | |
| # Arthur 2026-09-24: "path_id and full_marker the same ... I only annotate full marker": the address goes in both | |
| if (r.get("full_marker") or "").strip() != pid: r["full_marker"] = pid; renumbered += 1 | |
| if r.get("path_id") == pid: continue | |
| if r.get("path_id"): r["path_id"] = pid; renumbered += 1; continue # the number only: no new flag | |
| r["path_id"] = pid; r.setdefault("code_edit", []).append({"what": "path_id", "at": NOW, "why": why, "old": {"path_id": None}}); changed += 1 | |
| for r, pid, why in out[:40]: print(f"{r['row_id']:26} {r['full_marker']!r:24} -> {pid!r:40} {why}") | |
| print(f"{len(out)} rows with a path_id ({changed} new, {renumbered} renumbered, {removed} removed) in {len({r['document_id'] for r, _, _ in out})} documents;", dict(why_count), | |
| "(dry run)" if a.dry_run else "(written)") | |
| if a.dry_run: 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": "Claude, at Arthur's request (12_path_ids.py: bracketed path_id for repeated markers, flagged code_edit)", | |
| "field": "path_id", "changes": [{"row_id": r["row_id"], "full_marker": r["full_marker"], "path_id": pid, "why": why} for r, pid, why in out]}, | |
| ensure_ascii=False) + "\n") | |
| if __name__ == "__main__": | |
| main() | |