Skip to content

fix: label numbered headings without making them list items, and skip section-break paragraphs - #4538

Merged
qued merged 20 commits into
mainfrom
qued/docx-list-label-followups
Oct 20, 2026
Merged

qued merged 20 commits into
mainfrom
qued/docx-list-label-followups

Conversation

@qued

@qued qued commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What

Follow-up to #4508, bringing partition_docx() closer to what Word renders for auto-numbered paragraphs:

  • A numbered paragraph of any element type now carries its label in the text, not only list items. Numbered headings come out as, for example, Title "4.2. Overview". Bullets stay unprefixed.
  • A numbered heading is no longer classified as a ListItem, whether its number comes from its style or from the paragraph's own numbering. A heading is a paragraph in a title-mapped style (Heading 1, Title, and so on) or whose style chain or own properties give it an outline level of 0 to 8. It still advances the list counter, as it does in Word. Paragraphs in other styles that carry their own numbering, such as List Paragraph or Caption, stay ListItems.
  • An empty paragraph that only holds a section break no longer consumes a list number. Word does not number it, so every later item in the list was shifted by one (for example 11.3.2. came out as 11.3.3.).

🤖 Generated with Claude Code

@qued qued changed the title fix: stop numbering section-break paragraphs and treating numbered headings as list items fix: label numbered headings without making them list items, and skip section-break paragraphs Oct 8, 2026
cragwolfe pushed a commit that referenced this pull request Oct 16, 2026
…1.0 s outside spaCy) (#4554)

`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:

| Document | total before | total after | outside spaCy before | outside
spaCy after |
|---|---|---|---|---|
| 3,000 paragraphs on python-docx's default template (164 styles) | 12.5
s | 8.5 s | 5.30 s | 0.97 s |
| `example-docs/handbook-872p.docx` (48 styles) | 13.98 s | 10.36 s |
5.26 s | 1.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.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4554?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
@qued
qued force-pushed the qued/docx-list-label-followups branch from 37310cf to 92dfa3a Compare October 19, 2026 15:37
@qued
qued marked this pull request as ready for review October 19, 2026 16:29

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 4 files

Shadow auto-approve: would not auto-approve. This PR does not meet the repository auto-approval settings.

View guided diff | Re-trigger cubic

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 92dfa3a4cda4fca4cfd01c15c0bb16a4e1d0d57d with GPT Pro. One numbering regression remains: the section-break filter can skip a real paragraph and shift subsequent labels. Details and suggested regression coverage are inline.

The required checks passed on this commit. No local tests were run.

(authored by codex)

Comment thread unstructured/partition/docx.py Outdated
def _is_section_break_mark(paragraph: Paragraph) -> bool:
"""True for an empty paragraph that only holds a section break; Word does not number it."""
return (
bool(paragraph._p.xpath("./w:pPr/w:sectPr")) and not _paragraph_text(paragraph).strip()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Check the original paragraph before skipping its counter

This predicate also receives page fragments, whose pPr retains the original sectPr. For a numbered section-ending paragraph with whitespace before a rendered page break and nonblank text after it, the first fragment has no nonwhitespace text and returns here without advancing the counter. _iter_paragraph_elements() still sets seen_fragment = True, so the text-bearing continuation never calls label() either. With numbered A, this paragraph B, then C, C gets 2. instead of 3.; a skipped parent level also misses its child-level restart. An image-only numbered section-ending paragraph hits the same extracted-text check.

Determine whether the original paragraph is only an empty section-break marker before splitting it, account for visible nontext content, and advance numbering exactly once for real paragraphs. Add regressions for a section-ending numbered paragraph with whitespace or a drawing before a rendered page break and text afterward, plus an image-only section-ending paragraph. Keep the genuinely empty section-break case uncounted.

(authored by codex)

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 3 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Re-trigger cubic

Comment thread unstructured/partition/docx.py Resolved
qued and others added 13 commits October 19, 2026 17:52
@qued
qued force-pushed the qued/docx-list-label-followups branch from 7d3e157 to 2536aaa Compare October 19, 2026 22:53

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 2536aaac0de09bdade1143f0529d2d68956b9a18 with GPT Pro. Four medium-severity correctness issues remain: an extraction failure during style traversal, skipped numbering for real section-ending paragraphs, incorrect parent metadata for numbered headings, and classification changes when numbering is explicitly disabled. Details and focused regression suggestions are inline.

The whitespace and drawing counter fixes address the earlier examples, but do not cover every page-fragment case. Exact-head CI reports 53 successful entries and one neutral automated-review entry, including unit and DOCX extras tests on Python 3.11–3.13. No local tests were run. GitHub still reports that an approving review is required.

(authored by codex)

Comment thread unstructured/partition/docx.py Outdated
if level:
result = self._is_heading_outline_level(level[0])
break
style = style.base_style

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Stop outline traversal safely at incompatible style parents

A directly numbered paragraph with a custom paragraph style whose w:basedOn points to an existing numbering style now aborts extraction. In supported python-docx 1.2.0, that parent is a _NumberingStyle, which has no base_style property. If neither the paragraph nor the style supplies an outline level, this assignment raises AttributeError. The numbering renderer catches the same failure, but the new heading-classification traversal does not; main previously returned a list item and continued. Ignore incompatible parent types or terminate this lookup safely. Add an end-to-end regression asserting that this paragraph and subsequent text are still extracted.

(authored by codex)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Covered: the outline traversal uses getattr(style, 'base_style', None) since cbdc7d6, and 45a2cbb applies the same to label resolution, so the paragraph keeps its label as well as being extracted (test: numbered paragraph in a style based on a numbering style).

Comment thread unstructured/partition/docx.py Outdated
A paragraph that also holds any text, drawing, object, field, break or tab is not empty.
"""
return (
bool(paragraph._p.xpath("./w:pPr/w:sectPr"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Check the original paragraph before skipping its counter

The whitespace and drawing fixes address the earlier examples, but this predicate still receives page fragments. A numbered section-ending paragraph containing an empty formatting run, then a run with w:lastRenderedPageBreak, then text produces an empty preceding fragment in python-docx 1.2.0: its break is in the second run, and the cloned fragment retains sectPr. This guard skips its counter, then seen_fragment=True prevents the text-bearing continuation from advancing it. With A, this paragraph B, then C, C becomes 2. C instead of 3. C; parent-level restart effects are skipped too. Equation-only section-ending paragraphs are also mistaken for empty markers because neither text extraction nor the content XPath recognizes m:oMath/m:oMathPara. Decide emptiness from the complete original paragraph before splitting, and advance real paragraphs exactly once. Add split/empty-leading-run, child-restart, and equation-content regressions while retaining the genuinely empty marker case.

(authored by codex)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Covered at cbdc7d6 and 45a2cbb: the label is now taken once from the original paragraph before it is split, so fragments never reach the section-break check. Regressions exist for an empty leading run before a page break, an equation-only section-ending paragraph, and (45a2cbb) a child-level restart after a split section-break paragraph. Leaving the thread open for you to confirm.


if "<w:numPr>" in paragraph._p.xml:
return True
return not self._is_numbered_heading(paragraph)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve heading depth when a numbered paragraph becomes a Title

This changes a directly numbered Heading 2 into a Title, but _parse_category_depth_by_style() still takes direct numbering ilvl before heading style. For Heading 1 followed by Heading 2 using a single-level list (ilvl=0), both Titles receive depth zero. set_element_hierarchy() therefore pops Heading 1 and gives Heading 2 no parent. Main attached the former ListItem to Heading 1; an unnumbered Heading 2 already receives depth one. Derive depth from the heading style/outline for emitted Titles, preserving list-level depth for actual list items. Cover depths, parent IDs, numbering text, and serialization for this case.

(authored by codex)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Covered at cbdc7d6 (directly numbered Heading 2 keeps depth 1 and its parent) and 45a2cbb (Heading 1 keeps depth 0 whatever its list level, with the parent id asserted). Leaving the thread open for you to confirm.

Comment thread unstructured/partition/docx.py Outdated

Its type is then left to the text heuristics, like any other numbered heading.
"""
is_numbered = "<w:numPr>" in paragraph._p.xml or self._list_labels.has_style_numbering(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Exclude disabled numbering from the list-style override

The presence of numPr is not effective numbering: numId=0 explicitly disables it. A List Paragraph containing text x, direct numId=0, and outlineLvl=0 now loses its ListItem mapping and falls through to Text. The renderer correctly emits no label and advances no counter, so classification disagrees with numbering resolution. Main preserves ListItem for this input. Resolve the effective number ID without advancing counters and exclude disabled numbering before suppressing the style mapping; a direct zero must override inherited numbering. Add a list-style/zero-ID regression alongside the existing Heading 1 zero-ID test. An empty rendered label is not a reliable predicate because bullets can still have active numbering.

(authored by codex)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Covered at cbdc7d6: the list-style override now ignores a direct numId of 0 (test: a List Paragraph with numId 0 and outlineLvl 0 stays a ListItem). Leaving the thread open for you to confirm.

…e numbering-style parents

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Re-trigger cubic

Comment thread unstructured/partition/docx.py Resolved
Comment thread unstructured/partition/docx.py Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Shadow auto-approve: would not auto-approve. Auto-approval skipped because cubic reviewed only this push, not the earlier force-push. Comment @cubic review to review the whole pull request.

View guided diff | Re-trigger cubic

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 45a2cbb11b661db6565905026f062de94865e7ef with GPT Pro. The four previously reported examples now have fixes and focused regression coverage. One P2 numbering regression remains: a section-ending paragraph with text inside an inline content control is treated as an empty section marker, so later labels and child restarts can be wrong. Details are inline.

No local tests were run. On this head, the required changelog, Python 3.12 lint, and ingest checks passed; required Python 3.12 unit and Docker checks are still running. GitHub also reports that an approving review is required. Source review and merge readiness remain separate.

(authored by codex)

Comment thread unstructured/partition/docx.py Outdated
"""
return (
bool(paragraph._p.xpath("./w:pPr/w:sectPr"))
and not _paragraph_text(paragraph)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Count section-ending paragraphs with inline content-control text

_paragraph_text() only selects direct runs/hyperlinks and certain drawing runs. For a numbered paragraph with sectPr whose visible text is under w:sdt/w:sdtContent/w:r/w:t, it returns an empty string; the nontext XPath also finds nothing. This predicate then skips the counter. In a numbered A / content-control-only section-ending B / C sequence, C becomes 2. C instead of 3. C. A parent-level B also fails to restart child counters. Main already omits the content-control text, but still advances its counter before dropping the empty extracted text, so the later numbering change is introduced here.

Establish that the original paragraph is empty independently of the extraction helper, including text inside inline wrappers. This can preserve numbering without adding content-control extraction. Add regressions for the A/B/C case and a child restart, while retaining the genuinely empty section-marker behavior.

(authored by codex)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9000032 / 84d28ea: emptiness of the section marker is now decided from any non-empty w:t anywhere in the paragraph (including content controls) plus the existing non-text content. Test: A / content-control-only section-ending B / C with a child level. Leaving the thread open for you to confirm.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Re-trigger cubic

Comment thread unstructured/partition/docx.py Resolved
…n, positional tab or non-breaking hyphen

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Shadow auto-approve: would not auto-approve. Auto-approval skipped because cubic reviewed only this push, not the earlier force-push. Comment @cubic review to review the whole pull request.

View guided diff | Re-trigger cubic

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the full change at 603eff5 with GPT Pro. The previously reported examples are repaired, including content-control text, page fragments, incompatible style parents, heading depth, and disabled numbering. One P2 counter regression remains, described inline.

This is a source review. No local tests were run. Exact-head CI is still incomplete: required unit and Dockerfile checks are running; lint, changelog, ingestion, and Socket checks have passed.

(authored by codex)

Comment thread unstructured/partition/docx.py Outdated

_CONTENT_XPATH = (
".//w:t[string-length(.) > 0] | .//w:drawing | .//w:pict | .//w:object | .//w:br | .//w:tab"
" | .//w:cr | .//w:ptab | .//w:noBreakHyphen | .//w:sym | .//w:fldChar | .//w:fldSimple"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Count section-ending paragraphs containing note references

The content check omits w:footnoteReference and w:endnoteReference. A valid numbered paragraph with sectPr whose only run content is one of these visible reference marks has no w:t, so _is_section_break_mark() treats it as empty and label() returns before advancing the counter. In an A / reference-only section-ending B / C sequence using the same numbering, C becomes 2. C instead of 3. C. A parent-level B also fails to restart child counters. Main already omits the reference text from extraction, but still counts its paragraph, so the later numbering change is introduced here.

Include both reference elements in the original-paragraph content check. Add regressions with valid footnote/endnote definitions for A/B/C and for A / child a1 / reference-only parent B / child b1, asserting the child restarts without another intervening parent. Keep the genuinely empty section marker uncounted. This fix does not require extracting note text.

(authored by codex)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6ad9fde. Rather than extend a list of content tags, the section-break check is now inverted: a paragraph is an empty marker only if it has no non-empty w:t and no element other than run/wrapper/bookmark-style containers and properties. Note and endnote references (and the fldSimple case) are covered by parametrized tests. Leaving the thread open for you to confirm.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Shadow auto-approve: would not auto-approve. Auto-approval skipped because cubic reviewed only this push, not the earlier force-push. Comment @cubic review to review the whole pull request.

View guided diff | Re-trigger cubic

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed f56b3bb39583bea7202b267d9a5200148781b462 with GPT Pro against current main. No actionable production defects remain. The prior findings are fixed, including counter advancement and child-level restarts for note-reference-only section-ending paragraphs.

Checked-in regression tests were reviewed as source; no local tests were run. On this exact head, required changelog, lint, and ingestion checks passed. Required test_unit (3.12) and test_dockerfile checks are still in progress, so this source approval does not establish merge readiness.

(authored by codex)

@qued
qued added this pull request to the merge queue Oct 20, 2026
Merged via the queue into main with commit 3f716e2 Oct 20, 2026
58 checks passed
@qued
qued deleted the qued/docx-list-label-followups branch October 20, 2026 17:34
joaquinhuigomez pushed a commit to joaquinhuigomez/unstructured that referenced this pull request Oct 20, 2026
…Unstructured-IO#4419)

## What

Partitioning and file-type detection read a `SpooledTemporaryFile`
upload in place. They no longer copy the whole document into a `BytesIO`
first.

```
Before: upload spool (disk) → BytesIO copy in detect_filetype → BytesIO copy in DOCX/PPTX/PDF/TSV/XML partitioner
After:  upload spool (disk) → read in place by both
```

Two related robustness fixes come with it, since removing the detector
copy exposes both:

| Input | Before | After |
|---|---|---|
| `detect_filetype(file=<rolled-over spool>, metadata_file_path="a.md")`
| `.name` is an int fd, so extension lookup raises `TypeError`
(previously hidden by the copy) | `.md` taken from `metadata_file_path`
|
| `convert_to_bytes(tempfile.TemporaryFile())` or any file-like wrapper
| `ValueError: Invalid file-like object type` (text-encoding detection,
PDF page rendering) | bytes, stream rewound |

A spool passed to `detect_filetype()` still comes back at position 0, as
before.

## Why

Python 3.11+ (this package's minimum) gives `SpooledTemporaryFile` the
full buffered-I/O interface that `zipfile`, `pandas` and the detectors
need. The `BytesIO` copies were a <3.11 workaround, and each one is an
extra heap allocation the size of the document. Fixing it here also
removes the need for API callers to wrap uploads in proxy objects to
avoid the copy.

## Release

Targets **0.27.32** (0.27.31 was taken by Unstructured-IO#4538, which merged first.)
Released together with Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517, Unstructured-IO#4524, Unstructured-IO#4523, Unstructured-IO#4562 (XLSX
workbook reader) and Unstructured-IO#4563 (dense worksheets). Each PR takes the next
`0.27.32-devN` in that merge order (0.27.32-dev0 here); whichever merges
after another rebases and renumbers the CHANGELOG heading, as usual for
this repo.

## Impact

Partitioning a large DOCX upload: peak memory drops by roughly the size
of the document (the removed copy), with no change in latency.

## Validation

- New regression tests for in-place detection (in-memory and rolled-over
spools), the non-string-name fallback, and `convert_to_bytes` on generic
streams. All fail without this change.
- Before/after comparison over `file_utils`, `partition/common`, DOCX,
PPTX, text, XML, TSV, MD, HTML and auto suites: no new failures. The one
existing test that read the detection context after closing the spool
now asserts inside the `with` block.
- Files named by a `bytes` path or a path object, text or binary, are
still re-read from their path, so their cursor is untouched; a text file
opened on a bare descriptor is read as bytes through its binary buffer
(regression tests for each).
- Non-seekable streams (a pipe or subprocess stdout, binary or text) are
read once instead of failing on a rewind (regression tests for both
modes).
- Ruff check/format pass.
joaquinhuigomez pushed a commit to joaquinhuigomez/unstructured that referenced this pull request Oct 20, 2026
…#4516)

## Summary

OCR-only PDF partitioning kept ten decoded page images in memory at
once, and the OCR step copied the whole upload into one byte string for
the entire OCR run. This PR renders one page at a time, copies uploads
to temporary disk in 1 MiB blocks, and closes each rendered page image
after OCR, including when OCR fails. Pixels, format, rotation metadata,
page order, upload cursor behavior and caller-owned stream lifetime are
preserved. Uploads may be any readable, seekable stream (duck-typed
`read`/`seek`), not only `BytesIO`, `SpooledTemporaryFile` or buffered
files.


## Validation

- New ownership, bounded-read, generator cancellation, OCR cleanup,
native render parity and generic-stream tests pass locally; the original
13 also passed in an isolated Linux container.
- Full PDF/OCR/utilities and new regression suite pass locally (with
Korean OCR data installed).
- OCR-only partitioning of rotated and content-bearing multi-page
fixtures in a Linux container: every element matches the baseline JSON
hashes exactly.
- Large synthetic OCR-only PDF in a memory-limited Linux container:
`main` runs out of memory where this branch completes at the same limit.
With enough memory for both, peak RSS drops to under a third, runtime is
unchanged and output hashes match.
- Uploads opened through a `bytes` path are re-read from that path,
leaving the caller's cursor untouched (regression test for text and
binary modes).
- Repository Ruff checks/format and the Linux version-sync checker pass.

## Operational impact

OCR rendering reads uploads from temporary disk instead of holding a
full upload-sized copy in memory. Spooled uploads
(`SpooledTemporaryFile`) are still copied in full, briefly, by
`spooled_to_bytes_io_if_needed` for the text-extraction check before the
OCR branch; the saving is that this copy is not held while OCR runs.
There is no new upload size cap. Working render memory is bounded by one
page; extracted output and memory retained by callers still scale with
content. Public render-generator images remain usable after iteration
and are owned by the caller.

## Follow-up

`_pdf_source_path` and `convert_to_bytes` (Unstructured-IO#4419) both decide how to
read a given upload type. Once Unstructured-IO#4419 lands, both should use one shared
helper in `unstructured/partition/common/common.py` that copies a stream
to disk in blocks.

## Release

Targets **0.27.32** (0.27.31 was taken by Unstructured-IO#4538, which merged first.)
Released together with Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517, Unstructured-IO#4524, Unstructured-IO#4523, Unstructured-IO#4562 (XLSX
workbook reader) and Unstructured-IO#4563 (dense worksheets). Each PR takes the next
`0.27.32-devN` in that merge order (0.27.32-dev1 here); whichever merges
after another rebases and renumbers the CHANGELOG heading, as usual for
this repo.
joaquinhuigomez pushed a commit to joaquinhuigomez/unstructured that referenced this pull request Oct 20, 2026
…n memory (Unstructured-IO#4517)

## Summary

A stream of empty images can hold every base64 payload until a later
text element even when `include_orig_elements=False` and those image
fields are dropped from output. Fold metadata incrementally for
contiguous empty-image runs and release excluded image payloads
immediately, preserving metadata order and chunk boundaries.

Original-element serialization now adjusts and encodes one element at a
time, escapes large JSON strings in bounded fragments (values without
large strings still use one standard `json.dumps` call), and spills
compressed buffers above 1 MiB to temporary disk. Avoid the redundant
deep copy of the whole original-element graph in
`ElementMetadata.to_dict()`.


## Validation

- Chunking, original-element staging and element suites pass locally;
the new regression cases also pass in an isolated Linux container.
- 120 mixed-image/text/title/table/page-break cases with overlap
preserve chunk boundaries and metadata against the identity-preserving
path. Original Image identity remains intact with the default
`include_orig_elements=True`.
- Exact legacy JSON field order is preserved, including continuation
metadata and empty originals.
- Exact legacy compressed bytes match for empty inputs, multiple
elements, long Unicode/control-character strings, metadata precision and
sorted JSON keys on the same zlib implementation.
- Many streamed large image payloads in a Linux container: chunking peak
RSS drops to under a quarter and runs faster; serialization peak RSS
drops by roughly an order of magnitude with slightly lower runtime.
Output hashes match exactly.
- Under a constrained container memory limit, both `main` cases run out
of memory; both cases on this branch complete with no OOM events.
- Metadata nested as deeply as the standard JSON encoder accepts still
serializes: the large-string scan is iterative, not recursive
(regression test with 600 nested lists).
- Repository Ruff checks/format and the Linux version-sync checker pass.

## Operational impact

Compressed original-element buffers above 1 MiB use temporary disk.
Final serialized output and metadata actually included in chunks still
require memory proportional to output. `include_orig_elements=True`
continues retaining original objects; changing that identity contract
would require a separate API decision.

## Release

Targets **0.27.32** (0.27.31 was taken by Unstructured-IO#4538, which merged first.)
Released together with Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517, Unstructured-IO#4524, Unstructured-IO#4523, Unstructured-IO#4562 (XLSX
workbook reader) and Unstructured-IO#4563 (dense worksheets). Each PR takes the next
`0.27.32-devN` in that merge order (0.27.32-dev2 here); whichever merges
after another rebases and renumbers the CHANGELOG heading, as usual for
this repo.
linhongyu510 pushed a commit to linhongyu510/unstructured that referenced this pull request Oct 21, 2026
…tructured-IO#4562)

## What

Adds a public way to read a workbook one worksheet at a time with the
same protections `partition_xlsx()` uses:

```python
from unstructured.partition.xlsx import open_excel_workbook

with open_excel_workbook(file_bytes, compact_empty_rows=True) as workbook:
    for name in workbook.sheet_names:
        frame = workbook.parse(name, header=None)
        ...  # release `frame` before parsing the next sheet
```

`open_excel_workbook()`:
- rejects non-Office and password-protected files with
`UnprocessableEntityError`, as `partition_xlsx()` does;
- picks the engine from the file signature (`openpyxl` for XLSX, `xlrd`
for XLS) and rejects anything else with `UnprocessableEntityError`;
- runs the existing `XLSX_MAX_CELLS` worksheet cell-count check before
any worksheet is read;
- optionally reads with runs of empty rows compacted (XLSX only), as
subtable detection already does;
- closes the reader when the block exits, including on errors.

`partition_xlsx()` now reads through the same function, so its behavior
is unchanged.

## Why

Integrations that need their own per-worksheet processing currently have
two options: call `pandas.read_excel` directly, which skips the
cell-count limit and reads every sheet into memory at once, or import
private helpers (`_check_worksheet_cell_count`,
`_RowCompactingOpenpyxlReader`) that can change without notice. A tiny
file with one far-away cell can still expand into a huge dense
data-frame through the first route. This gives such callers a supported,
guarded entry point.

## Validation

- New `test_xlsx_reader.py`: engine selection, password-protected
rejection, cell-limit enforcement before reading (independent of the
ambient `XLSX_MAX_CELLS`), empty-row compaction, repeated worksheet
reads, and reader cleanup on success and on a consumer error.
- XLSX partitioner suite passes unchanged; baseline-vs-branch workbook
comparisons produce identical elements.
- Ruff check/format pass.

## Release

Targets **0.27.32** as `0.27.32-dev5` (0.27.31 was taken by Unstructured-IO#4538, which
merged first.) Released together with Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517, Unstructured-IO#4524 and
Unstructured-IO#4523, and followed by the stacked dense-worksheet PR. Whichever merges
after another rebases and renumbers the CHANGELOG heading, as usual for
this repo.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4562?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
linhongyu510 pushed a commit to linhongyu510/unstructured that referenced this pull request Oct 21, 2026
…IO#4563)

## What

`partition_xlsx()` with subtable detection (the default) needs
substantially less memory on dense worksheets, and the saving grows with
sheet size. Output is unchanged.

On synthetic dense sheets (a ten-column sheet split into three dense
subtables, half integers, half short Unicode strings), peak RSS in a
fresh process drops by roughly 40–60% depending on size, with comparable
runtime. Working memory per populated cell drops to roughly a third.
Serialized element JSON is byte-identical before and after.

## Why

Two whole-sheet intermediates dominated memory on dense sheets:

1. **Subtable detection built a NetworkX graph** with a node per
populated cell and an edge per neighbor pair. It now uses an iterative
four-neighbor flood fill over populated cells (the approach from Unstructured-IO#4357),
with the same component admission order, cell membership, row-overlap
merging, table order and bounding boxes.
2. **Table HTML was rendered for the whole table at once** (pandas
`to_html` string, its parsed DOM and a full-table token list). Rows are
now formatted by pandas' formatter for the whole column, so
float/date/string formatting is unchanged, and each row is rendered and
parsed on its own before the next.

`networkx` is no longer needed at runtime by the XLSX partitioner, so it
moves from the `xlsx` extra to the test dependencies (it's still used by
other extras that depend on it).

## Behavior

- Same elements, text, `text_as_html` and metadata; exact-output tests
cover mixed types, NaN/empty cells, wide floats that switch to
scientific notation in another row, dates and HTML escaping.
- The renderer uses pandas' private formatter classes, as the existing
reader already does for `OpenpyxlReader`. Verified on pandas 2.1.4
(renderer-parity comparisons), 2.2.3 and 2.3.3.
- The worksheet cell limit, empty-row compaction, empty-sheet handling
and XLS padding handling are unchanged.

## Validation

- XLSX and dense-memory suites pass. New tests compare component
detection and rendered HTML against the previous implementation on
generated sheets.
- Ruff check/format pass.

## Release

Sets the release to **0.27.32** (0.27.31 was taken by Unstructured-IO#4538, which
merged first). It merges after Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517 and Unstructured-IO#4562, and its
CHANGELOG collects their entries and this one into a single 0.27.32
section. Unstructured-IO#4524 and Unstructured-IO#4523 are not included and will go into a later
release.

Supersedes Unstructured-IO#4357.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4563?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
L4XB added a commit to L4XB/unstructured that referenced this pull request Oct 21, 2026
Version 0.27.34 with this branch's changelog section on top. Unstructured-IO#4538's
test_partition_docx_counts_a_section_break_paragraph_whose_text_is_in_a_content_control
expected the content control's text to stay unread; with the content
control read, that paragraph is numbered and shown, so it expects
'2. b' between '1. a' and '3. c'.
feiiiiii5 pushed a commit to feiiiiii5/unstructured that referenced this pull request Oct 21, 2026
…structured-IO#4524)

## Summary

Restoring `orig_elements` now releases each intermediate buffer before
the next stage builds its own copy. Previously the compressed bytes,
decompressed bytes and JSON text all stayed alive until the end.

Restoring one element that carries a very large image payload:
- Peak memory drops by roughly a quarter.
- Under a constrained memory limit, `main` runs out of memory and this
branch completes.
- Restored elements are identical.

## Behavior

- Unchanged:
  - the Base64, zlib, UTF-8, JSON and element constructors;
  - restored values, metadata order and error behavior;
  - the existing 200 MiB decompressed-byte cap.
- No new cap is added. The existing cap bounds UTF-8 bytes, not Python
string size, so wide-Unicode JSON can still grow in memory. The full
element graph is still returned.
- This removes avoidable overlap between buffers. It does not guarantee
that every input fits a fixed memory budget.

## Validation

- Staging tests pass. New regression tests cover Unicode, nested
originals, metadata and order, malformed input, trailing data and the
exact size boundary.
- A `tracemalloc` test checks that `json.loads` and element construction
each start with only their own input alive. Removing any one of the
three releases fails it.
- The new tests also pass in an isolated Linux container against the
module from this commit (import path and SHA256 verified).
- Included benchmark: one element with a very large BMP stored as a
Base64 payload.
- Under a constrained memory limit, `main` runs out of memory. This
branch completes with identical metadata, text and payload hash.
- With enough memory for both, peak RSS falls as above; decode time is
essentially unchanged.
- Escaped wide-Unicode text and raw UTF-8 mixed with the image payload
also restore identically, with a similar peak-memory reduction.
- Ruff, diff checks and the version checker pass.

## Release

Targets **0.27.32** (0.27.31 was taken by Unstructured-IO#4538, which merged first.)
Released together with Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517, Unstructured-IO#4524, Unstructured-IO#4523, Unstructured-IO#4562 (XLSX
workbook reader) and Unstructured-IO#4563 (dense worksheets). Each PR takes the next
`0.27.32-devN` in that merge order (0.27.32-dev3 here); whichever merges
after another rebases and renumbers the CHANGELOG heading, as usual for
this repo.

Unstructured-IO#4517 changes the serializing side of `orig_elements` in the same
module. A test merge with this branch conflicts only on version and
changelog lines, passes the staging, element and chunking suites, and
round-trips identical elements.
linhongyu510 pushed a commit to linhongyu510/unstructured that referenced this pull request Oct 21, 2026
…d-IO#4523)

## Summary

Image and PDF figure extraction now frees each decoded page, crop and
JPEG buffer as soon as it is no longer needed. Image uploads are copied
to the temporary file in 1 MiB blocks instead of being held in memory
whole.

Extracting full-page figures from a very large synthetic image:
- Peak memory drops by roughly 40%.
- Under a constrained memory limit, `main` runs out of memory and this
branch completes.
- Output is byte-identical.

## What changed

- Uploads are copied to the existing temporary file in 1 MiB blocks.
- Decoded pages, RGBA intermediates, output crops and JPEG buffers are
closed as soon as their pixels or bytes are used.

## Behavior

- Unchanged: JPEG bytes, Base64 payloads, saved filenames, element
order, metadata and padding. Caller-owned streams keep the same
rewind/EOF behavior.
- No size cap or disk policy is added; image uploads already used the
same temporary file.
- Output payloads, and the current page plus its crop, can still be
large.

## Validation

- Extraction/utility tests pass. They include:
- exact JPEG bytes for RGB, RGBA and grayscale, in both payload and
saved-file output;
  - bounded upload reads;
  - caller stream ownership and EOF;
  - multi-crop cleanup after an encoder failure.
- The new regression tests also pass in an isolated Linux container
against the module from this commit (import path and SHA256 verified).
- Included benchmark
(`scripts/performance/benchmark_image_extraction_memory.py`): full-page
figures from a deterministic very-high-resolution image.
- Under a constrained memory limit, `main` runs out of memory and this
branch completes.
  - A healthy `main` run produces the same metadata and payload hash.
- With enough memory for both, peak RSS falls as above and extraction is
slightly faster.
- This measures the extraction stage, not end-to-end partition latency.
- Full native PDF/image suite passes. Ruff, diff checks and the version
checker pass.

## Release

Targets **0.27.32** (0.27.31 was taken by Unstructured-IO#4538, which merged first.)
Released together with Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517, Unstructured-IO#4524, Unstructured-IO#4523, Unstructured-IO#4562 (XLSX
workbook reader) and Unstructured-IO#4563 (dense worksheets). Each PR takes the next
`0.27.32-devN` in that merge order (0.27.32-dev4 here); whichever merges
after another rebases and renumbers the CHANGELOG heading, as usual for
this repo.

Unstructured-IO#4516 also edits `pdf_image_utils.py`, but a different function.
Downstream dependency bumps need the published release.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants