Graphify / class_diagram_generator.py
ZahirJS's picture
Update class_diagram_generator.py
457337e verified
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.
output_format (str): The output format for the generated diagram.
Supported formats: "png" or "svg"
Expected JSON Format Example:
{
"classes": [
{
"name": "Student",
"type": "class",
"attributes": [
{"name": "studentId", "type": "String", "visibility": "-"},
{"name": "username", "type": "String", "visibility": "+"},
{"name": "email", "type": "String", "visibility": "+"},
{"name": "enrollmentDate", "type": "Date", "visibility": "+"},
{"name": "currentLevel", "type": "String", "visibility": "+"}
],
"methods": [
{"name": "Student", "parameters": [{"name": "username", "type": "String"}, {"name": "email", "type": "String"}], "return_type": "Student", "visibility": "+"},
{"name": "enrollCourse", "parameters": [{"name": "courseId", "type": "String"}], "return_type": "boolean", "visibility": "+"},
{"name": "updateProgress", "parameters": [{"name": "lessonId", "type": "String"}], "return_type": "void", "visibility": "+"}
]
},
{
"name": "CourseEnrollment",
"type": "class",
"attributes": [
{"name": "enrollmentId", "type": "String", "visibility": "-"},
{"name": "studentId", "type": "String", "visibility": "+"},
{"name": "courseId", "type": "String", "visibility": "+"},
{"name": "enrollmentDate", "type": "Date", "visibility": "+"},
{"name": "progress", "type": "double", "visibility": "+"}
],
"methods": [
{"name": "CourseEnrollment", "parameters": [{"name": "studentId", "type": "String"}, {"name": "courseId", "type": "String"}], "return_type": "CourseEnrollment", "visibility": "+"},
{"name": "calculateProgress", "return_type": "double", "visibility": "+"}
]
},
{
"name": "Course",
"type": "class",
"attributes": [
{"name": "courseId", "type": "String", "visibility": "-"},
{"name": "title", "type": "String", "visibility": "+"},
{"name": "description", "type": "String", "visibility": "+"},
{"name": "difficulty", "type": "String", "visibility": "+"},
{"name": "duration", "type": "int", "visibility": "+"}
],
"methods": [
{"name": "Course", "parameters": [{"name": "title", "type": "String"}], "return_type": "Course", "visibility": "+"},
{"name": "addLesson", "parameters": [{"name": "lesson", "type": "Lesson"}], "return_type": "void", "visibility": "+"}
]
},
{
"name": "Instructor",
"type": "class",
"attributes": [
{"name": "instructorId", "type": "String", "visibility": "-"},
{"name": "name", "type": "String", "visibility": "+"},
{"name": "expertise", "type": "String", "visibility": "+"},
{"name": "rating", "type": "double", "visibility": "+"}
],
"methods": [
{"name": "Instructor", "parameters": [{"name": "name", "type": "String"}, {"name": "expertise", "type": "String"}], "return_type": "Instructor", "visibility": "+"},
{"name": "createCourse", "parameters": [{"name": "title", "type": "String"}], "return_type": "Course", "visibility": "+"}
]
},
{
"name": "Lesson",
"type": "class",
"attributes": [
{"name": "lessonId", "type": "String", "visibility": "-"},
{"name": "title", "type": "String", "visibility": "+"},
{"name": "courseId", "type": "String", "visibility": "+"},
{"name": "duration", "type": "int", "visibility": "+"},
{"name": "order", "type": "int", "visibility": "+"}
],
"methods": [
{"name": "Lesson", "parameters": [{"name": "title", "type": "String"}], "return_type": "Lesson", "visibility": "+"},
{"name": "markCompleted", "parameters": [{"name": "studentId", "type": "String"}], "return_type": "void", "visibility": "+"}
]
},
{
"name": "VideoContent",
"type": "class",
"attributes": [
{"name": "videoId", "type": "String", "visibility": "-"},
{"name": "lessonId", "type": "String", "visibility": "+"},
{"name": "videoUrl", "type": "String", "visibility": "+"},
{"name": "duration", "type": "int", "visibility": "+"}
],
"methods": [
{"name": "VideoContent", "parameters": [{"name": "lessonId", "type": "String"}, {"name": "videoUrl", "type": "String"}], "return_type": "VideoContent", "visibility": "+"},
{"name": "play", "return_type": "void", "visibility": "+"}
]
},
{
"name": "WatchProgress",
"type": "class",
"attributes": [
{"name": "progressId", "type": "String", "visibility": "-"},
{"name": "studentId", "type": "String", "visibility": "+"},
{"name": "videoId", "type": "String", "visibility": "+"},
{"name": "watchedMinutes", "type": "int", "visibility": "+"}
],
"methods": [
{"name": "WatchProgress", "parameters": [{"name": "studentId", "type": "String"}, {"name": "videoId", "type": "String"}], "return_type": "WatchProgress", "visibility": "+"},
{"name": "updateProgress", "parameters": [{"name": "minutes", "type": "int"}], "return_type": "void", "visibility": "+"}
]
},
{
"name": "Quiz",
"type": "class",
"attributes": [
{"name": "quizId", "type": "String", "visibility": "-"},
{"name": "lessonId", "type": "String", "visibility": "+"},
{"name": "title", "type": "String", "visibility": "+"},
{"name": "passingScore", "type": "int", "visibility": "+"}
],
"methods": [
{"name": "Quiz", "parameters": [{"name": "title", "type": "String"}], "return_type": "Quiz", "visibility": "+"},
{"name": "addQuestion", "parameters": [{"name": "question", "type": "Question"}], "return_type": "void", "visibility": "+"}
]
},
{
"name": "Question",
"type": "class",
"attributes": [
{"name": "questionId", "type": "String", "visibility": "-"},
{"name": "quizId", "type": "String", "visibility": "+"},
{"name": "questionText", "type": "String", "visibility": "+"},
{"name": "questionType", "type": "String", "visibility": "+"}
],
"methods": [
{"name": "Question", "parameters": [{"name": "questionText", "type": "String"}], "return_type": "Question", "visibility": "+"},
{"name": "addOption", "parameters": [{"name": "option", "type": "String"}], "return_type": "void", "visibility": "+"}
]
},
{
"name": "QuizAttempt",
"type": "class",
"attributes": [
{"name": "attemptId", "type": "String", "visibility": "-"},
{"name": "studentId", "type": "String", "visibility": "+"},
{"name": "quizId", "type": "String", "visibility": "+"},
{"name": "score", "type": "int", "visibility": "+"},
{"name": "attemptDate", "type": "Date", "visibility": "+"}
],
"methods": [
{"name": "QuizAttempt", "parameters": [{"name": "studentId", "type": "String"}, {"name": "quizId", "type": "String"}], "return_type": "QuizAttempt", "visibility": "+"},
{"name": "submitAnswer", "parameters": [{"name": "questionId", "type": "String"}, {"name": "answer", "type": "String"}], "return_type": "void", "visibility": "+"}
]
},
{
"name": "Discussion",
"type": "class",
"attributes": [
{"name": "discussionId", "type": "String", "visibility": "-"},
{"name": "courseId", "type": "String", "visibility": "+"},
{"name": "title", "type": "String", "visibility": "+"},
{"name": "createdDate", "type": "Date", "visibility": "+"}
],
"methods": [
{"name": "Discussion", "parameters": [{"name": "title", "type": "String"}], "return_type": "Discussion", "visibility": "+"},
{"name": "addPost", "parameters": [{"name": "studentId", "type": "String"}, {"name": "message", "type": "String"}], "return_type": "void", "visibility": "+"}
]
},
{
"name": "Post",
"type": "class",
"attributes": [
{"name": "postId", "type": "String", "visibility": "-"},
{"name": "discussionId", "type": "String", "visibility": "+"},
{"name": "authorId", "type": "String", "visibility": "+"},
{"name": "content", "type": "String", "visibility": "+"},
{"name": "postDate", "type": "Date", "visibility": "+"}
],
"methods": [
{"name": "Post", "parameters": [{"name": "authorId", "type": "String"}, {"name": "content", "type": "String"}], "return_type": "Post", "visibility": "+"},
{"name": "reply", "parameters": [{"name": "replyContent", "type": "String"}], "return_type": "void", "visibility": "+"}
]
},
{
"name": "Certificate",
"type": "class",
"attributes": [
{"name": "certificateId", "type": "String", "visibility": "-"},
{"name": "studentId", "type": "String", "visibility": "+"},
{"name": "courseId", "type": "String", "visibility": "+"},
{"name": "issueDate", "type": "Date", "visibility": "+"},
{"name": "grade", "type": "String", "visibility": "+"}
],
"methods": [
{"name": "Certificate", "parameters": [{"name": "studentId", "type": "String"}, {"name": "courseId", "type": "String"}], "return_type": "Certificate", "visibility": "+"},
{"name": "generatePDF", "return_type": "String", "visibility": "+"}
]
},
{
"name": "Payment",
"type": "class",
"attributes": [
{"name": "paymentId", "type": "String", "visibility": "-"},
{"name": "studentId", "type": "String", "visibility": "+"},
{"name": "courseId", "type": "String", "visibility": "+"},
{"name": "amount", "type": "double", "visibility": "+"},
{"name": "paymentDate", "type": "Date", "visibility": "+"}
],
"methods": [
{"name": "Payment", "parameters": [{"name": "studentId", "type": "String"}, {"name": "amount", "type": "double"}], "return_type": "Payment", "visibility": "+"},
{"name": "processPayment", "return_type": "boolean", "visibility": "+"}
]
}
],
"relationships": [
{
"from": "Student",
"to": "CourseEnrollment",
"type": "association",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "CourseEnrollment",
"to": "Course",
"type": "association",
"multiplicity_from": "*",
"multiplicity_to": "1"
},
{
"from": "Instructor",
"to": "Course",
"type": "association",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "Course",
"to": "Lesson",
"type": "composition",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "Lesson",
"to": "VideoContent",
"type": "association",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "Student",
"to": "WatchProgress",
"type": "association",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "VideoContent",
"to": "WatchProgress",
"type": "association",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "Lesson",
"to": "Quiz",
"type": "association",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "Quiz",
"to": "Question",
"type": "composition",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "Student",
"to": "QuizAttempt",
"type": "association",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "Quiz",
"to": "QuizAttempt",
"type": "association",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "Course",
"to": "Discussion",
"type": "aggregation",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "Discussion",
"to": "Post",
"type": "composition",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "Student",
"to": "Certificate",
"type": "association",
"multiplicity_from": "1",
"multiplicity_to": "*"
},
{
"from": "Student",
"to": "Payment",
"type": "association",
"multiplicity_from": "1",
"multiplicity_to": "*"
}
]
}
Returns:
str: The filepath to the generated 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', nodesep='0.8', ranksep='1.2', splines='ortho')
dot.attr('node', shape='plaintext', fontname='Arial', fontsize='11')
dot.attr('edge', color='#4a4a4a', fontname='Arial', fontsize='9', minlen='1')
header_color = '#BEBEBE'
body_color = '#E8E8E8'
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
html_label = f'<TABLE BORDER="1" CELLBORDER="0" CELLSPACING="0" CELLPADDING="5" STYLE="rounded" BGCOLOR="{body_color}">'
if class_type == 'abstract':
html_label += f'<TR><TD ALIGN="CENTER" BGCOLOR="{header_color}"><B>&lt;&lt;abstract&gt;&gt;<BR/>{class_name}</B></TD></TR>'
elif class_type == 'interface':
html_label += f'<TR><TD ALIGN="CENTER" BGCOLOR="{header_color}"><B>&lt;&lt;interface&gt;&gt;<BR/>{class_name}</B></TD></TR>'
elif class_type == 'enum':
html_label += f'<TR><TD ALIGN="CENTER" BGCOLOR="{header_color}"><B>&lt;&lt;enumeration&gt;&gt;<BR/>{class_name}</B></TD></TR>'
else:
html_label += f'<TR><TD ALIGN="CENTER" BGCOLOR="{header_color}"><B>{class_name}</B></TD></TR>'
html_label += f'<HR/><TR><TD BGCOLOR="{body_color}" HEIGHT="5"></TD></TR>'
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>"
html_label += f'<TR><TD ALIGN="LEFT" BGCOLOR="{body_color}">{line}</TD></TR>'
else:
html_label += f'<TR><TD ALIGN="LEFT" BGCOLOR="{body_color}"> </TD></TR>'
html_label += f'<TR><TD BGCOLOR="{body_color}" HEIGHT="5"></TD></TR><HR/><TR><TD BGCOLOR="{body_color}" HEIGHT="5"></TD></TR>'
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>"
if is_abstract:
line = f"<I>{line}</I>"
html_label += f'<TR><TD ALIGN="LEFT" BGCOLOR="{body_color}">{line}</TD></TR>'
else:
html_label += f'<TR><TD ALIGN="LEFT" BGCOLOR="{body_color}"> </TD></TR>'
html_label += '</TABLE>'
dot.node(class_name, f'<{html_label}>', style='rounded')
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 = {
'color': '#4a4a4a'
}
if multiplicity_from:
edge_attrs['taillabel'] = multiplicity_from
if multiplicity_to:
edge_attrs['headlabel'] = multiplicity_to
if rel_type == 'inheritance':
edge_attrs['arrowhead'] = 'empty'
edge_attrs['color'] = '#4a4a4a'
elif rel_type == 'composition':
edge_attrs['arrowhead'] = 'normal'
edge_attrs['arrowtail'] = 'diamond'
edge_attrs['dir'] = 'both'
edge_attrs['color'] = '#4a4a4a'
elif rel_type == 'aggregation':
edge_attrs['arrowhead'] = 'normal'
edge_attrs['arrowtail'] = 'odiamond'
edge_attrs['dir'] = 'both'
edge_attrs['color'] = '#4a4a4a'
elif rel_type == 'realization':
edge_attrs['arrowhead'] = 'empty'
edge_attrs['style'] = 'dashed'
edge_attrs['color'] = '#4a4a4a'
elif rel_type == 'dependency':
edge_attrs['arrowhead'] = 'normal'
edge_attrs['style'] = 'dashed'
edge_attrs['color'] = '#4a4a4a'
else:
edge_attrs['arrowhead'] = 'normal'
edge_attrs['color'] = '#4a4a4a'
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)}"