Graphify / graph_generator_utils.py
ZahirJS's picture
Update graph_generator_utils.py
bc7de95 verified
raw
history blame
2.51 kB
import graphviz
def add_nodes_and_edges(dot: graphviz.Digraph, parent_id: str, nodes_list: list, current_depth: int, base_color: str):
"""
Recursively adds nodes and edges to a Graphviz Digraph object,
applying a color gradient and consistent styling.
Args:
dot (graphviz.Digraph): The Graphviz Digraph object to modify.
parent_id (str): The ID of the parent node for the current set of nodes.
nodes_list (list): A list of dictionaries, each representing a node
with 'id', 'label', 'relationship', and optional 'subnodes'.
current_depth (int): The current depth in the graph hierarchy (0 for central node).
base_color (str): The hexadecimal base color for the deepest nodes.
"""
lightening_factor = 0.06
if not isinstance(base_color, str) or not base_color.startswith('#') or len(base_color) != 7:
base_color = '#BEBEBE'
base_r = int(base_color[1:3], 16)
base_g = int(base_color[3:5], 16)
base_b = int(base_color[5:7], 16)
current_r = base_r + int((255 - base_r) * current_depth * lightening_factor)
current_g = base_g + int((255 - base_g) * current_depth * lightening_factor)
current_b = base_b + int((255 - base_b) * current_depth * lightening_factor)
current_r = min(255, current_r)
current_g = min(255, current_g)
current_b = min(255, current_b)
node_fill_color = f'#{current_r:02x}{current_g:02x}{current_b:02x}'
font_color = 'black'
edge_color = '#4a4a4a'
font_size = max(9, 14 - (current_depth * 2))
edge_font_size = max(7, 10 - (current_depth * 1))
for node in nodes_list:
node_id = node.get('id')
label = node.get('label')
relationship = node.get('relationship')
if not all([node_id, label, relationship]):
raise ValueError(f"Invalid node: {node}")
dot.node(
node_id,
label,
shape='box',
style='filled,rounded',
fillcolor=node_fill_color,
fontcolor=font_color,
fontsize=str(font_size)
)
dot.edge(
parent_id,
node_id,
label=relationship,
color=edge_color,
fontcolor=edge_color,
fontsize=str(edge_font_size)
)
if 'subnodes' in node:
add_nodes_and_edges(dot, node_id, node['subnodes'], current_depth + 1, base_color)