# OCR - PDF to Text

> 使用 OCR（光学字符识别）从 PDF 文档中抽取文本。

Source: https://docs.sommatic.ai/zh/nodes/ai.ocr/

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

使用 OCR（光学字符识别）从 PDF 文档中抽取文本。

自动检测 PDF 是包含内嵌文本还是扫描图像，并采用最合适的抽取方式。

**操作：**
- **Auto：** 先尝试文本抽取（pdftotext），文本过少时回退到 OCR。
- **Text Extract：** 仅快速抽取内嵌文本（不做 OCR）。最适合数字原生 PDF。
- **OCR Only：** 对所有页面强制 OCR。最适合扫描文档。

## 配置

- `mode` (string, 可选): Auto 先尝试 pdftotext，再回退到 OCR。Text Extract 处理数字原生 PDF 速度快。OCR Only 强制基于图像识别。 默认值: `auto`. 可选值: `auto`, `text_extract`, `ocr_only`.
- `language` (string, 可选): Tesseract 语言代码（例如 spa、eng、fra、deu、por）。 默认值: `spa`.
- `dpi` (number, 可选): PDF 转图像的分辨率。越高质量越好，但速度越慢。 默认值: `300`.
- `page_range` (string, 可选, 支持表达式): 可选：处理指定页面（例如“1-50”）。留空则处理所有页面。

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

## 输出端口

- `extracted` (默认): 文本抽取成功。
- `empty`: 文件存在，但无法抽取出有意义的文本。
- `error`: OCR 处理失败。

## 输入契约

- `content_base64` (string, 可选): 以 base64 字符串编码的文件内容。
- `file_path` (string, 可选): 替代方式：PDF 或图片的本地文件路径。
- `content_type` (string, 可选): MIME 类型（application/pdf、image/png、image/jpeg 等）。可选，但有助于路由。

## 输出契约

- `text` (string, 可选): 带页面标记的抽取文本。
- `pages` (number, 可选): 已处理的总页数。
- `method` (string, 可选): 所用的抽取方式（pdftotext 或 ocr）。
- `chars` (number, 可选): 总字符数。
- `empty` (boolean, 可选): 未抽取到有意义的文本时为 true。

## 在表达式中

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

- `$("OCR - PDF to Text").item.json.text` (string) = `"--- PAGE 1 ---\nINVOICE 2026-118\nCustomer: …"`: 带页面标记的抽取文本。
- `$("OCR - PDF to Text").item.json.pages` (number) = `2`: 已处理的总页数。
- `$("OCR - PDF to Text").item.json.method` (string) = `"ocr"`: 所用的抽取方式（pdftotext 或 ocr）。
- `$("OCR - PDF to Text").item.json.chars` (number) = `90`: 总字符数。
- `$("OCR - PDF to Text").item.json.empty` (boolean) = `false`: 未抽取到有意义的文本时为 true。


## 工作原理

