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 | class UnstructuredFileConverter(BaseConverter):
"""
A component for converting files to Documents using the Unstructured API (hosted or running locally).
For the supported file types and the specific API parameters, see
[Unstructured docs](https://unstructured-io.github.io/unstructured/api.html).
Usage example:
```python
from dynamiq.components.converters.unstructured.file_converter import UnstructuredFileConverter
# make sure to either set the environment variable UNSTRUCTURED_API_KEY
# or run the Unstructured API locally:
# docker run -p 8000:8000 -d --rm --name unstructured-api quay.io/unstructured-io/unstructured-api:latest
# --port 8000 --host 0.0.0.0
converter = UnstructuredFileConverter()
documents = converter.run(paths=["a/file/path.pdf", "a/directory/path"])["documents"]
```
"""
connection: UnstructuredConnection = None
document_creation_mode: DocumentCreationMode = DocumentCreationMode.ONE_DOC_PER_FILE
separator: str = "\n\n"
strategy: ConvertStrategy = ConvertStrategy.AUTO
unstructured_kwargs: dict[str, Any] | None = None
def __init__(self, *args, **kwargs):
if kwargs.get("client") is None and kwargs.get("connection") is None:
kwargs["connection"] = UnstructuredConnection()
super().__init__(**kwargs)
"""
Initializes the object with the configuration for converting documents using
the Unstructured API.
Args:
connection (UnstructuredConnection, optional): The connection to use for the Unstructured API.
Defaults to None, which will initialize a new UnstructuredConnection.
document_creation_mode (Literal["one-doc-per-file", "one-doc-per-page", "one-doc-per-element"], optional):
Determines how to create Documents from the elements returned by Unstructured. Options are:
- `"one-doc-per-file"`: Creates one Document per file.
All elements are concatenated into one text field.
- `"one-doc-per-page"`: Creates one Document per page.
All elements on a page are concatenated into one text field.
- `"one-doc-per-element"`: Creates one Document per element.
Each element is converted to a separate Document.
Defaults to `"one-doc-per-file"`.
separator (str, optional): The separator to use between elements when concatenating them into one text field.
Defaults to "\n\n".
strategy (Literal["auto", "fast", "hi_res", "ocr_only"], optional): The strategy to use for document processing.
Defaults to "auto".
unstructured_kwargs (Optional[dict[str, Any]], optional): Additional parameters to pass to the Unstructured API.
See [Unstructured API docs](https://unstructured-io.github.io/unstructured/apis/api_parameters.html)
for available parameters.
Defaults to None.
progress_bar (bool, optional): Whether to show a progress bar during the conversion process.
Defaults to True.
Returns:
None
"""
def _process_file(self, file: Path | str | BytesIO, metadata: dict[str, Any]) -> list[Any]:
"""
Process a single file and create documents.
Args:
file (Union[Path, str, BytesIO]): The file to process.
metadata (Dict[str, Any]): Metadata to attach to the documents.
Returns:
List[Any]: A list of created documents.
Raises:
ValueError: If the file object doesn't have a name and its extension can't be guessed.
TypeError: If the file argument is neither a Path, string, nor a BytesIO object.
"""
if isinstance(file, (Path, str)):
file_name = str(file)
elements = self._partition_file_into_elements_by_filepath(file_name)
elif isinstance(file, BytesIO):
file_name = get_filename_for_bytesio(file)
elements = self._partition_file_into_elements_by_file(file, file_name)
else:
raise TypeError("Expected a Path object, a string path, or a BytesIO object.")
return self._create_documents(
filepath=file_name,
elements=elements,
document_creation_mode=self.document_creation_mode,
metadata=metadata,
)
def _partition_file_into_elements_by_filepath(self, filepath: Path | str) -> list[dict[str, Any]]:
"""
Partition a file into elements using the Unstructured API.
Args:
filepath (Path | str): The path to the file to partition.
Returns:
List[Dict[str, Any]]: A list of elements extracted from the file.
Raises:
FileNotFoundError: If the file doesn't exist
ValueError: If the file is empty or cannot be processed
Exception: Any other exception that occurs during processing
"""
if isinstance(filepath, str):
filepath = Path(filepath)
if not filepath.exists():
raise FileNotFoundError(f"File not found: {filepath}")
if filepath.stat().st_size == 0:
raise ValueError(f"Empty file cannot be processed: {filepath}")
return partition_via_api(
filename=str(filepath),
api_url=self.connection.url,
api_key=self.connection.api_key,
strategy=self.strategy,
**self.unstructured_kwargs or {},
)
def _partition_file_into_elements_by_file(
self,
file: BytesIO,
metadata_filename: str,
) -> list[dict[str, Any]]:
"""
Partition a file into elements using the Unstructured API.
Args:
file (BytesIO): The file object to partition.
metadata_filename (str): The filename to store in element metadata.
Returns:
List[Dict[str, Any]]: A list of elements extracted from the file.
Raises:
ValueError: If the file is empty or cannot be processed
Exception: Any other exception that occurs during processing
"""
return partition_via_api(
filename=None,
file=file,
metadata_filename=metadata_filename,
api_url=self.connection.url,
api_key=self.connection.api_key,
strategy=self.strategy,
**self.unstructured_kwargs or {},
)
def _create_documents(
self,
filepath: str,
elements: list[dict],
document_creation_mode: DocumentCreationMode,
metadata: dict[str, Any],
**kwargs,
) -> list[Document]:
"""
Create Documents from the elements returned by Unstructured.
"""
separator = self.separator
docs = []
if document_creation_mode == DocumentCreationMode.ONE_DOC_PER_FILE:
element_texts = []
for el in elements:
text = str(el.get("text", ""))
if el.get("category") == "Title":
element_texts.append("# " + text)
else:
element_texts.append(text)
text = separator.join(element_texts)
metadata = copy.deepcopy(metadata)
metadata["file_path"] = str(filepath)
docs = [Document(content=text, metadata=metadata)]
elif document_creation_mode == DocumentCreationMode.ONE_DOC_PER_PAGE:
texts_per_page: defaultdict[int, str] = defaultdict(str)
meta_per_page: defaultdict[int, dict] = defaultdict(dict)
for el in elements:
text = str(el.get("text", ""))
metadata = copy.deepcopy(metadata)
metadata["file_path"] = str(filepath)
element_medata = el.get("metadata")
if element_medata:
metadata.update(element_medata)
page_number = int(metadata.get("page_number", 1))
texts_per_page[page_number] += text + separator
meta_per_page[page_number].update(metadata)
docs = [
Document(content=texts_per_page[page], metadata=meta_per_page[page])
for page in texts_per_page.keys()
]
elif document_creation_mode == DocumentCreationMode.ONE_DOC_PER_ELEMENT:
for index, el in enumerate(elements):
text = str(el.get("text", ""))
metadata = copy.deepcopy(metadata)
metadata["file_path"] = str(filepath)
metadata["element_index"] = index
element_medata = el.get("metadata")
if element_medata:
metadata.update(element_medata)
element_category = el.get("category")
if element_category:
metadata["category"] = element_category
doc = Document(content=str(el), metadata=metadata)
docs.append(doc)
return docs
|