Skip to content

Commit 3ea1e5a

Browse files
authored
feat: added element metadata to unstructured loader (#1068)
### Summary Adds tracked metadata from `unstructured` elements to the document metadata when `UnstructuredFileLoader` is used in `"elements"` mode. Tracked metadata is available in `unstructured>=0.4.9`, but the code is written for backward compatibility with older `unstructured` versions. ### Testing Before running, make sure to upgrade to `unstructured==0.4.9`. In the code snippet below, you should see `page_number`, `filename`, and `category` in the metadata for each document. `doc[0]` should have `page_number: 1` and `doc[-1]` should have `page_number: 2`. The example document is `layout-parser-paper-fast.pdf` from the [`unstructured` sample docs](https://github.com/Unstructured-IO/unstructured/tree/main/example-docs). ```python from langchain.document_loaders import UnstructuredFileLoader loader = UnstructuredFileLoader(file_path=f"layout-parser-paper-fast.pdf", mode="elements") docs = loader.load() ```
1 parent bac676c commit 3ea1e5a

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

langchain/document_loaders/unstructured.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,19 @@ def _get_elements(self) -> List:
3333
def load(self) -> List[Document]:
3434
"""Load file."""
3535
elements = self._get_elements()
36-
metadata = {"source": self.file_path}
3736
if self.mode == "elements":
38-
docs = [
39-
Document(page_content=str(el), metadata=metadata) for el in elements
40-
]
37+
docs: List[Document] = list()
38+
for element in elements:
39+
metadata = {"source": self.file_path}
40+
# NOTE(MthwRobinson) - the attribute check is for backward compatibility
41+
# with unstructured<0.4.9. The metadata attributed was added in 0.4.9.
42+
if hasattr(element, "metadata"):
43+
metadata.update(element.metadata.to_dict())
44+
if hasattr(element, "category"):
45+
metadata["category"] = element.category
46+
docs.append(Document(page_content=str(element), metadata=metadata))
4147
elif self.mode == "single":
48+
metadata = {"source": self.file_path}
4249
text = "\n\n".join([str(el) for el in elements])
4350
docs = [Document(page_content=text, metadata=metadata)]
4451
else:

0 commit comments

Comments
 (0)