<!--
  canonical-url: https://www.avonture.be/blog/docker-python-mermaid
  published:     2026-04-20
  This is a static plain-Markdown mirror generated at build time.
  Visit the canonical URL above for the fully rendered page, with images and interactive components.
-->

# Documentation as Code - Transform Your Infrastructure into Beautiful Diagrams with Python and Mermaid

> Automate your Documentation as Code by building a Dockerized Python and Mermaid CLI stack to generate dynamic architecture diagrams directly from your codebase.

---
![Documentation as Code: Transform Your Infrastructure into Beautiful Diagrams with Python and Mermaid](/img/v2/docker-python-mermaid.webp)

**TL;DR**Manual documentation gets outdated the second your code changes. To solve this, you can embrace Documentation as Code by building a custom Docker image equipped with Python and the Mermaid CLI to automatically generate your visual assets. By writing straightforward Python scripts that parse your compose.yaml files or scan your project directories, you can dynamically output Mermaid pseudocode and render it directly into clean, up-to-date PNG diagrams (like mindmaps and pie charts) using a single command.

I like documentation, and what is more inefficient than writing docs for things that can be self-documented?

As you might know, I love Docker and I do almost everything in a dockerized way. So, in every one of my projects, there is a `compose.yaml` file. If I want to document it for my colleagues, I could start writing: *There are three services, one is for PHP, one for Nginx, one for PostgreSQL. That one is using a volume to make data persistent on disk and blah blah blah. The Nginx service is publishing on port xxx and the database is accessible using port yyy.* I can do that, for sure, but isn't there a better way to do this? What if I add a new service or update a port number? My documentation would already be outdated, unless...

Let's see how to automate the documentation using Docker, Python and Mermaid.

