# Multimodal Text Extraction

> Format-agnostic dispatcher that accepts a single file, detects its MIME type, and routes it to the appropriate extractor, returning a unified text output.

Source: https://docs.sommatic.ai/en/nodes/ai.multimodal.extract.text/

- Slug: `ai.multimodal.extract.text`
- Family: AI
- Version: 1.0.0
- Status: Available
- Execution: async

Format-agnostic dispatcher that accepts a single file, detects its MIME type, and routes it to the appropriate extractor, returning a unified text output.

Backed by MarkItDown as the orchestration layer for Office and markup formats and by pytesseract for image OCR. Produces deterministic text suitable for classification, RAG indexing, or downstream LLM consumption without the caller having to pre-identify the format.

**Supported formats:**
- **Documents:** PDF (text layer only — no OCR fallback in this tier), DOCX, XLSX, PPTX.
- **Markup and structured text:** HTML, XHTML, Markdown, plain text, CSV, TSV, JSON, XML.
- **Images:** PNG, JPG, JPEG, TIFF, BMP, WebP — processed with a single-pass OCR engine.

**Operational notes:**
- **Single-file scope:** Processes one file per invocation. For batch inputs (email attachments, archive contents), compose `ai.email.parse` or `ai.archive.decompress` upstream with `flow.split`, then fan in with `flow.join`.
- **Silent-fail detection:** When the underlying extractor returns no meaningful text (common with scanned PDFs and low-quality images), the worker emits port `empty` rather than a silent empty string.
- **Tier upgrade:** For quality-driven cascade with OCR fallback, confidence scoring, adaptive preprocessing, language detection, and per-segment error recovery, use `ai.multimodal.extract.text.cascade-pipeline`.

## Configuration

This node has no configuration fields.

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): Extracted
- `empty`: Empty
- `error`: Error

## Input contract

- `content_base64` (string, optional)
- `file_path` (string, optional)
- `name` (string, optional): Filename hint (helps MIME detection).
- `content_type` (string, optional): MIME override.

## Output contract

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

## In expressions

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

- `$("Multimodal Text Extraction").item.json.text` (string) = `"## Sheet1\n| Region | Total |\n| --- | --- |…"`
- `$("Multimodal Text Extraction").item.json.chars` (number) = `56`
- `$("Multimodal Text Extraction").item.json.empty` (boolean) = `false`
- `$("Multimodal Text Extraction").item.json.method` (string) = `"markitdown:application/vnd.openxmlformats-of…"`
- `$("Multimodal Text Extraction").item.json.metadata` (object) = `{…}`
- `$("Multimodal Text Extraction").item.json.metadata.content_type_detected` (string) = `"application/vnd.openxmlformats-officedocumen…"` (Not suggested by the editor)
- `$("Multimodal Text Extraction").item.json.metadata.title` (string) = `""` (Not suggested by the editor)


## How it works

Converts one file to Markdown-like text with MarkItDown (PDF text layer, Office files, HTML, CSV, JSON, XML, plain text) and flags results with too little text as `empty`.

1. Reads `content_base64`, `file_path`, `name` and `content_type` from the node config, falling back to the upstream payload; fails on `error` when neither `content_base64` nor `file_path` is present.
2. Uses `file_path` when that file exists on the host; otherwise writes the base64 bytes to a temp file named after `name` (default `input.bin`, unsafe characters replaced by `_`).
3. Records the MIME type: `content_type` if given, otherwise detected from the file bytes. It is reported only; MarkItDown picks the converter from the file itself.
4. Converts the file and trims the text. `empty` is `true` when the text has fewer than 10 letters or digits.
5. Routes to `empty` or `extracted` accordingly.

## In a workflow

### Node

```json
{
  "node_id": "node-read-attachment",
  "label": "Read attachment",
  "operator_slug": "ai.multimodal.extract.text",
  "operator_version": "1.0.0",
  "config": {
    "content_base64": "{{ $json.content_base64 }}",
    "name": "{{ $json.name }}",
    "execution": {
      "timeout_ms": 180000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "text": "## Sheet1\n| Region | Total |\n| --- | --- |\n| North | 1200 |",
    "chars": 56,
    "empty": false,
    "method": "markitdown:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "metadata": {
      "content_type_detected": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      "title": ""
    }
  },
  "port": "extracted"
}
```

