# OCR - Adaptive

> Adaptive multi-engine OCR with intelligent preprocessing, table detection, and confidence scoring.

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

- Slug: `ai.ocr.adaptive`
- Family: AI
- Version: 1.0.0
- Status: Available
- Execution: async

Adaptive multi-engine OCR with intelligent preprocessing, table detection, and confidence scoring.

Uses multiple OCR engines (pytesseract + EasyOCR) in parallel and selects the highest-confidence result per page. Includes OpenCV-based preprocessing for scanned documents.

**Features:**
- **Multi-engine comparison:** Runs pytesseract and EasyOCR, picks the best result per page based on confidence score.
- **Preprocessing:** Binarization (Otsu), deskew correction, noise removal, and contrast enhancement via OpenCV.
- **Table detection:** Optional morphological detection of table structures with cell-level text extraction.
- **Confidence scoring:** Per-page confidence metrics and aggregated processing statistics.
- **Batch processing:** Handles large documents efficiently by processing pages in batches of 5.

## Configuration

- `language` (string, optional): Tesseract language code (e.g., spa, eng, fra, deu, por). EasyOCR uses the same language mapping. Default: `spa`.
- `dpi` (number, optional): Resolution for PDF-to-image conversion. Higher = better quality but slower. Default: `300`.
- `page_range` (string, optional, accepts expressions): Optional: process specific pages (e.g., "1-50"). Leave empty for all.
- `enable_table_detection` (boolean, optional): Detect tables using morphological analysis and extract cell-level text. Default: `false`.
- `enable_preprocessing` (boolean, optional): Apply image preprocessing: binarization, deskew, noise removal. Default: `true`.
- `engines` (array<string>, optional): OCR engines to combine. Confidence voting picks the best per page. Default: `["pytesseract","easyocr"]`.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `extracted` (default): Text successfully extracted with confidence scores.
- `empty`: No meaningful text could be extracted.
- `error`: Adaptive OCR processing failed.

## Input contract

- `content_base64` (string, optional): PDF content encoded as base64 string.
- `file_path` (string, optional): Alternative: local file path to the PDF.

## Output contract

- `text` (string, optional): Extracted text with page markers.
- `pages` (number, optional): Total pages processed.
- `method` (string, optional): Extraction method identifier (adaptive_multi_engine).
- `chars` (number, optional): Total character count.
- `empty` (boolean, optional): True when no meaningful text was extracted.
- `confidence_per_page` (array<number>, optional): Confidence score (0-100) for each page.
- `tables` (array, optional): Detected tables (when enabled).
- `processing_stats` (object, optional): Engine wins, avg confidence, preprocessing flag.

## In expressions

What a later node can read from this node's output with `$("OCR - Adaptive").item.json.<path>` (write your node's label instead of `OCR - Adaptive`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `extracted`, from the output shown in Ports.

- `$("OCR - Adaptive").item.json.text` (string) = `"--- PAGE 1 ---\nCERTIFICATE OF DELIVERY\nRec…"`: Extracted text with page markers.
- `$("OCR - Adaptive").item.json.pages` (number) = `2`: Total pages processed.
- `$("OCR - Adaptive").item.json.method` (string) = `"adaptive_multi_engine"`: Extraction method identifier (adaptive_multi_engine).
- `$("OCR - Adaptive").item.json.chars` (number) = `92`: Total character count.
- `$("OCR - Adaptive").item.json.empty` (boolean) = `false`: True when no meaningful text was extracted.
- `$("OCR - Adaptive").item.json.confidence_per_page` (array) = `[…] (2)`: Confidence score (0-100) for each page.
- `$("OCR - Adaptive").item.json.tables` (array) = `[…] (1)`: Detected tables (when enabled).
- `$("OCR - Adaptive").item.json.processing_stats` (object) = `{…}`: Engine wins, avg confidence, preprocessing flag.
- `$("OCR - Adaptive").item.json.processing_stats.pytesseract_wins` (number) = `1` (Not suggested by the editor)
- `$("OCR - Adaptive").item.json.processing_stats.easyocr_wins` (number) = `1` (Not suggested by the editor)
- `$("OCR - Adaptive").item.json.processing_stats.avg_confidence` (number) = `84.73` (Not suggested by the editor)
- `$("OCR - Adaptive").item.json.processing_stats.preprocessing_applied` (boolean) = `true` (Not suggested by the editor)


