File size: 12,620 Bytes
d1aacb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c73b6d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1aacb9
 
 
 
 
 
 
 
 
 
 
febb28d
d1aacb9
 
febb28d
d1aacb9
 
c73b6d7
 
 
 
 
 
d1aacb9
 
 
 
 
 
c73b6d7
 
 
 
 
 
 
 
d1aacb9
c73b6d7
 
d1aacb9
 
c73b6d7
 
 
 
d1aacb9
c73b6d7
 
 
 
d1aacb9
c73b6d7
 
d1aacb9
 
 
 
 
 
 
 
 
 
c73b6d7
 
 
 
 
d1aacb9
c73b6d7
 
 
 
 
 
 
 
 
 
 
 
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
# import graphviz
# import json
# from tempfile import NamedTemporaryFile
# import os

# def generate_process_flow_diagram(json_input: str, output_format: str) -> str:
#     """
#     Generates a Process Flow Diagram (Flowchart) from JSON input.

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

#     Expected JSON Format Example:
#     {
#       "start_node": "Start Inference Request",
#       "nodes": [
#         {
#           "id": "user_input",
#           "label": "Receive User Input (Data)",
#           "type": "io"
#         },
#         {
#           "id": "preprocess_data",
#           "label": "Preprocess Data",
#           "type": "process"
#         },
#         {
#           "id": "validate_data",
#           "label": "Validate Data Format/Type",
#           "type": "decision"
#         },
#         {
#           "id": "data_valid_yes",
#           "label": "Data Valid?",
#           "type": "decision"
#         },
#         {
#           "id": "load_model",
#           "label": "Load AI Model (if not cached)",
#           "type": "process"
#         },
#         {
#           "id": "run_inference",
#           "label": "Run AI Model Inference",
#           "type": "process"
#         },
#         {
#           "id": "postprocess_output",
#           "label": "Postprocess Model Output",
#           "type": "process"
#         },
#         {
#           "id": "send_response",
#           "label": "Send Response to User",
#           "type": "io"
#         },
#         {
#           "id": "log_error",
#           "label": "Log Error & Notify User",
#           "type": "process"
#         },
#         {
#           "id": "end_inference_process",
#           "label": "End Inference Process",
#           "type": "end"
#         }
#       ],
#       "connections": [
#         {"from": "start_node", "to": "user_input", "label": "Request"},
#         {"from": "user_input", "to": "preprocess_data", "label": "Data Received"},
#         {"from": "preprocess_data", "to": "validate_data", "label": "Cleaned"},
#         {"from": "validate_data", "to": "data_valid_yes", "label": "Check"},
#         {"from": "data_valid_yes", "to": "load_model", "label": "Yes"},
#         {"from": "data_valid_yes", "to": "log_error", "label": "No"},
#         {"from": "load_model", "to": "run_inference", "label": "Model Ready"},
#         {"from": "run_inference", "to": "postprocess_output", "label": "Output Generated"},
#         {"from": "postprocess_output", "to": "send_response", "label": "Ready"},
#         {"from": "send_response", "to": "end_inference_process", "label": "Response Sent"},
#         {"from": "log_error", "to": "end_inference_process", "label": "Error Handled"}
#       ]
#     }

#     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 'start_node' not in data or 'nodes' not in data or 'connections' not in data:
#             raise ValueError("Missing required fields: 'start_node', 'nodes', or 'connections'")

#         node_shapes = {
#             "process": "box",          # Rectangle for processes
#             "decision": "diamond",     # Diamond for decisions
#             "start": "oval",           # Oval for start
#             "end": "oval",             # Oval for end
#             "io": "parallelogram",     # Input/Output
#             "document": "note",        # Document symbol
#             "default": "box"           # Fallback
#         }

#         dot = graphviz.Digraph(
#             name='ProcessFlowDiagram',
#             format='png',
#             graph_attr={
#                 'rankdir': 'TB',        # Top-to-Bottom flow is common for flowcharts
#                 'splines': 'ortho',     # Straight lines with 90-degree bends
#                 'bgcolor': 'white',     # White background
#                 'pad': '0.5',           # Padding around the graph
#                 'nodesep': '0.6',       # Spacing between nodes on same rank
#                 'ranksep': '0.8'        # Spacing between ranks
#             }
#         )
        
#         base_color = '#19191a' 

#         fill_color_for_nodes = base_color
#         font_color_for_nodes = 'white' if base_color == '#19191a' or base_color.lower() in ['#000000', '#19191a'] else 'black'
        
#         all_defined_nodes = {node['id']: node for node in data['nodes']}
        
#         start_node_id = data['start_node']
#         dot.node(
#             start_node_id,
#             start_node_id, # Label is typically the ID itself for start/end
#             shape=node_shapes['start'],
#             style='filled,rounded',
#             fillcolor='#2196F3', # A distinct blue for Start
#             fontcolor='white',
#             fontsize='14'
#         )

#         for node_id, node_info in all_defined_nodes.items():
#             if node_id == start_node_id: # Skip if it's the start node, already added
#                 continue

#             node_type = node_info.get("type", "default")
#             shape = node_shapes.get(node_type, "box")

#             node_label = node_info['label']

