# What Is the drawio_extract.py Script in diagram-design? A Complete Technical Guide

> Learn about the drawio_extract.py script in diagram-design. This utility converts draw.io files to a normalized intermediate representation for easier diagram generation. Understand its technical function.

- Repository: [Cathryn Lavery/diagram-design](https://github.com/cathrynlavery/diagram-design)
- Tags: deep-dive
- Published: 2026-08-14

---

**[`drawio_extract.py`](https://github.com/cathrynlavery/diagram-design/blob/main/drawio_extract.py) is a command-line utility that reads any draw.io diagram file and produces a normalized intermediate representation (IR) for downstream diagram generation.**

This script serves as the foundational parser in the `cathrynlavery/diagram-design` repository. It handles multiple input formats—from plain `.drawio` XML to embedded PNG and SVG containers—and transforms them into structured data that other components of the diagram-design skill can consume.

## Core Capabilities of drawio_extract.py

The script operates as a **pure extraction engine**. It never makes design decisions; it only extracts raw structural data and leaves interpretation to downstream "skills."

### Supported Input Formats

[`drawio_extract.py`](https://github.com/cathrynlavery/diagram-design/blob/main/drawio_extract.py) automatically detects and processes:

- Plain `.drawio` XML files
- PNG images with embedded `<mxfile>` metadata
- SVG files with embedded diagram XML
- Compressed, URL-encoded draw.io formats

## The Four-Stage Processing Pipeline

### 1. Input Handling and Payload Decoding

The script first determines file type by inspecting magic bytes, then extracts or decompresses the embedded XML accordingly.

| Format | Handler Function | Source Location |
|--------|-----------------|-----------------|
| PNG with embedded XML | `_png_embedded_xml` | `drawio_extract.py#L41-L105` |
| SVG with embedded XML | `_svg_embedded_xml` | `drawio_extract.py#L41-L105` |
| Base64-deflated payloads | `_inflate` | `drawio_extract.py#L41-L105` |

The `load_mxfile` function orchestrates this selection:

```python
def load_mxfile(file_path: Path) -> ET.Element:
    # Detects file magic, routes to appropriate decoder

    # Returns the root <mxfile> or <mxGraphModel> element

```

### 2. XML Parsing and Data Model Construction

Once XML is extracted, the parser walks each page and builds **Node**, **Edge**, and **Page** dataclasses stored in `drawio_extract.py#L91-L136`.

Key attributes captured:

- **Geometry**: Absolute coordinates (x, y, width, height)
- **Styling**: Raw style strings and parsed properties
- **Hierarchy**: Parent-child relationships and container nesting

The `parse_page` function executes a three-pass algorithm:

```python
def parse_page(root: ET.Element, page_idx: int = 0) -> Page:
    # Pass 1: Collect raw cells

    # Pass 2: Resolve absolute positions from relative geometry

    # Pass 3: Build parent-child links and instantiate edges

```

### 3. Structural Analysis

The `analyze` function (`drawio_extract.py#L80-L129`) computes derivative signals useful for downstream classification:

- **Cycle detection**: Identifies circular dependencies in edge topology
- **Hub node identification**: Finds nodes with high connection centrality
- **Depth metrics**: Measures hierarchical nesting levels
- **Type candidates**: Suggests diagram classifications (sequence, flowchart, architecture)
- **Collapsible groups**: Detects logical clusterings

### 4. Output Generation

The script provides two output modes controlled by CLI flags.

**Default: Markdown Digest**

- Summarizes pages, node counts, edge counts
- Displays analysis results in readable tables
- Respects `--max-rows` for pagination control

**JSON IR Mode (`--json`)**

- Emits the complete intermediate representation
- Includes raw geometries, styles, hierarchy, and analysis signals
- Suitable for machine consumption by downstream processors

## Command-Line Reference

```bash

# Basic usage – produce a Markdown digest

python3 drawio_extract.py path/to/diagram.drawio

# Export the full intermediate representation as JSON

python3 drawio_extract.py path/to/diagram.drawio --json > diagram.json

# Limit tables to 20 rows per page

python3 drawio_extract.py diagram.drawio --max-rows 20

# Process specific page by index

python3 drawio_extract.py diagram.drawio --page 2

# Process specific page by name

python3 drawio_extract.py diagram.drawio --page "Overview"

# Process all pages explicitly

python3 drawio_extract.py diagram.drawio --page all

# Write output to file instead of stdout

python3 drawio_extract.py diagram.drawio --out analysis.md

```

The CLI entry point at `drawio_extract.py#L156-L52` validates arguments, routes to the appropriate output formatter, and handles error conditions for malformed inputs.

## Integration Within diagram-design

[`drawio_extract.py`](https://github.com/cathrynlavery/diagram-design/blob/main/drawio_extract.py) operates within a broader ecosystem in the `cathrynlavery/diagram-design` repository:

| File | Role |
|------|------|
| [`skills/diagram-design/scripts/drawio_extract.py`](https://github.com/cathrynlavery/diagram-design/blob/main/skills/diagram-design/scripts/drawio_extract.py) | Core extractor and analyzer (this script) |
| [`scripts/verify-drawio-import.py`](https://github.com/cathrynlavery/diagram-design/blob/main/scripts/verify-drawio-import.py) | Test harness validating extractor against sample files |
| `scripts/fixtures/sample-architecture.drawio` | Example input for verification |
| [`commands/import-drawio.md`](https://github.com/cathrynlavery/diagram-design/blob/main/commands/import-drawio.md) | Public CLI documentation wrapping this script |

As implemented in `cathrynlavery/diagram-design`, this extraction pipeline enables import of existing draw.io assets into the diagram-design workflow, preserving structural intent while enabling transformation into other diagram types or refinement through the skill's generative capabilities.

## Key Design Decisions

The script follows **separation of concerns** principles:

1. **Extraction is pure**: No interpretation of diagram semantics—only structural facts
2. **Normalization is absolute**: All coordinates converted to absolute positioning
3. **Analysis is non-destructive**: Signals computed but not acted upon
4. **Output is flexible**: Human-readable Markdown or machine-readable JSON

This architecture allows downstream components to make context-appropriate decisions about diagram type, level of detail, and visual styling without coupling to the parser's implementation.

## Summary

- **[`drawio_extract.py`](https://github.com/cathrynlavery/diagram-design/blob/main/drawio_extract.py) is the foundational parser** in diagram-design that reads draw.io files in multiple formats and produces structured intermediate representations.

- **Four-stage pipeline**: input handling → XML parsing → structural analysis → output generation (Markdown digest or JSON IR).

- **Key functions**: `load_mxfile`, `parse_page`, `analyze`, `digest`, `to_json`, with dataclasses `Node`, `Edge`, `Page` defining the core data model.

- **Extraction is decoupled from design**: The script never decides diagram type or styling—only provides normalized structural data for downstream interpretation.

- **CLI supports flexible workflows**: page selection, row limits, output format switching, and file redirection.

## Frequently Asked Questions

### What file formats can drawio_extract.py handle?

[`drawio_extract.py`](https://github.com/cathrynlavery/diagram-design/blob/main/drawio_extract.py) handles plain `.drawio` XML, PNG images with embedded diagram metadata, SVG files with embedded XML, and compressed URL-encoded draw.io formats. The `_png_embedded_xml`, `_svg_embedded_xml`, and `_inflate` functions in `drawio_extract.py#L41-L105` implement format-specific decoding.

### How does the script determine diagram type?

It doesn't—directly. The `analyze` function computes signals like cycles, hub nodes, and depth metrics that suggest type candidates (sequence, flowchart, architecture). Downstream skills interpret these signals to classify and regenerate the diagram appropriately.

### Can I extract data from a specific page in a multi-page diagram?

Yes. Use the `--page` flag with either a zero-based index (`--page 2`), exact page name (`--page "Overview"`), or `all` to process every page. Without this flag, the script processes the first page by default.

### What's the difference between the default output and --json mode?

The default produces a compact Markdown digest with human-readable tables summarizing nodes, edges, and analysis. The `--json` flag emits the complete intermediate representation including raw geometries, style strings, hierarchy links, and all computed analysis signals—intended for programmatic consumption.