Create concept_map_generator.py
Browse files- concept_map_generator.py +56 -0
concept_map_generator.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import graphviz
|
| 2 |
+
import json
|
| 3 |
+
from tempfile import NamedTemporaryFile
|
| 4 |
+
import os
|
| 5 |
+
from graph_generator_utils import add_nodes_and_edges
|
| 6 |
+
|
| 7 |
+
def generate_concept_map(json_input: str) -> str:
|
| 8 |
+
"""
|
| 9 |
+
Generates a concept map from JSON input.
|
| 10 |
+
"""
|
| 11 |
+
try:
|
| 12 |
+
if not json_input.strip():
|
| 13 |
+
return "Error: Empty input"
|
| 14 |
+
|
| 15 |
+
data = json.loads(json_input)
|
| 16 |
+
|
| 17 |
+
if 'central_node' not in data or 'nodes' not in data:
|
| 18 |
+
raise ValueError("Missing required fields: central_node or nodes")
|
| 19 |
+
|
| 20 |
+
dot = graphviz.Digraph(
|
| 21 |
+
name='ConceptMap',
|
| 22 |
+
format='png',
|
| 23 |
+
graph_attr={
|
| 24 |
+
'rankdir': 'TB', # Top-to-Bottom layout (vertical hierarchy)
|
| 25 |
+
'splines': 'ortho', # Straight lines
|
| 26 |
+
'bgcolor': 'white', # White background
|
| 27 |
+
'pad': '0.5' # Padding around the graph
|
| 28 |
+
}
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
base_color = '#19191a' # Base color for the central node and gradient
|
| 32 |
+
|
| 33 |
+
# Central node styling (rounded box, dark color)
|
| 34 |
+
dot.node(
|
| 35 |
+
'central',
|
| 36 |
+
data['central_node'],
|
| 37 |
+
shape='box', # Rectangular shape
|
| 38 |
+
style='filled,rounded', # Filled and rounded corners
|
| 39 |
+
fillcolor=base_color, # Darkest color
|
| 40 |
+
fontcolor='white', # White text for dark background
|
| 41 |
+
fontsize='16' # Larger font for central node
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# Add child nodes and edges recursively starting from depth 1
|
| 45 |
+
add_nodes_and_edges(dot, 'central', data.get('nodes', []), current_depth=1, base_color=base_color)
|
| 46 |
+
|
| 47 |
+
# Save to temporary file
|
| 48 |
+
with NamedTemporaryFile(delete=False, suffix='.png') as tmp:
|
| 49 |
+
dot.render(tmp.name, format='png', cleanup=True)
|
| 50 |
+
return tmp.name + '.png'
|
| 51 |
+
|
| 52 |
+
except json.JSONDecodeError:
|
| 53 |
+
return "Error: Invalid JSON format"
|
| 54 |
+
except Exception as e:
|
| 55 |
+
return f"Error: {str(e)}"
|
| 56 |
+
|