Skip to content

Commit 2e844af

Browse files
badGarnetclaude
andcommitted
feat(pptx): client-side slide splitting for hi_res PPTX
Mirror the existing client-side PDF page-splitting for PPTX decks. When split_pdf_page=true and strategy=hi_res and the upload is a .pptx, the deck is split into slide-chunks that are partitioned in parallel and recombined, parallelizing the expensive per-slide hi_res work and avoiding large-payload timeouts. - New stdlib-only pptx_utils (zipfile + xml), no new dependency: is_pptx, get_pptx_slide_count, and in-memory/cache-to-disk chunk builders. Each chunk is a minimal valid .pptx keeping shared parts (masters/layouts/themes/notes master/media) and only the chunk's slides plus the notes slides they reference; presentation.xml, its rels, and [Content_Types].xml are rewritten so nothing dangles. - request_utils: generalize create_pdf_chunk_request into create_document_chunk_request(content_type); PDF path is a thin wrapper. - split_pdf_hook: one new branch reusing all shared machinery (sizing, concurrency, caching, retries, recombination). PDF behavior unchanged; legacy .ppt and non-hi_res requests fall through unsplit. - Reuses the existing split_pdf_page flag (no new API field). Verified: 233 unit tests pass (19 new), clean mypy. python-pptx opens the synthesized 1000-slide deck and every chunk with exact slide/notes counts. Live (stage): 1000 slides -> 50 parallel chunks -> contiguous pages 1..1000. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 7ab4de9 commit 2e844af

4 files changed

Lines changed: 873 additions & 59 deletions

File tree

