On this page
Sommatic Docs
Open portal

Multimodal Cascade Text Extraction

Multi-stage text extraction pipeline with quality-driven fallback, adaptive preprocessing, and per-segment error recovery.

View as Markdown
Open in
AI Available ai.multimodal.extract.text.cascade-pipeline Version 1.0.0 Execution: async

Extracts text from one file with a per-format extractor; PDFs are read page by page, trusting the text layer when its quality is good and running Tesseract OCR on the other pages. Adds a quality score and language detection.

Selects a primary extractor by MIME type, scores the extraction quality, and escalates to secondary engines when the primary result is empty or unreadable. Produces rich metadata so downstream classifiers can reason about confidence and language without re-reading the source.

Primary extractors by format:

  • PDF: Per-page, text-layer-first. Each page that carries a good embedded text layer is trusted as-is; pages without one are OCR'd individually with Tesseract (LSTM). Pages are rasterized one at a time in grayscale via PyMuPDF, so peak memory is bounded regardless of document length (no whole-document rasterization).
  • DOCX / XLSX / PPTX: python-docx / openpyxl / python-pptx with structural preservation (headings, tables as markdown, presenter notes).
  • HTML / XHTML: trafilatura with boilerplate removal and metadata harvesting.
  • Images: Tesseract (LSTM) with escalation-gated preprocessing (autocontrast, projection-profile deskew, Otsu binarization) applied when the first pass scores low.
  • Plain text / CSV / JSON / XML: direct decoding with charset sniffing.

OCR quality (per page): OCR runs through image_to_data to capture per-word confidence. When a page's mean confidence or quality score is low, that single page is re-rendered at a higher DPI and preprocessed, and the higher-confidence pass is kept — escalation is per-page so memory stays flat. Tunable via the ocr_* config knobs.

Quality scoring:

  • Shannon entropy of the character distribution detects uniform noise.
  • Alphanumeric ratio rejects OCR output dominated by symbols or isolated glyphs.
  • Sentence-density heuristic (tokens per sentence, average word length) catches garbled passages that pass char-level checks.
  • Aggregated score in [0, 1]; below 0.5 triggers the fallback path automatically and is reported as metadata.fallback_reason.

Operational features:

  • Per-segment error recovery: Page, sheet, or slide failures are isolated — the rest of the file continues and failed segments are reported in metadata rather than aborting the whole extraction.
  • Language detection: langdetect runs on the final text and populates metadata.language, useful for downstream routing and localized classification.
  • Partial results port: When the aggregate quality score falls below the HITL threshold, the worker emits port partial so the workflow can route to a reviewer instead of silently accepting a low-quality extraction.
  • Single-file scope: Processes one file per invocation. Compose ai.email.parse or ai.archive.decompress upstream with flow.split for batch inputs.

Output enrichment:

  • quality_score: aggregate score in [0, 1].
  • metadata.language: ISO 639-1 code detected from the final text.
  • metadata.fallback_reason: why the primary extractor was bypassed (empty_text_layer, low_quality, not_supported).
  • metadata.segment_quality: per-page / per-sheet / per-slide quality array.
  • metadata.extractor_chain: ordered list of engines actually invoked.

