File size: 21,285 Bytes
8828f63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5754cf
 
 
 
 
 
79ea405
 
 
 
 
 
 
 
 
 
 
8828f63
79ea405
 
8828f63
 
 
 
 
 
 
 
79ea405
 
 
8828f63
79ea405
 
8828f63
 
 
79ea405
 
 
8828f63
79ea405
 
8828f63
 
 
79ea405
 
 
8828f63
79ea405
 
8828f63
 
 
 
79ea405
 
 
 
 
8828f63
79ea405
8828f63
79ea405
8828f63
 
79ea405
 
 
8828f63
79ea405
8828f63
79ea405
8828f63
 
 
 
 
 
79ea405
 
8828f63
79ea405
8828f63
79ea405
8828f63
 
79ea405
 
 
8828f63
79ea405
8828f63
79ea405
8828f63
 
 
 
 
79ea405
 
 
8828f63
 
 
79ea405
8828f63
 
 
 
 
 
79ea405
 
8828f63
 
 
79ea405
8828f63
 
79ea405
 
 
 
 
 
 
 
f5754cf
 
 
 
 
 
 
 
 
7474f3d
8828f63
7474f3d
 
f5754cf
 
 
 
8828f63
0e101d5
f5754cf
 
 
 
7474f3d
f5754cf
8828f63
 
f5754cf
8828f63
 
f5754cf
8828f63
 
 
 
 
 
 
f5754cf
8828f63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5754cf
8828f63
f5754cf
 
 
 
 
8828f63
 
f5754cf
 
7474f3d
f5754cf
8828f63
 
f5754cf
8828f63
 
f5754cf
8828f63
 
f5754cf
8828f63
 
 
 
 
 
 
 
 
f5754cf
8828f63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5754cf
 
 
 
 
 
 
 
 
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# import graphviz
# import json
# from tempfile import NamedTemporaryFile
# import os

# def generate_entity_relationship_diagram(json_input: str, output_format: str) -> str:
#     """
#     Generates an entity relationship diagram from JSON input.

#     Args:
#         json_input (str): A JSON string describing the entity relationship diagram structure.
#                           It must follow the Expected JSON Format Example below.

#     Expected JSON Format Example:
#     {
#       "entities": [
#         {
#           "name": "Customer",
#           "type": "strong",
#           "attributes": [
#             {"name": "customer_id", "type": "primary_key"},
#             {"name": "first_name", "type": "regular"},
#             {"name": "last_name", "type": "regular"},
#             {"name": "email", "type": "regular"},
#             {"name": "phone", "type": "multivalued", "multivalued": true},
#             {"name": "age", "type": "derived", "derived": true},
#             {"name": "address", "type": "composite", "composite": true}
#           ]
#         },
#         {
#           "name": "Order",
#           "type": "strong",
#           "attributes": [
#             {"name": "order_id", "type": "primary_key"},
#             {"name": "customer_id", "type": "foreign_key"},
#             {"name": "order_date", "type": "regular"},
#             {"name": "total_amount", "type": "regular"},
#             {"name": "status", "type": "regular"},
#             {"name": "shipping_address", "type": "composite", "composite": true}
#           ]
#         },
#         {
#           "name": "Product",
#           "type": "strong",
#           "attributes": [
#             {"name": "product_id", "type": "primary_key"},
#             {"name": "name", "type": "regular"},
#             {"name": "description", "type": "regular"},
#             {"name": "price", "type": "regular"},
#             {"name": "category_id", "type": "foreign_key"},
#             {"name": "stock_quantity", "type": "regular"}
#           ]
#         },
#         {
#           "name": "Category",
#           "type": "strong",
#           "attributes": [
#             {"name": "category_id", "type": "primary_key"},
#             {"name": "name", "type": "regular"},
#             {"name": "description", "type": "regular"},
#             {"name": "parent_category_id", "type": "foreign_key"}
#           ]
#         },
#         {
#           "name": "OrderItem",
#           "type": "weak",
#           "attributes": [
#             {"name": "order_id", "type": "primary_key"},
#             {"name": "product_id", "type": "primary_key"},
#             {"name": "quantity", "type": "regular"},
#             {"name": "unit_price", "type": "regular"},
#             {"name": "discount", "type": "regular"}
#           ]
#         },
#         {
#           "name": "Payment",
#           "type": "strong",
#           "attributes": [
#             {"name": "payment_id", "type": "primary_key"},
#             {"name": "order_id", "type": "foreign_key"},
#             {"name": "payment_method", "type": "regular"},
#             {"name": "amount", "type": "regular"},
#             {"name": "payment_date", "type": "regular"},
#             {"name": "transaction_id", "type": "regular"}
#           ]
#         },
#         {
#           "name": "Supplier",
#           "type": "strong",
#           "attributes": [
#             {"name": "supplier_id", "type": "primary_key"},
#             {"name": "company_name", "type": "regular"},
#             {"name": "contact_person", "type": "regular"},
#             {"name": "email", "type": "regular"},
#             {"name": "phone", "type": "multivalued", "multivalued": true},
#             {"name": "address", "type": "composite", "composite": true}
#           ]
#         },
#         {
#           "name": "Review",
#           "type": "weak",
#           "attributes": [
#             {"name": "customer_id", "type": "primary_key"},
#             {"name": "product_id", "type": "primary_key"},
#             {"name": "rating", "type": "regular"},
#             {"name": "comment", "type": "regular"},
#             {"name": "review_date", "type": "regular"}
#           ]
#         }
#       ],
#       "relationships": [
#         {
#           "name": "Places",
#           "type": "regular",
#           "entities": ["Customer", "Order"],
#           "cardinalities": {
#             "Customer": "1",
#             "Order": "N"
#           }
#         },
#         {
#           "name": "Contains",
#           "type": "identifying",
#           "entities": ["Order", "OrderItem"],
#           "cardinalities": {
#             "Order": "1",
#             "OrderItem": "N"
#           }
#         },
#         {
#           "name": "Includes",
#           "type": "regular",
#           "entities": ["OrderItem", "Product"],
#           "cardinalities": {
#             "OrderItem": "N",
#             "Product": "1"
#           }
#         },
#         {
#           "name": "BelongsTo",
#           "type": "regular",
#           "entities": ["Product", "Category"],
#           "cardinalities": {
#             "Product": "N",
#             "Category": "1"
#           }
#         },
#         {
#           "name": "ProcessedBy",
#           "type": "regular",
#           "entities": ["Order", "Payment"],
#           "cardinalities": {
#             "Order": "1",
#             "Payment": "1"
#           }
#         },
#         {
#           "name": "Supplies",
#           "type": "regular",
#           "entities": ["Supplier", "Product"],
#           "cardinalities": {
#             "Supplier": "N",
#             "Product": "M"
#           }
#         },
#         {
#           "name": "Writes",
#           "type": "weak",
#           "entities": ["Customer", "Review"],
#           "cardinalities": {
#             "Customer": "1",
#             "Review": "N"
#           }
#         },
#         {
#           "name": "ReviewsProduct",
#           "type": "weak",
#           "entities": ["Review", "Product"],
#           "cardinalities": {
#             "Review": "N",
#             "Product": "1"
#           }
#         },
#         {
#           "name": "Subcategory",
#           "type": "regular",
#           "entities": ["Category", "Category"],
#           "cardinalities": {
#             "Category": "1",
#             "Category": "N"
#           }
#         }
#       ]
#     }

