-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathtest_integration.py
More file actions
341 lines (291 loc) · 10.1 KB
/
test_integration.py
File metadata and controls
341 lines (291 loc) · 10.1 KB
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
from __future__ import annotations
import asyncio
import json
import os
from pathlib import Path
import pytest
from deepdiff import DeepDiff
from unstructured_client import UnstructuredClient
from unstructured_client.models import shared, operations
from unstructured_client.models.errors import SDKError, ServerError, HTTPValidationError
from unstructured_client.utils.retries import BackoffStrategy, RetryConfig
@pytest.fixture(scope="module")
def client() -> UnstructuredClient:
_client = UnstructuredClient(api_key_auth=os.getenv("UNSTRUCTURED_API_KEY"))
yield _client
@pytest.fixture(scope="module")
def doc_path() -> Path:
return Path(__file__).resolve().parents[2] / "_sample_docs"
@pytest.mark.parametrize("split_pdf", [True, False])
@pytest.mark.parametrize("strategy", ["fast", "ocr_only", "hi_res"])
def test_partition_strategies(split_pdf, strategy, client, doc_path):
filename = "layout-parser-paper-fast.pdf"
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
req = operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy=strategy,
languages=["eng"],
split_pdf_page=split_pdf,
)
)
response = client.general.partition(
request=req
)
assert response.status_code == 200
assert len(response.elements)
@pytest.mark.parametrize("split_pdf", [True, False])
@pytest.mark.parametrize("error", [(500, ServerError), (403, SDKError), (422, HTTPValidationError)])
def test_partition_handling_server_error(error, split_pdf, monkeypatch, doc_path):
"""
Mock different error responses, assert that the client throws the correct error
"""
filename = "layout-parser-paper-fast.pdf"
import httpx
error_code, sdk_raises = error
# Create the mock response
json_data = {"detail": "An error occurred"}
response = httpx.Response(
status_code=error_code,
headers={'Content-Type': 'application/json'},
content=json.dumps(json_data),
request=httpx.Request("POST", "http://mock-request"),
)
monkeypatch.setattr(httpx.AsyncClient, "send", lambda *args, **kwargs: response)
monkeypatch.setattr(httpx.Client, "send", lambda *args, **kwargs: response)
# initialize client after patching
client = UnstructuredClient(
api_key_auth=os.getenv("UNSTRUCTURED_API_KEY"),
retry_config=RetryConfig("backoff", BackoffStrategy(1, 10, 1.5, 30), False),
)
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
req = operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="fast",
languages=["eng"],
split_pdf_page=split_pdf,
)
)
with pytest.raises(sdk_raises):
response = client.general.partition(
request=req
)
@pytest.mark.asyncio
async def test_partition_async_returns_elements(client, doc_path):
filename = "layout-parser-paper.pdf"
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
req = operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="fast",
languages=["eng"],
split_pdf_page=True,
)
)
response = await client.general.partition_async(request=req)
assert response.status_code == 200
assert len(response.elements)
@pytest.mark.asyncio
async def test_partition_async_processes_concurrent_files(client, doc_path):
"""
Assert that partition_async can be used to send multiple files concurrently.
Send two separate portions of the test doc, serially and then using asyncio.gather.
The results for both runs should match.
"""
filename = "layout-parser-paper.pdf"
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
# Set up two SDK requests
# For different page ranges
requests = [
operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="fast",
languages=["eng"],
split_pdf_page=True,
split_pdf_page_range=[1, 3],
)
),
operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="fast",
languages=["eng"],
split_pdf_page=True,
split_pdf_page_range=[10, 12],
)
)
]
serial_responses = []
for req in requests:
res = await client.general.partition_async(request=req)
assert res.status_code == 200
serial_responses.append(res.elements)
concurrent_responses = []
results = await asyncio.gather(
client.general.partition_async(request=requests[0]),
client.general.partition_async(request=requests[1])
)
for res in results:
assert res.status_code == 200
concurrent_responses.append(res.elements)
diff = DeepDiff(
t1=serial_responses,
t2=concurrent_responses,
ignore_order=True,
)
assert len(diff) == 0
def test_uvloop_partitions_without_errors(client, doc_path):
async def call_api():
filename = "layout-parser-paper-fast.pdf"
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
req = operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="fast",
languages=["eng"],
split_pdf_page=True,
)
)
resp = client.general.partition(
request=req
)
if resp is not None:
return resp.elements
else:
return []
import uvloop
uvloop.install()
elements = asyncio.run(call_api())
assert len(elements) > 0
@pytest.mark.parametrize("split_pdf", [True, False])
@pytest.mark.parametrize("vlm_model", ["gpt-4o"])
@pytest.mark.parametrize("vlm_model_provider", ["openai"])
@pytest.mark.parametrize(
"filename",
[
"layout-parser-paper-fast.pdf",
"fake-power-point.ppt",
"embedded-images-tables.jpg",
]
)
def test_partition_strategy_vlm_openai(split_pdf, vlm_model, vlm_model_provider, client, doc_path, filename):
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
req = operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="vlm",
vlm_model=vlm_model,
vlm_model_provider=vlm_model_provider,
languages=["eng"],
split_pdf_page=split_pdf,
)
)
response = client.general.partition(
request=req
)
assert response.status_code == 200
assert len(response.elements) > 0
assert response.elements[0]["metadata"]["partitioner_type"] == "vlm_partition"
@pytest.mark.parametrize("split_pdf", [True, False])
@pytest.mark.parametrize("vlm_model",
[
"us.amazon.nova-pro-v1:0",
"us.amazon.nova-lite-v1:0",
"us.anthropic.claude-3-5-sonnet-20241022-v2:0",
"us.anthropic.claude-3-opus-20240229-v1:0",
"us.anthropic.claude-3-haiku-20240307-v1:0",
"us.anthropic.claude-3-sonnet-20240229-v1:0",
"us.meta.llama3-2-90b-instruct-v1:0",
"us.meta.llama3-2-11b-instruct-v1:0",
]
)
@pytest.mark.parametrize("vlm_model_provider", ["bedrock"])
@pytest.mark.parametrize(
"filename",
[
"layout-parser-paper-fast.pdf",
"fake-power-point.ppt",
"embedded-images-tables.jpg",
]
)
def test_partition_strategy_vlm_bedrock(split_pdf, vlm_model, vlm_model_provider, client, doc_path, filename):
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
req = operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="vlm",
vlm_model=vlm_model,
vlm_model_provider=vlm_model_provider,
languages=["eng"],
split_pdf_page=split_pdf,
)
)
response = client.general.partition(
request=req
)
assert response.status_code == 200
assert len(response.elements) > 0
assert response.elements[0]["metadata"]["partitioner_type"] == "vlm_partition"
@pytest.mark.parametrize("split_pdf", [True, False])
@pytest.mark.parametrize("vlm_model", ["claude-3-5-sonnet-20241022",])
@pytest.mark.parametrize("vlm_model_provider", ["anthropic"])
@pytest.mark.parametrize(
"filename",
[
"layout-parser-paper-fast.pdf",
"fake-power-point.ppt",
"embedded-images-tables.jpg",
]
)
def test_partition_strategy_vlm_anthropic(split_pdf, vlm_model, vlm_model_provider, client, doc_path, filename):
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
req = operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="vlm",
vlm_model=vlm_model,
vlm_model_provider=vlm_model_provider,
languages=["eng"],
split_pdf_page=split_pdf,
)
)
response = client.general.partition(
request=req
)
assert response.status_code == 200
assert len(response.elements) > 0
assert response.elements[0]["metadata"]["partitioner_type"] == "vlm_partition"