이 노트북은 Unstructured document loader를 사용하여 다양한 유형의 파일을 로드하는 방법을 다룹니다. Unstructured는 현재 텍스트 파일, 파워포인트, html, pdf, 이미지 등의 로드를 지원합니다. 필요한 시스템 종속성 설정을 포함하여 Unstructured를 로컬에서 설정하는 방법에 대한 자세한 지침은 이 가이드를 참조하세요.

Overview

Integration details

ClassPackageLocalSerializableJS support
UnstructuredLoaderlangchain-unstructured

Loader features

SourceDocument Lazy LoadingNative Async Support
UnstructuredLoader

Setup

Credentials

기본적으로 langchain-unstructured는 파티셔닝 로직을 Unstructured API로 오프로드해야 하는 더 작은 설치 공간을 설치하며, 이를 위해서는 API key가 필요합니다. 로컬 설치를 사용하는 경우 API key가 필요하지 않습니다. API key를 얻으려면 이 사이트로 이동하여 API key를 받은 다음 아래 셀에 설정하세요:
import getpass
import os

if "UNSTRUCTURED_API_KEY" not in os.environ:
    os.environ["UNSTRUCTURED_API_KEY"] = getpass.getpass(
        "Enter your Unstructured API key: "
    )

Installation

Normal Installation

다음 패키지는 이 노트북의 나머지 부분을 실행하는 데 필요합니다.
# Install package, compatible with API partitioning
pip install -qU langchain-unstructured unstructured-client unstructured "unstructured[pdf]" python-magic

Installation for Local

파티셔닝 로직을 로컬에서 실행하려면 여기 Unstructured 문서에 설명된 대로 시스템 종속성 조합을 설치해야 합니다. 예를 들어, Mac에서는 다음과 같이 필요한 종속성을 설치할 수 있습니다:
# base dependencies
brew install libmagic poppler tesseract

# If parsing xml / html documents:
brew install libxml2 libxslt
로컬에 필요한 pip 종속성은 다음과 같이 설치할 수 있습니다:
pip install "langchain-unstructured[local]"

Initialization

UnstructuredLoader는 다양한 파일 유형에서 로드할 수 있습니다. unstructured 패키지에 대한 모든 내용을 읽으려면 해당 문서를 참조하세요. 이 예제에서는 텍스트 파일과 PDF 파일 모두에서 로드하는 방법을 보여줍니다.
from langchain_unstructured import UnstructuredLoader

file_paths = [
    "./example_data/layout-parser-paper.pdf",
    "./example_data/state_of_the_union.txt",
]


loader = UnstructuredLoader(file_paths)

Load

docs = loader.load()

docs[0]
INFO: pikepdf C++ to Python logger bridge initialized
Document(metadata={'source': './example_data/layout-parser-paper.pdf', 'coordinates': {'points': ((16.34, 213.36), (16.34, 253.36), (36.34, 253.36), (36.34, 213.36)), 'system': 'PixelSpace', 'layout_width': 612, 'layout_height': 792}, 'file_directory': './example_data', 'filename': 'layout-parser-paper.pdf', 'languages': ['eng'], 'last_modified': '2024-02-27T15:49:27', 'page_number': 1, 'filetype': 'application/pdf', 'category': 'UncategorizedText', 'element_id': 'd3ce55f220dfb75891b4394a18bcb973'}, page_content='1 2 0 2')
print(docs[0].metadata)
{'source': './example_data/layout-parser-paper.pdf', 'coordinates': {'points': ((16.34, 213.36), (16.34, 253.36), (36.34, 253.36), (36.34, 213.36)), 'system': 'PixelSpace', 'layout_width': 612, 'layout_height': 792}, 'file_directory': './example_data', 'filename': 'layout-parser-paper.pdf', 'languages': ['eng'], 'last_modified': '2024-02-27T15:49:27', 'page_number': 1, 'filetype': 'application/pdf', 'category': 'UncategorizedText', 'element_id': 'd3ce55f220dfb75891b4394a18bcb973'}

Lazy Load

pages = []
for doc in loader.lazy_load():
    pages.append(doc)

