# PDF Text Extraction

> 使用 PyMuPDF 抽取 PDF 文档中内嵌的文本层。

Source: https://docs.sommatic.ai/zh/nodes/ai.pdf.extract.text/

- 标识: `ai.pdf.extract.text`
- 类别: AI
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

使用 PyMuPDF 抽取 PDF 文档中内嵌的文本层。

直接读取 PDF 的原生文本流，不做栅格化或 OCR，保留文档的逻辑阅读顺序，并在输出中加入页面级标记。

**运行说明：**
- **仅文本层：** 返回 PDF 内嵌的文本。扫描版 PDF 和基于图像的 PDF 没有文本层，会触发 `empty` 端口。
- **页码范围：** 可选过滤，只处理部分页面（例如 `1-50`、`1,5,10-20`）。
- **元数据：** 返回页数、字符数，以及文档元数据（标题、作者、生成工具，如有）。
- **下游回退：** 对于扫描版 PDF，请将 `empty` 输出路由到 `ai.ocr` 或 `ai.ocr.adaptive`。

## 配置

- `page_range` (string, 可选, 支持表达式): 可选：处理指定页面（例如“1-50”）。

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `extracted` (默认): Extracted
- `empty`: No Text Layer
- `error`: Error

## 输入契约

- `content_base64` (string, 可选)
- `file_path` (string, 可选)

## 输出契约

- `text` (string, 可选)
- `chars` (number, 可选)
- `empty` (boolean, 可选)
- `method` (string, 可选)
- `metadata` (object, 可选)

## 在表达式中

后续节点可通过 `$("PDF Text Extraction").item.json.<路径>` 读取此节点输出中的内容（请把 `PDF Text Extraction` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `extracted` 返回的路径，依据“端口”一节所示的输出。

- `$("PDF Text Extraction").item.json.text` (string) = `"--- PAGE 1 ---\nPurchase order 4471\nTotal: …"`
- `$("PDF Text Extraction").item.json.chars` (number) = `87`
- `$("PDF Text Extraction").item.json.empty` (boolean) = `false`
- `$("PDF Text Extraction").item.json.method` (string) = `"pymupdf_text_layer"`
- `$("PDF Text Extraction").item.json.metadata` (object) = `{…}`
- `$("PDF Text Extraction").item.json.metadata.total_pages` (number) = `2` (编辑器不提示)
- `$("PDF Text Extraction").item.json.metadata.pages_processed` (number) = `2` (编辑器不提示)
- `$("PDF Text Extraction").item.json.metadata.pages_with_text` (number) = `2` (编辑器不提示)
- `$("PDF Text Extraction").item.json.metadata.has_text_layer` (boolean) = `true` (编辑器不提示)


## 工作原理

