|
import graphviz |
|
import json |
|
from tempfile import NamedTemporaryFile |
|
import os |
|
from graph_generator_utils import add_nodes_and_edges |
|
|
|
def generate_concept_map(json_input: str, base_color: str) -> str: |
|
""" |
|
Generates a concept map from JSON input. |
|
|
|
Args: |
|
json_input (str): A JSON string describing the concept map structure. |
|
It must follow the Expected JSON Format Example below. |
|
base_color (str): The hexadecimal color string (e.g., '#19191a') for the base |
|
color of the nodes, from which a gradient will be generated. |
|
|
|
Returns: |
|
str: The filepath to the generated PNG image file. |
|
|
|
Expected JSON Format Example: |
|
{ |
|
"central_node": "Artificial Intelligence (AI)", |
|
"nodes": [ |
|
{ |
|
"id": "ml_fundamental", |
|
"label": "Machine Learning", |
|
"relationship": "is essential for", |
|
"subnodes": [ |
|
{ |
|
"id": "dl_branch", |
|
"label": "Deep Learning", |
|
"relationship": "for example", |
|
"subnodes": [ |
|
{"id": "cnn_example", "label": "CNNs", "relationship": "for example"}, |
|
{"id": "rnn_example", "label": "RNNs", "relationship": "for example"} |
|
] |
|
} |
|
] |
|
}, |
|
{ |
|
"id": "ai_types", |
|
"label": "Types", |
|
"relationship": "formed by", |
|
"subnodes": [ |
|
{ |
|
"id": "agi_type", |
|
"label": "AGI", |
|
"relationship": "this is", |
|
"subnodes": [ |
|
{"id": "strong_ai", "label": "Strong AI", "relationship": "provoked by"} |
|
] |
|
} |
|
] |
|
} |
|
] |
|
} |
|
""" |
|
try: |
|
if not json_input.strip(): |
|
return "Error: Empty input" |
|
|
|
data = json.loads(json_input) |
|
|
|
if 'central_node' not in data or 'nodes' not in data: |
|
raise ValueError("Missing required fields: central_node or nodes") |
|
|
|
dot = graphviz.Digraph( |
|
name='ConceptMap', |
|
format='png', |
|
graph_attr={ |
|
'rankdir': 'TB', |
|
'splines': 'ortho', |
|
'bgcolor': 'white', |
|
'pad': '0.5' |
|
} |
|
) |
|
|
|
|
|
|
|
|
|
|
|
dot.node( |
|
'central', |
|
data['central_node'], |
|
shape='box', |
|
style='filled,rounded', |
|
fillcolor=base_color, |
|
fontcolor='white', |
|
fontsize='16' |
|
) |
|
|
|
|
|
add_nodes_and_edges(dot, 'central', data.get('nodes', []), current_depth=1, base_color=base_color) |
|
|
|
|
|
with NamedTemporaryFile(delete=False, suffix='.png') as tmp: |
|
dot.render(tmp.name, format='png', cleanup=True) |
|
return tmp.name + '.png' |
|
|
|
except json.JSONDecodeError: |
|
return "Error: Invalid JSON format" |
|
except Exception as e: |
|
return f"Error: {str(e)}" |
|
|
|
|