# Multimodal Text Extraction

> 与格式无关的分发器：接收单个文件，检测其 MIME 类型并路由到合适的抽取器，返回统一的文本输出。

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

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

与格式无关的分发器：接收单个文件，检测其 MIME 类型并路由到合适的抽取器，返回统一的文本输出。

Office 和标记类格式以 MarkItDown 作为编排层，图片 OCR 则由 pytesseract 支撑。它生成确定性的文本，可直接用于分类、RAG 索引或下游 LLM，调用方无需预先识别文件格式。

**支持的格式：**
- **文档：** PDF（仅文本层，此层级不提供 OCR 回退）、DOCX、XLSX、PPTX。
- **标记与结构化文本：** HTML、XHTML、Markdown、纯文本、CSV、TSV、JSON、XML。
- **图片：** PNG、JPG、JPEG、TIFF、BMP、WebP，使用单轮 OCR 引擎处理。

**运行说明：**
- **单文件范围：** 每次调用处理一个文件。对于批量输入（邮件附件、归档内容），请在上游组合 `ai.email.parse` 或 `ai.archive.decompress` 与 `flow.split`，再用 `flow.join` 汇合。
- **静默失败检测：** 当底层抽取器未返回有意义的文本时（扫描版 PDF 和低质量图片中常见），worker 会触发 `empty` 端口，而不是静默返回空字符串。
- **升级层级：** 如需按质量驱动的级联处理（含 OCR 回退、置信度评分、自适应预处理、语言检测和逐片段错误恢复），请使用 `ai.multimodal.extract.text.cascade-pipeline`。

## 配置

该节点没有配置项。

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

## 输出端口

- `extracted` (默认): Extracted
- `empty`: Empty
- `error`: Error

## 输入契约

- `content_base64` (string, 可选)
- `file_path` (string, 可选)
- `name` (string, 可选): 文件名提示（有助于 MIME 检测）。
- `content_type` (string, 可选): 手动指定 MIME 类型。

## 输出契约

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

## 在表达式中

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

- `$("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…"` (编辑器不提示)
- `$("Multimodal Text Extraction").item.json.metadata.title` (string) = `""` (编辑器不提示)


## 工作原理

使用 MarkItDown 把单个文件转换为类 Markdown 文本（PDF 文本层、Office 文件、HTML、CSV、JSON、XML、纯文本），文本过少的结果标记为 `empty`。

1. 从节点配置读取 `content_base64`、`file_path`、`name` 和 `content_type`，缺失时回退到上游载荷；`content_base64` 和 `file_path` 都没有时从 `error` 输出。
2. 若主机上存在 `file_path` 指向的文件则直接使用；否则把 base64 字节写入以 `name` 命名的临时文件（默认 `input.bin`，不安全字符替换为 `_`）。
3. 记录 MIME 类型：若提供了 `content_type` 则使用，否则根据文件字节检测。该值仅用于报告；MarkItDown 依据文件本身选择转换器。
4. 转换文件并去除首尾空白。文本中字母和数字少于 10 个时 `empty` 为 `true`。
5. 据此从 `empty` 或 `extracted` 输出。

## 在工作流中

### 节点

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

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

### `extracted`

转换结果至少包含 10 个字母或数字。

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

文本中字母和数字少于 10 个：无文本层的扫描 PDF、图片、不支持的文件。仍会返回（可能很短的）文本。

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

### `error`

未提供输入、MarkItDown 处理文件失败或脚本失败。

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

## 代码中的行为

- `content_base64, file_path, name, content_type`: 未在配置 schema 中声明，但会先从节点配置读取，再从上游载荷读取。通常用表达式从上一个节点映射。
- `name`: 对于 base64 输入，`name` 会成为临时文件名，其扩展名决定 MarkItDown 如何路由该文件。不提供时文件名为 `input.bin`。
- `execution`: 仅读取 `execution.timeout_ms`（缺省回退 180000 毫秒）。`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail` 和 `alwaysOutputData` 均被忽略。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | 节点配置和上游载荷都没有提供文件。请从上一个节点映射 `content_base64`（或 `file_path`）。 |
| `Either content_base64 or file_path is required` | `error` | 当只提供了 `file_path` 而主机上不存在该文件时由脚本抛出。 |
| `<parser exception message>` | `error` | Python 解析器抛出异常（文件不受支持或已损坏）。该消息原样放入 `data.error`，脚本的 stderr 放入 `data.stderr`。 |
| `Python timed out after <timeout_ms>ms` | `error` | 脚本超出了节点超时。请调大 `execution.timeout_ms` 或发送更小的文件。 |
| `Python stdout exceeded MAX_STDOUT_BYTES (52428800 bytes)` | `error` | 结果（文本或 base64 文件）超过 50 MB 上限。请在上游拆分输入。 |
| `Python runtime not available (ENOENT)` | `error` | 主机上没有 Python 解释器。若依赖安装失败，消息为 `PythonRunner failed: <message>`。两者都是主机问题，而非工作流问题。 |

## 说明与限制

- 在子进程中运行 Python 脚本。某台 worker 主机上的首次运行会创建虚拟环境并安装脚本锁定的依赖（可能耗时数分钟，且不计入节点超时）；之后的运行会复用该环境。
- `file_path` 必须指向运行该节点的编排器主机本地磁盘上的文件；它不是 URL，也不会从存储中下载。
- 脚本会在 `execution.timeout_ms` 到期后被终止；未设置该键时代码使用 180000 毫秒，而不是 schema 默认的 300000。
- 未配置 OCR 引擎：扫描 PDF 和图片不会进行文字识别，通常会走 `empty`。扫描内容请使用 `ai.multimodal.extract.text.cascade-pipeline`。
- 每次运行处理一个文件；如需处理多个文件，请在上游使用 `flow.split`。


## 契约（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
  }
]
```