使用 PyMuPDF 逐页读取 PDF 内嵌的文本层，不进行 OCR。所有页面都没有文本的 PDF 从 `empty` 输出，便于转交 OCR。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 先从配置、再从传入条目读取 `content_base64` 或 `file_path`。两者都没有时返回 `error`。
3. 使用 `content_base64`、`file_path` 和 `page_range` 运行 Python 脚本；从 base64 字节或路径打开 PDF。
4. 提取范围内每页的文本，并在每页前加上 `--- PAGE n ---` 标记后拼接。
5. 当没有任何页面含有文本时设置 `empty: true`，并在 `metadata` 中返回计数。
6. 脚本失败时返回 `error`，附带 Python 消息和 stderr。否则 `empty: true` 从 `empty` 输出，其他结果从 `extracted` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-pdf-text",
  "label": "Read PDF text",
  "operator_slug": "ai.pdf.extract.text",
  "operator_version": "1.0.0",
  "config": {
    "page_range": "1-20",
    "execution": {
      "timeout_ms": 120000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "extracted",
  "data": {
    "text": "--- PAGE 1 ---\nPurchase order 4471\nTotal: 1,250.00\n\n--- PAGE 2 ---\nTerms and conditions",
    "chars": 87,
    "empty": false,
    "method": "pymupdf_text_layer",
    "metadata": {
      "total_pages": 2,
      "pages_processed": 2,
      "pages_with_text": 2,
      "has_text_layer": true
    }
  }
}
```

## 输出端口 (代码中的行为)

### `extracted`

范围内至少有一页含有文本。

```json
{
  "text": "--- PAGE 1 ---\nPurchase order 4471\nTotal: 1,250.00\n\n--- PAGE 2 ---\nTerms and conditions",
  "chars": 87,
  "empty": false,
  "method": "pymupdf_text_layer",
  "metadata": {
    "total_pages": 2,
    "pages_processed": 2,
    "pages_with_text": 2,
    "has_text_layer": true
  }
}
```

### `empty`

范围内没有任何页面含有文本（通常是扫描版 PDF）。结构相同，`empty: true`；`text` 中仍包含页面标记。

```json
{
  "text": "--- PAGE 1 ---\n\n\n--- PAGE 2 ---",
  "chars": 31,
  "empty": true,
  "method": "pymupdf_text_layer",
  "metadata": {
    "total_pages": 2,
    "pages_processed": 2,
    "pages_with_text": 0,
    "has_text_layer": false
  }
}
```

### `error`

缺少输入或脚本失败。`data` 为 `{ error }` 或 `{ error, stderr }`。

```json
{
  "error": "Python timed out after 120000ms",
  "stderr": ""
}
```

## 代码中的行为

- `page_range`: 仅支持 `N-M` 形式（从 1 开始，含两端；结束页会被限制在最后一页）。其他值（如 `7` 或 `1,5,10-20`）会处理全部页面。
- `execution.timeout_ms`: Python 子进程的超时时间。未设置时代码使用 120000 毫秒（schema 显示的默认值为 300000）。
- `content_base64 / file_path`: 它们未在配置 schema 中声明，但会先于传入条目从配置读取。可用表达式指向文件，例如 `{{ $json.attachment.content_base64 }}`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | 配置和传入条目中都没有 `content_base64` 或 `file_path`。请从上一个节点映射文件。 |
| `Either content_base64 or file_path is required` | `error` | 当 `file_path` 在编排器主机上不存在时由 Python 脚本抛出。数据中还包含 `stderr`。 |
| `<exception message from the Python library>` | `error` | 无法将文件读取为PDF（文件损坏、已加密或为其他格式）。详情见 `data.stderr`。 |
| `Python timed out after <timeout_ms>ms` | `error` | 脚本超过了 `execution.timeout_ms`。请调大该值或减少处理的页数。 |
| `Python runtime not available (ENOENT)` | `error` | 编排器主机上没有可用的 Python 解释器。 |

## 说明与限制

- 不做 OCR：扫描页或纯图片页不会产生文本。请将 `empty` 连接到 `ai.ocr` 或 `ai.ocr.adaptive`。
- `chars` 统计整个 `text`，包括页面标记。
- 描述中提到了文档元数据（标题、作者、生成工具）；代码并不返回这些信息。`metadata` 仅包含页数统计。
- `file_path` 是编排器主机上的路径。两者同时存在时以 `content_base64` 为准。
- 提取在 Python 子进程中运行。首次使用时，编排器会创建虚拟环境并安装固定版本的依赖，可能需要数分钟；之后的运行会复用该环境。
- Python 结果的输出上限为 50 MB；超过后节点从 `error` 端口输出。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "ai.pdf.extract.text",
  "name": "PDF Text Extraction",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extracts the embedded text layer from PDF documents using PyMuPDF.\n\n  Reads the native text stream of a PDF without rasterization or OCR, preserving the document's logical reading order and emitting page-level markers in the output.\n\n  **Operational notes:**\n  - **Text layer only:** Returns the PDF's embedded text. Scanned PDFs and image-based PDFs have no text layer and will emit port `empty`.\n  - **Page range:** Optional filter to process a subset of pages (e.g. `1-50`, `1,5,10-20`).\n  - **Metadata:** Returns page count, character count, and document metadata (title, author, producer) when present.\n  - **Downstream fallback:** For scanned PDFs, route `empty` output to `ai.ocr` or `ai.ocr.adaptive`.",
  "capabilities": [
    "pdf",
    "text-extraction",
    "document"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "page_range": {
        "type": "string",
        "title": "Page Range",
        "format": "expression",
        "description": "Optional: process specific pages (e.g., \"1-50\")."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "content_base64": {
        "type": "string"
      },
      "file_path": {
        "type": "string"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string"
      },
      "chars": {
        "type": "number"
      },
      "empty": {
        "type": "boolean"
      },
      "method": {
        "type": "string"
      },
      "metadata": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Extracted",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "No Text Layer",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "pdf",
    "text"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "page_range": {
      "type": "string",
      "title": "Page Range",
      "format": "expression",
      "description": "Optional: process specific pages (e.g., \"1-50\")."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content_base64": {
      "type": "string"
    },
    "file_path": {
      "type": "string"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string"
    },
    "chars": {
      "type": "number"
    },
    "empty": {
      "type": "boolean"
    },
    "method": {
      "type": "string"
    },
    "metadata": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "extracted",
    "label": "Extracted",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "No Text Layer",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "is_default": false,
    "supports_condition": false
  }
]
```