#     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 'entities' not in data:
#             raise ValueError("Missing required field: entities")

#         dot = graphviz.Graph(comment='ER Diagram', engine='dot')
#         dot.attr(rankdir='TB', bgcolor='white', pad='0.5')
#         dot.attr('node', fontname='Arial', fontsize='10', color='black')
#         dot.attr('edge', fontname='Arial', fontsize='9', color='black')
        
#         entities = data.get('entities', [])
#         relationships = data.get('relationships', [])
        
#         for entity in entities:
#             entity_name = entity.get('name')
#             entity_type = entity.get('type', 'strong')
#             attributes = entity.get('attributes', [])
            
#             if not entity_name:
#                 continue
            
#             label_parts = [entity_name]
            
#             if attributes:
#                 attr_lines = []
#                 for attr in attributes:
#                     attr_name = attr.get('name', '')
#                     attr_type = attr.get('type', 'regular')
#                     is_multivalued = attr.get('multivalued', False)
#                     is_derived = attr.get('derived', False)
#                     is_composite = attr.get('composite', False)
                    
#                     if attr_type == 'primary_key':
#                         if is_multivalued:
#                             attr_display = f"PK: {{ {attr_name} }}"
#                         else:
#                             attr_display = f"PK: {attr_name}"
#                     elif attr_type == 'foreign_key':
#                         attr_display = f"FK: {attr_name}"
#                     else:
#                         attr_display = attr_name
#                         if is_derived:
#                             attr_display = f"/ {attr_display} /"
#                         if is_multivalued:
#                             attr_display = f"{{ {attr_display} }}"
#                         if is_composite:
#                             attr_display = f"( {attr_display} )"
                    
#                     attr_lines.append(attr_display)
                
#                 if attr_lines:
#                     label_parts.extend(attr_lines)
            
#             label = "\\n".join(label_parts)
            
#             if entity_type == 'weak':
#                 style = 'filled'
#                 fillcolor = '#e8e8e8'
#                 penwidth = '2'
#             else:
#                 style = 'filled'
#                 fillcolor = '#d0d0d0'
#                 penwidth = '1'
            
