# Multimodal Text Extraction

> Despachador independiente del formato que recibe un único archivo, detecta su tipo MIME, lo dirige al extractor adecuado y devuelve una salida de texto unificada.

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

- Slug: `ai.multimodal.extract.text`
- Familia: IA
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Despachador independiente del formato que recibe un único archivo, detecta su tipo MIME, lo dirige al extractor adecuado y devuelve una salida de texto unificada.

Usa MarkItDown como capa de orquestación para los formatos de Office y de marcado, y pytesseract para el OCR de imágenes. Produce un texto determinista apto para clasificación, indexación RAG o consumo por un LLM posterior, sin que quien llama tenga que identificar antes el formato.

**Formatos admitidos:**
- **Documentos:** PDF (solo la capa de texto; en este nivel no hay OCR de respaldo), DOCX, XLSX, PPTX.
- **Marcado y texto estructurado:** HTML, XHTML, Markdown, texto plano, CSV, TSV, JSON, XML.
- **Imágenes:** PNG, JPG, JPEG, TIFF, BMP, WebP, procesadas con un motor de OCR de una sola pasada.

**Notas operativas:**
- **Un archivo por invocación:** Procesa un archivo en cada invocación. Para entradas por lotes (adjuntos de correo, contenido de archivos comprimidos), compón antes `ai.email.parse` o `ai.archive.decompress` con `flow.split` y luego reúne con `flow.join`.
- **Detección de fallos silenciosos:** Cuando el extractor subyacente no devuelve texto útil (algo habitual en PDF escaneados e imágenes de baja calidad), el worker emite el puerto `empty` en lugar de una cadena vacía silenciosa.
- **Nivel superior:** Para una cascada orientada a la calidad, con OCR de respaldo, puntuación de confianza, preprocesamiento adaptativo, detección de idioma y recuperación de errores por segmento, usa `ai.multimodal.extract.text.cascade-pipeline`.

## Configuración

Este nodo no tiene campos de configuración.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `extracted` (por defecto): Extracted
- `empty`: Empty
- `error`: Error

## Contrato de entrada

- `content_base64` (string, opcional)
- `file_path` (string, opcional)
- `name` (string, opcional): Nombre del archivo como pista (ayuda a detectar el tipo MIME).
- `content_type` (string, opcional): Tipo MIME forzado.

## Contrato de salida

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

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Multimodal Text Extraction").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Multimodal Text Extraction`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `extracted`, según la salida que muestra Puertos.

- `$("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…"` (El editor no la sugiere)
- `$("Multimodal Text Extraction").item.json.metadata.title` (string) = `""` (El editor no la sugiere)


## Cómo funciona

Convierte un archivo a texto tipo Markdown con MarkItDown (capa de texto de PDF, archivos de Office, HTML, CSV, JSON, XML, texto plano) y marca como `empty` los resultados con muy poco texto.

1. Lee `content_base64`, `file_path`, `name` y `content_type` de la configuración del nodo y, si faltan, del payload anterior; sale por `error` si no hay `content_base64` ni `file_path`.
2. Usa `file_path` si ese archivo existe en el host; si no, escribe los bytes en base64 en un archivo temporal con el nombre de `name` (por defecto `input.bin`, con los caracteres no seguros cambiados por `_`).
3. Registra el tipo MIME: `content_type` si se envió; si no, se detecta por los bytes del archivo. Solo se informa; MarkItDown elige el conversor a partir del propio archivo.
4. Convierte el archivo y recorta el texto. `empty` es `true` cuando el texto tiene menos de 10 letras o dígitos.
5. Sale por `empty` o por `extracted` según corresponda.

## En un workflow

### Nodo

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

## Puertos de salida (comportamiento en el código)

### `extracted`

La conversión produjo al menos 10 letras o dígitos.

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

El texto tiene menos de 10 letras o dígitos: PDF escaneados sin capa de texto, imágenes, archivos no soportados. El texto (quizá corto) se devuelve igual.

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

### `error`

No se recibió entrada, MarkItDown falló con el archivo o el script falló.

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

## Comportamiento en el código

- `content_base64, file_path, name, content_type`: No están declaradas en el esquema de configuración, pero se leen primero de la configuración del nodo y luego del payload anterior. Lo habitual es mapearlas desde el nodo previo con expresiones.
- `name`: Con entrada en base64, `name` pasa a ser el nombre del archivo temporal, y su extensión es lo que permite a MarkItDown enrutar el archivo. Sin él, el archivo se llama `input.bin`.
- `execution`: Solo se lee `execution.timeout_ms` (valor de respaldo 180000 ms). `retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail` y `alwaysOutputData` se ignoran.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | Ni la configuración del nodo ni el payload anterior traen el archivo. Mapea `content_base64` (o `file_path`) desde el nodo previo. |
| `Either content_base64 or file_path is required` | `error` | Lo lanza el script cuando solo se pasó `file_path` y el archivo no existe en el host. |
| `<parser exception message>` | `error` | El parser de Python lanzó una excepción (archivo no soportado o dañado). El mensaje llega tal cual en `data.error`, con el stderr del script en `data.stderr`. |
| `Python timed out after <timeout_ms>ms` | `error` | El script superó el timeout del nodo. Sube `execution.timeout_ms` o envía un archivo más pequeño. |
| `Python stdout exceeded MAX_STDOUT_BYTES (52428800 bytes)` | `error` | El resultado (texto o archivos en base64) supera el tope de 50 MB. Divide la entrada antes de este nodo. |
| `Python runtime not available (ENOENT)` | `error` | El host no tiene intérprete de Python. Si falla la instalación de dependencias, el mensaje es `PythonRunner failed: <message>`. Ambos son problemas del host, no del flujo. |

## Notas y límites

- Ejecuta un script de Python en un proceso hijo. La primera ejecución en un host crea un entorno virtual e instala las dependencias fijadas del script (puede tardar minutos y no cuenta para el timeout del nodo); las siguientes lo reutilizan.
- `file_path` debe apuntar a un archivo en el disco local del host del orquestador que ejecuta el nodo; no es una URL y no se descarga de ningún almacenamiento.
- El script se termina al cumplirse `execution.timeout_ms`; si esa clave no está definida, el código usa 180000 ms, no el valor por defecto del esquema (300000).
- No hay motor de OCR configurado: los PDF escaneados y las imágenes no obtienen reconocimiento de texto y suelen terminar en `empty`. Usa `ai.multimodal.extract.text.cascade-pipeline` para contenido escaneado.
- Un archivo por ejecución; usa `flow.split` antes para procesar varios archivos.


## Contratos (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
  }
]
```
