# DOCX Text Extraction

> 借助 python-docx 遍历 Office Open XML Wordprocessing 结构，从 Microsoft Word（.docx）文档中抽取文本。

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

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

借助 python-docx 遍历 Office Open XML Wordprocessing 结构，从 Microsoft Word（.docx）文档中抽取文本。

保留文档的逻辑流程：标题层级、段落顺序、列表嵌套和表格结构。

**功能特性：**
- **结构保留：** 按大纲级别输出标题，按文档顺序输出段落，并为列表项保留项目符号/编号标识。
- **表格转为 markdown：** 文档中的每个表格都渲染为 markdown 表格，下游 LLM 和解析器可以识别单元格边界而不丢失上下文。
- **内联注释：** 对嵌入图片、超链接和脚注的引用以内联标记呈现，并附带其目标元数据。
- **元数据：** 若文档核心属性中存在，则抽取标题、作者、最后修改时间和修订次数。

## 配置

该节点没有配置项。

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

## 输出端口

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

## 输入契约

- `content_base64` (string, 可选)
- `file_path` (string, 可选)

## 输出契约

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

## 在表达式中

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

- `$("DOCX Text Extraction").item.json.text` (string) = `"Service agreement\n\nThe parties agree as fo…"`
- `$("DOCX Text Extraction").item.json.chars` (number) = `92`
- `$("DOCX Text Extraction").item.json.empty` (boolean) = `false`
- `$("DOCX Text Extraction").item.json.method` (string) = `"python-docx"`
- `$("DOCX Text Extraction").item.json.metadata` (object) = `{…}`
- `$("DOCX Text Extraction").item.json.metadata.paragraphs_count` (number) = `14` (编辑器不提示)
- `$("DOCX Text Extraction").item.json.metadata.tables_count` (number) = `1` (编辑器不提示)


## 工作原理

使用 python-docx 提取单个 DOCX 文件的文本：段落为纯文本行，表格为 Markdown 表格。

1. 从节点配置读取 `content_base64` 和 `file_path`，缺失时回退到上游载荷；两者都没有时从 `error` 输出。两者都有时以 `content_base64` 为准。
2. 按顺序遍历文档正文。每个非空段落去除首尾空白后加入；每个顶层表格转换为以首行为表头的 Markdown 表格。
3. 用空行把所有部分拼接为 `text` 并统计 `chars`。
4. 文本为空时从 `empty` 输出，否则从 `extracted` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-read-contract",
  "label": "Read contract",
  "operator_slug": "ai.docx.extract.text",
  "operator_version": "1.0.0",
  "config": {
    "content_base64": "{{ $json.content_base64 }}",
    "execution": {
      "timeout_ms": 120000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "text": "Service agreement\n\nThe parties agree as follows.",
    "chars": 47,
    "empty": false,
    "method": "python-docx",
    "metadata": {
      "paragraphs_count": 14,
      "tables_count": 0
    }
  },
  "port": "extracted"
}
```

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

### `extracted`

文档提取出了文本。

```json
{
  "text": "Service agreement\n\nThe parties agree as follows.\n\n| Item | Amount |\n| --- | --- |\n| Setup | 1200 |",
  "chars": 92,
  "empty": false,
  "method": "python-docx",
  "metadata": {
    "paragraphs_count": 14,
    "tables_count": 1
  }
}
```

### `empty`

文档没有文本（例如只有图片）。

```json
{
  "text": "",
  "chars": 0,
  "empty": true,
  "method": "python-docx",
  "metadata": {
    "paragraphs_count": 0,
    "tables_count": 0
  }
}
```

### `error`

未提供输入、文件不是有效的 DOCX 或脚本失败。

```json
{
  "error": "File is not a zip file",
  "stderr": ""
}
```

## 代码中的行为

- `content_base64, file_path`: 未在配置 schema 中声明，但会先从节点配置读取，再从上游载荷读取。通常用表达式从上一个节点映射。
- `execution`: 仅读取 `execution.timeout_ms`（缺省回退 120000 毫秒）。`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail` 和 `alwaysOutputData` 均被忽略。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | 节点配置和上游载荷都没有提供文件。请从上一个节点映射 `content_base64`（或 `file_path`）。 |
| `<parser exception message>` | `error` | Python 解析器抛出异常（文件不是 DOCX：旧版 `.doc`、PDF 或损坏的数据）。该消息原样放入 `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` 到期后被终止；未设置该键时代码使用 120000 毫秒，而不是 schema 默认的 300000。
- 标题和列表项以普通行输出，不带 Markdown 标记。表格单元格中的文本会出现两次：一次在 Markdown 表格中，一次以独立行形式出现在表格之后。
- 仅支持 `.docx`（Office Open XML）；不读取页眉、页脚、批注和嵌入图片。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.docx.extract.text",
  "name": "DOCX Text Extraction",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extracts text from Microsoft Word (.docx) documents by traversing the Office Open XML Wordprocessing structure with python-docx.\n\n  Preserves the logical flow of the document: heading hierarchy, paragraph order, list nesting, and table structure.\n\n  **Features:**\n  - **Structural preservation:** Emits headings with their outline level, paragraphs in document order, and list items with bullet/number indicators.\n  - **Tables as markdown:** Each in-document table is rendered as a markdown table so downstream LLMs and parsers can consume cell boundaries without losing context.\n  - **Inline annotations:** References to embedded images, hyperlinks, and footnotes are surfaced as inline markers with their target metadata.\n  - **Metadata:** Document title, author, last modified, and revision count extracted from the core properties when present.",
  "capabilities": [
    "docx",
    "office",
    "word",
    "text-extraction",
    "document"
  ],
  "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"
      }
    }
  },
  "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": "No Content",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "docx",
    "office",
    "word",
    "text"
  ],
  "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"
    }
  }
}
```

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