#             # Use distinct color for end node if it exists
#             if node_type == 'end':
#                  dot.node(
#                     node_id,
#                     node_label,
#                     shape=shape,
#                     style='filled,rounded',
#                     fillcolor='#F44336', # A distinct red for End
#                     fontcolor='white',
#                     fontsize='14'
#                 )
#             else: # Regular process, decision, etc. nodes use the selected base color
#                 dot.node(
#                     node_id,
#                     node_label,
#                     shape=shape,
#                     style='filled,rounded',
#                     fillcolor=fill_color_for_nodes, 
#                     fontcolor=font_color_for_nodes,
#                     fontsize='14'
#                 )

#         # Add connections (edges)
#         for connection in data['connections']:
#             dot.edge(
#                 connection['from'],
#                 connection['to'],
#                 label=connection.get('label', ''),
#                 color='#4a4a4a', # Dark gray for lines
#                 fontcolor='#4a4a4a',
#                 fontsize='10'
#             )
        
#         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_process_flow_diagram(json_input: str, output_format: str) -> str:
    """
    Generates a Process Flow Diagram (Flowchart) from JSON input.

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

    Expected JSON Format Example:
    {
      "start_node": "Start Inference Request",
      "nodes": [
        {
          "id": "user_input",
          "label": "Receive User Input (Data)",
          "type": "io"
        },
        {
          "id": "preprocess_data",
          "label": "Preprocess Data",
          "type": "process"
        },
        {
          "id": "validate_data",
          "label": "Validate Data Format/Type",
          "type": "decision"
        },
        {
          "id": "data_valid_yes",
          "label": "Data Valid?",
          "type": "decision"
        },
        {
          "id": "load_model",
          "label": "Load AI Model (if not cached)",
          "type": "process"
        },
        {
          "id": "run_inference",
          "label": "Run AI Model Inference",
          "type": "process"
        },
        {
          "id": "postprocess_output",
          "label": "Postprocess Model Output",
          "type": "process"
        },
        {
          "id": "send_response",
          "label": "Send Response to User",
          "type": "io"
        },
        {
          "id": "log_error",
          "label": "Log Error & Notify User",
          "type": "process"
        },
        {
          "id": "end_inference_process",
          "label": "End Inference Process",
          "type": "end"
        }
      ],
      "connections": [
        {"from": "start_node", "to": "user_input", "label": "Request"},
        {"from": "user_input", "to": "preprocess_data", "label": "Data Received"},
        {"from": "preprocess_data", "to": "validate_data", "label": "Cleaned"},
        {"from": "validate_data", "to": "data_valid_yes", "label": "Check"},
        {"from": "data_valid_yes", "to": "load_model", "label": "Yes"},
        {"from": "data_valid_yes", "to": "log_error", "label": "No"},
        {"from": "load_model", "to": "run_inference", "label": "Model Ready"},
        {"from": "run_inference", "to": "postprocess_output", "label": "Output Generated"},
        {"from": "postprocess_output", "to": "send_response", "label": "Ready"},
        {"from": "send_response", "to": "end_inference_process", "label": "Response Sent"},
        {"from": "log_error", "to": "end_inference_process", "label": "Error Handled"}
      ]
    }

    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 'start_node' not in data or 'nodes' not in data or 'connections' not in data:
            raise ValueError("Missing required fields: 'start_node', 'nodes', or 'connections'")

        node_shapes = {
            "process": "box",
            "decision": "diamond",
            "start": "oval",
            "end": "oval",
            "io": "parallelogram",
            "document": "note",
            "default": "box"
        }

        node_colors = {
            "process": "#BEBEBE",
            "decision": "#FFF9C4",
            "start": "#A8E6CF",
            "end": "#FFB3BA",
            "io": "#B8D4F1",
            "document": "#F0F8FF",
            "default": "#BEBEBE"
        }

        dot = graphviz.Digraph(
            name='ProcessFlowDiagram',
            format='png',
            graph_attr={
                'rankdir': 'TB',
                'splines': 'ortho',
                'bgcolor': 'white',
                'pad': '0.5',
                'nodesep': '0.6',
                'ranksep': '0.8'
            }
        )
        
        all_defined_nodes = {node['id']: node for node in data['nodes']}
        
        start_node_id = data['start_node']
        dot.node(
            start_node_id,
            start_node_id,
            shape=node_shapes['start'],
            style='filled,rounded',
            fillcolor=node_colors['start'],
            fontcolor='black',
            fontsize='14'
        )

        for node_id, node_info in all_defined_nodes.items():
            if node_id == start_node_id:
                continue

            node_type = node_info.get("type", "default")
            shape = node_shapes.get(node_type, "box")
            color = node_colors.get(node_type, node_colors["default"])
            node_label = node_info['label']

            dot.node(
                node_id,
                node_label,
                shape=shape,
                style='filled,rounded',
                fillcolor=color,
                fontcolor='black',
                fontsize='14'
            )

        for connection in data['connections']:
            dot.edge(
                connection['from'],
                connection['to'],
                label=connection.get('label', ''),
                color='#4a4a4a',
                fontcolor='#4a4a4a',
                fontsize='10'
            )
        
        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)}"