Datasets:
File size: 19,328 Bytes
6df6889 | 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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 | """LLM-facing view of a .docx contract.
A `DocumentView` is a frozen snapshot of a document for the LLM to reason
about: it carries paragraph IDs the model can cite, a Markdown serialization
that fits in a prompt, and enumerations of any pre-existing comments and
tracked changes (so the model can reply on threads and accept prior edits).
The view is built fresh each time the document is loaded; paragraph IDs are
assigned by load-order (`p-000`, `p-001`, ...) and are stable for the duration
of one redlining session. After we apply edits and save, reloading produces a
new view — the LLM must re-read in that case.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Iterable
from docx import Document
from docx.document import Document as DocxDocument
from docx.text.paragraph import Paragraph
from lxml import etree
from .ooxml_utils import NSMAP, qn
_PARAGRAPH_ID_FMT = "p-{:03d}"
def _iter_body_paragraphs(doc: DocxDocument) -> "list[Paragraph]":
"""Every paragraph in the document body **in document order, including
paragraphs inside tables** (and nested tables).
python-docx's `Document.paragraphs` only returns body-level `<w:p>` and
silently skips `<w:tbl>//<w:p>`, so any edit inside a pricing schedule,
SLA grid, or credit table was invisible to the grader (see the
"table blindness" QC finding). We walk the body XML ourselves: yield each
`<w:p>` where it sits, descending rows → cells → (recursively) nested
tables, so paragraph IDs stay in reading order.
"""
body = doc.element.body
parent = doc._body # a valid python-docx parent (resolves .part for styles)
def walk(el):
for child in el.iterchildren():
if child.tag == qn("w:p"):
yield Paragraph(child, parent)
elif child.tag == qn("w:tbl"):
for row in child.iterchildren(qn("w:tr")):
for cell in row.iterchildren(qn("w:tc")):
yield from walk(cell)
return list(walk(body))
@dataclass
class ParagraphInfo:
"""A paragraph in the document, with the metadata the LLM and engine need."""
id: str
index: int
text: str
style: str
is_empty: bool
has_revisions: bool
has_comments: bool
# Word's auto-numbering is driven by w:numPr; we record the abstract
# level (0 = top-level) when present so the serializer can indent.
list_level: int | None = None
@dataclass
class ExistingComment:
"""A pre-existing comment in the document the LLM may need to reply to."""
id: int
author: str
initials: str
text: str
paragraph_ids: list[str] = field(default_factory=list)
parent_id: int | None = None # if this comment is itself a reply
# Set by annotated_view.tag_this_turn(): True if this comment is net-new by
# the represented party THIS turn, False if carried-in (counterparty / prior
# turn), None if turn attribution was not computed (no baseline). Never read
# from the model-writable docx — derived from the parsed baseline diff only.
is_this_turn: bool | None = None
@dataclass
class ExistingRevision:
"""A pre-existing tracked change the LLM may need to accept/reject."""
id: int
type: str # "ins" | "del" | "moveFrom" | "moveTo"
author: str
text: str
paragraph_ids: list[str] = field(default_factory=list)
# w:date on the revision element (ISO string) if present, else None.
date: str | None = None
# Set by annotated_view.tag_this_turn(): True if this revision is net-new by
# the represented party THIS turn, False if carried-in (counterparty / prior
# turn), None if turn attribution was not computed (no baseline). Derived only
# from the parsed OOXML/baseline diff — never model-controllable.
is_this_turn: bool | None = None
@dataclass
class DocumentView:
docx_path: Path
paragraphs: list[ParagraphInfo]
comments: list[ExistingComment]
revisions: list[ExistingRevision]
# B1 (Class B): raw model-controlled w:id -> grader-canonical sequential id
# (the enumeration index) for comments and revisions. The annotated (judge) view
# resolves every rendered id through these maps, so no raw, model-forgeable w:id
# ever reaches the judge. Populated by load(); default empty for direct
# construction / backward compatibility.
comment_id_map: dict[int, int] = field(default_factory=dict, repr=False)
revision_id_map: dict[int, int] = field(default_factory=dict, repr=False)
# Map paragraph ID → underlying python-docx Paragraph object (not serialized
# for the LLM; used internally when applying edits).
_paragraph_objects: dict[str, Paragraph] = field(default_factory=dict, repr=False)
_docx: DocxDocument | None = field(default=None, repr=False)
@classmethod
def load(cls, path: str | Path) -> "DocumentView":
path = Path(path)
doc = Document(str(path))
paragraphs: list[ParagraphInfo] = []
paragraph_objects: dict[str, Paragraph] = {}
for i, p in enumerate(_iter_body_paragraphs(doc)):
pid = _PARAGRAPH_ID_FMT.format(i)
info = ParagraphInfo(
id=pid,
index=i,
text=p.text,
style=p.style.name if p.style else "",
is_empty=not p.text.strip(),
has_revisions=_paragraph_has_revisions(p),
has_comments=_paragraph_has_comments(p),
list_level=_paragraph_list_level(p),
)
paragraphs.append(info)
paragraph_objects[pid] = p
comments = _enumerate_comments(doc, paragraphs, paragraph_objects)
revisions = _enumerate_revisions(doc, paragraphs, paragraph_objects)
# B1: grader-canonical id = enumeration index; map the raw, model-set w:id
# (.id) -> canonical so the render never surfaces a raw w:id.
comment_id_map = {c.id: i for i, c in enumerate(comments)}
revision_id_map = {r.id: i for i, r in enumerate(revisions)}
return cls(
docx_path=path,
paragraphs=paragraphs,
comments=comments,
revisions=revisions,
comment_id_map=comment_id_map,
revision_id_map=revision_id_map,
_paragraph_objects=paragraph_objects,
_docx=doc,
)
def get(self, paragraph_id: str) -> ParagraphInfo | None:
for p in self.paragraphs:
if p.id == paragraph_id:
return p
return None
def runtime_paragraph(self, paragraph_id: str) -> Paragraph | None:
"""Return the underlying python-docx `Paragraph` object for the given id."""
return self._paragraph_objects.get(paragraph_id)
def to_markdown(self, max_chars: int | None = None) -> str:
"""Serialize the document into an LLM-friendly Markdown view.
Blank paragraphs are omitted from the visible output but their IDs are
preserved (skipped) so paragraph IDs match the underlying document.
If `max_chars` is set, truncates with a sentinel — useful for prompt
budgeting. The LargeCo template is ~90 KB; most current frontier models
comfortably fit the whole thing, but smaller models or budget runs may
need windowing.
"""
lines: list[str] = [f"# {self.docx_path.name}", ""]
for p in self.paragraphs:
if p.is_empty:
continue
flags = []
if p.has_revisions:
flags.append("REVS")
if p.has_comments:
flags.append("CMTS")
flag_str = f" {{{','.join(flags)}}}" if flags else ""
indent = " " * (p.list_level or 0)
lines.append(f"[{p.id}] ({p.style}){flag_str} {indent}{p.text}")
if self.comments:
lines.append("")
lines.append("## Existing comments")
for c in self.comments:
head = f"[cmt-{c.id}] {c.author!r}"
if c.parent_id is not None:
head += f" (reply to cmt-{c.parent_id})"
spans = ",".join(c.paragraph_ids) or "?"
lines.append(f"{head} on [{spans}]: {c.text}")
if self.revisions:
lines.append("")
lines.append("## Existing tracked changes")
for r in self.revisions:
spans = ",".join(r.paragraph_ids) or "?"
lines.append(
f"[rev-{r.id}] {r.type} by {r.author!r} on [{spans}]: {r.text!r}"
)
out = "\n".join(lines)
if max_chars is not None and len(out) > max_chars:
out = out[: max_chars - 100] + "\n\n[... document truncated ...]"
return out
def stats(self) -> dict[str, int]:
return {
"paragraphs": len(self.paragraphs),
"non_empty_paragraphs": sum(1 for p in self.paragraphs if not p.is_empty),
"existing_comments": len(self.comments),
"existing_revisions": len(self.revisions),
}
# --- Paragraph metadata helpers -------------------------------------------- #
def _paragraph_has_revisions(p: Paragraph) -> bool:
for tag in ("w:ins", "w:del", "w:moveFrom", "w:moveTo"):
if next(p._p.iter(qn(tag)), None) is not None:
return True
return False
def _paragraph_has_comments(p: Paragraph) -> bool:
for tag in ("w:commentRangeStart", "w:commentRangeEnd", "w:commentReference"):
if next(p._p.iter(qn(tag)), None) is not None:
return True
return False
def _paragraph_list_level(p: Paragraph) -> int | None:
"""Return the list nesting level if the paragraph is part of a numbered/bulleted list."""
numPr = p._p.find(f"{qn('w:pPr')}/{qn('w:numPr')}")
if numPr is None:
return None
ilvl = numPr.find(qn("w:ilvl"))
if ilvl is None:
return 0
val = ilvl.get(qn("w:val"))
try:
return int(val) if val is not None else 0
except ValueError:
return 0
# --- Comment & revision enumeration ---------------------------------------- #
def _paragraph_ids_for_element_range(
start_id_attr: str,
end_id_attr: str,
el_id: int,
paragraphs: list[ParagraphInfo],
paragraph_objects: dict[str, Paragraph],
) -> list[str]:
"""Find paragraph IDs that the given range marker pair spans.
Walks paragraphs in document order looking for `w:commentRangeStart`/`End`
(or analogous markers) with matching IDs. Returns paragraph IDs from start
to end inclusive.
"""
started = False
spans: list[str] = []
target = str(el_id)
for pi in paragraphs:
p = paragraph_objects[pi.id]
# Did this paragraph contain start?
for el in p._p.iter(qn(start_id_attr)):
if el.get(qn("w:id")) == target:
started = True
break
if started:
spans.append(pi.id)
# Did this paragraph contain end?
for el in p._p.iter(qn(end_id_attr)):
if el.get(qn("w:id")) == target:
return spans
return spans
def _enumerate_comments(
doc: DocxDocument,
paragraphs: list[ParagraphInfo],
paragraph_objects: dict[str, Paragraph],
) -> list[ExistingComment]:
out: list[ExistingComment] = []
# python-docx exposes `Document.comments` (CommentCollection) in 1.2.
try:
collection = doc.comments
except AttributeError:
return out
# Build a paraId → parent_id lookup from commentsExtended.xml so we can
# mark replies. The commentsExtended part is optional; absence just means
# no thread metadata available.
paraid_parent = _read_comments_extended(doc)
for c in collection:
cid = int(c._element.get(qn("w:id"), -1))
if cid < 0:
continue
spans = _paragraph_ids_for_element_range(
"w:commentRangeStart",
"w:commentRangeEnd",
cid,
paragraphs,
paragraph_objects,
)
# Text — join all w:t descendants of the w:comment element.
text = "".join(t.text or "" for t in c._element.iter(qn("w:t")))
# Determine if this is a reply: look up our first paragraph's paraId.
parent_id = None
first_para = c._element.find(qn("w:p"))
if first_para is not None:
pid_attr = first_para.get(qn("w14:paraId"))
if pid_attr and pid_attr in paraid_parent:
parent_id = paraid_parent[pid_attr]
out.append(
ExistingComment(
id=cid,
author=c._element.get(qn("w:author"), ""),
initials=c._element.get(qn("w:initials"), ""),
text=text,
paragraph_ids=spans,
parent_id=parent_id,
)
)
# A threaded reply has no body comment-range, so its paragraph_ids are empty
# and it would render `on [?]`. Inherit the anchor from its thread root so the
# read view / judge appendix show the real paragraph.
_by_id = {c.id: c for c in out}
for c in out:
if c.paragraph_ids or c.parent_id is None:
continue
seen: set[int] = set()
anc = _by_id.get(c.parent_id)
while anc is not None and anc.id not in seen:
seen.add(anc.id)
if anc.paragraph_ids:
c.paragraph_ids = list(anc.paragraph_ids)
break
anc = _by_id.get(anc.parent_id) if anc.parent_id is not None else None
return out
def _read_comments_extended(doc: DocxDocument) -> dict[str, int]:
"""Return a paraId → parent_comment_id map from commentsExtended.xml.
Word stores comment-thread parentage by paraId (a w14 attribute on the
paragraph inside the comment body) rather than by comment IDs directly.
We resolve that mapping here.
"""
out: dict[str, int] = {}
package_part = doc.part.package
# Walk for any part whose URI ends with /word/commentsExtended.xml
for rel in doc.part.rels.values():
if rel.target_ref.endswith("commentsExtended.xml"):
blob = rel.target_part.blob
root = etree.fromstring(blob)
# Build paraId → parent_paraId from <w15:commentEx>
paraid_to_parent = {}
for ex in root.iter(qn("w15:commentEx")):
pid = ex.get(qn("w15:paraId"))
ppid = ex.get(qn("w15:paraIdParent"))
if pid:
paraid_to_parent[pid] = ppid
if not paraid_to_parent:
return out
# Now we need to resolve parent paraId → comment id by walking
# comments.xml.
paraid_to_commentid = {}
for crel in doc.part.rels.values():
if crel.target_ref.endswith("comments.xml"):
cblob = crel.target_part.blob
croot = etree.fromstring(cblob)
for c in croot.iter(qn("w:comment")):
first_p = c.find(qn("w:p"))
if first_p is None:
continue
pid = first_p.get(qn("w14:paraId"))
cid = c.get(qn("w:id"))
if pid and cid is not None:
try:
paraid_to_commentid[pid] = int(cid)
except ValueError:
continue
for pid, ppid in paraid_to_parent.items():
if ppid in paraid_to_commentid:
out[pid] = paraid_to_commentid[ppid]
break
return out
def _enumerate_revisions(
doc: DocxDocument,
paragraphs: list[ParagraphInfo],
paragraph_objects: dict[str, Paragraph],
) -> list[ExistingRevision]:
out: list[ExistingRevision] = []
seen_ids: set[int] = set()
for pi in paragraphs:
p = paragraph_objects[pi.id]
for tag in ("w:ins", "w:del", "w:moveFrom", "w:moveTo"):
for el in p._p.iter(qn(tag)):
raw = el.get(qn("w:id"))
if raw is None:
continue
try:
rid = int(raw)
except ValueError:
continue
if rid in seen_ids:
continue
seen_ids.add(rid)
out.append(
ExistingRevision(
id=rid,
type=etree.QName(el).localname,
author=el.get(qn("w:author"), ""),
# Text belonging to THIS wrapper only — NOT the text of a
# deeper nested revision (a model edit made inside a
# counterparty insertion is a separate revision, usually a
# different author). The old flat ``el.iter(w:t/w:delText)``
# folded that nested text into the outer revision, so the
# appendix mis-attributed the model's insert/strike to the
# counterparty (R4). See _own_revision_text.
text=_own_revision_text(el),
paragraph_ids=[pi.id],
date=el.get(qn("w:date")),
)
)
return out
# Wrapper tags whose text is a SEPARATE (nested) revision, and transparent
# wrappers we descend through without crossing a revision boundary.
_REVISION_WRAPPER_TAGS = frozenset(
qn(t) for t in ("w:ins", "w:del", "w:moveFrom", "w:moveTo")
)
_TRANSPARENT_WRAPPER_TAGS = frozenset(
qn(t) for t in ("w:smartTag", "w:hyperlink", "w:sdt", "w:sdtContent")
)
def _own_revision_text(el) -> str:
"""Text of a revision wrapper (`w:ins`/`w:del`/`w:moveFrom`/`w:moveTo`) that
belongs to IT, excluding any text inside a DEEPER nested revision wrapper.
A nested revision (e.g. a model `w:del` inside a counterparty `w:ins`) is a
distinct tracked change with its own author; folding its text into the outer
revision's ``.text`` mis-attributes it in the appendix and corrupts the
signature used for this-turn diffing (R4). We walk children, gathering
``w:r`` run text (``w:t`` + ``w:delText``) and descending only through
transparent wrappers, stopping at any nested revision wrapper. For a
non-nested revision this returns exactly the old flat join.
"""
out: list[str] = []
def walk(node) -> None:
for c in node.iterchildren():
if not isinstance(c.tag, str):
continue # XML comment / PI node
if c.tag in _REVISION_WRAPPER_TAGS:
continue # separate nested revision — its text is its own
if c.tag in _TRANSPARENT_WRAPPER_TAGS:
walk(c)
elif c.tag == qn("w:r"):
for t in c.iter(qn("w:t")):
out.append(t.text or "")
for t in c.iter(qn("w:delText")):
out.append(t.text or "")
# else: pPr / rPr / bookmarks / comment refs — no revision text
walk(el)
return "".join(out)
|