# OCR - Adaptive

> 自适应多引擎 OCR，具备智能预处理、表格检测和置信度评分。

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

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

自适应多引擎 OCR，具备智能预处理、表格检测和置信度评分。

并行使用多个 OCR 引擎（pytesseract + EasyOCR），逐页选取置信度最高的结果。包含基于 OpenCV 的扫描文档预处理。

**功能特性：**
- **多引擎对比：** 运行 pytesseract 和 EasyOCR，根据置信度得分逐页选取最佳结果。
- **预处理：** 通过 OpenCV 进行二值化（Otsu）、纠偏、去噪和对比度增强。
- **表格检测：** 可选地通过形态学方法检测表格结构，并抽取单元格级文本。
- **置信度评分：** 逐页置信度指标和汇总的处理统计。
- **批量处理：** 按每批 5 页处理，高效应对大型文档。

## 配置

- `language` (string, 可选): Tesseract 语言代码（例如 spa、eng、fra、deu、por）。EasyOCR 使用相同的语言映射。 默认值: `spa`.
- `dpi` (number, 可选): PDF 转图像的分辨率。越高质量越好，但速度越慢。 默认值: `300`.
- `page_range` (string, 可选, 支持表达式): 可选：处理指定页面（例如“1-50”）。留空则处理全部页面。
- `enable_table_detection` (boolean, 可选): 通过形态学分析检测表格，并抽取单元格级文本。 默认值: `false`.
- `enable_preprocessing` (boolean, 可选): 应用图像预处理：二值化、纠偏、去噪。 默认值: `true`.
- `engines` (array<string>, 可选): 要组合使用的 OCR 引擎。通过置信度投票逐页选出最佳结果。 默认值: `["pytesseract","easyocr"]`.

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

## 输出端口

- `extracted` (默认): 文本抽取成功，并附带置信度得分。
- `empty`: 无法抽取出有意义的文本。
- `error`: 自适应 OCR 处理失败。

## 输入契约

- `content_base64` (string, 可选): 以 base64 字符串编码的 PDF 内容。
- `file_path` (string, 可选): 替代方式：PDF 的本地文件路径。

## 输出契约

- `text` (string, 可选): 带页面标记的抽取文本。
- `pages` (number, 可选): 已处理的总页数。
- `method` (string, 可选): 抽取方式标识（adaptive_multi_engine）。
- `chars` (number, 可选): 总字符数。
- `empty` (boolean, 可选): 未抽取到有意义的文本时为 true。
- `confidence_per_page` (array<number>, 可选): 每页的置信度得分（0-100）。
- `tables` (array, 可选): 检测到的表格（启用时）。
- `processing_stats` (object, 可选): 各引擎胜出次数、平均置信度、是否预处理。

## 在表达式中

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

- `$("OCR - Adaptive").item.json.text` (string) = `"--- PAGE 1 ---\nCERTIFICATE OF DELIVERY\nRec…"`: 带页面标记的抽取文本。
- `$("OCR - Adaptive").item.json.pages` (number) = `2`: 已处理的总页数。
- `$("OCR - Adaptive").item.json.method` (string) = `"adaptive_multi_engine"`: 抽取方式标识（adaptive_multi_engine）。
- `$("OCR - Adaptive").item.json.chars` (number) = `92`: 总字符数。
- `$("OCR - Adaptive").item.json.empty` (boolean) = `false`: 未抽取到有意义的文本时为 true。
- `$("OCR - Adaptive").item.json.confidence_per_page` (array) = `[…] (2)`: 每页的置信度得分（0-100）。
- `$("OCR - Adaptive").item.json.tables` (array) = `[…] (1)`: 检测到的表格（启用时）。
- `$("OCR - Adaptive").item.json.processing_stats` (object) = `{…}`: 各引擎胜出次数、平均置信度、是否预处理。
- `$("OCR - Adaptive").item.json.processing_stats.pytesseract_wins` (number) = `1` (编辑器不提示)
- `$("OCR - Adaptive").item.json.processing_stats.easyocr_wins` (number) = `1` (编辑器不提示)
- `$("OCR - Adaptive").item.json.processing_stats.avg_confidence` (number) = `84.73` (编辑器不提示)
- `$("OCR - Adaptive").item.json.processing_stats.preprocessing_applied` (boolean) = `true` (编辑器不提示)