pages[0]
Document(metadata={'source': './example_data/layout-parser-paper.pdf', 'coordinates': {'points': ((16.34, 213.36), (16.34, 253.36), (36.34, 253.36), (36.34, 213.36)), 'system': 'PixelSpace', 'layout_width': 612, 'layout_height': 792}, 'file_directory': './example_data', 'filename': 'layout-parser-paper.pdf', 'languages': ['eng'], 'last_modified': '2024-02-27T15:49:27', 'page_number': 1, 'filetype': 'application/pdf', 'category': 'UncategorizedText', 'element_id': 'd3ce55f220dfb75891b4394a18bcb973'}, page_content='1 2 0 2')

Post Processing

추출 후 unstructured 요소를 후처리해야 하는 경우, UnstructuredLoader를 인스턴스화할 때 post_processors kwarg에 str -> str 함수 목록을 전달할 수 있습니다. 이는 다른 Unstructured loader에도 적용됩니다. 아래는 예제입니다.
from langchain_unstructured import UnstructuredLoader
from unstructured.cleaners.core import clean_extra_whitespace

loader = UnstructuredLoader(
    "./example_data/layout-parser-paper.pdf",
    post_processors=[clean_extra_whitespace],
)

docs = loader.load()

docs[5:10]
[Document(metadata={'source': './example_data/layout-parser-paper.pdf', 'coordinates': {'points': ((16.34, 393.9), (16.34, 560.0), (36.34, 560.0), (36.34, 393.9)), 'system': 'PixelSpace', 'layout_width': 612, 'layout_height': 792}, 'file_directory': './example_data', 'filename': 'layout-parser-paper.pdf', 'languages': ['eng'], 'last_modified': '2024-02-27T15:49:27', 'page_number': 1, 'parent_id': '89565df026a24279aaea20dc08cedbec', 'filetype': 'application/pdf', 'category': 'UncategorizedText', 'element_id': 'e9fa370aef7ee5c05744eb7bb7d9981b'}, page_content='2 v 8 4 3 5 1 . 3 0 1 2 : v i X r a'),
 Document(metadata={'source': './example_data/layout-parser-paper.pdf', 'coordinates': {'points': ((157.62199999999999, 114.23496279999995), (157.62199999999999, 146.5141628), (457.7358962799999, 146.5141628), (457.7358962799999, 114.23496279999995)), 'system': 'PixelSpace', 'layout_width': 612, 'layout_height': 792}, 'file_directory': './example_data', 'filename': 'layout-parser-paper.pdf', 'languages': ['eng'], 'last_modified': '2024-02-27T15:49:27', 'page_number': 1, 'filetype': 'application/pdf', 'category': 'Title', 'element_id': 'bde0b230a1aa488e3ce837d33015181b'}, page_content='LayoutParser: A Unified Toolkit for Deep Learning Based Document Image Analysis'),
 Document(metadata={'source': './example_data/layout-parser-paper.pdf', 'coordinates': {'points': ((134.809, 168.64029940800003), (134.809, 192.2517444), (480.5464199080001, 192.2517444), (480.5464199080001, 168.64029940800003)), 'system': 'PixelSpace', 'layout_width': 612, 'layout_height': 792}, 'file_directory': './example_data', 'filename': 'layout-parser-paper.pdf', 'languages': ['eng'], 'last_modified': '2024-02-27T15:49:27', 'page_number': 1, 'parent_id': 'bde0b230a1aa488e3ce837d33015181b', 'filetype': 'application/pdf', 'category': 'UncategorizedText', 'element_id': '54700f902899f0c8c90488fa8d825bce'}, page_content='Zejiang Shen1 ((cid:0)), Ruochen Zhang2, Melissa Dell3, Benjamin Charles Germain Lee4, Jacob Carlson3, and Weining Li5'),
 Document(metadata={'source': './example_data/layout-parser-paper.pdf', 'coordinates': {'points': ((207.23000000000002, 202.57205439999996), (207.23000000000002, 311.8195408), (408.12676, 311.8195408), (408.12676, 202.57205439999996)), 'system': 'PixelSpace', 'layout_width': 612, 'layout_height': 792}, 'file_directory': './example_data', 'filename': 'layout-parser-paper.pdf', 'languages': ['eng'], 'last_modified': '2024-02-27T15:49:27', 'page_number': 1, 'parent_id': 'bde0b230a1aa488e3ce837d33015181b', 'filetype': 'application/pdf', 'category': 'UncategorizedText', 'element_id': 'b650f5867bad9bb4e30384282c79bcfe'}, page_content='1 Allen Institute for AI [email protected] 2 Brown University ruochen [email protected] 3 Harvard University {melissadell,jacob carlson}@fas.harvard.edu 4 University of Washington [email protected] 5 University of Waterloo [email protected]'),
 Document(metadata={'source': './example_data/layout-parser-paper.pdf', 'coordinates': {'points': ((162.779, 338.45008160000003), (162.779, 566.8455408), (454.0372021523199, 566.8455408), (454.0372021523199, 338.45008160000003)), 'system': 'PixelSpace', 'layout_width': 612, 'layout_height': 792}, 'file_directory': './example_data', 'filename': 'layout-parser-paper.pdf', 'languages': ['eng'], 'last_modified': '2024-02-27T15:49:27', 'links': [{'text': ':// layout - parser . github . io', 'url': 'https://layout-parser.github.io', 'start_index': 1477}], 'page_number': 1, 'parent_id': 'bde0b230a1aa488e3ce837d33015181b', 'filetype': 'application/pdf', 'category': 'NarrativeText', 'element_id': 'cfc957c94fe63c8fd7c7f4bcb56e75a7'}, page_content='Abstract. Recent advances in document image analysis (DIA) have been primarily driven by the application of neural networks. Ideally, research outcomes could be easily deployed in production and extended for further investigation. However, various factors like loosely organized codebases and sophisticated model configurations complicate the easy reuse of im- portant innovations by a wide audience. Though there have been on-going efforts to improve reusability and simplify deep learning (DL) model development in disciplines like natural language processing and computer vision, none of them are optimized for challenges in the domain of DIA. This represents a major gap in the existing toolkit, as DIA is central to academic research across a wide range of disciplines in the social sciences and humanities. This paper introduces LayoutParser, an open-source library for streamlining the usage of DL in DIA research and applica- tions. The core LayoutParser library comes with a set of simple and intuitive interfaces for applying and customizing DL models for layout de- tection, character recognition, and many other document processing tasks. To promote extensibility, LayoutParser also incorporates a community platform for sharing both pre-trained models and full document digiti- zation pipelines. We demonstrate that LayoutParser is helpful for both lightweight and large-scale digitization pipelines in real-word use cases. The library is publicly available at https://layout-parser.github.io.')]