## Output ports (behaviour in the code)

### `extracted`

The conversion produced at least 10 letters or digits.

```json
{
  "text": "## Sheet1\n| Region | Total |\n| --- | --- |\n| North | 1200 |",
  "chars": 56,
  "empty": false,
  "method": "markitdown:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  "metadata": {
    "content_type_detected": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "title": ""
  }
}
```

### `empty`

The text has fewer than 10 letters or digits: scanned PDFs without a text layer, images, unsupported files. The (possibly short) text is still returned.

```json
{
  "text": "",
  "chars": 0,
  "empty": true,
  "method": "markitdown:application/pdf",
  "metadata": {
    "content_type_detected": "application/pdf",
    "title": ""
  }
}
```

### `error`

No input was given, MarkItDown failed on the file or the script failed.

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

## Behaviour in the code

- `content_base64, file_path, name, content_type`: Not declared in the config schema, but read from the node config first and then from the upstream payload. Usually you map them from the previous node with expressions.
- `name`: For base64 input, `name` becomes the temp file name, and its extension is what lets MarkItDown route the file. Without it the file is `input.bin`.
- `execution`: Only `execution.timeout_ms` is read (fallback 180000 ms). `retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail` and `alwaysOutputData` are ignored.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | Neither the node config nor the upstream payload carries the file. Map `content_base64` (or `file_path`) from the previous node. |
| `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 (unsupported or damaged file). 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. |

## 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 180000 ms, not the schema default of 300000.
- No OCR engine is configured: scanned PDFs and images do not get their text recognised and usually end on `empty`. Use `ai.multimodal.extract.text.cascade-pipeline` for scanned content.
- One file per run; use `flow.split` upstream to process several files.


## Contracts (JSON Schema)

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

```json
{
  "slug": "ai.multimodal.extract.text",
  "name": "Multimodal Text Extraction",
  "category": "ai",
  "version": "1.0.0",
  "description": "Format-agnostic dispatcher that accepts a single file, detects its MIME type, and routes it to the appropriate extractor, returning a unified text output.\n\n  Backed by MarkItDown as the orchestration layer for Office and markup formats and by pytesseract for image OCR. Produces deterministic text suitable for classification, RAG indexing, or downstream LLM consumption without the caller having to pre-identify the format.\n\n  **Supported formats:**\n  - **Documents:** PDF (text layer only — no OCR fallback in this tier), DOCX, XLSX, PPTX.\n  - **Markup and structured text:** HTML, XHTML, Markdown, plain text, CSV, TSV, JSON, XML.\n  - **Images:** PNG, JPG, JPEG, TIFF, BMP, WebP — processed with a single-pass OCR engine.\n\n  **Operational notes:**\n  - **Single-file scope:** Processes one file per invocation. For batch inputs (email attachments, archive contents), compose `ai.email.parse` or `ai.archive.decompress` upstream with `flow.split`, then fan in with `flow.join`.\n  - **Silent-fail detection:** When the underlying extractor returns no meaningful text (common with scanned PDFs and low-quality images), the worker emits port `empty` rather than a silent empty string.\n  - **Tier upgrade:** For quality-driven cascade with OCR fallback, confidence scoring, adaptive preprocessing, language detection, and per-segment error recovery, use `ai.multimodal.extract.text.cascade-pipeline`.",
  "capabilities": [
    "multimodal",
    "text-extraction",
    "dispatcher",
    "document",
    "markup",
    "image"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "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"
      },
      "name": {
        "type": "string",
        "description": "Filename hint (helps MIME detection)."
      },
      "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"
      },
      "metadata": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Extracted",
      "is_default": true,
      "supports_condition": true
    },
    {
      "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",
    "text",
    "super-node"
  ],
  "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": {
    "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"
    },
    "name": {
      "type": "string",
      "description": "Filename hint (helps MIME detection)."
    },
    "content_type": {
      "type": "string",
      "description": "MIME override."
    }
  }
}
```

### 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": "Empty",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "is_default": false,
    "supports_condition": false
  }
]
```
