> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Amazon Textract 集成

> 使用 LangChain Python 集成 Amazon Textract 文档加载器。

> [Amazon Textract](https://docs.aws.amazon.com/managedservices/latest/userguide/textract.html) 是一项机器学习（ML）服务，可自动从扫描文档中提取文本、手写内容和数据。
>
> 它超越了简单的光学字符识别（OCR），能够识别、理解并从表单和表格中提取数据。如今，许多公司仍手动从扫描文档（如 PDF、图像、表格和表单）中提取数据，或通过需要手动配置的简单 OCR 软件（通常必须在表单更改时更新）进行提取。为了克服这些手动且成本高昂的流程，`Textract` 利用机器学习来读取和处理任何类型的文档，无需人工干预即可准确提取文本、手写内容、表格和其他数据。

`Textract` 支持 `JPEG`、`PNG`、`PDF` 和 `TIFF` 文件格式；更多信息请参阅[文档](https://docs.aws.amazon.com/textract/latest/dg/limits-document.html)。

以下示例展示了将 `Amazon Textract` 与 LangChain 结合使用作为 DocumentLoader 的方法。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU  boto3 langchain-openai tiktoken python-dotenv
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU  "amazon-textract-caller>=0.2.0"
```

## 示例 1：从本地文件加载

第一个示例使用本地文件，该文件将在内部发送到 Amazon Textract 同步 API [DetectDocumentText](https://docs.aws.amazon.com/textract/latest/dg/API_DetectDocumentText.html)。

对于 Textract，本地文件或 HTTP:// 等 URL 端点仅限于单页文档。
多页文档必须存储在 S3 上。此示例文件为 jpeg 格式。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.document_loaders import AmazonTextractPDFLoader

loader = AmazonTextractPDFLoader("example_data/alejandro_rosalez_sample-small.jpeg")
documents = loader.load()
```

文件输出

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
documents
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[Document(page_content='Patient Information First Name: ALEJANDRO Last Name: ROSALEZ Date of Birth: 10/10/1982 Sex: M Marital Status: MARRIED Email Address: Address: 123 ANY STREET City: ANYTOWN State: CA Zip Code: 12345 Phone: 646-555-0111 Emergency Contact 1: First Name: CARLOS Last Name: SALAZAR Phone: 212-555-0150 Relationship to Patient: BROTHER Emergency Contact 2: First Name: JANE Last Name: DOE Phone: 650-555-0123 Relationship FRIEND to Patient: Did you feel fever or feverish lately? Yes No Are you having shortness of breath? Yes No Do you have a cough? Yes No Did you experience loss of taste or smell? Yes No Where you in contact with any confirmed COVID-19 positive patients? Yes No Did you travel in the past 14 days to any regions affected by COVID-19? Yes No Patient Information First Name: ALEJANDRO Last Name: ROSALEZ Date of Birth: 10/10/1982 Sex: M Marital Status: MARRIED Email Address: Address: 123 ANY STREET City: ANYTOWN State: CA Zip Code: 12345 Phone: 646-555-0111 Emergency Contact 1: First Name: CARLOS Last Name: SALAZAR Phone: 212-555-0150 Relationship to Patient: BROTHER Emergency Contact 2: First Name: JANE Last Name: DOE Phone: 650-555-0123 Relationship FRIEND to Patient: Did you feel fever or feverish lately? Yes No Are you having shortness of breath? Yes No Do you have a cough? Yes No Did you experience loss of taste or smell? Yes No Where you in contact with any confirmed COVID-19 positive patients? Yes No Did you travel in the past 14 days to any regions affected by COVID-19? Yes No ', metadata={'source': 'example_data/alejandro_rosalez_sample-small.jpeg', 'page': 1})]
```

## 示例 2：从 URL 加载

下一个示例从 HTTPS 端点加载文件。
它必须是单页的，因为 Amazon Textract 要求所有多页文档都存储在 S3 上。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.document_loaders import AmazonTextractPDFLoader

loader = AmazonTextractPDFLoader(
    "https://amazon-textract-public-content.s3.us-east-2.amazonaws.com/langchain/alejandro_rosalez_sample_1.jpg"
)
documents = loader.load()
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
documents
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[Document(page_content='Patient Information First Name: ALEJANDRO Last Name: ROSALEZ Date of Birth: 10/10/1982 Sex: M Marital Status: MARRIED Email Address: Address: 123 ANY STREET City: ANYTOWN State: CA Zip Code: 12345 Phone: 646-555-0111 Emergency Contact 1: First Name: CARLOS Last Name: SALAZAR Phone: 212-555-0150 Relationship to Patient: BROTHER Emergency Contact 2: First Name: JANE Last Name: DOE Phone: 650-555-0123 Relationship FRIEND to Patient: Did you feel fever or feverish lately? Yes No Are you having shortness of breath? Yes No Do you have a cough? Yes No Did you experience loss of taste or smell? Yes No Where you in contact with any confirmed COVID-19 positive patients? Yes No Did you travel in the past 14 days to any regions affected by COVID-19? Yes No Patient Information First Name: ALEJANDRO Last Name: ROSALEZ Date of Birth: 10/10/1982 Sex: M Marital Status: MARRIED Email Address: Address: 123 ANY STREET City: ANYTOWN State: CA Zip Code: 12345 Phone: 646-555-0111 Emergency Contact 1: First Name: CARLOS Last Name: SALAZAR Phone: 212-555-0150 Relationship to Patient: BROTHER Emergency Contact 2: First Name: JANE Last Name: DOE Phone: 650-555-0123 Relationship FRIEND to Patient: Did you feel fever or feverish lately? Yes No Are you having shortness of breath? Yes No Do you have a cough? Yes No Did you experience loss of taste or smell? Yes No Where you in contact with any confirmed COVID-19 positive patients? Yes No Did you travel in the past 14 days to any regions affected by COVID-19? Yes No ', metadata={'source': 'example_data/alejandro_rosalez_sample-small.jpeg', 'page': 1})]
```

## 示例 3：加载多页 PDF 文档

处理多页文档要求文档位于 S3 上。示例文档存储在 us-east-2 区域的一个存储桶中，Textract 需要在同一区域调用才能成功，因此我们在客户端上设置 region\_name 并将其传递给加载器，以确保从 us-east-2 调用 Textract。您也可以让您的笔记本在 us-east-2 中运行，将 AWS\_DEFAULT\_REGION 设置为 us-east-2，或者在另一个环境中运行时，传入一个具有该区域名称的 boto3 Textract 客户端，如下方单元格所示。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import boto3

textract_client = boto3.client("textract", region_name="us-east-2")

file_path = "s3://amazon-textract-public-content/langchain/layout-parser-paper.pdf"
loader = AmazonTextractPDFLoader(file_path, client=textract_client)
documents = loader.load()
```

现在获取页数以验证响应（打印完整响应会很长...）。我们预期有 16 页。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
len(documents)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
16
```

## 示例 4：自定义输出格式

当 Amazon Textract 处理 PDF 时，它会提取所有文本，包括页眉、页脚和页码等元素。这些额外信息可能会带来“噪音”并降低输出的有效性。

将文档的二维布局转换为干净的一维文本字符串的过程称为线性化。

AmazonTextractPDFLoader 通过 `linearization_config` 参数让您精确控制此过程。您可以使用它来指定要从最终输出中排除哪些元素。

以下示例展示了如何隐藏页眉、页脚和图形，从而生成更干净的文本块。有关更高级的用例，请参阅此[AWS 博客文章](https://aws.amazon.com/blogs/machine-learning/amazon-textracts-new-layout-feature-introduces-efficiencies-in-general-purpose-and-generative-ai-document-processing-tasks/)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.document_loaders import AmazonTextractPDFLoader
from textractor.data.text_linearization_config import TextLinearizationConfig

loader = AmazonTextractPDFLoader(
    "s3://amazon-textract-public-content/langchain/layout-parser-paper.pdf",
    linearization_config=TextLinearizationConfig(
        hide_header_layout=True,
        hide_footer_layout=True,
        hide_figure_layout=True,
    ),
)
documents = loader.load()
```

## 在 LangChain 链中使用 AmazonTextractPDFLoader（例如 OpenAI）

AmazonTextractPDFLoader 可以像其他加载器一样在链中使用。
Textract 本身具有[查询功能](https://docs.aws.amazon.com/textract/latest/dg/API_Query.html)，它提供了与本示例中 QA 链类似的功能，也值得一试。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 您也可以将 OPENAI_API_KEY 存储在 .env 文件中
# import os
# from dotenv import load_dotenv

# load_dotenv()
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 或者直接在环境中设置 OpenAI 密钥
import os

os.environ["OPENAI_API_KEY"] = "your-OpenAI-API-key"
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_classic.chains.question_answering import load_qa_chain
from langchain_openai import OpenAI

chain = load_qa_chain(llm=OpenAI(), chain_type="map_reduce")
query = ["Who are the authors?"]

chain.run(input_documents=documents, question=query)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
' The authors are Zejiang Shen, Ruochen Zhang, Melissa Dell, Benjamin Charles Germain Lee, Jacob Carlson, Weining Li, Gardner, M., Grus, J., Neumann, M., Tafjord, O., Dasigi, P., Liu, N., Peters, M., Schmitz, M., Zettlemoyer, L., Lukasz Garncarek, Powalski, R., Stanislawek, T., Topolski, B., Halama, P., Gralinski, F., Graves, A., Fernández, S., Gomez, F., Schmidhuber, J., Harley, A.W., Ufkes, A., Derpanis, K.G., He, K., Gkioxari, G., Dollár, P., Girshick, R., He, K., Zhang, X., Ren, S., Sun, J., Kay, A., Lamiroy, B., Lopresti, D., Mears, J., Jakeway, E., Ferriter, M., Adams, C., Yarasavage, N., Thomas, D., Zwaard, K., Li, M., Cui, L., Huang,'
```

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\python\integrations\document_loaders\amazon_textract.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
