### Install Mermaid CLI and Playwright Browsers
Source: https://github.com/seigok/mermaid-cli-python/blob/main/README.md
Installs the mermaid-cli Python package and the necessary Playwright browsers for rendering.
```bash
pip install mermaid-cli
playwright install chromium
```
--------------------------------
### Create Mermaid Git Graph
Source: https://github.com/seigok/mermaid-cli-python/blob/main/test-positive/mermaid.md
Illustrates the creation of a Git graph using Mermaid syntax. This example highlights how to define commits, branches, and merges, with manual ID assignment for commits.
```mermaid
gitGraph
%% Need to manually set id, otherwise they are auto-generated
commit id: "abcdef"
commit id: "123456"
branch feature
commit id: "789012"
checkout main
merge feature
```
--------------------------------
### Create Mermaid Flowchart with KaTeX Math
Source: https://github.com/seigok/mermaid-cli-python/blob/main/test-positive/mermaid.md
Illustrates the integration of KaTeX for rendering mathematical formulas within a Mermaid flowchart. This example uses inline ($$) and display math ($$) syntax for equations and expressions.
```mermaid
---
title: My flowchart with KaTeX in it.
---
flowchart LR
A["$$x^2$$"] -->|"$$\sqrt{x+3}$$"| B("$$\frac{1}{2}$$ ")
```
--------------------------------
### Mermaid Diagram Examples (Text)
Source: https://github.com/seigok/mermaid-cli-python/blob/main/README.md
Examples of various Mermaid diagram syntaxes including Flowchart, Sequence Diagram, and Class Diagram.
```mermaid
graph TD
A[Start] --> B{Is it?}
B -->|Yes| C[OK]
C --> D[Rethink]
D --> B
B ---->|No| E[End]
```
```mermaid
sequenceDiagram
participant Alice
participant Bob
Alice->>John: Hello John, how are you?
loop Healthcheck
John->>John: Fight against hypochondria
end
Note right of John: Rational thoughts prevail!
John-->>Alice: Great!
John->>Bob: How about you?
Bob-->>John: Jolly good!
```
```mermaid
classDiagram
Animal <|-- Duck
Animal <|-- Fish
Animal <|-- Zebra
Animal : +int age
Animal : +String gender
Animal: +isMammal()
Animal: +mate()
class Duck{
+String beakColor
+swim()
+quack()
}
class Fish{
-int sizeInFeet
-canEat()
}
class Zebra{
+bool is_wild
+run()
}
```
--------------------------------
### Create Mermaid Sequence Diagram with Loops and Notes
Source: https://github.com/seigok/mermaid-cli-python/blob/main/test-positive/mermaid.md
Generates a sequence diagram featuring loops and notes to illustrate complex interactions over time. This example shows how to define repeating actions and add contextual information.
```mermaid
sequenceDiagram
%% See https://mermaidjs.github.io/sequenceDiagram.html
loop everyday D-2 working days 16:00
ABCD->>DEE: [14:25] BEE (Calculation per TC until ACK becomes OK)
ABCD->>FGG: BEE (Calculation per TC until ACK becomes OK)
Note over ABCD,FGG: D-2 weekdays at 14:25
ABCD->>HII: Projected Authorisations to HII
Note over ABCD,HII: D-2 weekdays at 16:00
end
loop D-1 before deadline at 7:45
HII->>DEE: Submission
Note over HII,DEE: D-1 before deadline
HII->>FGG: Submission
Note over HII,FGG: D-1 before deadline
end
```
--------------------------------
### Create Mermaid Flowchart with Font Awesome Icons
Source: https://github.com/seigok/mermaid-cli-python/blob/main/test-positive/mermaid.md
Shows how to incorporate Font Awesome icons into Mermaid flowchart nodes. This example utilizes the 'fa:' prefix to reference specific icons within node text and connection labels.
```mermaid
graph TD
B["fa:fa-car for peace"]
B-->C[fa:fa-ban forbidden]
B-->D(fa:fa-spinner);
B-->E(A fa:fa-camera-retro perhaps?);
%% Test whether embed
work correctly
D-->F("
Red Circle")
```
--------------------------------
### Create Mermaid Graph with Japanese Characters
Source: https://github.com/seigok/mermaid-cli-python/blob/main/test-positive/mermaid.md
Illustrates the support for non-ASCII characters, specifically Japanese, in Mermaid diagrams. This example shows a simple graph with a Japanese label on a connection.
```mermaid
graph LR
A -->|こんにちは| B
```
--------------------------------
### Command Line Usage for Mermaid CLI
Source: https://github.com/seigok/mermaid-cli-python/blob/main/README.md
Demonstrates basic and advanced command-line usage for rendering Mermaid diagrams and processing Markdown files. Includes examples for simple rendering, Markdown processing, and output customization.
```bash
# Simple diagram rendering
mmdc -i input.mmd -o output.svg
# Markdown file with mermaid diagrams
mmdc -i input.md -o output.md
# Customize output
mmdc -i input.mmd -o output.png -t dark -b transparent -w 1024 -H 768
```
--------------------------------
### Create Mermaid Graph with Emojis
Source: https://github.com/seigok/mermaid-cli-python/blob/main/test-positive/mermaid.md
Generates a simple Mermaid graph with nodes containing emojis. This example showcases the ability to embed Unicode characters directly within node definitions.
```mermaid
graph TD
A-->B("hello 🐛")
```
--------------------------------
### Create Mermaid Graph with Line Breaks
Source: https://github.com/seigok/mermaid-cli-python/blob/main/test-positive/mermaid.md
Demonstrates how to create line breaks within a Mermaid node using HTML-like tags. This is useful for displaying multi-line text within a single node.
```mermaid
graph TD
subgraph sub
node(Line 1
Line 2
Line 3)
end
```
--------------------------------
### Create Mermaid State Diagram with Trailing Spaces
Source: https://github.com/seigok/mermaid-cli-python/blob/main/test-positive/mermaid.md
Generates a state diagram, verifying that Mermaid syntax is correctly parsed even with trailing spaces after the opening and closing code fences.
```mermaid
stateDiagram
state Choose <>
[*] --> Still
Still --> [*]
Still --> Moving
Moving --> Choose
Choose --> Still
Choose --> Crash
Crash --> [*]
```
--------------------------------
### Create Mermaid Flowchart with Elk Layout and Hand-Drawn Look
Source: https://github.com/seigok/mermaid-cli-python/blob/main/test-positive/mermaid.md
Demonstrates a flowchart using the 'elk' layout engine and the 'handDrawn' visual style. This combination provides a more organic and less rigid appearance for the diagram.
```mermaid
---
config:
look: handDrawn
layout: elk
handDrawnSeed: 1 # this is so visual regression tests are constant
---
flowchart LR
A --> B --> C & D
```
--------------------------------
### Create Mermaid Flowchart with Nested Subgraphs
Source: https://github.com/seigok/mermaid-cli-python/blob/main/test-positive/mermaid.md
Demonstrates a complex flowchart with nested subgraphs and various node shapes (e.g., rounded, circle). It illustrates hierarchical structuring and different connection types.
```mermaid
graph BT
subgraph initramfs
/ === ibin[bin]
/ --- DEV((dev))
/ === ilib[lib]
/ --- proc((proc))
/ === tmp
/ === usr
usr === bin
bin === ENV(env)
tmp --- root
tmp --- users((users))
root --- RDEV((dev))
root --- rproc((proc))
root --- rtmp((tmp))
root --- home((home))
end
subgraph usersfs
.workdirs
nodeos
uroot[root]
nodeos --- NDEV((dev))
nodeos --- nproc((proc))
nodeos --- ntmp((tmp))
end
home === .workdirs
home === nodeos
home === uroot
users -.-> home
DEV -.- NDEV
proc -.- nproc
DEV -.- RDEV
proc -.- rproc
```
--------------------------------
### Create Mermaid State Diagram with Escaped Quotes
Source: https://github.com/seigok/mermaid-cli-python/blob/main/test-positive/mermaid.md
Generates a state diagram, demonstrating the handling of escaped double quotes within the diagram's title and description. This example also includes square brackets and backslashes.
```mermaid
stateDiagram
accTitle: State diagram example with \"double-quotes"
accDescr: State diagram describing movement states and containing [] square brackets and \[]
state Choose <>
[*] --> Still
Still --> [*]
Still --> Moving
Moving --> Choose
Choose --> Still
Choose --> Crash
Crash --> [*]
```
--------------------------------
### Python Library: Render Mermaid Diagrams Asynchronously
Source: https://github.com/seigok/mermaid-cli-python/blob/main/README.md
Shows how to use the asynchronous Python library functions `render_mermaid` and `render_mermaid_file` to generate diagrams from definitions or files. Includes examples for rendering a direct definition and from an input file, with output to SVG.
```python
import asyncio
from mermaid_cli import render_mermaid, render_mermaid_file
# Render a diagram directly
async def render_diagram():
definition = """
graph TD
A[Start] --> B{Is it?}
B -->|Yes| C[OK]
C --> D[Rethink]
D --> B
B ---->|No| E[End]
"""
title, desc, svg_data = await render_mermaid(
definition,
output_format="svg",
background_color="white",
mermaid_config={"theme": "forest"}
)
with open("output.svg", "wb") as f:
f.write(svg_data)
# Render from a file
async def render_file():
await render_mermaid_file(
input_file="input.mmd",
output_file="output.svg",
output_format="svg",
mermaid_config={"theme": "dark"}
)
# Run the async functions
asyncio.run(render_diagram())
asyncio.run(render_file())
# Or use the synchronous wrapper
from mermaid_cli import render_mermaid_file_sync
render_mermaid_file_sync(
input_file="input.mmd",
output_file="output.png",
output_format="png"
)
```
--------------------------------
### Python: Advanced Mermaid Diagram Rendering with Customization
Source: https://context7.com/seigok/mermaid-cli-python/llms.txt
This Python script uses the `mermaid_cli` library to render a sequence diagram with advanced customization. It includes examples of custom themes, CSS styling, and Playwright browser configuration. The output is saved as a PNG file.
```python
import asyncio
from mermaid_cli import render_mermaid
async def advanced_rendering():
# Sequence diagram with custom styling
sequence = """
sequenceDiagram
participant Client
participant API
participant Database
Client->>API: POST /users
API->>Database: INSERT user
Database-->>API: user_id
API-->>Client: 201 Created
"""
# Custom theme configuration
custom_config = {
"theme": "base",
"themeVariables": {
"primaryColor": "#ff6b6b",
"secondaryColor": "#4ecdc4",
"tertiaryColor": "#ffe66d",
"primaryTextColor": "#2d3436",
"lineColor": "#636e72",
"fontFamily": "Arial, sans-serif"
},
"sequence": {
"actorMargin": 50,
"noteMargin": 10,
"messageMargin": 35
}
}
# Custom CSS for fine-grained control
custom_css = """
.actor {
stroke: #2d3436;
stroke-width: 2px;
}
.messageLine0 {
stroke-dasharray: 5, 5;
}
text {
font-weight: 600;
}
"""
# Playwright browser configuration
playwright_config = {
"headless": True,
"args": ["--no-sandbox"]
}
title, desc, png_data = await render_mermaid(
sequence,
output_format="png",
viewport={"width": 1200, "height": 800, "deviceScaleFactor": 2},
background_color="#ffffff",
mermaid_config=custom_config,
css=custom_css,
playwright_config=playwright_config
)
with open("custom_sequence.png", "wb") as f:
f.write(png_data)
asyncio.run(advanced_rendering())
```
--------------------------------
### Basic Mermaid CLI Usage with stdin/stdout and Icon Packs
Source: https://context7.com/seigok/mermaid-cli-python/llms.txt
Demonstrates using the Mermaid CLI executable for pipeline integration via stdin/stdout and for rendering diagrams with custom icon packs. Assumes the `mmdc` executable is in the system's PATH.
```shell
cat diagram.mmd | mmdc -i - -o - -e svg > output.svg
mmdc -i diagram.mmd -o diagram.svg --icon-packs @iconify-json/logos
```
--------------------------------
### Synchronous File Rendering with render_mermaid_file_sync (Python)
Source: https://context7.com/seigok/mermaid-cli-python/llms.txt
Provides a synchronous wrapper for `render_mermaid_file`, allowing file-based Mermaid diagram rendering without async/await. Suitable for simpler scripts or blocking environments. Supports PDF fitting and batch processing.
```python
from mermaid_cli import render_mermaid_file_sync
# Simple synchronous usage - no async/await needed
render_mermaid_file_sync(
input_file="sequence.mmd",
output_file="sequence.pdf",
output_format="pdf",
pdf_fit=True,
mermaid_config={"theme": "default"}
)
# Process multiple files in a loop
diagrams = ["flow.mmd", "sequence.mmd", "class.mmd"]
for diagram in diagrams:
output = diagram.replace(".mmd", ".png")
render_mermaid_file_sync(
input_file=diagram,
output_file=output,
output_format="png",
background_color="#f8f9fa"
)
```
--------------------------------
### Command-Line Rendering (Bash)
Source: https://context7.com/seigok/mermaid-cli-python/llms.txt
Utilizes the `mmdc` command-line tool to render Mermaid diagrams from files or Markdown. Supports various flags for input/output files, formats, dimensions, themes, custom CSS, and configuration files.
```bash
# Basic SVG rendering
mmdc -i diagram.mmd -o diagram.svg
# PNG with custom dimensions and theme
mmdc -i flowchart.mmd -o output.png -e png -w 1920 -H 1080 -t dark
# Process Markdown file with embedded diagrams
mmdc -i README.md -o README_processed.md
# Advanced: Custom config, CSS, transparent background
mmdc -i diagram.mmd -o diagram.svg \
-c mermaid-config.json \
-C custom-styles.css \
-b transparent \
-s 2
# PDF with fit-to-content
mmdc -i sequence.mmd -o sequence.pdf -e pdf -f
```
--------------------------------
### Synchronously Render Mermaid File
Source: https://github.com/seigok/mermaid-cli-python/blob/main/README.md
This function provides a synchronous wrapper for rendering Mermaid diagrams from a file. It takes an input file path, an output file path, and an optional output format. Additional keyword arguments can be passed for further customization.
```python
def render_mermaid_file_sync(
input_file: Optional[str],
output_file: str,
output_format: Optional[str] = None,
**kwargs
) -> None:
"""Synchronous wrapper for render_mermaid_file."""
pass
```
--------------------------------
### Async File Rendering with render_mermaid_file (Python)
Source: https://context7.com/seigok/mermaid-cli-python/llms.txt
Asynchronously renders Mermaid diagrams from input files or processes Markdown files containing Mermaid blocks. Supports various output formats and customization options. When processing Markdown, it replaces code blocks with image files.
```python
import asyncio
from mermaid_cli import render_mermaid_file
async def process_documentation():
# Render a single .mmd file to PNG
await render_mermaid_file(
input_file="architecture.mmd",
output_file="architecture.png",
output_format="png",
viewport={"width": 1920, "height": 1080},
background_color="white",
mermaid_config={"theme": "neutral"}
)
# Process Markdown file with embedded diagrams
# Extracts all ```mermaid blocks and replaces them with image links
await render_mermaid_file(
input_file="documentation.md",
output_file="documentation_processed.md",
output_format="svg",
mermaid_config={"theme": "forest"},
quiet=False
)
# Creates: documentation_processed-1.svg, documentation_processed-2.svg, etc.
asyncio.run(process_documentation())
```
--------------------------------
### Async Diagram Rendering with render_mermaid (Python)
Source: https://context7.com/seigok/mermaid-cli-python/llms.txt
Renders a Mermaid definition string to SVG, PNG, or PDF asynchronously. Supports customization of viewport, background color, Mermaid configuration, and CSS. Outputs diagram data and metadata.
```python
import asyncio
from mermaid_cli import render_mermaid
async def generate_flowchart():
definition = """
graph TD
A[Start] --> B{Is it working?}
B -->|Yes| C[Great!]
B -->|No| D[Debug]
D --> B
C --> E[End]
"""
title, description, svg_data = await render_mermaid(
definition,
output_format="svg",
viewport={"width": 1024, "height": 768, "deviceScaleFactor": 2},
background_color="transparent",
mermaid_config={
"theme": "dark",
"themeVariables": {
"primaryColor": "#6366f1",
"primaryTextColor": "#fff",
"primaryBorderColor": "#4f46e5"
}
},
css=".node rect { rx: 8; ry: 8; }",
svg_id="my-flowchart"
)
with open("flowchart.svg", "wb") as f:
f.write(svg_data)
print(f"Generated diagram with title: {title}")
asyncio.run(generate_flowchart())
```
--------------------------------
### Mermaid Sequence Diagram in Python
Source: https://github.com/seigok/mermaid-cli-python/blob/main/example/example.md
This snippet illustrates a sequence diagram using Mermaid syntax within a Python context. It requires the Mermaid CLI for rendering.
```mermaid
sequenceDiagram
participant Alice
participant Bob
Alice->>John: Hello John, how are you?
loop Healthcheck
John->>John: Fight against hypochondria
end
Note right of John: Rational thoughts
prevail!
John-->>Alice: Great!
John->>Bob: How about you?
Bob-->>John: Jolly good!
```
--------------------------------
### Python: Batch Processing of Multiple Mermaid Diagrams
Source: https://context7.com/seigok/mermaid-cli-python/llms.txt
This Python script demonstrates batch processing of various Mermaid diagram types (graph, flowchart) and outputs them in different formats (SVG, PNG). It utilizes the `mermaid_cli` library and saves generated diagrams to a specified directory, applying different themes based on diagram type.
```python
import asyncio
from pathlib import Path
from mermaid_cli import render_mermaid
async def batch_process_diagrams():
diagrams = {
"architecture": """
graph TB
Client[Client App] --> LB[Load Balancer]
LB --> API1[API Server 1]
LB --> API2[API Server 2]
API1 --> DB[(Database)]
API2 --> DB
API1 --> Cache[Redis Cache]
API2 --> Cache
""",
"deployment": """
flowchart LR
Dev[Development] --> |git push| CI[CI/CD]
CI --> |build| Docker[Docker Image]
Docker --> |deploy| Staging[Staging Env]
Staging --> |test| Prod[Production]
""",
"data_flow": """
graph LR
A[User Input] --> B[Validation]
B --> C{Valid?}
C -->|Yes| D[Process Data]
C -->|No| E[Error Response]
D --> F[Save to DB]
F --> G[Success Response]
"""
}
output_dir = Path("generated_diagrams")
output_dir.mkdir(exist_ok=True)
themes = {"architecture": "dark", "deployment": "forest", "data_flow": "neutral"}
for name, definition in diagrams.items():
for fmt in ["svg", "png"]:
title, desc, data = await render_mermaid(
definition,
output_format=fmt,
mermaid_config={"theme": themes[name]},
background_color="white" if fmt == "png" else "transparent"
)
output_file = output_dir / f"{name}.{fmt}"
with open(output_file, "wb") as f:
f.write(data)
print(f"Generated: {output_file}")
asyncio.run(batch_process_diagrams())
```
--------------------------------
### Mermaid Graph Diagram in Python
Source: https://github.com/seigok/mermaid-cli-python/blob/main/example/example.md
This snippet displays a simple flowchart using Mermaid syntax within a Python context. It requires the Mermaid CLI to render the diagram.
```mermaid
graph TD
A[Start] --> B{Is it?}
B -->|Yes| C[OK]
C --> D[Rethink]
D --> B
B ---->|No| E[End]
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.