mermaid-py

repository·main·Indexed 41 days ago

https://github.com/ouhammmourachid/mermaid-py

A Python interface for the mermaid-js library used to generate diagrams, flowcharts, and visualizations. Version 0.9.0 supports programmatic creation via specialized classes or raw Mermaid-syntax strings, with built-in support for Jupyter notebooks via the %%mermaidjs magic command. It allows exporting diagrams to SVG, PNG, and PDF, and provides customization through Config and Style classes for themes and colors. Users can also configure custom Mermaid Ink servers via environment variables.

Tokens
21.8K
Snippets
67
Records
95
Agent score
50%

What's inside mermaid-py

  1. Overview of Mermaid-py capabilities

    main

    Mermaid-py is a Python library based on Mermaid.js that enables the generation of diagrams and flowcharts using a simple syntax. It allows you to create visual representations of systems, processes, and relationships, which can be exported in several formats including SVG, PNG, and PDF.

    Supported diagram types include:

    • Flowcharts
    • Sequence diagrams
    • Gantt charts
    • And more
  2. Supported diagram types in mermaid-py

    main

    The mermaid-py package provides complete support for the following diagram types:

    • FlowChart: Process flows, algorithms, and workflows. Uses FlowChart, Node, and Link classes.
    • Sequence Diagram: API interactions and communication flows. Uses SequenceDiagram, Actor, and Participant classes.
    • Entity Relationship (ER) Diagram: Database schema visualization. Uses ERDiagram, Entity, and Link classes.
    • Requirement Diagram: System requirements tracking. Uses RequirementDiagram, Requirement, and Element classes.
    • State Diagram: State machines and system behavior. Uses StateDiagram, State, and Transition classes.
    • Mindmap: Hierarchical information visualization. Uses Mindmap and Level classes.
    • User Journey: Customer journey mapping and UX documentation. Uses UserJourney, Section, and Task classes.
    • Pie Chart: Data distribution visualization (e.g., market share, budget allocation). Uses PieChart class.
  3. Use logic constructs in Sequence Diagrams

    main

    You can model complex workflows using logic constructs:

    • Alt (Alternative): Represents conditional logic using a dictionary where keys are conditions and values are lists of links.
    • Loop: Represents repeated interactions. Requires a description string and a list of links.
    • Parallel: Represents parallel interactions using a dictionary where keys are task names and values are lists of links.
    • Optional: Represents optional interactions. Requires a description string and a list of links.
    # Alt example
    alt = Alt({
        "valid credentials": [link1, link2],
        "invalid credentials": [link3]
    })
    
    # Loop example
    loop = Loop("while data available", [interaction1, interaction2])
    
    # Parallel example
    parallel = Parallel({
        "Task 1": [links1],
        "Task 2": [links2]
    })
    
    # Optional example
    optional = Optional("if needed", [link1, link2])
  4. Add notes and highlights to diagrams

    main

    Enhance your diagram with annotations:

    • Note: Adds a text note to a specific participant. Use NotePosition to specify placement (e.g., NotePosition.RIGHT_OF).
    • Rect: Highlights a specific section of interactions with a background color using an RGB tuple.
    from mermaid.sequence import Note, NotePosition, Rect
    
    # Add a note
    note = Note("This is a note", participant, position=NotePosition.RIGHT_OF)
    
    # Highlight a section
    rect = Rect([link1, link2], (255, 200, 150))
  5. Format data for PieChart

    main

    The data parameter must be a dictionary where keys are strings (labels) and values are numbers (floats/ints). The library calculates the proportion of each slice based on the sum of all values.

    Example:

    data = {
        "Category A": 100,
        "Category B": 50,
        "Category C": 25,
        "Category D": 25
    }
    # Results in: A=50%, B=25%, C=12.5%, D=12.5%
    data = {
        "Category A": 100,
        "Category B": 50,
        "Category C": 25,
        "Category D": 25
    }
  6. Configure and style mermaid-py diagrams

    main

    You can customize the appearance of your diagrams using two primary mechanisms:

    1. Global Configuration: Use the Config class to manage themes and general color configurations across your diagrams.
    2. Custom Styling: Use the Style class to apply specific styles to individual elements within a diagram.
  7. Organize large flowcharts with sub-nodes

    main

    For complex diagrams, you can organize elements into sections by using sub_nodes within a Node. This allows you to create parent nodes that contain a group of child nodes, and you can specify the internal direction (e.g., Direction.TOP_TO_BOTTOM) for that section.

    from mermaid.flowchart import Node, Link, FlowChart
    from mermaid import Direction
    
    # Create sub-sections
    section1_nodes = [Node("s1_1", "Task 1"), Node("s1_2", "Task 2")]
    section2_nodes = [Node("s2_1", "Task 3"), Node("s2_2", "Task 4")]
    
    # Create parent nodes with sub-nodes
    section1_parent = Node(
        "section1",
        "Section 1",
        sub_nodes=section1_nodes,
        direction=Direction.TOP_TO_BOTTOM
    )
    
    section2_parent = Node(
        "section2",
        "Section 2",
        sub_nodes=section2_nodes,
        direction=Direction.TOP_TO_BOTTOM
    )
  8. Create subgraphs using sub_nodes

    main

    You can group nodes into subgraphs by passing a list of Node objects to the sub_nodes parameter of a parent Node. You can control the layout of these nested nodes using the direction parameter.

    Supported directions (via str or mermaid.Direction):

    • "LR" or Direction.LEFT_TO_RIGHT (default)
    • "RL" or Direction.RIGHT_TO_LEFT
    • "TB" or Direction.TOP_TO_BOTTOM
    • "BT" or Direction.BOTTOM_TO_TOP
    from mermaid import Direction
    from mermaid.flowchart import Node
    
    # Create child nodes
    child1 = Node("child1", "Step 1")
    child2 = Node("child2", "Step 2")
    
    # Create parent node with children
    parent = Node(
        "process_group",
        "Process Group",
        sub_nodes=[child1, child2],
        direction=Direction.TOP_TO_BOTTOM
    )
  9. Core concepts of mermaid-py

    main

    The library is built around a hierarchical class structure:

    • Graph Module: The Graph class serves as the base class for all diagram types in the package.
    • Diagram Modules: Each diagram type (FlowChart, Sequence, etc.) is encapsulated in its own module containing specialized classes for elements (e.g., Node for FlowCharts, Actor for Sequence diagrams) and connections (e.g., Link).
    • Configuration & Styling: Global themes and colors are managed via the Config class, while individual element appearance is managed via the Style class.
  10. Define different types of States

    main

    The library provides several specialized state types to represent different structural patterns:

    • Simple State: A standard state with an ID and a label. state = State("state_id", "State Label")
    • Start State: Represents the entry point [*]. start = Start()
    • End State: Represents the exit point [*]. end = End()
    • Composite State: A state that contains its own internal sub-states and transitions. composite = Composite("id", "Label", sub_states=[...], direction=...)
    • Concurrent State: A state containing parallel sub-groups that run simultaneously. concurrent = Concurrent("id", "Label", sub_groups=[(group1, []), (group2, [])])
    from mermaid.statediagram import State, Start, End, Composite, Concurrent, Direction
    
    # Simple
    state = State("s1", "Simple")
    
    # Start/End
    start = Start()
    end = End()
    
    # Composite
    sub_states = [State("sub1", "Sub 1"), State("sub2", "Sub 2")]
    composite = Composite("comp", "Composite", sub_states=sub_states, direction=Direction.TOP_TO_BOTTOM)
    
    # Concurrent
    g1 = [State("p1", "P1")]
    g2 = [State("p2", "P2")]
    concurrent = Concurrent("par", "Parallel", sub_groups=[(g1, []), (g2, [])])