perf(docx): resolve each paragraph style once per document (5.3 s -> 1.0 s outside spaCy)

Merged
DE
2mo ago
+56-7

partition_docx() looks up a paragraph's style through python-docx's Paragraph.style up to six times per paragraph (paragraph.style and paragraph.style.name reads it twice, at three call sites). For a paragraph with no explicit style, which is most of them, each read scans every style definition in the document to find the default, so the cost grows with paragraphs times styles.

The style name and the style-chain numbering only depend on the paragraph's style id, so each is now resolved once per document and kept in a dict on the partitioner and on _ListLabels. Both dicts live on objects created per call, so nothing is shared between documents.

Median of 7 alternating fresh-process runs, Python 3.13, Apple M5:

Documenttotal beforetotal afteroutside spaCy beforeoutside spaCy after
3,000 paragraphs on python-docx's default template (164 styles)12.5 s8.5 s5.30 s0.97 s
example-docs/handbook-872p.docx (48 styles)13.98 s10.36 s5.26 s1.94 s

Output is unchanged: elements_to_json() is byte-identical before and after for every .docx in example-docs, with and without page breaks and table inference, including the 872-page handbook. A new test checks that a 60-paragraph document resolves its 3 styles 6 times instead of 360. test_docx.py passes and ruff is clean. CHANGELOG and __version__ are bumped to 0.27.28-dev3.

Draft #4538 adds a similar style cache inside _ListLabels for its heading check; if both land they can share it.