Skip to main content
Open In ColabOpen on GitHub

Azure AI 文档智能

Azure AI Document Intelligence (formerly known as Azure Form Recognizer) is machine-learning based service that extracts texts (including handwriting), tables, document structures (e.g., titles, section headings, etc.) and key-value-pairs from digital or scanned PDFs, images, Office and HTML files.

Document Intelligence supports PDF, JPEG/JPG, PNG, BMP, TIFF, HEIF, DOCX, XLSX, PPTX and HTML.

当前使用Document Intelligence的加载器实现可以按页整合内容,并将其转换为 LangChain 文档。默认输出格式为 Markdown,可轻松与MarkdownHeaderTextSplitter链接以实现语义文档分块。您也可以使用mode="single"mode="page"返回单页纯文本,或返回按页分割的文档。

前置条件

在以下三个预览区域之一的 Azure AI 文档智能资源:美国东部美国西部2欧洲西部 - 如果您还没有,请按照此文档创建一个。您将向加载器传递 <endpoint><key> 作为参数。

%pip install --upgrade --quiet  langchain langchain-community azure-ai-documentintelligence

示例 1

第一个示例使用一个本地文件,该文件将被发送到 Azure AI Document Intelligence。

使用已初始化的文档分析客户端,我们可以继续创建 DocumentIntelligenceLoader 的实例:

from langchain_community.document_loaders import AzureAIDocumentIntelligenceLoader

file_path = "<filepath>"
endpoint = "<endpoint>"
key = "<key>"
loader = AzureAIDocumentIntelligenceLoader(
api_endpoint=endpoint, api_key=key, file_path=file_path, api_model="prebuilt-layout"
)

documents = loader.load()

默认输出包含一个采用 Markdown 格式内容的 LangChain 文档:

documents

示例 2

输入文件也可以是公共 URL 路径。例如,https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/layout.png

url_path = "<url>"
loader = AzureAIDocumentIntelligenceLoader(
api_endpoint=endpoint, api_key=key, url_path=url_path, api_model="prebuilt-layout"
)

documents = loader.load()
documents

示例 3

您也可以指定 mode="page" 以按页加载文档。

from langchain_community.document_loaders import AzureAIDocumentIntelligenceLoader

file_path = "<filepath>"
endpoint = "<endpoint>"
key = "<key>"
loader = AzureAIDocumentIntelligenceLoader(
api_endpoint=endpoint,
api_key=key,
file_path=file_path,
api_model="prebuilt-layout",
mode="page",
)

documents = loader.load()

输出结果将是列表中的每个页面都存储为单独的文档:

for document in documents:
print(f"Page Content: {document.page_content}")
print(f"Metadata: {document.metadata}")

示例 4

您也可以指定 analysis_feature=["ocrHighResolution"] 以启用附加功能。有关更多信息,请参阅:https://aka.ms/azsdk/python/documentintelligence/analysisfeature

from langchain_community.document_loaders import AzureAIDocumentIntelligenceLoader

file_path = "<filepath>"
endpoint = "<endpoint>"
key = "<key>"
analysis_features = ["ocrHighResolution"]
loader = AzureAIDocumentIntelligenceLoader(
api_endpoint=endpoint,
api_key=key,
file_path=file_path,
api_model="prebuilt-layout",
analysis_features=analysis_features,
)

documents = loader.load()

输出内容包含具备高分辨率附加组件能力的 LangChain 文档识别结果:

documents