Graphify / class_diagram_generator.py
ZahirJS's picture
Update class_diagram_generator.py
b2d22b3 verified
raw
history blame
30.3 kB
# import graphviz
# import json
# from tempfile import NamedTemporaryFile
# import os
# def generate_class_diagram(json_input: str, output_format: str) -> str:
# """
# Generates a class diagram from JSON input.
# Args:
# json_input (str): A JSON string describing the class diagram structure.
# It must follow the Expected JSON Format Example below.
# Expected JSON Format Example:
# {
# "classes": [
# {
# "name": "Vehicle",
# "type": "abstract",
# "attributes": [
# {"name": "id", "type": "String", "visibility": "-"},
# {"name": "brand", "type": "String", "visibility": "#"},
# {"name": "model", "type": "String", "visibility": "#"},
# {"name": "year", "type": "int", "visibility": "#"},
# {"name": "price", "type": "double", "visibility": "+"},
# {"name": "vehicleCount", "type": "int", "visibility": "+", "static": true}
# ],
# "methods": [
# {"name": "Vehicle", "parameters": [{"name": "brand", "type": "String"}, {"name": "model", "type": "String"}], "return_type": "Vehicle", "visibility": "+"},
# {"name": "startEngine", "return_type": "void", "visibility": "+", "abstract": true},
# {"name": "stopEngine", "return_type": "void", "visibility": "+"},
# {"name": "getPrice", "return_type": "double", "visibility": "+"},
# {"name": "setPrice", "parameters": [{"name": "price", "type": "double"}], "return_type": "void", "visibility": "+"},
# {"name": "getTotalVehicles", "return_type": "int", "visibility": "+", "static": true}
# ]
# },
# {
# "name": "Car",
# "type": "class",
# "attributes": [
# {"name": "doors", "type": "int", "visibility": "-"},
# {"name": "transmission", "type": "TransmissionType", "visibility": "-"},
# {"name": "fuelType", "type": "FuelType", "visibility": "-"}
# ],
# "methods": [
# {"name": "Car", "parameters": [{"name": "brand", "type": "String"}, {"name": "model", "type": "String"}, {"name": "doors", "type": "int"}], "return_type": "Car", "visibility": "+"},
# {"name": "startEngine", "return_type": "void", "visibility": "+"},
# {"name": "openTrunk", "return_type": "void", "visibility": "+"},
# {"name": "getDoors", "return_type": "int", "visibility": "+"},
# {"name": "setTransmission", "parameters": [{"name": "transmission", "type": "TransmissionType"}], "return_type": "void", "visibility": "+"}
# ]
# },
# {
# "name": "Motorcycle",
# "type": "class",
# "attributes": [
# {"name": "engineSize", "type": "int", "visibility": "-"},
# {"name": "hasWindshield", "type": "boolean", "visibility": "-"}
# ],
# "methods": [
# {"name": "Motorcycle", "parameters": [{"name": "brand", "type": "String"}, {"name": "model", "type": "String"}], "return_type": "Motorcycle", "visibility": "+"},
# {"name": "startEngine", "return_type": "void", "visibility": "+"},
# {"name": "wheelie", "return_type": "void", "visibility": "+"},
# {"name": "getEngineSize", "return_type": "int", "visibility": "+"}
# ]
# },
# {
# "name": "Engine",
# "type": "class",
# "attributes": [
# {"name": "horsepower", "type": "int", "visibility": "-"},
# {"name": "cylinders", "type": "int", "visibility": "-"},
# {"name": "fuelType", "type": "FuelType", "visibility": "-"}
# ],
# "methods": [
# {"name": "Engine", "parameters": [{"name": "horsepower", "type": "int"}, {"name": "cylinders", "type": "int"}], "return_type": "Engine", "visibility": "+"},
# {"name": "start", "return_type": "boolean", "visibility": "+"},
# {"name": "stop", "return_type": "void", "visibility": "+"},
# {"name": "getHorsepower", "return_type": "int", "visibility": "+"}
# ]
# },
# {
# "name": "TransmissionType",
# "type": "enum",
# "attributes": [
# {"name": "MANUAL", "type": "TransmissionType", "visibility": "+", "static": true},
# {"name": "AUTOMATIC", "type": "TransmissionType", "visibility": "+", "static": true},
# {"name": "CVT", "type": "TransmissionType", "visibility": "+", "static": true}
# ],
# "methods": []
# },
# {
# "name": "FuelType",
# "type": "enum",
# "attributes": [
# {"name": "GASOLINE", "type": "FuelType", "visibility": "+", "static": true},
# {"name": "DIESEL", "type": "FuelType", "visibility": "+", "static": true},
# {"name": "ELECTRIC", "type": "FuelType", "visibility": "+", "static": true},
# {"name": "HYBRID", "type": "FuelType", "visibility": "+", "static": true}
# ],
# "methods": []
# },
# {
# "name": "VehicleService",
# "type": "interface",
# "attributes": [],
# "methods": [
# {"name": "maintenance", "parameters": [{"name": "vehicle", "type": "Vehicle"}], "return_type": "void", "visibility": "+", "abstract": true},
# {"name": "repair", "parameters": [{"name": "vehicle", "type": "Vehicle"}, {"name": "issue", "type": "String"}], "return_type": "boolean", "visibility": "+", "abstract": true},
# {"name": "inspectVehicle", "parameters": [{"name": "vehicle", "type": "Vehicle"}], "return_type": "InspectionReport", "visibility": "+", "abstract": true}
# ]
# },
# {
# "name": "GarageService",
# "type": "class",
# "attributes": [
# {"name": "garageName", "type": "String", "visibility": "-"},
# {"name": "location", "type": "String", "visibility": "-"}
# ],
# "methods": [
# {"name": "GarageService", "parameters": [{"name": "name", "type": "String"}], "return_type": "GarageService", "visibility": "+"},
# {"name": "maintenance", "parameters": [{"name": "vehicle", "type": "Vehicle"}], "return_type": "void", "visibility": "+"},
# {"name": "repair", "parameters": [{"name": "vehicle", "type": "Vehicle"}, {"name": "issue", "type": "String"}], "return_type": "boolean", "visibility": "+"},
# {"name": "inspectVehicle", "parameters": [{"name": "vehicle", "type": "Vehicle"}], "return_type": "InspectionReport", "visibility": "+"}
# ]
# }
# ],
# "relationships": [
# {
# "from": "Car",
# "to": "Vehicle",
# "type": "inheritance",
# "label": "extends"
# },
# {
# "from": "Motorcycle",
# "to": "Vehicle",
# "type": "inheritance",
# "label": "extends"
# },
# {
# "from": "Car",
# "to": "Engine",
# "type": "composition",
# "label": "has",
# "multiplicity_from": "1",
# "multiplicity_to": "1"
# },
# {
# "from": "Motorcycle",
# "to": "Engine",
# "type": "composition",
# "label": "has",
# "multiplicity_from": "1",
# "multiplicity_to": "1"
# },
# {
# "from": "Car",
# "to": "TransmissionType",
# "type": "association",
# "label": "uses",
# "multiplicity_from": "1",
# "multiplicity_to": "1"
# },
# {
# "from": "Vehicle",
# "to": "FuelType",
# "type": "association",
# "label": "uses",
# "multiplicity_from": "1",
# "multiplicity_to": "1"
# },
# {
# "from": "GarageService",
# "to": "VehicleService",
# "type": "realization",
# "label": "implements"
# },
# {
# "from": "GarageService",
# "to": "Vehicle",
# "type": "dependency",
# "label": "services",
# "multiplicity_from": "1",
# "multiplicity_to": "*"
# }
# ]
# }
# Returns:
# str: The filepath to the generated PNG image file.
# """
# try:
# if not json_input.strip():
# return "Error: Empty input"
# data = json.loads(json_input)
# if 'classes' not in data:
# raise ValueError("Missing required field: classes")
# dot = graphviz.Digraph(comment='Class Diagram')
# dot.attr(rankdir='TB', bgcolor='white', pad='0.5')
# dot.attr('node', shape='box', style='filled', fillcolor='white', color='black', fontname='Arial', fontsize='10')
# dot.attr('edge', color='black', fontname='Arial', fontsize='9')
# classes = data.get('classes', [])
# relationships = data.get('relationships', [])
# for cls in classes:
# class_name = cls.get('name')
# class_type = cls.get('type', 'class')
# attributes = cls.get('attributes', [])
# methods = cls.get('methods', [])
# if not class_name:
# continue
# label_parts = []
# if class_type == 'abstract':
# label_parts.append(f"<<abstract>>\\n{class_name}")
# elif class_type == 'interface':
# label_parts.append(f"<<interface>>\\n{class_name}")
# elif class_type == 'enum':
# label_parts.append(f"<<enumeration>>\\n{class_name}")
# else:
# label_parts.append(class_name)
# if attributes:
# attr_lines = []
# for attr in attributes:
# visibility = attr.get('visibility', '+')
# name = attr.get('name', '')
# attr_type = attr.get('type', '')
# is_static = attr.get('static', False)
# line = f"{visibility} {name}"
# if attr_type:
# line += f" : {attr_type}"
# if is_static:
# line += " [static]"
# attr_lines.append(line)
# if attr_lines:
# label_parts.append("\\n".join(attr_lines))
# if methods:
# method_lines = []
# for method in methods:
# visibility = method.get('visibility', '+')
# name = method.get('name', '')
# parameters = method.get('parameters', [])
# return_type = method.get('return_type', 'void')
# is_static = method.get('static', False)
# is_abstract = method.get('abstract', False)
# line = f"{visibility} {name}("
# if parameters:
# params = []
# for param in parameters:
# param_name = param.get('name', '')
# param_type = param.get('type', '')
# params.append(f"{param_name}: {param_type}")
# line += ", ".join(params)
# line += f") : {return_type}"
# if is_static:
# line += " [static]"
# if is_abstract:
# line += " [abstract]"
# method_lines.append(line)
# if method_lines:
# label_parts.append("\\n".join(method_lines))
# label = "\\n\\n".join(label_parts)
# if class_type == 'interface':
# fillcolor = '#f5f5f5'
# style = 'filled,dashed'
# elif class_type == 'abstract':
# fillcolor = '#eeeeee'
# style = 'filled'
# else:
# fillcolor = 'white'
# style = 'filled'
# dot.node(class_name, label, fillcolor=fillcolor, style=style)
# for relationship in relationships:
# from_class = relationship.get('from')
# to_class = relationship.get('to')
# rel_type = relationship.get('type', 'association')
# label = relationship.get('label', '')
# multiplicity_from = relationship.get('multiplicity_from', '')
# multiplicity_to = relationship.get('multiplicity_to', '')
# if not from_class or not to_class:
# continue
# edge_attrs = {}
# if label:
# edge_attrs['label'] = label
# if multiplicity_from:
# edge_attrs['taillabel'] = multiplicity_from
# if multiplicity_to:
# edge_attrs['headlabel'] = multiplicity_to
# if rel_type == 'inheritance':
# edge_attrs['arrowhead'] = 'empty'
# elif rel_type == 'composition':
# edge_attrs['arrowhead'] = 'normal'
# edge_attrs['arrowtail'] = 'diamond'
# edge_attrs['dir'] = 'both'
# elif rel_type == 'aggregation':
# edge_attrs['arrowhead'] = 'normal'
# edge_attrs['arrowtail'] = 'odiamond'
# edge_attrs['dir'] = 'both'
# elif rel_type == 'realization':
# edge_attrs['arrowhead'] = 'empty'
# edge_attrs['style'] = 'dashed'
# elif rel_type == 'dependency':
# edge_attrs['arrowhead'] = 'normal'
# edge_attrs['style'] = 'dashed'
# else:
# edge_attrs['arrowhead'] = 'normal'
# dot.edge(from_class, to_class, **edge_attrs)
# with NamedTemporaryFile(delete=False, suffix=f'.{output_format}') as tmp:
# dot.render(tmp.name, format=output_format, cleanup=True)
# return f"{tmp.name}.{output_format}"
# except json.JSONDecodeError:
# return "Error: Invalid JSON format"
# except Exception as e:
# return f"Error: {str(e)}"
import graphviz
import json
from tempfile import NamedTemporaryFile
import os
def generate_class_diagram(json_input: str, output_format: str) -> str:
"""
Generates a class diagram from JSON input.
Args:
json_input (str): A JSON string describing the class diagram structure.
It must follow the Expected JSON Format Example below.
Expected JSON Format Example:
{
"classes": [
{
"name": "Vehicle",
"type": "abstract",
"attributes": [
{"name": "id", "type": "String", "visibility": "-"},
{"name": "brand", "type": "String", "visibility": "#"},
{"name": "model", "type": "String", "visibility": "#"},
{"name": "year", "type": "int", "visibility": "#"},
{"name": "price", "type": "double", "visibility": "+"},
{"name": "vehicleCount", "type": "int", "visibility": "+", "static": true}
],
"methods": [
{"name": "Vehicle", "parameters": [{"name": "brand", "type": "String"}, {"name": "model", "type": "String"}], "return_type": "Vehicle", "visibility": "+"},
{"name": "startEngine", "return_type": "void", "visibility": "+", "abstract": true},
{"name": "stopEngine", "return_type": "void", "visibility": "+"},
{"name": "getPrice", "return_type": "double", "visibility": "+"},
{"name": "setPrice", "parameters": [{"name": "price", "type": "double"}], "return_type": "void", "visibility": "+"},
{"name": "getTotalVehicles", "return_type": "int", "visibility": "+", "static": true}
]
},
{
"name": "Car",
"type": "class",
"attributes": [
{"name": "doors", "type": "int", "visibility": "-"},
{"name": "transmission", "type": "TransmissionType", "visibility": "-"},
{"name": "fuelType", "type": "FuelType", "visibility": "-"}
],
"methods": [
{"name": "Car", "parameters": [{"name": "brand", "type": "String"}, {"name": "model", "type": "String"}, {"name": "doors", "type": "int"}], "return_type": "Car", "visibility": "+"},
{"name": "startEngine", "return_type": "void", "visibility": "+"},
{"name": "openTrunk", "return_type": "void", "visibility": "+"},
{"name": "getDoors", "return_type": "int", "visibility": "+"},
{"name": "setTransmission", "parameters": [{"name": "transmission", "type": "TransmissionType"}], "return_type": "void", "visibility": "+"}
]
},
{
"name": "Motorcycle",
"type": "class",
"attributes": [
{"name": "engineSize", "type": "int", "visibility": "-"},
{"name": "hasWindshield", "type": "boolean", "visibility": "-"}
],
"methods": [
{"name": "Motorcycle", "parameters": [{"name": "brand", "type": "String"}, {"name": "model", "type": "String"}], "return_type": "Motorcycle", "visibility": "+"},
{"name": "startEngine", "return_type": "void", "visibility": "+"},
{"name": "wheelie", "return_type": "void", "visibility": "+"},
{"name": "getEngineSize", "return_type": "int", "visibility": "+"}
]
},
{
"name": "Engine",
"type": "class",
"attributes": [
{"name": "horsepower", "type": "int", "visibility": "-"},
{"name": "cylinders", "type": "int", "visibility": "-"},
{"name": "fuelType", "type": "FuelType", "visibility": "-"}
],
"methods": [
{"name": "Engine", "parameters": [{"name": "horsepower", "type": "int"}, {"name": "cylinders", "type": "int"}], "return_type": "Engine", "visibility": "+"},
{"name": "start", "return_type": "boolean", "visibility": "+"},
{"name": "stop", "return_type": "void", "visibility": "+"},
{"name": "getHorsepower", "return_type": "int", "visibility": "+"}
]
},
{
"name": "TransmissionType",
"type": "enum",
"attributes": [
{"name": "MANUAL", "type": "TransmissionType", "visibility": "+", "static": true},
{"name": "AUTOMATIC", "type": "TransmissionType", "visibility": "+", "static": true},
{"name": "CVT", "type": "TransmissionType", "visibility": "+", "static": true}
],
"methods": []
},
{
"name": "FuelType",
"type": "enum",
"attributes": [
{"name": "GASOLINE", "type": "FuelType", "visibility": "+", "static": true},
{"name": "DIESEL", "type": "FuelType", "visibility": "+", "static": true},
{"name": "ELECTRIC", "type": "FuelType", "visibility": "+", "static": true},
{"name": "HYBRID", "type": "FuelType", "visibility": "+", "static": true}
],
"methods": []
},
{
"name": "VehicleService",
"type": "interface",
"attributes": [],
"methods": [
{"name": "maintenance", "parameters": [{"name": "vehicle", "type": "Vehicle"}], "return_type": "void", "visibility": "+", "abstract": true},
{"name": "repair", "parameters": [{"name": "vehicle", "type": "Vehicle"}, {"name": "issue", "type": "String"}], "return_type": "boolean", "visibility": "+", "abstract": true},
{"name": "inspectVehicle", "parameters": [{"name": "vehicle", "type": "Vehicle"}], "return_type": "InspectionReport", "visibility": "+", "abstract": true}
]
},
{
"name": "GarageService",
"type": "class",
"attributes": [
{"name": "garageName", "type": "String", "visibility": "-"},
{"name": "location", "type": "String", "visibility": "-"}
],
"methods": [
{"name": "GarageService", "parameters": [{"name": "name", "type": "String"}], "return_type": "GarageService", "visibility": "+"},
{"name": "maintenance", "parameters": [{"name": "vehicle", "type": "Vehicle"}], "return_type": "void", "visibility": "+"},
{"name": "repair", "parameters": [{"name": "vehicle", "type": "Vehicle"}, {"name": "issue", "type": "String"}], "return_type": "boolean", "visibility": "+"},
{"name": "inspectVehicle", "parameters": [{"name": "vehicle", "type": "Vehicle"}], "return_type": "InspectionReport", "visibility": "+"}
]
}
],
"relationships": [
{
"from": "Car",
"to": "Vehicle",
"type": "inheritance",
"label": "extends"
},
{
"from": "Motorcycle",
"to": "Vehicle",
"type": "inheritance",
"label": "extends"
},
{
"from": "Car",
"to": "Engine",
"type": "composition",
"label": "has",
"multiplicity_from": "1",
"multiplicity_to": "1"
},
{
"from": "Motorcycle",
"to": "Engine",
"type": "composition",
"label": "has",
"multiplicity_from": "1",
"multiplicity_to": "1"
},
{
"from": "Car",
"to": "TransmissionType",
"type": "association",
"label": "uses",
"multiplicity_from": "1",
"multiplicity_to": "1"
},
{
"from": "Vehicle",
"to": "FuelType",
"type": "association",
"label": "uses",
"multiplicity_from": "1",
"multiplicity_to": "1"
},
{
"from": "GarageService",
"to": "VehicleService",
"type": "realization",
"label": "implements"
},
{
"from": "GarageService",
"to": "Vehicle",
"type": "dependency",
"label": "services",
"multiplicity_from": "1",
"multiplicity_to": "*"
}
]
}
Returns:
str: The filepath to the generated PNG image file.
"""
try:
if not json_input.strip():
return "Error: Empty input"
data = json.loads(json_input)
if 'classes' not in data:
raise ValueError("Missing required field: classes")
# Configuración del diagrama con espaciado reducido
dot = graphviz.Digraph(comment='Class Diagram')
dot.attr(rankdir='TB', bgcolor='white', pad='0.5', nodesep='0.8', ranksep='1.2')
dot.attr('node', shape='plaintext', fontname='Arial', fontsize='11')
dot.attr('edge', color='black', fontname='Arial', fontsize='9', minlen='1')
classes = data.get('classes', [])
relationships = data.get('relationships', [])
for cls in classes:
class_name = cls.get('name')
class_type = cls.get('type', 'class')
attributes = cls.get('attributes', [])
methods = cls.get('methods', [])
if not class_name:
continue
# Crear tabla HTML para estructura de clase
html_label = '<TABLE BORDER="1" CELLBORDER="0" CELLSPACING="0" CELLPADDING="5" BGCOLOR="white">'
# Header con nombre de clase y estereotipo
if class_type == 'abstract':
html_label += f'<TR><TD ALIGN="CENTER"><B>&lt;&lt;abstract&gt;&gt;<BR/>{class_name}</B></TD></TR>'
elif class_type == 'interface':
html_label += f'<TR><TD ALIGN="CENTER"><B>&lt;&lt;interface&gt;&gt;<BR/>{class_name}</B></TD></TR>'
elif class_type == 'enum':
html_label += f'<TR><TD ALIGN="CENTER"><B>&lt;&lt;enumeration&gt;&gt;<BR/>{class_name}</B></TD></TR>'
else:
html_label += f'<TR><TD ALIGN="CENTER"><B>{class_name}</B></TD></TR>'
# Línea separadora después del nombre
html_label += '<HR/>'
# Sección de atributos
if attributes:
for attr in attributes:
visibility = attr.get('visibility', '+')
name = attr.get('name', '')
attr_type = attr.get('type', '')
is_static = attr.get('static', False)
line = f"{visibility} {name}"
if attr_type:
line += f" : {attr_type}"
if is_static:
line = f"<U>{line}</U>" # Subrayado para elementos estáticos
html_label += f'<TR><TD ALIGN="LEFT">{line}</TD></TR>'
else:
# Espacio vacío si no hay atributos
html_label += '<TR><TD ALIGN="LEFT"> </TD></TR>'
# Línea separadora entre atributos y métodos
html_label += '<HR/>'
# Sección de métodos
if methods:
for method in methods:
visibility = method.get('visibility', '+')
name = method.get('name', '')
parameters = method.get('parameters', [])
return_type = method.get('return_type', 'void')
is_static = method.get('static', False)
is_abstract = method.get('abstract', False)
line = f"{visibility} {name}("
if parameters:
params = []
for param in parameters:
param_name = param.get('name', '')
param_type = param.get('type', '')
params.append(f"{param_name}: {param_type}")
line += ", ".join(params)
line += f") : {return_type}"
if is_static:
line = f"<U>{line}</U>" # Subrayado para métodos estáticos
if is_abstract:
line = f"<I>{line}</I>" # Cursiva para métodos abstractos
html_label += f'<TR><TD ALIGN="LEFT">{line}</TD></TR>'
else:
# Espacio vacío si no hay métodos
html_label += '<TR><TD ALIGN="LEFT"> </TD></TR>'
html_label += '</TABLE>'
# Agregar nodo con la tabla HTML
dot.node(class_name, f'<{html_label}>')
# Procesar relaciones con líneas rectas
for relationship in relationships:
from_class = relationship.get('from')
to_class = relationship.get('to')
rel_type = relationship.get('type', 'association')
label = relationship.get('label', '')
multiplicity_from = relationship.get('multiplicity_from', '')
multiplicity_to = relationship.get('multiplicity_to', '')
if not from_class or not to_class:
continue
edge_attrs = {
'splines': 'ortho', # Líneas estrictamente ortogonales (solo horizontales/verticales)
'concentrate': 'false', # Evita que las líneas se combinen
'constraint': 'true' # Mantiene la estructura jerárquica
}
if label:
edge_attrs['label'] = label
if multiplicity_from:
edge_attrs['taillabel'] = multiplicity_from
if multiplicity_to:
edge_attrs['headlabel'] = multiplicity_to
# Configurar estilos de flecha según el tipo de relación
if rel_type == 'inheritance':
edge_attrs['arrowhead'] = 'empty'
edge_attrs['color'] = 'black'
elif rel_type == 'composition':
edge_attrs['arrowhead'] = 'normal'
edge_attrs['arrowtail'] = 'diamond'
edge_attrs['dir'] = 'both'
edge_attrs['color'] = 'black'
elif rel_type == 'aggregation':
edge_attrs['arrowhead'] = 'normal'
edge_attrs['arrowtail'] = 'odiamond'
edge_attrs['dir'] = 'both'
edge_attrs['color'] = 'black'
elif rel_type == 'realization':
edge_attrs['arrowhead'] = 'empty'
edge_attrs['style'] = 'dashed'
edge_attrs['color'] = 'black'
elif rel_type == 'dependency':
edge_attrs['arrowhead'] = 'normal'
edge_attrs['style'] = 'dashed'
edge_attrs['color'] = 'black'
else: # association
edge_attrs['arrowhead'] = 'normal'
edge_attrs['color'] = 'black'
dot.edge(from_class, to_class, **edge_attrs)
# Renderizar el diagrama
with NamedTemporaryFile(delete=False, suffix=f'.{output_format}') as tmp:
dot.render(tmp.name, format=output_format, cleanup=True)
return f"{tmp.name}.{output_format}"
except json.JSONDecodeError:
return "Error: Invalid JSON format"
except Exception as e:
return f"Error: {str(e)}"