File size: 7,216 Bytes
5f8bd16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import graphviz
import json
from tempfile import NamedTemporaryFile
import os

def generate_class_diagram(json_input: str, output_format: str) -> str:
    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(
            name='ClassDiagram',
            format='png',
            graph_attr={
                'rankdir': 'TB',
                'splines': 'ortho',
                'bgcolor': 'white',
                'pad': '0.5',
                'nodesep': '1.5',
                'ranksep': '2.0'
            }
        )
        
        base_color = '#19191a'
        lightening_factor = 0.15
        
        classes = data.get('classes', [])
        relationships = data.get('relationships', [])
        
        for i, cls in enumerate(classes):
            class_name = cls.get('name')
            class_type = cls.get('type', 'class')
            attributes = cls.get('attributes', [])
            methods = cls.get('methods', [])
            
            if not class_name:
                raise ValueError(f"Invalid class: {cls}")
            
            current_depth = i % 6
            
            if not isinstance(base_color, str) or not base_color.startswith('#') or len(base_color) != 7:
                base_color_safe = '#19191a'
            else:
                base_color_safe = base_color
                
            base_r = int(base_color_safe[1:3], 16)
            base_g = int(base_color_safe[3:5], 16)
            base_b = int(base_color_safe[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_color = f'#{current_r:02x}{current_g:02x}{current_b:02x}'
            font_color = 'white' if current_depth * lightening_factor < 0.6 else 'black'
            
            class_label = ""
            
            if class_type == 'abstract':
                class_label += "<<abstract>>\\n"
            elif class_type == 'interface':
                class_label += "<<interface>>\\n"
            elif class_type == 'enum':
                class_label += "<<enumeration>>\\n"
            
            class_label += f"{class_name}\\l"
            
            if attributes:
                class_label += "\\l"
                for attr in attributes:
                    visibility = attr.get('visibility', '+')
                    name = attr.get('name', '')
                    attr_type = attr.get('type', '')
                    is_static = attr.get('static', False)
                    
                    attr_line = f"{visibility} "
                    if is_static:
                        attr_line += f"<<static>> "
                    attr_line += f"{name}"
                    if attr_type:
                        attr_line += f" : {attr_type}"
                    class_label += f"{attr_line}\\l"
            
            if methods:
                class_label += "\\l"
                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)
                    
                    method_line = f"{visibility} "
                    if is_static:
                        method_line += f"<<static>> "
                    if is_abstract:
                        method_line += f"<<abstract>> "
                    
                    method_line += f"{name}("
                    if parameters:
                        param_strs = []
                        for param in parameters:
                            param_name = param.get('name', '')
                            param_type = param.get('type', '')
                            param_strs.append(f"{param_name}: {param_type}")
                        method_line += ", ".join(param_strs)
                    method_line += f") : {return_type}"
                    class_label += f"{method_line}\\l"
            
            if class_type == 'interface':
                style = 'filled,dashed'
            else:
                style = 'filled'
            
            dot.node(
                class_name,
                class_label,
                shape='record',
                style=style,
                fillcolor=node_color,
                fontcolor=font_color,
                fontsize='10',
                fontname='Helvetica'
            )
        
        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 all([from_class, to_class]):
                raise ValueError(f"Invalid relationship: {relationship}")
            
            edge_label = label
            if multiplicity_from or multiplicity_to:
                edge_label += f"\\n{multiplicity_from} --- {multiplicity_to}"
            
            if rel_type == 'inheritance':
                dot.edge(from_class, to_class, arrowhead='empty', color='#4a4a4a', label=edge_label, fontsize='9')
            elif rel_type == 'composition':
                dot.edge(from_class, to_class, arrowhead='normal', arrowtail='diamond', dir='both', color='#4a4a4a', label=edge_label, fontsize='9')
            elif rel_type == 'aggregation':
                dot.edge(from_class, to_class, arrowhead='normal', arrowtail='odiamond', dir='both', color='#4a4a4a', label=edge_label, fontsize='9')
            elif rel_type == 'realization':
                dot.edge(from_class, to_class, arrowhead='empty', style='dashed', color='#4a4a4a', label=edge_label, fontsize='9')
            elif rel_type == 'dependency':
                dot.edge(from_class, to_class, arrowhead='normal', style='dashed', color='#4a4a4a', label=edge_label, fontsize='9')
            else:
                dot.edge(from_class, to_class, arrowhead='normal', color='#4a4a4a', label=edge_label, fontsize='9')

        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)}"