## How it works

OCR for scanned PDFs: renders each page, optionally cleans it (binarization, deskew), runs Tesseract and/or EasyOCR, and keeps the text of the engine with the higher confidence for that page. It can also detect ruled tables.

1. Resolves the node config: expressions in config keys are evaluated against the run; the incoming item is used as-is.
2. Reads `content_base64` or `file_path` from the config first, then from the incoming item. If neither is present it returns `error`.
3. Renders the PDF pages in `page_range` at `dpi` (PDF input only; images are not supported).
4. For each page: applies Otsu binarization, deskew (when the angle exceeds 0.5°) and a light cleanup if `enable_preprocessing` is not `false`.
5. Runs the enabled engines one after another on the page and keeps the text of the one with the higher confidence (0–100). Ties keep Tesseract.
6. With `enable_table_detection: true` and Tesseract enabled, finds ruled grids on the original page and reads each cell with Tesseract.
7. Joins the pages with `--- PAGE n ---` markers and returns per-page confidence, tables and engine statistics. Python failures return `error`; `empty: true` or `chars: 0` returns `empty`; anything else `extracted`.

## In a workflow

### Node

```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
    }
  }
}
```

## Output ports (behaviour in the code)

### `extracted`

At least one page was rendered. Check `confidence_per_page`: pages where nothing was read still count.

```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`

No page was rendered. Because every page adds a marker, a document with pages never comes out here.

```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`

The input is missing or the script fails. `data` is `{ error }` or `{ error, stderr }`.

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

## Behaviour in the code

- `language`: Tesseract code, default `spa`. For EasyOCR it is mapped (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); other codes are passed unchanged.
- `page_range`: Only the `N-M` form is applied; any other value processes all pages.
- `engines`: Recognized values are `pytesseract` and `easyocr`. With one engine there is no voting.
- `enable_table_detection`: Ignored when `pytesseract` is not among the engines. Only grids drawn with lines are found.
- `execution.timeout_ms`: Timeout of the whole Python run. When unset the code uses 1200000 ms (20 min); the schema shows 300000.
- `content_base64 / file_path`: Not declared in the config schema, but read from the config before the incoming item. Use them to point at a file with an expression, e.g. `{{ $json.attachment.content_base64 }}`.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | Neither the config nor the incoming item has `content_base64` or `file_path`. Map the file from the previous node. |
| `At least one engine must be enabled` | `error` | `engines` contains neither `pytesseract` nor `easyocr`. Other names are ignored. |
| `<pdf2image, Tesseract or EasyOCR error>` | `error` | The input is not a PDF, Poppler or Tesseract (with the `language` data) is missing on the host, or EasyOCR does not support the language. |
| `Python timed out after <timeout_ms>ms` | `error` | The script exceeded `execution.timeout_ms`. Raise it or process fewer pages. |
| `Python runtime not available (ENOENT)` | `error` | No Python interpreter is available on the orchestrator host. |

## Notes and limits

- The engines run sequentially on CPU, not in parallel; with both enabled each page is read twice. Expect seconds per page.
- Tesseract confidence is the mean of its word confidences; EasyOCR confidence is the mean of its detections × 100. EasyOCR joins its detections with spaces, so its text has no line breaks.
- `file_path` is a path on the orchestrator host. `content_base64` wins when both are present.
- The extraction runs in a Python subprocess. On first use the orchestrator creates a virtual environment and installs the pinned requirements, which can take minutes; later runs reuse it.
- The Python result is limited to 50 MB of output; above it the node leaves through `error`.
- The engine does not apply `execution.retryOnFail`, `maxTries`, `waitBetweenTries` or `continueOnFail` to this node. Handle failures by wiring the `error` port.


## Contracts (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."
  }
]
```