Lines changed: 398 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,398 @@
1+
from __future__ import annotations
2+
3+
import io
4+
import math
5+
import zipfile
6+
from pathlib import Path
7+
from typing import Iterable, Optional
8+
from unittest.mock import patch
9+
10+
import httpx
11+
import pytest
12+
13+
from unstructured_client._hooks.custom import pptx_utils
14+
from unstructured_client._hooks.custom.split_pdf_hook import (
15+
DEFAULT_CONCURRENCY_LEVEL,
16+
HI_RES_STRATEGY,
17+
SplitPdfHook,
18+
get_optimal_split_size,
19+
)
20+
from unstructured_client._hooks.types import BeforeRequestContext
21+
22+
23+
# ---------------------------------------------------------------------------
24+
# Synthetic .pptx builder
25+
#
26+
# The splitter only reads the OOXML package structure (presentation.xml,
27+
# its rels, the per-slide rels, and [Content_Types].xml) — it never parses
28+
# slide *content*. So a structurally-faithful package with placeholder XML
29+
# bodies is enough to exercise every code path hermetically, without depending
30+
# on a real PowerPoint file checked into the repo.
31+
# ---------------------------------------------------------------------------
32+
33+
_REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
34+
35+
36+
def build_synthetic_pptx(
37+
num_slides: int,
38+
notes_for: Optional[Iterable[int]] = None,
39+
rels_overrides: bool = False,
40+
) -> bytes:
41+
"""Build a minimal but structurally valid .pptx with ``num_slides`` slides.
42+
43+
Args:
44+
num_slides: Number of slides to create.
45+
notes_for: 1-based slide numbers that should reference a notes slide.
46+
rels_overrides: If True, declare a ``<Override>`` content-type for every
47+
``.rels`` part too (mirroring decks that don't rely solely on the
48+
``<Default Extension="rels">`` rule). Exercises the override pruning.
49+
"""
50+
notes = set(notes_for or ())
51+
parts: dict[str, bytes] = {}
52+
53+
# Shared parts.
54+
parts["_rels/.rels"] = (
55+
f'<?xml version="1.0"?><Relationships xmlns="{_REL_NS.replace("officeDocument/2006", "package/2006")}">'
56+
f'<Relationship Id="rId1" Type="{_REL_NS}/officeDocument" Target="ppt/presentation.xml"/>'
57+
"</Relationships>"
58+
).encode()
59+
parts["ppt/theme/theme1.xml"] = b"<theme/>"
60+
parts["ppt/media/image1.png"] = b"\x89PNG\r\n\x1a\nshared-image"
61+
parts["ppt/slideMasters/slideMaster1.xml"] = b"<sldMaster/>"
62+
parts["ppt/slideMasters/_rels/slideMaster1.xml.rels"] = (
63+
f'<Relationships xmlns="{_REL_NS.replace("officeDocument/2006", "package/2006")}">'
64+
f'<Relationship Id="rId1" Type="{_REL_NS}/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>'
65+
f'<Relationship Id="rId2" Type="{_REL_NS}/theme" Target="../theme/theme1.xml"/>'
66+
"</Relationships>"
67+
).encode()
68+
parts["ppt/slideLayouts/slideLayout1.xml"] = b"<sldLayout/>"
69+
parts["ppt/slideLayouts/_rels/slideLayout1.xml.rels"] = (
70+
f'<Relationships xmlns="{_REL_NS.replace("officeDocument/2006", "package/2006")}">'
71+
f'<Relationship Id="rId1" Type="{_REL_NS}/slideMaster" Target="../slideMasters/slideMaster1.xml"/>'
72+
"</Relationships>"
73+
).encode()
74+
parts["ppt/notesMasters/notesMaster1.xml"] = b"<notesMaster/>"
75+
76+
# Slides + their rels (+ optional notes).
77+
for n in range(1, num_slides + 1):
78+
parts[f"ppt/slides/slide{n}.xml"] = f"<sld n='{n}'/>".encode()
79+
slide_rels = [
80+
f'<Relationship Id="rId1" Type="{_REL_NS}/slideLayout" '
81+
'Target="../slideLayouts/slideLayout1.xml"/>',
82+
f'<Relationship Id="rId2" Type="{_REL_NS}/image" '
83+
'Target="../media/image1.png"/>',
84+
]
85+
if n in notes:
86+
slide_rels.append(
87+
f'<Relationship Id="rId3" Type="{_REL_NS}/notesSlide" '
88+
f'Target="../notesSlides/notesSlide{n}.xml"/>'
89+
)
90+
parts[f"ppt/notesSlides/notesSlide{n}.xml"] = f"<notes n='{n}'/>".encode()
91+
parts[f"ppt/notesSlides/_rels/notesSlide{n}.xml.rels"] = (
92+
f'<Relationships xmlns="{_REL_NS.replace("officeDocument/2006", "package/2006")}">'
93+
f'<Relationship Id="rId1" Type="{_REL_NS}/notesMaster" '
94+
'Target="../notesMasters/notesMaster1.xml"/>'
95+
f'<Relationship Id="rId2" Type="{_REL_NS}/slide" '
96+
f'Target="../slides/slide{n}.xml"/>'
97+
"</Relationships>"
98+
).encode()
99+
parts[f"ppt/slides/_rels/slide{n}.xml.rels"] = (
100+
f'<Relationships xmlns="{_REL_NS.replace("officeDocument/2006", "package/2006")}">'
101+
+ "".join(slide_rels)
102+
+ "</Relationships>"
103+
).encode()
104+
105+
# presentation.xml: master id list + slide id list (rId14.. for slides).
106+
sld_ids = "".join(
107+
f'<p:sldId id="{255 + n}" r:id="rId{13 + n}"/>' for n in range(1, num_slides + 1)
108+
)
109+
parts["ppt/presentation.xml"] = (
110+
'<?xml version="1.0"?>'
111+
'<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" '
112+
f'xmlns:r="{_REL_NS}">'
113+
'<p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId2"/></p:sldMasterIdLst>'
114+
f"<p:sldIdLst>{sld_ids}</p:sldIdLst>"
115+
'<p:sldSz cx="9144000" cy="6858000"/>'
116+
"</p:presentation>"
117+
).encode()
118+
119+
pres_rels = [
120+
f'<Relationship Id="rId1" Type="{_REL_NS}/theme" Target="theme/theme1.xml"/>',
121+
f'<Relationship Id="rId2" Type="{_REL_NS}/slideMaster" Target="slideMasters/slideMaster1.xml"/>',
122+
f'<Relationship Id="rId3" Type="{_REL_NS}/notesMaster" Target="notesMasters/notesMaster1.xml"/>',
123+
]
124+
for n in range(1, num_slides + 1):
125+
pres_rels.append(
126+
f'<Relationship Id="rId{13 + n}" Type="{_REL_NS}/slide" '
127+
f'Target="slides/slide{n}.xml"/>'
128+
)
129+
parts["ppt/_rels/presentation.xml.rels"] = (
130+
f'<Relationships xmlns="{_REL_NS.replace("officeDocument/2006", "package/2006")}">'
131+
+ "".join(pres_rels)
132+
+ "</Relationships>"
133+
).encode()
134+
135+
# [Content_Types].xml
136+
overrides = [
137+
'<Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/>',
138+
'<Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"/>',
139+
'<Override PartName="/ppt/slideLayouts/slideLayout1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/>',
140+
'<Override PartName="/ppt/notesMasters/notesMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"/>',
141+
]
142+
for n in range(1, num_slides + 1):
143+
overrides.append(
144+
f'<Override PartName="/ppt/slides/slide{n}.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>'
145+
)
146+
if rels_overrides:
147+
overrides.append(
148+
f'<Override PartName="/ppt/slides/_rels/slide{n}.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
149+
)
150+
if n in notes:
151+
overrides.append(
152+
f'<Override PartName="/ppt/notesSlides/notesSlide{n}.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"/>'
153+
)
154+
parts["[Content_Types].xml"] = (
155+
'<?xml version="1.0"?>'
156+
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
157+
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
158+
'<Default Extension="xml" ContentType="application/xml"/>'
159+
'<Default Extension="png" ContentType="image/png"/>'
160+
+ "".join(overrides)
161+
+ "</Types>"
162+
).encode()
163+
164+
buffer = io.BytesIO()
165+
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as out:
166+
# [Content_Types].xml must be first per OPC convention.
167+
out.writestr("[Content_Types].xml", parts.pop("[Content_Types].xml"))
168+
for name, data in parts.items():
169+
out.writestr(name, data)
170+
return buffer.getvalue()
171+
172+
173+
def _names(chunk: bytes) -> set[str]:
174+
with zipfile.ZipFile(io.BytesIO(chunk)) as z:
175+
return set(z.namelist())
176+
177+
178+
def _override_partnames(chunk: bytes) -> list[str]:
179+
import re
180+
181+
with zipfile.ZipFile(io.BytesIO(chunk)) as z:
182+
ct = z.read("[Content_Types].xml").decode()
183+
return [p.lstrip("/") for p in re.findall(r'<Override PartName="([^"]+)"', ct)]
184+
185+
186+
# ---------------------------------------------------------------------------
187+
# Detection / counting
188+
# ---------------------------------------------------------------------------
189+
190+
191+
def test_is_pptx_true_for_pptx():
192+
assert pptx_utils.is_pptx(build_synthetic_pptx(3)) is True
193+
194+
195+
def test_is_pptx_false_for_non_zip():
196+
assert pptx_utils.is_pptx(b"%PDF-1.7 not a zip") is False
197+
198+
199+
def test_is_pptx_false_for_zip_without_presentation():
200+
buf = io.BytesIO()
201+
with zipfile.ZipFile(buf, "w") as z:
202+
z.writestr("word/document.xml", b"<doc/>")
203+
assert pptx_utils.is_pptx(buf.getvalue()) is False
204+
205+
206+
def test_is_pptx_accepts_binaryio():
207+
stream = io.BytesIO(build_synthetic_pptx(2))
208+
assert pptx_utils.is_pptx(stream) is True
209+
210+
211+
def test_get_pptx_slide_count():
212+
assert pptx_utils.get_pptx_slide_count(build_synthetic_pptx(7)) == 7
213+
214+
215+
# ---------------------------------------------------------------------------
216+
# Chunking
217+
# ---------------------------------------------------------------------------
218+
219+
220+
@pytest.mark.parametrize(
221+
("num_slides", "split_size"),
222+
[(10, 3), (10, 5), (1, 2), (20, 20), (368, 20)],
223+
)
224+
def test_chunk_count_and_slide_totals(num_slides, split_size):
225+
content = build_synthetic_pptx(num_slides)
226+
chunks = pptx_utils.get_pptx_chunks_in_memory(content, split_size=split_size)
227+
228+
assert len(chunks) == math.ceil(num_slides / split_size)
229+
230+
total = 0
231+
for index, (buf, offset) in enumerate(chunks):
232+
chunk_bytes = buf.getvalue()
233+
count = pptx_utils.get_pptx_slide_count(chunk_bytes)
234+
expected = min(split_size, num_slides - index * split_size)
235+
assert count == expected
236+
assert offset == index * split_size
237+
total += count
238+
assert total == num_slides
239+
240+
241+
def test_chunks_are_valid_zip_with_no_dangling_overrides():
242+
content = build_synthetic_pptx(10, rels_overrides=True)
243+
chunks = pptx_utils.get_pptx_chunks_in_memory(content, split_size=4)
244+
245+
for buf, _ in chunks:
246+
chunk_bytes = buf.getvalue()
247+
names = _names(chunk_bytes)
248+
# Every content-type Override must point at a part that exists.
249+
for partname in _override_partnames(chunk_bytes):
250+
assert partname in names, f"dangling override: {partname}"
251+
252+
253+
def test_chunks_retain_shared_parts_and_drop_other_slides():
254+
content = build_synthetic_pptx(10)
255+
chunks = pptx_utils.get_pptx_chunks_in_memory(content, split_size=4)
256+
257+
first = chunks[0][0].getvalue()
258+
names = _names(first)
259+
# Shared parts retained.
260+
for shared_part in (
261+
"ppt/slideMasters/slideMaster1.xml",
262+
"ppt/slideLayouts/slideLayout1.xml",
263+
"ppt/theme/theme1.xml",
264+
"ppt/media/image1.png",
265+
"ppt/notesMasters/notesMaster1.xml",
266+
):
267+
assert shared_part in names
268+
# Only this chunk's slides (1-4) are present.
269+
assert "ppt/slides/slide1.xml" in names
270+
assert "ppt/slides/slide4.xml" in names
271+
assert "ppt/slides/slide5.xml" not in names
272+
assert "ppt/slides/_rels/slide5.xml.rels" not in names
273+
274+
275+
def test_notes_slides_follow_their_slides():
276+
# Slides 2 and 9 have notes.
277+
content = build_synthetic_pptx(10, notes_for={2, 9})
278+
chunks = pptx_utils.get_pptx_chunks_in_memory(content, split_size=4)
279+
280+
# Chunk 0 = slides 1-4 -> keeps notesSlide2, drops notesSlide9.
281+
chunk0 = _names(chunks[0][0].getvalue())
282+
assert "ppt/notesSlides/notesSlide2.xml" in chunk0
283+
assert "ppt/notesSlides/notesSlide9.xml" not in chunk0
284+
285+
# Chunk 2 = slides 9-10 -> keeps notesSlide9, not notesSlide2.
286+
chunk2 = _names(chunks[2][0].getvalue())
287+
assert "ppt/notesSlides/notesSlide9.xml" in chunk2
288+
assert "ppt/notesSlides/notesSlide2.xml" not in chunk2
289+
290+
291+
def test_page_range_subsetting():
292+
content = build_synthetic_pptx(10)
293+
chunks = pptx_utils.get_pptx_chunks_in_memory(
294+
content, split_size=2, page_start=3, page_end=6
295+
)
296+
# Slides 3..6 inclusive -> 4 slides, 2 chunks of 2.
297+
assert len(chunks) == 2
298+
assert [offset for _, offset in chunks] == [2, 4]
299+
assert sum(pptx_utils.get_pptx_slide_count(b.getvalue()) for b, _ in chunks) == 4
300+
301+
302+
def test_chunk_paths_writes_files(tmp_path):
303+
content = build_synthetic_pptx(7)
304+
tempdir, chunk_paths = pptx_utils.get_pptx_chunk_paths(
305+
content, cache_tmp_data_dir=str(tmp_path), split_size=3
306+
)
307+
try:
308+
assert len(chunk_paths) == 3
309+
for path, _offset in chunk_paths:
310+
assert Path(path).exists()
311+
assert pptx_utils.is_pptx(Path(path).read_bytes())
312+
finally:
313+
tempdir.cleanup()
314+
315+
316+
# ---------------------------------------------------------------------------
317+
# Hook gating
318+
# ---------------------------------------------------------------------------
319+
320+
321+
def _make_ctx() -> BeforeRequestContext:
322+
class _Config:
323+
timeout_ms = None
324+
retry_config = None
325+
326+
ctx = BeforeRequestContext.__new__(BeforeRequestContext)
327+
ctx.operation_id = "partition"
328+
ctx.config = _Config()
329+
return ctx
330+
331+
332+
def _run_before_request(strategy: str, split_pdf_page: str, num_slides: int = 30):
333+
hook = SplitPdfHook()
334+
hook.client = httpx.Client()
335+
content = build_synthetic_pptx(num_slides)
336+
form_data = {
337+
"files": {
338+
"filename": "deck.pptx",
339+
"content_type": pptx_utils.PPTX_CONTENT_TYPE,
340+
"file": io.BytesIO(content),
341+
},
342+
"split_pdf_page": split_pdf_page,
343+
"strategy": strategy,
344+
}
345+
request = httpx.Request(
346+
"POST",
347+
"http://localhost:8000/general/v0/general",
348+
headers={"Content-Type": "multipart/form-data; boundary=b"},
349+
)
350+
with patch(
351+
"unstructured_client._hooks.custom.split_pdf_hook.request_utils.get_multipart_stream_fields",
352+
return_value=form_data,
353+
):
354+
result = hook.before_request(_make_ctx(), request)
355+
return hook, result
356+
357+
358+
def _is_split(result) -> bool:
359+
return isinstance(result, httpx.Request) and result.url.path.endswith("/general/docs")
360+
361+
362+
def test_hook_splits_pptx_for_hi_res():
363+
num_slides = 30
364+
hook, result = _run_before_request(HI_RES_STRATEGY, "true", num_slides=num_slides)
365+
assert _is_split(result)
366+
operation_id = result.headers["operation_id"]
367+
coros = hook.coroutines_to_execute[operation_id]
368+
369+
# The hook reuses the PDF default split sizing.
370+
split_size = get_optimal_split_size(num_slides, DEFAULT_CONCURRENCY_LEVEL)
371+
assert len(coros) == math.ceil(num_slides / split_size)
372+
# Page numbers continue contiguously across chunks, starting at 1.
373+
page_numbers = [c.keywords["page_number"] for c in coros]
374+
assert page_numbers == list(range(1, num_slides + 1, split_size))
375+
hook._clear_operation(operation_id)
376+
377+
378+
def test_hook_does_not_split_pptx_for_fast():
379+
_hook, result = _run_before_request("fast", "true")
380+
assert not _is_split(result)
381+
382+
383+
def test_hook_does_not_split_pptx_when_flag_false():
384+
_hook, result = _run_before_request(HI_RES_STRATEGY, "false")
385+
assert not _is_split(result)
386+
387+
388+
def test_hook_chunk_request_uses_pptx_content_type():
389+
hook, result = _run_before_request(HI_RES_STRATEGY, "true", num_slides=30)
390+
operation_id = result.headers["operation_id"]
391+
chunk_request = hook.coroutines_to_execute[operation_id][0].keywords[
392+
"pdf_chunk_request"
393+
]
394+
body = chunk_request.read().decode("latin1")
395+
assert pptx_utils.PPTX_CONTENT_TYPE in body
396+
assert "deck.pptx" in body
397+
assert 'name="split_pdf_page"' in body
398+
hook._clear_operation(operation_id)

0 commit comments

Comments
 (0)