How it works

  1. Reads content_base64, file_path, source_url, name, content_type and download_timeout_ms from the node config, falling back to the upstream payload. Priority: content_base64, then file_path, then source_url.
  2. With only source_url, streams a GET download to a temp folder (file named after name, or a random name), with download_timeout_ms (default 120000). The folder is deleted when the node ends.
  3. Detects the MIME type: content_type if given, otherwise from the file bytes, then from the extension. Routes to an extractor: PDF, image (PNG, JPEG, TIFF, BMP, WEBP), DOCX, XLSX, PPTX, HTML, or plain text for text/* and anything unknown.
  4. PDF: for each page, keeps the text layer when it has at least 20 non-space characters and a quality score of at least ocr_page_quality_threshold; otherwise renders the page at ocr_dpi and runs OCR. With ocr_preprocess: "auto", a page whose mean word confidence is below ocr_conf_threshold (or whose quality is below 0.5) is re-rendered at ocr_max_dpi, deskewed and binarised, and the better pass is kept. Each page is prefixed with --- PAGE <n> ---.
  5. Images get OCR with the same escalation rule (without re-rendering). Office, HTML and plain text use their own readers.
  6. Scores the final text (0–1, from character entropy, share of letters and digits, and punctuation density) into quality_score, and detects the language on the first 2000 characters when the text has at least 20 characters.
  7. Routes to empty when the text is empty; to partial when metadata.fallback_reason is set and quality_score is below 0.5; otherwise to extracted.

In a workflow

The node as it appears in a workflow file (draft_nodes[]), and the envelope of a successful run.

{
  "node_id": "node-ocr-attachment",
  "label": "OCR attachment",
  "operator_slug": "ai.multimodal.extract.text.cascade-pipeline",
  "operator_version": "1.0.0",
  "config": {
    "source_url": "{{ $json.download_url }}",
    "name": "{{ $json.name }}",
    "ocr_lang": "spa+eng",
    "ocr_dpi": 300,
    "ocr_max_dpi": 400,
    "ocr_preprocess": "auto",
    "ocr_psm": 6,
    "ocr_conf_threshold": 60,
    "ocr_page_quality_threshold": 0.5,
    "execution": {
      "timeout_ms": 600000
    }
  }
}

Configuration

ocr_lang string Optional

Tesseract language for OCR pages (e.g. "spa", "eng", "spa+eng"). Also used as a prior for language detection.

Default: spa

ocr_dpi integer Optional

Base render DPI for pages that require OCR.

Default: 300

ocr_max_dpi integer Optional

DPI used to re-render a single low-confidence page during escalation (capped at 450).

Default: 400

ocr_preprocess string Optional

none = no preprocessing; auto = deskew + Otsu only on low-confidence pages (recommended); always = preprocess every OCR page.

Default: auto

Allowed values: noneautoalways

ocr_psm integer Optional

Page-segmentation mode. 6 = single uniform block (dense single-column text); 3/4 for multi-column layouts.

Default: 6

ocr_conf_threshold number Optional

Mean word-confidence (0-100) below which a page is escalated (re-render + preprocess).

Default: 60

ocr_page_quality_threshold number Optional

Per-page quality score (0-1) the embedded text layer must reach to be trusted without OCR.

Default: 0.5

language string Optional

Deprecated — use ocr_lang. Kept for backward compatibility.

Default: spa

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

Behaviour in the code

What the implementation does with these keys beyond what the schema says.

content_base64, file_path, source_url, name, content_type, download_timeout_ms
Not declared in the config schema (they are in the input contract), but read from the node config first and then from the upstream payload.
ocr_lang
Tesseract language code(s), e.g. spa, eng or spa+eng; falls back to language, then spa. It is not used as a prior by the language detector.
ocr_max_dpi
Capped at 450. The escalation pass renders at the larger of ocr_max_dpi and ocr_dpi.
ocr_preprocess
none: single plain OCR pass. auto: escalate only low-confidence pages. always: preprocess every OCR page (no escalation pass).
execution
Only execution.timeout_ms is read (fallback 300000 ms). retryOnFail, maxTries, waitBetweenTries, continueOnFail and alwaysOutputData are ignored.

Output ports

extracted default

Text was extracted and, if OCR was used, its quality is at least 0.5.

Data
{
  "text": "--- PAGE 1 ---\nResolution 118 of 2026\n\n--- PAGE 2 ---\nArticle 1. The board approves the budget.",
  "chars": 92,
  "empty": false,
  "method": "pdf_per_page_cascade",
  "metadata": {
    "pages": 2,
    "pages_text_layer": 1,
    "pages_ocred": 1,
    "pages_failed": 0,
    "segment_quality": [
      {
        "page": 1,
        "source": "text_layer",
        "score": 0.912,
        "mean_conf": null,
        "dpi_used": null
      },
      {
        "page": 2,
        "source": "ocr",
        "score": 0.871,
        "mean_conf": 88.4,
        "dpi_used": 300,
        "escalated": false
      }
    ],
    "fallback_reason": "partial_ocr",
    "ocr_language": "spa",
    "language": "en",
    "language_confidence": 0.999
  },
  "quality_score": 0.884
}
partial

Only for PDFs where at least one page needed OCR (fallback_reason is empty_text_layer or partial_ocr) and the final quality_score is below 0.5. Images and other formats never reach this port.

Data
{
  "text": "--- PAGE 1 ---\nRe5olut1on 1l8 ,, 2O26",
  "chars": 36,
  "empty": false,
  "method": "pdf_per_page_cascade",
  "metadata": {
    "pages": 1,
    "pages_text_layer": 0,
    "pages_ocred": 1,
    "pages_failed": 0,
    "segment_quality": [
      {
        "page": 1,
        "source": "ocr",
        "score": 0.41,
        "mean_conf": 42.7,
        "dpi_used": 400,
        "escalated": true
      }
    ],
    "fallback_reason": "empty_text_layer",
    "ocr_language": "spa",
    "language": "en",
    "language_confidence": 0.71
  },
  "quality_score": 0.43
}
empty

The extractor returned no text. For PDFs this only happens with zero pages, because every page adds its --- PAGE <n> --- marker.

Data
{
  "text": "",
  "chars": 0,
  "empty": true,
  "method": "image_ocr_tesseract",
  "metadata": {
    "language": "spa",
    "mean_conf": 0,
    "preprocessed": true
  },
  "quality_score": 0
}
error

No source was given, the download failed, the file could not be read or the script failed.

Data
{
  "error": "Request failed with status code 404"
}

In expressions

What a later node can read from this node's output with $("Multimodal Cascade Text Extraction").item.json.<path> (write your node's label instead of Multimodal Cascade Text Extraction). 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.

ExpressionEditorWorker
$("Multimodal Cascade Text Extraction").item.json.textstring= "--- PAGE 1 ---\nResolution 118 of 2026\n\n--…"
$("Multimodal Cascade Text Extraction").item.json.charsnumber= 92
$("Multimodal Cascade Text Extraction").item.json.emptyboolean= false
$("Multimodal Cascade Text Extraction").item.json.methodstring= "pdf_per_page_cascade"
$("Multimodal Cascade Text Extraction").item.json.quality_scorenumber= 0.8840-1 quality assessment.
$("Multimodal Cascade Text Extraction").item.json.metadataobject= {…}Rich metadata: language, pages/sheets/slides, fallback_reason, etc.
$("Multimodal Cascade Text Extraction").item.json.metadata.pagesnumberNot suggested by the editor= 2—
$("Multimodal Cascade Text Extraction").item.json.metadata.pages_text_layernumberNot suggested by the editor= 1—
$("Multimodal Cascade Text Extraction").item.json.metadata.pages_ocrednumberNot suggested by the editor= 1—
$("Multimodal Cascade Text Extraction").item.json.metadata.pages_failednumberNot suggested by the editor= 0—
$("Multimodal Cascade Text Extraction").item.json.metadata.segment_qualityarrayNot suggested by the editor= […] (2)—
$("Multimodal Cascade Text Extraction").item.json.metadata.fallback_reasonstringNot suggested by the editor= "partial_ocr"—
$("Multimodal Cascade Text Extraction").item.json.metadata.ocr_languagestringNot suggested by the editor= "spa"—
$("Multimodal Cascade Text Extraction").item.json.metadata.languagestringNot suggested by the editor= "en"—
$("Multimodal Cascade Text Extraction").item.json.metadata.language_confidencenumberNot suggested by the editor= 0.999—

— Worker: The worker returns it but the editor does not suggest it: write it by hand. Keys inside objects can depend on your data or configuration (for example one key per label).

Errors

Message Port Cause and fix
One of `content_base64`, `file_path`, or `source_url` is required. error No source was found in the config or the upstream payload.
Request failed with status code <status> error The source_url download answered with a non-2xx status, or timed out (timeout of <ms>ms exceeded). Here data has only error, no stderr.
Either content_base64 or file_path is required error Raised by the script when only file_path was given and the file does not exist on the host.
<parser exception message> error The Python parser raised an exception (damaged Office file or unreadable image; a PDF page that fails is recorded in segment_quality with source: "failed" instead). The message is passed through as data.error, with the script's stderr in data.stderr.
Python timed out after <timeout_ms>ms error The script exceeded the node timeout. Raise execution.timeout_ms or send a smaller file.
Python stdout exceeded MAX_STDOUT_BYTES (52428800 bytes) error The result (text or base64 files) is larger than the 50 MB cap. Split the input upstream.
Python runtime not available (ENOENT) error The host has no Python interpreter. A failed dependency install shows PythonRunner failed: <message> instead. Both are host problems, not workflow problems.

Input contract

content_base64 string Optional

Raw bytes as base64. Suitable only for small files — bloats the workflow envelope.

file_path string Optional

Local filesystem path on this worker. For upstream nodes that already materialized a file to disk; caller owns cleanup.

source_url string Optional

HTTPS URL to stream-download into a temp file on this worker. Recommended for large attachments served from Blob / CDN / S3 — keeps the workflow payload free of base64 and bounds memory. The pipeline cleans up the temp file on exit.

download_timeout_ms number Optional

Timeout for the source_url download in milliseconds. Defaults to 120000 (2 min).

name string Optional

Filename hint (preserved as the extension-bearing name when downloading).

content_type string Optional

MIME override.

Output contract

text string Optional
chars number Optional
empty boolean Optional
method string Optional
quality_score number Optional

0-1 quality assessment.

metadata object Optional

Rich metadata: language, pages/sheets/slides, fallback_reason, etc.

Contracts (JSON Schema)

The definition exactly as the orchestrator declares it. All is the whole *.definition.js; compare it with the sections above to spot differences between the documentation and the schema. Use it to validate a node before you publish.

{
  "slug": "ai.multimodal.extract.text.cascade-pipeline",
  "name": "Multimodal Cascade Text Extraction",
  "category": "ai",
  "version": "1.0.0",
  "description": "Multi-stage text extraction pipeline with quality-driven fallback, adaptive preprocessing, and per-segment error recovery.\n\n  Selects a primary extractor by MIME type, scores the extraction quality, and escalates to secondary engines when the primary result is empty or unreadable. Produces rich metadata so downstream classifiers can reason about confidence and language without re-reading the source.\n\n  **Primary extractors by format:**\n  - **PDF:** Per-page, text-layer-first. Each page that carries a good embedded text layer is trusted as-is; pages without one are OCR'd individually with Tesseract (LSTM). Pages are rasterized one at a time in grayscale via PyMuPDF, so peak memory is bounded regardless of document length (no whole-document rasterization).\n  - **DOCX / XLSX / PPTX:** python-docx / openpyxl / python-pptx with structural preservation (headings, tables as markdown, presenter notes).\n  - **HTML / XHTML:** trafilatura with boilerplate removal and metadata harvesting.\n  - **Images:** Tesseract (LSTM) with escalation-gated preprocessing (autocontrast, projection-profile deskew, Otsu binarization) applied when the first pass scores low.\n  - **Plain text / CSV / JSON / XML:** direct decoding with charset sniffing.\n\n  **OCR quality (per page):** OCR runs through `image_to_data` to capture per-word confidence. When a page's mean confidence or quality score is low, that single page is re-rendered at a higher DPI and preprocessed, and the higher-confidence pass is kept — escalation is per-page so memory stays flat. Tunable via the `ocr_*` config knobs.\n\n  **Quality scoring:**\n  - Shannon entropy of the character distribution detects uniform noise.\n  - Alphanumeric ratio rejects OCR output dominated by symbols or isolated glyphs.\n  - Sentence-density heuristic (tokens per sentence, average word length) catches garbled passages that pass char-level checks.\n  - Aggregated score in `[0, 1]`; below `0.5` triggers the fallback path automatically and is reported as `metadata.fallback_reason`.\n\n  **Operational features:**\n  - **Per-segment error recovery:** Page, sheet, or slide failures are isolated — the rest of the file continues and failed segments are reported in metadata rather than aborting the whole extraction.\n  - **Language detection:** langdetect runs on the final text and populates `metadata.language`, useful for downstream routing and localized classification.\n  - **Partial results port:** When the aggregate quality score falls below the HITL threshold, the worker emits port `partial` so the workflow can route to a reviewer instead of silently accepting a low-quality extraction.\n  - **Single-file scope:** Processes one file per invocation. Compose `ai.email.parse` or `ai.archive.decompress` upstream with `flow.split` for batch inputs.\n\n  **Output enrichment:**\n  - `quality_score`: aggregate score in `[0, 1]`.\n  - `metadata.language`: ISO 639-1 code detected from the final text.\n  - `metadata.fallback_reason`: why the primary extractor was bypassed (`empty_text_layer`, `low_quality`, `not_supported`).\n  - `metadata.segment_quality`: per-page / per-sheet / per-slide quality array.\n  - `metadata.extractor_chain`: ordered list of engines actually invoked.",
  "capabilities": [
    "multimodal",
    "text-extraction",
    "cascade",
    "quality-scoring",
    "language-detection",
    "ocr-fallback",
    "adaptive-preprocessing"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "ocr_lang": {
        "type": "string",
        "title": "OCR Language",
        "default": "spa",
        "description": "Tesseract language for OCR pages (e.g. \"spa\", \"eng\", \"spa+eng\"). Also used as a prior for language detection."
      },
      "ocr_dpi": {
        "type": "integer",
        "title": "OCR DPI",
        "default": 300,
        "description": "Base render DPI for pages that require OCR."
      },
      "ocr_max_dpi": {
        "type": "integer",
        "title": "OCR Escalation DPI",
        "default": 400,
        "description": "DPI used to re-render a single low-confidence page during escalation (capped at 450)."
      },
      "ocr_preprocess": {
        "type": "string",
        "title": "OCR Preprocessing",
        "default": "auto",
        "enum": [
          "none",
          "auto",
          "always"
        ],
        "description": "none = no preprocessing; auto = deskew + Otsu only on low-confidence pages (recommended); always = preprocess every OCR page."
      },
      "ocr_psm": {
        "type": "integer",
        "title": "Tesseract PSM",
        "default": 6,
        "description": "Page-segmentation mode. 6 = single uniform block (dense single-column text); 3/4 for multi-column layouts."
      },
      "ocr_conf_threshold": {
        "type": "number",
        "title": "OCR Confidence Threshold",
        "default": 60,
        "description": "Mean word-confidence (0-100) below which a page is escalated (re-render + preprocess)."
      },
      "ocr_page_quality_threshold": {
        "type": "number",
        "title": "Text-Layer Quality Gate",
        "default": 0.5,
        "description": "Per-page quality score (0-1) the embedded text layer must reach to be trusted without OCR."
      },
      "language": {
        "type": "string",
        "title": "OCR Language (deprecated alias)",
        "default": "spa",
        "description": "Deprecated — use ocr_lang. Kept for backward compatibility."
      },
      "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": "Raw bytes as base64. Suitable only for small files — bloats the workflow envelope."
      },
      "file_path": {
        "type": "string",
        "description": "Local filesystem path on this worker. For upstream nodes that already materialized a file to disk; caller owns cleanup."
      },
      "source_url": {
        "type": "string",
        "description": "HTTPS URL to stream-download into a temp file on this worker. Recommended for large attachments served from Blob / CDN / S3 — keeps the workflow payload free of base64 and bounds memory. The pipeline cleans up the temp file on exit."
      },
      "download_timeout_ms": {
        "type": "number",
        "description": "Timeout for the source_url download in milliseconds. Defaults to 120000 (2 min)."
      },
      "name": {
        "type": "string",
        "description": "Filename hint (preserved as the extension-bearing name when downloading)."
      },
      "content_type": {
        "type": "string",
        "description": "MIME override."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string"
      },
      "chars": {
        "type": "number"
      },
      "empty": {
        "type": "boolean"
      },
      "method": {
        "type": "string"
      },
      "quality_score": {
        "type": "number",
        "description": "0-1 quality assessment."
      },
      "metadata": {
        "type": "object",
        "description": "Rich metadata: language, pages/sheets/slides, fallback_reason, etc."
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Extracted",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "partial",
      "label": "Partial (low quality)",
      "is_default": false,
      "supports_condition": true,
      "description": "Text extracted but quality is below threshold. Consider HITL."
    },
    {
      "port_id": "empty",
      "label": "Empty",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "multimodal",
    "cascade",
    "super-node",
    "advanced"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}

Execution

Execution
async
Stateful
No
Retries (retryOnFail)
No
Capabilities
multimodaltext-extractioncascadequality-scoringlanguage-detectionocr-fallbackadaptive-preprocessing
Tags
aimultimodalcascadesuper-nodeadvanced

Notes and limits

  • Runs a Python script in a child process. The first run on a worker host creates a virtual environment and installs the script's pinned dependencies (it can take minutes and is not counted in the node timeout); later runs reuse it.
  • file_path must point to a file on the local disk of the orchestrator host that runs the node; it is not a URL and is not fetched from storage.
  • The script is killed after execution.timeout_ms; when that key is not set the code uses 300000 ms, not the schema default of 300000.
  • The script's JSON answer is capped at 50 MB (52428800 bytes, configurable on the host). Because files travel as base64, large inputs or outputs can hit this cap.
  • source_url accepts any URL the host can reach, without authentication headers; use a pre-signed or public link. Prefer it over content_base64 for large files to keep base64 out of the workflow state.
  • OCR runs one page at a time on a single thread, so long scanned PDFs take time; raise execution.timeout_ms for them. During test runs, per-page progress is reported to the canvas.
  • For images, metadata.language starts as the OCR language and is replaced by the detected language when the text has at least 20 characters.
  • Legacy .doc, .xls and .ppt, and any unrecognised type, are read as plain UTF-8 text, which usually yields garbage with a low quality_score.

Reviewed against the orchestrator code · 31e874b · 2026-11-26

Install agent tools

Give your coding agent the official Sommatic AI docs: skills, the docs MCP server and Markdown pages, so it never has to scrape the site.

Skills only. They do not update by themselves; run it again to refresh.

npx skills add https://docs.sommatic.ai
How agents read these docs