Unstructured API

더 작은 패키지로 빠르게 시작하고 최신 파티셔닝을 사용하려면 pip install unstructured-clientpip install langchain-unstructured를 실행할 수 있습니다. UnstructuredLoader에 대한 자세한 내용은 Unstructured provider 페이지를 참조하세요. api_key를 전달하고 partition_via_api=True로 설정하면 loader가 호스팅된 Unstructured serverless API를 사용하여 문서를 처리합니다. 무료 Unstructured API key는 여기에서 생성할 수 있습니다. Unstructured API를 자체 호스팅하거나 로컬에서 실행하려면 여기의 지침을 확인하세요.
from langchain_unstructured import UnstructuredLoader

loader = UnstructuredLoader(
    file_path="example_data/fake.docx",
    api_key=os.getenv("UNSTRUCTURED_API_KEY"),
    partition_via_api=True,
)

docs = loader.load()
docs[0]
INFO: Preparing to split document for partition.
INFO: Given file doesn't have '.pdf' extension, so splitting is not enabled.
INFO: Partitioning without split.
INFO: Successfully partitioned the document.
Document(metadata={'source': 'example_data/fake.docx', 'category_depth': 0, 'filename': 'fake.docx', 'languages': ['por', 'cat'], 'filetype': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'category': 'Title', 'element_id': '56d531394823d81787d77a04462ed096'}, page_content='Lorem ipsum dolor sit amet.')
UnstructuredLoader를 사용하여 단일 API에서 여러 파일을 Unstructured API를 통해 일괄 처리할 수도 있습니다.
loader = UnstructuredLoader(
    file_path=["example_data/fake.docx", "example_data/fake-email.eml"],
    api_key=os.getenv("UNSTRUCTURED_API_KEY"),
    partition_via_api=True,
)

