# DOCX Text Extraction

> Extracts text from Microsoft Word (.docx) documents by traversing the Office Open XML Wordprocessing structure with python-docx.

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

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

Extracts text from Microsoft Word (.docx) documents by traversing the Office Open XML Wordprocessing structure with python-docx.

Preserves the logical flow of the document: heading hierarchy, paragraph order, list nesting, and table structure.

**Features:**
- **Structural preservation:** Emits headings with their outline level, paragraphs in document order, and list items with bullet/number indicators.
- **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.
- **Inline annotations:** References to embedded images, hyperlinks, and footnotes are surfaced as inline markers with their target metadata.
- **Metadata:** Document title, author, last modified, and revision count extracted from the core properties when present.

## 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`: No Content
- `error`: Error

## Input contract

- `content_base64` (string, optional)
- `file_path` (string, optional)

## 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 `$("DOCX Text Extraction").item.json.<path>` (write your node's label instead of `DOCX 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.

- `$("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` (Not suggested by the editor)
- `$("DOCX Text Extraction").item.json.metadata.tables_count` (number) = `1` (Not suggested by the editor)


## How it works

Extracts the text of one DOCX file with python-docx: paragraphs as plain lines and tables as Markdown tables.

1. Reads `content_base64` and `file_path` from the node config, falling back to the upstream payload; fails on `error` when both are missing. `content_base64` wins when both are set.
2. Walks the document body in order. Each non-empty paragraph is added trimmed; each top-level table is converted to a Markdown table whose first row is the header.
3. Joins all parts with blank lines into `text` and counts `chars`.
4. Routes to `empty` when the text is empty, otherwise to `extracted`.

## In a workflow

### Node

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

## Output ports (behaviour in the code)

### `extracted`

The document produced some text.

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

The document has no text (for example, only images).

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

### `error`

No input was given, the file is not a valid DOCX or the script failed.

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

## Behaviour in the code

- `content_base64, file_path`: 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.
- `execution`: Only `execution.timeout_ms` is read (fallback 120000 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. |
| `<parser exception message>` | `error` | The Python parser raised an exception (the file is not a DOCX: legacy `.doc`, PDF or corrupt data). 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 120000 ms, not the schema default of 300000.
- Headings and list items come out as plain lines, without Markdown markers. Text inside table cells appears twice: once in the Markdown table and again as separate lines after it.
- Only `.docx` (Office Open XML) is supported; headers, footers, comments and embedded images are not read.


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