**Quick Jump:** [See it in Action](#the-result) | [All needed files](#all-needed-files)

## The Result

Point the pipeline built in this article at a real `compose.yaml`, and one command produces this:

![The compose mindmap](./files/images/compose.webp)

This image has been generated entirely from the `compose.yaml` file — no manual drawing, no diagramming tool. Change the YAML, run the command again, and the diagram updates itself.

## Why Mermaid

> **Pseudocode in, image out:**
>
> [Mermaid](https://mermaid.js.org/) turns a small block of text — its own *pseudocode* — into a rendered diagram. Look at this [example](https://mermaid.live/edit#pako:eNpFjctqwzAQRX9FzNoNtmzJtrYtfUALhWbT4o1ijR0RWRMUmTYN-fcqCU3uauZw7swBejIICqKd0FmPnWcp0UaH7NnuIoU9o4F9UG-1Y29orGbvTseBwnRxeZ5zptir9Rs0L_4KqwQfdY8ros0FnqPYE9Ho8OqJhD5pXs6rG5OJLb9tjBgggzFYAyqGGTOYMEz6tMLhZHcQ1zhhByqNBgc9u9hB54-pttX-i2j6bwaaxzWoQbtd2uat0REfrB6DvinoDYZ7mn0EVYi6Ph8BdYAfUHdFVS7aVuZlK9uiraumzGAPipcLIaXkKTWvmrqRxwx-z4-LBW8L0XDR5GVTiroSxz-rtW0b): on the left, the pseudocode — readable at a glance; on the right, the rendered image.

![A timeline example from Mermaid Live Editor](./images/timeline.webp)

Go to [Mermaid Live Editor](https://mermaid.live/edit) and play with the *Sample Diagrams* bottom left to discover all the tool has to offer. A Python script can generate that same pseudocode from anything readable — a `compose.yaml`, a folder tree, whatever data you already have — and the Mermaid CLI renders it into a transparent PNG.

## Installation — Let's create the Docker image

The Dockerfile we'll use is this one. It's quite simple.

**Dockerfile**

```docker
FROM node:20-alpine

RUN apk add --no-cache \
    chromium \
    nss \
    freetype \
    harfbuzz \
    ca-certificates \
    ttf-freefont \
    font-noto-emoji \
    python3 \
    py3-pip \
    py3-yaml

RUN fc-cache -fv

RUN npm install -g @mermaid-js/mermaid-cli

RUN mkdir -p /home/node/.cache/puppeteer && \
    chmod -R 777 /home/node

ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
ENV HOME=/home/node

WORKDIR /app
```

To build this image run `docker build -t yourself/docker-python-mermaid .` in your terminal:

```bash
$ docker build -t yourself/docker-python-mermaid .
```

The final image size will be around 2GB.

![Building the image](./images/build.webp)

## Prepare Mermaid rendering

We need to have two external files for the rendering.

The first one will configure Puppeteer:

**puppeteer-config.json**

```json
{
  "args": [
    "--no-sandbox",
    "--disable-setuid-sandbox",
    "--disable-dev-shm-usage",
    "--disable-accelerated-2d-canvas",
    "--no-first-run",
    "--no-zygote",
    "--disable-gpu"
  ]
}
```

And the second one will allow us to use our own formatting (font, colors, ...) when rendering the pseudocode to an image:

**mermaid-config.json**

```json
{
  "theme": "base",
  "themeVariables": {
    "fontFamily": "Inter, Segoe UI, Arial",
    "fontSize": "16px",
    "lineColor": "#475569",
    "mainBkg": "#ffffff",

    "cScale0": "#0f172a",
    "cScaleLabel0": "#ffffff",

    "cScale1": "#2563eb",
    "cScaleLabel1": "#ffffff",

    "cScale2": "#059669",
    "cScaleLabel2": "#ffffff",

    "cScale3": "#d97706",
    "cScaleLabel3": "#ffffff",

    "cScale4": "#6366f1",
    "cScaleLabel4": "#ffffff",

    "nodeBorder": "#cbd5e1",
    "clusterBkg": "#f8fafc"
  }
}
```

## Finally, we need a Python script

We've our Docker image, we've our configuration files. The last thing is writing a Python script that will do "something", generate a Mermaid pseudocode and render that pseudocode as an image.

What can we do? Whatever you want to do! Just use your preferred AI engine and ask it to create the corresponding Python script.

Let's try two things:

### We'll read a Docker compose.yaml and create a mindmap

The script below will read a `compose.yaml` file and generate a visual mindmap. *There is also a ready-made tool for this, see [How to generate a graph from compose.yaml](/blog/docker-compose-viz), but writing the script ourselves gives us total freedom on the output.*

**mindmap.py**

```python
import yaml
import argparse
import subprocess
import os

def get_emoji(name):
    name = name.lower()
    if any(x in name for x in ['db', 'postgres', 'sql', 'redis', 'cache']):
        return "🗄️"
    if any(x in name for x in ['nginx', 'proxy', 'gateway', 'api']):
        return "🌐"
    if 'auth' in name:
        return "🔐"
    return "📦"

def generate_mindmap(compose_path):
    with open(compose_path, 'r') as f:
        data = yaml.safe_load(f)

    lines = ["mindmap", "  root(( 🏗️ INFRASTRUCTURE ))"]

    lines.append("    Services")
    for name, config in data.get('services', {}).items():
        emoji = get_emoji(name)
        lines.append(f"      ({emoji} {name})")

        if 'depends_on' in config:
            for dep in config['depends_on']:
                lines.append(f"        {{{{ 🔗 {dep} }}}}")

    lines.append("    Networks")
    for net in data.get('networks', {}).keys():
        lines.append(f"      ) {net} (")

    lines.append("    Volumes")
    for vol in data.get('volumes', {}).keys():
        lines.append(f"      [{vol}]")

    return "\n".join(lines)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("input", help="compose.yaml file")
    parser.add_argument("-o", "--output", default="infra_map.png")
    parser.add_argument("--style", default="/app/mermaid-config.json")
    args = parser.parse_args()

    mmd_code = generate_mindmap(args.input)
    with open("temp.mmd", "w") as f:
        f.write(mmd_code)

    print("🚀 Generating Pro diagram...")

    cmd = [
        "mmdc",
        "-i", "temp.mmd",
        "-o", args.output,
        "--width", "1600",
        "-p", "/app/puppeteer-config.json",
        "--backgroundColor", "transparent"
    ]

    if os.path.exists(args.style):
        cmd.extend(["-c", args.style])

    subprocess.run(cmd, check=True)
    os.remove("temp.mmd")
    print(f"✨ Done! Image: {args.output}")

if __name__ == "__main__":
    main()
```

Here is the dummy `compose.yaml` I'll use as an example:

**compose.yaml**

```yaml
services:
  nginx-proxy:
    image: nginx:alpine
    ports: ["80:80", "443:443"]
    networks: [frontend]
    volumes: ["./nginx.conf:/etc/nginx/nginx.conf"]

  api-gateway:
    build: ./services/gateway
    depends_on: [auth-service, user-service]
    networks: [frontend, backend]
    environment:
      - DB_URL=postgres://db:5432/app

  auth-service:
    image: node:18
    networks: [backend]
    volumes: ["auth_data:/data"]

  user-service:
    image: python:3.11
    networks: [backend, database]
    environment:
      - REDIS_URL=redis:6379

  db-primary:
    image: postgres:15
    networks: [database]
    volumes: ["pg_data:/var/lib/postgresql/data"]
    environment:
      - POSTGRES_PASSWORD=secret

  redis-cache:
    image: redis:alpine
    networks: [database]

networks:
  frontend:
  backend:
  database:
    driver: bridge

volumes:
  pg_data:
  auth_data:
```

Now, the best part: please run this command to render the image:

```bash
$ docker run --rm -u $(id -u):$(id -g) -e HOME=/tmp -v .:/app yourself/docker-python-mermaid python3 /app/scripts/mindmap.py /app/samples/compose.yaml -o /app/compose.png

Generating single mermaid chart

🚀 Generating Pro diagram...
✨ Done! Image: /app/compose.png
```

Using a single command line produces the mindmap shown at the top of this article. This image has been generated by the `mindmap.py` Python script once our `compose.yaml` file was processed. We can now change our YAML file, run the `docker run` command again, and the image will be updated automatically.

> **Colors:**
>
> Remember, simply update the `mermaid-config.json` file if you want another color scheme.

## More Examples

### Another example

This script will look at our file structure, identify the files we have, and create a mindmap as well:

**project-dna.py**

```python
import os
import argparse
import subprocess

def get_category(filename):
    ext = os.path.splitext(filename)[1].lower()
    name = filename.lower()

    if name == 'dockerfile' or ext == '.dockerfile': return '🐳 Docker'
    if ext in ['.py', '.sh', '.js', '.go']: return '💻 Code'
    if ext in ['.yaml', '.yml', '.json', '.conf', '.ini']: return '⚙️ Config'
    if ext in ['.md', '.txt', '.pdf']: return '📝 Doc'
    if ext in ['.png', '.jpg', '.svg', '.ico']: return '🎨 Assets'
    return '📄 Other'

def generate_dna(path):
    structure = {}

    # Analyze files
    for root, dirs, files in os.walk(path):
        # Ignore hidden and heavy folders
        dirs[:] = [d for d in dirs if not d.startswith('.') and d != '__pycache__']

        for file in files:
            cat = get_category(file)
            structure.setdefault(cat, set()).add(file)

    if not structure:
        return "mindmap\n  root(( 🧬 PROJECT DNA ))\n    (Empty or unreadable folder)"

    lines = ["mindmap", "  root(( 🧬 PROJECT DNA ))"]

    for cat, files in structure.items():
        lines.append(f"    {cat}")
        # Show max 6 files per category to avoid cluttering the image
        for i, f in enumerate(sorted(list(files))):
            if i >= 6:
                lines.append("      (...)")
                break
            # Clean special characters for Mermaid
            clean_name = f.replace('(', '').replace(')', '').replace('[', '').replace(']', '')
            lines.append(f"      ({clean_name})")

    return "\n".join(lines)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("path", help="Folder to scan")
    parser.add_argument("-o", "--output", default="dna.png")
    args = parser.parse_args()

    # Ensure the path is absolute
    target_path = os.path.abspath(args.path)
    mmd_code = generate_dna(target_path)

    with open("temp.mmd", "w", encoding='utf-8') as f:
        f.write(mmd_code)

    print(f"🔎 Analyzing {target_path}...")

    subprocess.run([
        "mmdc", "-i", "temp.mmd", "-o", args.output,
        "-p", "/app/puppeteer-config.json",
        "-c", "/app/mermaid-config.json",
        "--width", "1200"
    ], check=True)

    os.remove("temp.mmd")
    print(f"✨ DNA successfully generated in {args.output}")

if __name__ == "__main__":
    main()
```

```bash
$ docker run --rm -u $(id -u):$(id -g) -e HOME=/tmp -v .:/app yourself/docker-python-mermaid python3 /app/scripts/project-dna.py /app -o /app/project-dna.png

Generating single mermaid chart
🔎 Analyzing /app...
✨ DNA successfully generated in /app/project-dna.png
```

![The project-dna mindmap](./files/images/project-dna.webp)

This mindmap will not just show us our folders but will group files into categories like `Code`, `Configuration`, `Assets`, etc.

### Last example

This time a Pie chart:

**pie.py**

```python
import os
import argparse
import subprocess

def get_category(filename):
    ext = os.path.splitext(filename)[1].lower()
    name = filename.lower()

    if name == 'dockerfile' or ext == '.dockerfile': return '🐳 Docker'
    if ext in ['.py', '.sh', '.js', '.go']: return '💻 Code'
    if ext in ['.yaml', '.yml', '.json', '.conf', '.ini']: return '⚙️ Config'
    if ext in ['.md', '.txt', '.pdf']: return '📝 Doc'
    if ext in ['.png', '.jpg', '.svg', '.ico']: return '🎨 Assets'
    return '📄 Other'

def generate_pie_chart(path):
    counts = {}

    # Analyze files
    for root, dirs, files in os.walk(path):
        # Ignore hidden and heavy folders
        dirs[:] = [d for d in dirs if not d.startswith('.') and d != '__pycache__']

        for file in files:
            cat = get_category(file)
            counts[cat] = counts.get(cat, 0) + 1

    if not counts:
        return "pie title Empty or unreadable folder\n    \"None\" : 1"

    lines = ["pie title Project File Type Distribution"]

    for cat, count in counts.items():
        # Mermaid pie charts use raw numbers and automatically calculate percentages
        lines.append(f'    "{cat}" : {count}')

    return "\n".join(lines)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("path", help="Folder to scan")
    parser.add_argument("-o", "--output", default="file_types_pie.png")
    args = parser.parse_args()

    # Ensure the path is absolute
    target_path = os.path.abspath(args.path)
    mmd_code = generate_pie_chart(target_path)

    with open("temp.mmd", "w", encoding='utf-8') as f:
        f.write(mmd_code)

    print(f"🔎 Analyzing {target_path}...")

    subprocess.run([
        "mmdc", "-i", "temp.mmd", "-o", args.output,
        "-p", "/app/puppeteer-config.json",
        "-c", "/app/mermaid-config.json",
        "--width", "1200",
        "--backgroundColor", "transparent"
    ], check=True)

    os.remove("temp.mmd")
    print(f"✨ Pie chart successfully generated in {args.output}")

if __name__ == "__main__":
    main()
```

```bash
$ docker run --rm -u $(id -u):$(id -g) -e HOME=/tmp -v .:/app yourself/docker-python-mermaid python3 /app/scripts/pie.py /app -o /app/pie.png

Generating single mermaid chart
🔎 Analyzing /app...
✨ Pie chart successfully generated in /app/pie.png
```

![The project-dna pie](./files/images/pie.webp)

## All needed files

**Project: /tmp/mermaid**

> **Note:**
>
> Now, please run 'docker build -t yourself/docker-python-mermaid .' to
> create the Docker image.

**Dockerfile**

```docker
FROM node:20-alpine

RUN apk add --no-cache \
    chromium \
    nss \
    freetype \
    harfbuzz \
    ca-certificates \
    ttf-freefont \
    font-noto-emoji \
    python3 \
    py3-pip \
    py3-yaml

RUN fc-cache -fv

RUN npm install -g @mermaid-js/mermaid-cli

RUN mkdir -p /home/node/.cache/puppeteer && \
    chmod -R 777 /home/node

ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
ENV HOME=/home/node

WORKDIR /app
```

**puppeteer-config.json**

```json
{
  "args": [
    "--no-sandbox",
    "--disable-setuid-sandbox",
    "--disable-dev-shm-usage",
    "--disable-accelerated-2d-canvas",
    "--no-first-run",
    "--no-zygote",
    "--disable-gpu"
  ]
}
```

**mermaid-config.json**

```json
{
  "theme": "base",
  "themeVariables": {
    "fontFamily": "Inter, Segoe UI, Arial",
    "fontSize": "16px",
    "lineColor": "#475569",
    "mainBkg": "#ffffff",

    "cScale0": "#0f172a",
    "cScaleLabel0": "#ffffff",

    "cScale1": "#2563eb",
    "cScaleLabel1": "#ffffff",

    "cScale2": "#059669",
    "cScaleLabel2": "#ffffff",

    "cScale3": "#d97706",
    "cScaleLabel3": "#ffffff",

    "cScale4": "#6366f1",
    "cScaleLabel4": "#ffffff",

    "nodeBorder": "#cbd5e1",
    "clusterBkg": "#f8fafc"
  }
}
```

**scripts/mindmap.py**

```python
import yaml
import argparse
import subprocess
import os

def get_emoji(name):
    name = name.lower()
    if any(x in name for x in ['db', 'postgres', 'sql', 'redis', 'cache']):
        return "🗄️"
    if any(x in name for x in ['nginx', 'proxy', 'gateway', 'api']):
        return "🌐"
    if 'auth' in name:
        return "🔐"
    return "📦"

def generate_mindmap(compose_path):
    with open(compose_path, 'r') as f:
        data = yaml.safe_load(f)

    lines = ["mindmap", "  root(( 🏗️ INFRASTRUCTURE ))"]

    lines.append("    Services")
    for name, config in data.get('services', {}).items():
        emoji = get_emoji(name)
        lines.append(f"      ({emoji} {name})")

        if 'depends_on' in config:
            for dep in config['depends_on']:
                lines.append(f"        {{{{ 🔗 {dep} }}}}")

    lines.append("    Networks")
    for net in data.get('networks', {}).keys():
        lines.append(f"      ) {net} (")

    lines.append("    Volumes")
    for vol in data.get('volumes', {}).keys():
        lines.append(f"      [{vol}]")

    return "\n".join(lines)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("input", help="compose.yaml file")
    parser.add_argument("-o", "--output", default="infra_map.png")
    parser.add_argument("--style", default="/app/mermaid-config.json")
    args = parser.parse_args()

    mmd_code = generate_mindmap(args.input)
    with open("temp.mmd", "w") as f:
        f.write(mmd_code)

    print("🚀 Generating Pro diagram...")

    cmd = [
        "mmdc",
        "-i", "temp.mmd",
        "-o", args.output,
        "--width", "1600",
        "-p", "/app/puppeteer-config.json",
        "--backgroundColor", "transparent"
    ]

    if os.path.exists(args.style):
        cmd.extend(["-c", args.style])

    subprocess.run(cmd, check=True)
    os.remove("temp.mmd")
    print(f"✨ Done! Image: {args.output}")

if __name__ == "__main__":
    main()
```

**scripts/pie.py**

```python
import os
import argparse
import subprocess

def get_category(filename):
    ext = os.path.splitext(filename)[1].lower()
    name = filename.lower()

    if name == 'dockerfile' or ext == '.dockerfile': return '🐳 Docker'
    if ext in ['.py', '.sh', '.js', '.go']: return '💻 Code'
    if ext in ['.yaml', '.yml', '.json', '.conf', '.ini']: return '⚙️ Config'
    if ext in ['.md', '.txt', '.pdf']: return '📝 Doc'
    if ext in ['.png', '.jpg', '.svg', '.ico']: return '🎨 Assets'
    return '📄 Other'

def generate_pie_chart(path):
    counts = {}

    # Analyze files
    for root, dirs, files in os.walk(path):
        # Ignore hidden and heavy folders
        dirs[:] = [d for d in dirs if not d.startswith('.') and d != '__pycache__']

        for file in files:
            cat = get_category(file)
            counts[cat] = counts.get(cat, 0) + 1

    if not counts:
        return "pie title Empty or unreadable folder\n    \"None\" : 1"

    lines = ["pie title Project File Type Distribution"]

    for cat, count in counts.items():
        # Mermaid pie charts use raw numbers and automatically calculate percentages
        lines.append(f'    "{cat}" : {count}')

    return "\n".join(lines)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("path", help="Folder to scan")
    parser.add_argument("-o", "--output", default="file_types_pie.png")
    args = parser.parse_args()

    # Ensure the path is absolute
    target_path = os.path.abspath(args.path)
    mmd_code = generate_pie_chart(target_path)

    with open("temp.mmd", "w", encoding='utf-8') as f:
        f.write(mmd_code)

    print(f"🔎 Analyzing {target_path}...")

    subprocess.run([
        "mmdc", "-i", "temp.mmd", "-o", args.output,
        "-p", "/app/puppeteer-config.json",
        "-c", "/app/mermaid-config.json",
        "--width", "1200",
        "--backgroundColor", "transparent"
    ], check=True)

    os.remove("temp.mmd")
    print(f"✨ Pie chart successfully generated in {args.output}")

if __name__ == "__main__":
    main()
```

**samples/compose.yaml**

```yaml
services:
  nginx-proxy:
    image: nginx:alpine
    ports: ["80:80", "443:443"]
    networks: [frontend]
    volumes: ["./nginx.conf:/etc/nginx/nginx.conf"]

  api-gateway:
    build: ./services/gateway
    depends_on: [auth-service, user-service]
    networks: [frontend, backend]
    environment:
      - DB_URL=postgres://db:5432/app

  auth-service:
    image: node:18
    networks: [backend]
    volumes: ["auth_data:/data"]

  user-service:
    image: python:3.11
    networks: [backend, database]
    environment:
      - REDIS_URL=redis:6379

  db-primary:
    image: postgres:15
    networks: [database]
    volumes: ["pg_data:/var/lib/postgresql/data"]
    environment:
      - POSTGRES_PASSWORD=secret

  redis-cache:
    image: redis:alpine
    networks: [database]

networks:
  frontend:
  backend:
  database:
    driver: bridge

volumes:
  pg_data:
  auth_data:
```

**scripts/project-dna.py**

```python
import os
import argparse
import subprocess

def get_category(filename):
    ext = os.path.splitext(filename)[1].lower()
    name = filename.lower()

    if name == 'dockerfile' or ext == '.dockerfile': return '🐳 Docker'
    if ext in ['.py', '.sh', '.js', '.go']: return '💻 Code'
    if ext in ['.yaml', '.yml', '.json', '.conf', '.ini']: return '⚙️ Config'
    if ext in ['.md', '.txt', '.pdf']: return '📝 Doc'
    if ext in ['.png', '.jpg', '.svg', '.ico']: return '🎨 Assets'
    return '📄 Other'

def generate_dna(path):
    structure = {}

    # Analyze files
    for root, dirs, files in os.walk(path):
        # Ignore hidden and heavy folders
        dirs[:] = [d for d in dirs if not d.startswith('.') and d != '__pycache__']

        for file in files:
            cat = get_category(file)
            structure.setdefault(cat, set()).add(file)

    if not structure:
        return "mindmap\n  root(( 🧬 PROJECT DNA ))\n    (Empty or unreadable folder)"

    lines = ["mindmap", "  root(( 🧬 PROJECT DNA ))"]

    for cat, files in structure.items():
        lines.append(f"    {cat}")
        # Show max 6 files per category to avoid cluttering the image
        for i, f in enumerate(sorted(list(files))):
            if i >= 6:
                lines.append("      (...)")
                break
            # Clean special characters for Mermaid
            clean_name = f.replace('(', '').replace(')', '').replace('[', '').replace(']', '')
            lines.append(f"      ({clean_name})")

    return "\n".join(lines)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("path", help="Folder to scan")
    parser.add_argument("-o", "--output", default="dna.png")
    args = parser.parse_args()

    # Ensure the path is absolute
    target_path = os.path.abspath(args.path)
    mmd_code = generate_dna(target_path)

    with open("temp.mmd", "w", encoding='utf-8') as f:
        f.write(mmd_code)

    print(f"🔎 Analyzing {target_path}...")

    subprocess.run([
        "mmdc", "-i", "temp.mmd", "-o", args.output,
        "-p", "/app/puppeteer-config.json",
        "-c", "/app/mermaid-config.json",
        "--width", "1200"
    ], check=True)

    os.remove("temp.mmd")
    print(f"✨ DNA successfully generated in {args.output}")

if __name__ == "__main__":
    main()
```

## Conclusion

By combining the parsing power of Python with the rendering elegance of Mermaid, we've turned static documentation into a dynamic asset.

If you like the *Documentation as Code* approach, have a look at two other articles of mine going in the same direction: [Docker - Diagrams as code](/blog/docker-diagram-as-code) and [Python - Generate flows using pydot](/blog/python-pydot). And when there is no parser to write at all — a sentence describing a process, a config format I have no script for — [ai-diagram](/blog/ollama-ai-diagram) asks a local LLM for the Mermaid instead.