docs = loader.load()

print(docs[0].metadata["filename"], ": ", docs[0].page_content[:100])
print(docs[-1].metadata["filename"], ": ", docs[-1].page_content[:100])
INFO: Preparing to split document for partition.
INFO: Given file doesn't have '.pdf' extension, so splitting is not enabled.
INFO: Partitioning without split.
INFO: Successfully partitioned the document.
INFO: Preparing to split document for partition.
INFO: Given file doesn't have '.pdf' extension, so splitting is not enabled.
INFO: Partitioning without split.
INFO: Successfully partitioned the document.
fake.docx :  Lorem ipsum dolor sit amet.
fake-email.eml :  Violets are blue

Unstructured SDK Client

Unstructured API를 사용한 파티셔닝은 Unstructured SDK Client에 의존합니다. client를 커스터마이즈하려면 UnstructuredLoaderUnstructuredClient 인스턴스를 전달해야 합니다. 아래는 자체 requests.Session() 사용, 대체 server_url 전달, RetryConfig 객체 커스터마이징과 같은 client의 기능을 커스터마이즈하는 방법을 보여주는 예제입니다. client 커스터마이징 또는 sdk client가 허용하는 추가 매개변수에 대한 자세한 내용은 Unstructured Python SDK 문서와 API Parameters 문서의 client 섹션을 참조하세요. 모든 API Parameters는 UnstructuredLoader에 전달되어야 합니다.
경고: 아래 예제는 최신 버전의 UnstructuredClient를 사용하지 않을 수 있으며 향후 릴리스에서 호환성이 깨지는 변경 사항이 있을 수 있습니다. 최신 예제는 Unstructured Python SDK 문서를 참조하세요.
import requests
from langchain_unstructured import UnstructuredLoader
from unstructured_client import UnstructuredClient
from unstructured_client.utils import BackoffStrategy, RetryConfig

client = UnstructuredClient(
        api_key_auth=os.getenv(
        "UNSTRUCTURED_API_KEY"
    ),  # Note: the client API param is "api_key_auth" instead of "api_key"
        client=requests.Session(),  # Define your own requests session
        server_url="https://api.unstructuredapp.io/general/v0/general",  # Define your own api url
        retry_config=RetryConfig(
                strategy="backoff",
                retry_connection_errors=True,
                backoff=BackoffStrategy(
                        initial_interval=500,
                        max_interval=60000,
                        exponent=1.5,
                        max_elapsed_time=900000,
        ),
    ),  # Define your own retry config
)

loader = UnstructuredLoader(
    "./example_data/layout-parser-paper.pdf",
        partition_via_api=True,
        client=client,
        split_pdf_page=True,
        split_pdf_page_range=[1, 10],
)

docs = loader.load()

print(docs[0].metadata["filename"], ": ", docs[0].page_content[:100])
INFO: Preparing to split document for partition.
INFO: Concurrency level set to 5
INFO: Splitting pages 1 to 10 (10 total)
INFO: Determined optimal split size of 2 pages.
INFO: Partitioning 5 files with 2 page(s) each.
INFO: Partitioning set #1 (pages 1-2).
INFO: Partitioning set #2 (pages 3-4).
INFO: Partitioning set #3 (pages 5-6).
INFO: Partitioning set #4 (pages 7-8).
INFO: Partitioning set #5 (pages 9-10).
INFO: HTTP Request: POST https://api.unstructuredapp.io/general/v0/general "HTTP/1.1 200 OK"
INFO: HTTP Request: POST https://api.unstructuredapp.io/general/v0/general "HTTP/1.1 200 OK"
INFO: HTTP Request: POST https://api.unstructuredapp.io/general/v0/general "HTTP/1.1 200 OK"
INFO: HTTP Request: POST https://api.unstructuredapp.io/general/v0/general "HTTP/1.1 200 OK"
INFO: Successfully partitioned set #1, elements added to the final result.
INFO: Successfully partitioned set #2, elements added to the final result.
INFO: Successfully partitioned set #3, elements added to the final result.
INFO: Successfully partitioned set #4, elements added to the final result.
INFO: Successfully partitioned set #5, elements added to the final result.
INFO: Successfully partitioned the document.
layout-parser-paper.pdf :  LayoutParser: A Unified Toolkit for Deep Learning Based Document Image Analysis