#             dot.node(entity_name, label, shape='box', style=style, fillcolor=fillcolor, penwidth=penwidth)
        
#         for relationship in relationships:
#             rel_name = relationship.get('name')
#             rel_type = relationship.get('type', 'regular')
#             entities_involved = relationship.get('entities', [])
#             cardinalities = relationship.get('cardinalities', {})
            
#             if not rel_name or len(entities_involved) < 2:
#                 continue
            
#             if rel_type == 'identifying':
#                 style = 'filled'
#                 fillcolor = '#c0c0c0'
#                 penwidth = '2'
#             else:
#                 style = 'filled'
#                 fillcolor = '#c0c0c0'
#                 penwidth = '1'
            
#             dot.node(rel_name, rel_name, shape='diamond', style=style, fillcolor=fillcolor, penwidth=penwidth)
            
#             for entity in entities_involved:
#                 cardinality = cardinalities.get(entity, '1')
#                 dot.edge(entity, rel_name, label=cardinality)

#         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_entity_relationship_diagram(json_input: str, output_format: str) -> str:
    """
    Generates an entity relationship diagram from JSON input.

    Args:
        json_input (str): A JSON string describing the entity relationship diagram structure.
                          It must follow the Expected JSON Format Example below.

    Expected JSON Format Example:
    {
      "entities": [
        {
          "name": "EMPLEADO",
          "type": "strong",
          "attributes": [
            {"name": "RUT", "type": "primary_key"},
            {"name": "Nombre", "type": "regular"},
            {"name": "Apellido1", "type": "regular"},
            {"name": "Apellido2", "type": "regular"},
            {"name": "Dirección", "type": "regular"},
            {"name": "Sexo", "type": "regular"},
            {"name": "Salario", "type": "regular"},
            {"name": "FechaN", "type": "regular"}
          ]
        },
        {
          "name": "DEPARTAMENTO",
          "type": "strong",
          "attributes": [
            {"name": "Número", "type": "primary_key"},
            {"name": "Nombre", "type": "regular"},
            {"name": "Localizaciones", "type": "multivalued"}
          ]
        },
        {
          "name": "PROYECTO",
          "type": "strong",
          "attributes": [
            {"name": "Número", "type": "primary_key"},
            {"name": "Nombre", "type": "regular"},
            {"name": "Localización", "type": "regular"}
          ]
        },
        {
          "name": "DEPENDIENTE",
          "type": "weak",
          "attributes": [
            {"name": "Nombre", "type": "partial_key"},
            {"name": "Sexo", "type": "regular"},
            {"name": "FechaN", "type": "regular"},
            {"name": "Relación", "type": "regular"}
          ]
        }
      ],
      "relationships": [
        {
          "name": "TRABAJA_PARA",
          "type": "regular",
          "entities": ["EMPLEADO", "DEPARTAMENTO"],
          "cardinalities": {
            "EMPLEADO": "N",
            "DEPARTAMENTO": "1"
          }
        },
        {
          "name": "ADMINISTRA",
          "type": "regular",
          "entities": ["EMPLEADO", "DEPARTAMENTO"],
          "cardinalities": {
            "EMPLEADO": "1",
            "DEPARTAMENTO": "1"
          },
          "attributes": [
            {"name": "FechaInicio", "type": "regular"}
          ]
        },
        {
          "name": "CONTROLA",
          "type": "regular",
          "entities": ["DEPARTAMENTO", "PROYECTO"],
          "cardinalities": {
            "DEPARTAMENTO": "1",
            "PROYECTO": "N"
          }
        },
        {
          "name": "SUPERVISIÓN",
          "type": "regular",
          "entities": ["EMPLEADO", "EMPLEADO"],
          "cardinalities": {
            "EMPLEADO": "1",
            "EMPLEADO": "N"
          },
          "roles": {
            "EMPLEADO": ["supervisor", "supervisado"]
          }
        },
        {
          "name": "TRABAJA_PARA_PROYECTO",
          "type": "ternary",
          "entities": ["EMPLEADO", "PROYECTO"],
          "cardinalities": {
            "EMPLEADO": "M",
            "PROYECTO": "N"
          },
          "attributes": [
            {"name": "Horas", "type": "regular"}
          ]
        },
        {
          "name": "DEPENDIENTES",
          "type": "identifying",
          "entities": ["EMPLEADO", "DEPENDIENTE"],
          "cardinalities": {
            "EMPLEADO": "1",
            "DEPENDIENTE": "N"
          }
        }
      ]
    }

    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 'entities' not in data:
            raise ValueError("Missing required field: entities")

        dot = graphviz.Graph(comment='ER Diagram', engine='dot')
        dot.attr(rankdir='TB', bgcolor='white', pad='0.5', nodesep='1.0', ranksep='1.5')
        dot.attr('node', fontname='Arial', fontsize='10', color='black')
        dot.attr('edge', fontname='Arial', fontsize='9', color='black')
        
        entities = data.get('entities', [])
        relationships = data.get('relationships', [])
        
        # Crear entidades
        for entity in entities:
            entity_name = entity.get('name')
            entity_type = entity.get('type', 'strong')
            
            if not entity_name:
                continue
            
            # Entidades fuertes: rectángulo simple
            # Entidades débiles: rectángulo doble (simulado con penwidth)
            if entity_type == 'weak':
                dot.node(entity_name, entity_name, shape='box', style='filled', 
                        fillcolor='white', color='black', penwidth='3')
            else:
                dot.node(entity_name, entity_name, shape='box', style='filled', 
                        fillcolor='white', color='black', penwidth='1')
        
        # Crear atributos para cada entidad
        for entity in entities:
            entity_name = entity.get('name')
            attributes = entity.get('attributes', [])
            
            for attr in attributes:
                attr_name = attr.get('name', '')
                attr_type = attr.get('type', 'regular')
                
                attr_id = f"{entity_name}_{attr_name}"
                
                if attr_type == 'primary_key':
                    # Atributo clave: elipse con texto subrayado
                    dot.node(attr_id, f"<U>{attr_name}</U>", shape='ellipse', 
                            style='filled', fillcolor='white', color='black')
                elif attr_type == 'partial_key':
                    # Clave parcial: elipse con línea punteada
                    dot.node(attr_id, f"<U>{attr_name}</U>", shape='ellipse', 
                            style='filled,dashed', fillcolor='white', color='black')
                elif attr_type == 'multivalued':
                    # Atributo multivaluado: doble elipse (simulado con penwidth)
                    dot.node(attr_id, attr_name, shape='ellipse', 
                            style='filled', fillcolor='white', color='black', penwidth='3')
                elif attr_type == 'derived':
                    # Atributo derivado: elipse con línea punteada
                    dot.node(attr_id, attr_name, shape='ellipse', 
                            style='filled,dashed', fillcolor='white', color='black')
                elif attr_type == 'composite':
                    # Atributo compuesto: elipse normal (los componentes se conectarían por separado)
                    dot.node(attr_id, attr_name, shape='ellipse', 
                            style='filled', fillcolor='white', color='black')
                else:
                    # Atributo regular: elipse simple
                    dot.node(attr_id, attr_name, shape='ellipse', 
                            style='filled', fillcolor='white', color='black')
                
                # Conectar atributo con entidad
                dot.edge(entity_name, attr_id, color='black')
        
        # Crear relaciones
        for relationship in relationships:
            rel_name = relationship.get('name')
            rel_type = relationship.get('type', 'regular')
            entities_involved = relationship.get('entities', [])
            cardinalities = relationship.get('cardinalities', {})
            rel_attributes = relationship.get('attributes', [])
            roles = relationship.get('roles', {})
            
            if not rel_name or len(entities_involved) < 2:
                continue
            
            # Relaciones identificadoras: rombo doble
            # Relaciones regulares: rombo simple
            if rel_type == 'identifying':
                dot.node(rel_name, rel_name, shape='diamond', style='filled', 
                        fillcolor='white', color='black', penwidth='3')
            else:
                dot.node(rel_name, rel_name, shape='diamond', style='filled', 
                        fillcolor='white', color='black', penwidth='1')
            
            # Crear atributos de la relación
            for attr in rel_attributes:
                attr_name = attr.get('name', '')
                attr_type = attr.get('type', 'regular')
                attr_id = f"{rel_name}_{attr_name}"
                
                dot.node(attr_id, attr_name, shape='ellipse', 
                        style='filled', fillcolor='white', color='black')
                dot.edge(rel_name, attr_id, color='black')
            
            # Conectar entidades con la relación
            if len(entities_involved) == 2 and entities_involved[0] == entities_involved[1]:
                # Relación reflexiva (como supervisión)
                entity = entities_involved[0]
                cardinality1 = cardinalities.get(entity, '1')
                
                # Para relaciones reflexivas, necesitamos crear dos conexiones
                dot.edge(entity, rel_name, label=cardinality1, color='black')
                dot.edge(entity, rel_name, label='N', color='black')
                
                # Agregar roles si están definidos
                if roles and entity in roles:
                    role_list = roles[entity]
                    if len(role_list) >= 2:
                        # Crear nodos de texto para los roles
                        role1_id = f"{rel_name}_role1"
                        role2_id = f"{rel_name}_role2"
                        dot.node(role1_id, role_list[0], shape='plaintext', fontsize='8')
                        dot.node(role2_id, role_list[1], shape='plaintext', fontsize='8')
            else:
                # Relación normal entre diferentes entidades
                for entity in entities_involved:
                    cardinality = cardinalities.get(entity, '1')
                    dot.edge(entity, rel_name, label=cardinality, color='black')

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