从 PDF 或图片中提取文本。PDF 根据 `mode` 使用 `pdftotext`（Poppler）和/或 Tesseract OCR；图片始终使用 Tesseract。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 先从配置、再从传入条目读取 `content_base64`、`file_path` 和 `content_type`。没有 `content_base64` 和 `file_path` 时返回 `error`；`file_path` 不存在时返回 `File not found: <path>`。
3. 当 `content_type` 以 `image/` 开头，或 `file_path` 以 .png、.jpg、.jpeg、.tif、.tiff、.bmp 或 .webp 结尾时，将输入视为图片。无论 `mode` 为何，图片都作为单页进行 OCR。
4. 对于 PDF：`text_extract` 运行 `pdftotext -layout`；`ocr_only` 以 `dpi` 渲染页面并用 `language` 运行 Tesseract；`auto` 先运行 `pdftotext`，当每页平均字符数不超过 50 时改用 OCR。
5. PDF 文本在每页前加上 `--- PAGE n ---` 标记后拼接。`method` 表示结果来自哪条路径：`pdftotext` 或 `ocr`。
6. 当 `chars > 0` 且 `empty` 为 false 时返回 `extracted`，否则返回 `empty`。任何失败（pdftotext 或 Python）都返回 `error`，数据为 `{ error }`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-ocr",
  "label": "OCR document",
  "operator_slug": "ai.ocr",
  "operator_version": "1.0.0",
  "config": {
    "mode": "auto",
    "language": "eng",
    "dpi": 300,
    "page_range": "1-10",
    "execution": {
      "timeout_ms": 300000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "extracted",
  "data": {
    "text": "--- PAGE 1 ---\nINVOICE 2026-118\nCustomer: Example Corp\n\n--- PAGE 2 ---\nTotal due: 3,400.00",
    "pages": 2,
    "method": "ocr",
    "chars": 90,
    "empty": false
  }
}
```

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

### `extracted`

提取到了文本。

```json
{
  "text": "--- PAGE 1 ---\nINVOICE 2026-118\nCustomer: Example Corp\n\n--- PAGE 2 ---\nTotal due: 3,400.00",
  "pages": 2,
  "method": "ocr",
  "chars": 90,
  "empty": false
}
```

### `empty`

所选路径没有产生文本。结构相同，`empty: true`。

```json
{
  "text": "",
  "pages": 0,
  "method": "pdftotext",
  "chars": 0,
  "empty": true
}
```

### `error`

缺少输入、文件不存在或任何提取失败。

```json
{
  "error": "pdftotext failed: Command failed: pdftotext -layout …"
}
```

## 代码中的行为

- `mode`: 仅适用于 PDF。图片始终进行 OCR。
- `page_range`: 仅支持 `N-M` 形式，`pdftotext` 和 OCR 均如此。其他值会处理全部页面。
- `language`: Tesseract 语言代码，默认 `spa`。对 `pdftotext` 无影响。
- `content_type`: 未在配置 schema 中声明；从配置或传入条目读取。以 `content_base64` 发送图片时请设置它（例如 `image/png`）：否则字节会被当作 PDF 处理。
- `execution.timeout_ms`: 默认 300000 毫秒。在 `auto` 模式下分别作用于 `pdftotext` 和 OCR 步骤，因此节点最长可能耗时该值的两倍。
- `content_base64 / file_path`: 它们未在配置 schema 中声明，但会先于传入条目从配置读取。可用表达式指向文件，例如 `{{ $json.attachment.content_base64 }}`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | 配置和传入条目中都没有 `content_base64` 或 `file_path`。请从上一个节点映射文件。 |
| `File not found: <file_path>` | `error` | `file_path` 在编排器主机上不存在。 |
| `pdftotext failed: <message>` | `error` | 未安装 Poppler、文件不是有效的 PDF（例如未提供 `content_type` 的 base64 图片），或运行超时。 |
| `<Tesseract or pdf2image error>` | `error` | 主机上未安装 Tesseract 或 `language` 对应的语言包，或者 PDF 无法渲染。 |
| `Python timed out after <timeout_ms>ms` | `error` | 脚本超过了 `execution.timeout_ms`。请调大该值或减少处理的页数。 |

## 说明与限制

- 编排器主机上需要安装 `pdftotext`（Poppler）以及含 `language` 语言数据的 Tesseract。
- 使用 `pdftotext` 时，空白页会被丢弃，其余页面按 1、2、3… 重新编号，因此页面标记可能与实际页码不同。`pages` 统计非空白页数。
- OCR 输出会为每个渲染页面保留标记，因此 Tesseract 什么都没识别出的扫描 PDF 仍会从 `extracted` 输出，仅含标记。图片结果不带标记。
- 只需单引擎且无需预处理时，此节点即可满足；对于倾斜或噪声较多的扫描件，请使用 `ai.ocr.adaptive`。
- 提取在 Python 子进程中运行。首次使用时，编排器会创建虚拟环境并安装固定版本的依赖，可能需要数分钟；之后的运行会复用该环境。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.ocr",
  "name": "OCR - PDF to Text",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extract text from PDF documents using OCR (Optical Character Recognition).\n\n  Automatically detects whether the PDF contains embedded text or is a scanned image, and uses the optimal extraction method.\n\n  **Operations:**\n  - **Auto:** Try text extraction first (pdftotext), fall back to OCR if text is sparse.\n  - **Text Extract:** Fast extraction of embedded text only (no OCR). Best for digital PDFs.\n  - **OCR Only:** Force OCR on all pages. Best for scanned documents.",
  "capabilities": [
    "ocr",
    "pdf",
    "text-extraction",
    "document"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "mode": {
        "type": "string",
        "title": "Extraction Mode",
        "enum": [
          "auto",
          "text_extract",
          "ocr_only"
        ],
        "default": "auto",
        "description": "Auto tries pdftotext first, falls back to OCR. Text Extract is fast for digital PDFs. OCR Only forces image-based recognition."
      },
      "language": {
        "type": "string",
        "title": "OCR Language",
        "default": "spa",
        "description": "Tesseract language code (e.g., spa, eng, fra, deu, por)."
      },
      "dpi": {
        "type": "number",
        "title": "DPI",
        "default": 300,
        "description": "Resolution for PDF-to-image conversion. Higher = better quality but slower."
      },
      "page_range": {
        "type": "string",
        "title": "Page Range",
        "description": "Optional: process specific pages (e.g., \"1-50\"). Leave empty for all pages.",
        "format": "expression"
      },
      "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",
        "description": "File content encoded as base64 string."
      },
      "file_path": {
        "type": "string",
        "description": "Alternative: local file path to the PDF or image."
      },
      "content_type": {
        "type": "string",
        "description": "MIME type (application/pdf, image/png, image/jpeg, ...). Optional but helps the router."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Extracted text with page markers."
      },
      "pages": {
        "type": "number",
        "description": "Total pages processed."
      },
      "method": {
        "type": "string",
        "description": "Extraction method used (pdftotext or ocr)."
      },
      "chars": {
        "type": "number",
        "description": "Total character count."
      },
      "empty": {
        "type": "boolean",
        "description": "True when no meaningful text was extracted."
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Text Extracted",
      "description": "Text successfully extracted.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "No Text",
      "description": "File exists but no meaningful text could be extracted.",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "OCR processing failed.",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "ocr",
    "pdf",
    "image",
    "text",
    "document"
  ],
  "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": {
    "mode": {
      "type": "string",
      "title": "Extraction Mode",
      "enum": [
        "auto",
        "text_extract",
        "ocr_only"
      ],
      "default": "auto",
      "description": "Auto tries pdftotext first, falls back to OCR. Text Extract is fast for digital PDFs. OCR Only forces image-based recognition."
    },
    "language": {
      "type": "string",
      "title": "OCR Language",
      "default": "spa",
      "description": "Tesseract language code (e.g., spa, eng, fra, deu, por)."
    },
    "dpi": {
      "type": "number",
      "title": "DPI",
      "default": 300,
      "description": "Resolution for PDF-to-image conversion. Higher = better quality but slower."
    },
    "page_range": {
      "type": "string",
      "title": "Page Range",
      "description": "Optional: process specific pages (e.g., \"1-50\"). Leave empty for all pages.",
      "format": "expression"
    },
    "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",
      "description": "File content encoded as base64 string."
    },
    "file_path": {
      "type": "string",
      "description": "Alternative: local file path to the PDF or image."
    },
    "content_type": {
      "type": "string",
      "description": "MIME type (application/pdf, image/png, image/jpeg, ...). Optional but helps the router."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string",
      "description": "Extracted text with page markers."
    },
    "pages": {
      "type": "number",
      "description": "Total pages processed."
    },
    "method": {
      "type": "string",
      "description": "Extraction method used (pdftotext or ocr)."
    },
    "chars": {
      "type": "number",
      "description": "Total character count."
    },
    "empty": {
      "type": "boolean",
      "description": "True when no meaningful text was extracted."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "extracted",
    "label": "Text Extracted",
    "description": "Text successfully extracted.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "No Text",
    "description": "File exists but no meaningful text could be extracted.",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "OCR processing failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