Chunking

UnstructuredLoader는 이전 loader인 UnstructuredFileLoader 및 기타 loader가 했던 것처럼 텍스트를 그룹화하기 위한 매개변수로 mode를 지원하지 않습니다. 대신 “chunking”을 지원합니다. unstructured의 chunking은 “\n\n” 또는 “\n”과 같은 일반 텍스트 기능을 기반으로 청크를 형성하는 익숙한 다른 chunking 메커니즘과 다릅니다. 대신, 모든 문서는 각 문서 형식에 대한 특정 지식을 사용하여 문서를 의미론적 단위(문서 요소)로 분할하며, 단일 요소가 원하는 최대 청크 크기를 초과하는 경우에만 텍스트 분할을 사용합니다. 일반적으로 chunking은 최대 청크 크기를 초과하지 않으면서 가능한 한 큰 청크를 형성하기 위해 연속적인 요소를 결합합니다. Chunking은 CompositeElement, Table 또는 TableChunk 요소의 시퀀스를 생성합니다. 각 “chunk”는 이 세 가지 유형 중 하나의 인스턴스입니다. chunking 옵션에 대한 자세한 내용은 이 페이지를 참조하되, mode="single"과 동일한 동작을 재현하려면 chunking_strategy="basic", max_characters=<매우-큰-숫자>, include_orig_elements=False로 설정할 수 있습니다.
from langchain_unstructured import UnstructuredLoader

loader = UnstructuredLoader(
    "./example_data/layout-parser-paper.pdf",
    chunking_strategy="basic",
    max_characters=1000000,
    include_orig_elements=False,
)

docs = loader.load()

print("Number of LangChain documents:", len(docs))
print("Length of text in the document:", len(docs[0].page_content))
Number of LangChain documents: 1
Length of text in the document: 42772

Loading web pages

UnstructuredLoader는 로컬에서 실행될 때 기본 Unstructured partitionurl 매개변수를 채우는 web_url kwarg를 허용합니다. 이를 통해 HTML 웹 페이지와 같은 원격으로 호스팅되는 문서를 파싱할 수 있습니다. 사용 예제:
from langchain_unstructured import UnstructuredLoader

loader = UnstructuredLoader(web_url="https://www.example.com")
docs = loader.load()

for doc in docs:
    print(f"{doc}\n")
page_content='Example Domain' metadata={'category_depth': 0, 'languages': ['eng'], 'filetype': 'text/html', 'url': 'https://www.example.com', 'category': 'Title', 'element_id': 'fdaa78d856f9d143aeeed85bf23f58f8'}

page_content='This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.' metadata={'languages': ['eng'], 'parent_id': 'fdaa78d856f9d143aeeed85bf23f58f8', 'filetype': 'text/html', 'url': 'https://www.example.com', 'category': 'NarrativeText', 'element_id': '3652b8458b0688639f973fe36253c992'}

page_content='More information...' metadata={'category_depth': 0, 'link_texts': ['More information...'], 'link_urls': ['https://www.iana.org/domains/example'], 'languages': ['eng'], 'filetype': 'text/html', 'url': 'https://www.example.com', 'category': 'Title', 'element_id': '793ab98565d6f6d6f3a6d614e3ace2a9'}

API reference

모든 UnstructuredLoader 기능 및 구성에 대한 자세한 문서는 API reference를 참조하세요: python.langchain.com/api_reference/unstructured/document_loaders/langchain_unstructured.document_loaders.UnstructuredLoader.html
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I