## 工作原理

面向扫描版 PDF 的 OCR：渲染每一页，可选地进行清理（二值化、纠偏），运行 Tesseract 和/或 EasyOCR，并保留该页置信度更高的引擎结果。还可检测带边框线的表格。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 先从配置、再从传入条目读取 `content_base64` 或 `file_path`。两者都没有时返回 `error`。
3. 以 `dpi` 渲染 `page_range` 内的 PDF 页面（仅支持 PDF 输入，不支持图片）。
4. 对每一页：若 `enable_preprocessing` 不为 `false`，则执行 Otsu 二值化、纠偏（角度超过 0.5° 时）和轻度清理。
5. 在该页上依次运行已启用的引擎，保留置信度（0–100）更高者的文本。置信度相同时保留 Tesseract。
6. 当 `enable_table_detection: true` 且启用了 Tesseract 时，在原始页面上查找带线网格，并用 Tesseract 读取每个单元格。
7. 用 `--- PAGE n ---` 标记拼接各页，并返回每页置信度、表格和引擎统计。Python 失败返回 `error`；`empty: true` 或 `chars: 0` 返回 `empty`；其余返回 `extracted`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-ocr-adaptive",
  "label": "Adaptive OCR",
  "operator_slug": "ai.ocr.adaptive",
  "operator_version": "1.0.0",
  "config": {
    "language": "eng",
    "dpi": 300,
    "page_range": "1-5",
    "enable_preprocessing": true,
    "enable_table_detection": true,
    "engines": [
      "pytesseract",
      "easyocr"
    ],
    "execution": {
      "timeout_ms": 1200000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "extracted",
  "data": {
    "text": "--- PAGE 1 ---\nCERTIFICATE OF DELIVERY\nReceived by: J. Doe\n\n--- PAGE 2 ---\nItem Qty\nPallet 4",
    "pages": 2,
    "method": "adaptive_multi_engine",
    "chars": 92,
    "empty": false,
    "confidence_per_page": [
      91.4,
      78.06
    ],
    "tables": [
      {
        "page": 2,
        "rows": [
          [
            "Item",
            "Qty"
          ],
          [
            "Pallet",
            "4"
          ]
        ]
      }
    ],
    "processing_stats": {
      "pytesseract_wins": 1,
      "easyocr_wins": 1,
      "avg_confidence": 84.73,
      "preprocessing_applied": true
    }
  }
}
```

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

### `extracted`

至少渲染了一页。请查看 `confidence_per_page`：未识别出任何内容的页面同样计入。

```json
{
  "text": "--- PAGE 1 ---\nCERTIFICATE OF DELIVERY\nReceived by: J. Doe\n\n--- PAGE 2 ---\nItem Qty\nPallet 4",
  "pages": 2,
  "method": "adaptive_multi_engine",
  "chars": 92,
  "empty": false,
  "confidence_per_page": [
    91.4,
    78.06
  ],
  "tables": [
    {
      "page": 2,
      "rows": [
        [
          "Item",
          "Qty"
        ],
        [
          "Pallet",
          "4"
        ]
      ]
    }
  ],
  "processing_stats": {
    "pytesseract_wins": 1,
    "easyocr_wins": 1,
    "avg_confidence": 84.73,
    "preprocessing_applied": true
  }
}
```

### `empty`

没有渲染任何页面。由于每页都会添加标记，有页面的文档不会从此端口输出。

```json
{
  "text": "",
  "pages": 0,
  "method": "adaptive_multi_engine",
  "chars": 0,
  "empty": true,
  "confidence_per_page": [],
  "tables": [],
  "processing_stats": {
    "pytesseract_wins": 0,
    "easyocr_wins": 0,
    "avg_confidence": 0,
    "preprocessing_applied": true
  }
}
```

### `error`

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

```json
{
  "error": "At least one engine must be enabled",
  "stderr": ""
}
```

## 代码中的行为

- `language`: Tesseract 语言代码，默认 `spa`。对 EasyOCR 会进行映射（spa→es、eng→en、fra→fr、deu→de、por→pt、ita→it、nld→nl、pol→pl、rus→ru、jpn→ja、chi_sim→ch_sim、chi_tra→ch_tra、kor→ko、ara→ar）；其他代码原样传递。
- `page_range`: 仅支持 `N-M` 形式；其他值会处理全部页面。
- `engines`: 可识别的值为 `pytesseract` 和 `easyocr`。只启用一个引擎时不进行投票。
- `enable_table_detection`: 当引擎中不含 `pytesseract` 时会被忽略。只能找到用线条绘制的网格。
- `execution.timeout_ms`: 整个 Python 运行的超时时间。未设置时代码使用 1200000 毫秒（20 分钟）；schema 显示为 300000。
- `content_base64 / file_path`: 它们未在配置 schema 中声明，但会先于传入条目从配置读取。可用表达式指向文件，例如 `{{ $json.attachment.content_base64 }}`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | 配置和传入条目中都没有 `content_base64` 或 `file_path`。请从上一个节点映射文件。 |
| `At least one engine must be enabled` | `error` | `engines` 中既没有 `pytesseract` 也没有 `easyocr`。其他名称会被忽略。 |
| `<pdf2image, Tesseract or EasyOCR error>` | `error` | 输入不是 PDF、主机上缺少 Poppler 或 Tesseract（含 `language` 数据），或 EasyOCR 不支持该语言。 |
| `Python timed out after <timeout_ms>ms` | `error` | 脚本超过了 `execution.timeout_ms`。请调大该值或减少处理的页数。 |
| `Python runtime not available (ENOENT)` | `error` | 编排器主机上没有可用的 Python 解释器。 |

## 说明与限制

- 引擎在 CPU 上顺序运行，而非并行；两者都启用时每页会被读取两次。每页预计耗时数秒。
- Tesseract 的置信度是其各词置信度的平均值；EasyOCR 的置信度是其各检测结果的平均值 × 100。EasyOCR 用空格连接检测结果，因此其文本没有换行。
- `file_path` 是编排器主机上的路径。两者同时存在时以 `content_base64` 为准。
- 提取在 Python 子进程中运行。首次使用时，编排器会创建虚拟环境并安装固定版本的依赖，可能需要数分钟；之后的运行会复用该环境。
- Python 结果的输出上限为 50 MB；超过后节点从 `error` 端口输出。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.ocr.adaptive",
  "name": "OCR - Adaptive",
  "category": "ai",
  "version": "1.0.0",
  "description": "Adaptive multi-engine OCR with intelligent preprocessing, table detection, and confidence scoring.\n\n  Uses multiple OCR engines (pytesseract + EasyOCR) in parallel and selects the highest-confidence result per page. Includes OpenCV-based preprocessing for scanned documents.\n\n  **Features:**\n  - **Multi-engine comparison:** Runs pytesseract and EasyOCR, picks the best result per page based on confidence score.\n  - **Preprocessing:** Binarization (Otsu), deskew correction, noise removal, and contrast enhancement via OpenCV.\n  - **Table detection:** Optional morphological detection of table structures with cell-level text extraction.\n  - **Confidence scoring:** Per-page confidence metrics and aggregated processing statistics.\n  - **Batch processing:** Handles large documents efficiently by processing pages in batches of 5.",
  "capabilities": [
    "ocr",
    "pdf",
    "text-extraction",
    "document",
    "table-detection",
    "multi-engine",
    "preprocessing"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "language": {
        "type": "string",
        "title": "OCR Language",
        "default": "spa",
        "description": "Tesseract language code (e.g., spa, eng, fra, deu, por). EasyOCR uses the same language mapping."
      },
      "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",
        "format": "expression",
        "description": "Optional: process specific pages (e.g., \"1-50\"). Leave empty for all."
      },
      "enable_table_detection": {
        "type": "boolean",
        "title": "Enable Table Detection",
        "default": false,
        "description": "Detect tables using morphological analysis and extract cell-level text."
      },
      "enable_preprocessing": {
        "type": "boolean",
        "title": "Enable Preprocessing",
        "default": true,
        "description": "Apply image preprocessing: binarization, deskew, noise removal."
      },
      "engines": {
        "type": "array",
        "title": "OCR Engines",
        "items": {
          "type": "string"
        },
        "default": [
          "pytesseract",
          "easyocr"
        ],
        "description": "OCR engines to combine. Confidence voting picks the best per page."
      },
      "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": "PDF content encoded as base64 string."
      },
      "file_path": {
        "type": "string",
        "description": "Alternative: local file path to the PDF."
      }
    }
  },
  "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 identifier (adaptive_multi_engine)."
      },
      "chars": {
        "type": "number",
        "description": "Total character count."
      },
      "empty": {
        "type": "boolean",
        "description": "True when no meaningful text was extracted."
      },
      "confidence_per_page": {
        "type": "array",
        "items": {
          "type": "number"
        },
        "description": "Confidence score (0-100) for each page."
      },
      "tables": {
        "type": "array",
        "description": "Detected tables (when enabled)."
      },
      "processing_stats": {
        "type": "object",
        "description": "Engine wins, avg confidence, preprocessing flag."
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Text Extracted",
      "is_default": true,
      "supports_condition": true,
      "description": "Text successfully extracted with confidence scores."
    },
    {
      "port_id": "empty",
      "label": "No Text",
      "is_default": false,
      "supports_condition": true,
      "description": "No meaningful text could be extracted."
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false,
      "description": "Adaptive OCR processing failed."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "ocr",
    "pdf",
    "text",
    "document",
    "adaptive",
    "multi-engine"
  ],
  "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": {
    "language": {
      "type": "string",
      "title": "OCR Language",
      "default": "spa",
      "description": "Tesseract language code (e.g., spa, eng, fra, deu, por). EasyOCR uses the same language mapping."
    },
    "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",
      "format": "expression",
      "description": "Optional: process specific pages (e.g., \"1-50\"). Leave empty for all."
    },
    "enable_table_detection": {
      "type": "boolean",
      "title": "Enable Table Detection",
      "default": false,
      "description": "Detect tables using morphological analysis and extract cell-level text."
    },
    "enable_preprocessing": {
      "type": "boolean",
      "title": "Enable Preprocessing",
      "default": true,
      "description": "Apply image preprocessing: binarization, deskew, noise removal."
    },
    "engines": {
      "type": "array",
      "title": "OCR Engines",
      "items": {
        "type": "string"
      },
      "default": [
        "pytesseract",
        "easyocr"
      ],
      "description": "OCR engines to combine. Confidence voting picks the best per page."
    },
    "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": "PDF content encoded as base64 string."
    },
    "file_path": {
      "type": "string",
      "description": "Alternative: local file path to the PDF."
    }
  }
}
```

### 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 identifier (adaptive_multi_engine)."
    },
    "chars": {
      "type": "number",
      "description": "Total character count."
    },
    "empty": {
      "type": "boolean",
      "description": "True when no meaningful text was extracted."
    },
    "confidence_per_page": {
      "type": "array",
      "items": {
        "type": "number"
      },
      "description": "Confidence score (0-100) for each page."
    },
    "tables": {
      "type": "array",
      "description": "Detected tables (when enabled)."
    },
    "processing_stats": {
      "type": "object",
      "description": "Engine wins, avg confidence, preprocessing flag."
    }
  }
}
```

### ports

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