iamironman4279 commited on
Commit
76da4ab
·
verified ·
1 Parent(s): 89b6631

Upload 3 files

Browse files
Files changed (3) hide show
  1. .env +1 -0
  2. main.py +340 -0
  3. requirements.txt +5 -0
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ GROQ_API_KEY=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
main.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import subprocess
3
+ import os
4
+ import sys
5
+ import re
6
+ from PIL import Image
7
+ from groq import Groq
8
+
9
+ # Set page configuration for a better experience
10
+ st.set_page_config(page_title="Diagram Generator", page_icon=":art:", layout="wide")
11
+
12
+ # Custom CSS for a polished look
13
+ st.markdown("""
14
+ <style>
15
+ .main { background-color: #f5f5f5; }
16
+ .stButton>button {
17
+ background-color: #007bff;
18
+ color: white;
19
+ font-weight: bold;
20
+ }
21
+ </style>
22
+ """, unsafe_allow_html=True)
23
+
24
+ # Sidebar: let the user choose which type of diagram they want to generate
25
+ diagram_type = st.sidebar.selectbox("Select Diagram Type", ["AWS Architecture Diagram", "Flowchart Diagram"])
26
+
27
+ if diagram_type == "AWS Architecture Diagram":
28
+ st.sidebar.header("Instructions for AWS Diagrams")
29
+ st.sidebar.write("""
30
+ 1. Enter a detailed AWS architecture description in the text area.
31
+ 2. Click **Generate Diagram** to create the diagram.
32
+ 3. Once generated, the diagram image will be shown along with a download option.
33
+ 4. Expand the **Show Generated Code** section to view the code.
34
+ """)
35
+ else:
36
+ st.sidebar.header("Instructions for Flowchart Diagrams")
37
+ st.sidebar.write("""
38
+ 1. Enter a detailed flowchart description in the text area.
39
+ 2. Click **Generate Diagram** to create the flowchart.
40
+ 3. Once generated, the flowchart image will be shown along with a download option.
41
+ 4. Expand the **Show Generated Code** section to view the code and error details.
42
+ """)
43
+
44
+ # ----- Common Imports Block -----
45
+ common_imports = (
46
+ "class NodeList(list):\n"
47
+ " def __rshift__(self, other):\n"
48
+ " for item in self:\n"
49
+ " item >> other\n"
50
+ " return other\n"
51
+ "\n"
52
+ " def __lshift__(self, other):\n"
53
+ " for item in self:\n"
54
+ " other >> item\n"
55
+ " return other\n"
56
+ "\n"
57
+ "def list_rshift(self, other):\n"
58
+ " return NodeList(self).__rshift__(other)\n"
59
+ "\n"
60
+ "def list_lshift(self, other):\n"
61
+ " return NodeList(self).__lshift__(other)\n"
62
+ "\n"
63
+ "try:\n"
64
+ " list.__rshift__ = list_rshift\n"
65
+ " list.__lshift__ = list_lshift\n"
66
+ "except Exception as e:\n"
67
+ " pass"
68
+ )
69
+
70
+ # ----- AWS Imports Block -----
71
+ aws_imports = (
72
+ common_imports +
73
+ "\n" +
74
+ "from diagrams.aws.compute import *\n"
75
+ "from diagrams.aws.database import *\n"
76
+ "from diagrams.aws.analytics import *\n"
77
+ "from diagrams.aws.integration import *\n"
78
+ "from diagrams.aws.management import *\n"
79
+ "from diagrams.aws.ml import *\n"
80
+ "from diagrams.aws.network import *\n"
81
+ "from diagrams.aws.storage import *\n"
82
+ "from diagrams import Diagram, Cluster, Edge\n"
83
+ "from diagrams.aws.security import *"
84
+ )
85
+
86
+ # ----- Flowchart Imports Block -----
87
+ flowchart_imports = (
88
+ common_imports +
89
+ "\n" +
90
+ "from diagrams.programming.flowchart import *\n"
91
+ "from diagrams import Diagram, Cluster, Edge"
92
+ )
93
+
94
+ # ----- Groq API Call Function -----
95
+ def call_groq_api(prompt):
96
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
97
+ chat_completion = client.chat.completions.create(
98
+ messages=[{"role": "user", "content": prompt}],
99
+ model="deepseek-r1-distill-llama-70b",
100
+ stream=False,
101
+ )
102
+ return chat_completion.choices[0].message.content
103
+
104
+ # ----- Diagram Generation Function -----
105
+ import re
106
+ import subprocess
107
+ import sys
108
+ import os
109
+
110
+ def generate_diagram(diagram_code, import_block):
111
+ # Extract content between the three backticks (```diagram and closing backticks)
112
+ match = re.search(r'```diagram\n(.*?)\n```', diagram_code, re.DOTALL)
113
+ if not match:
114
+ raise ValueError("Invalid diagram code format. No content found between the diagram code backticks.")
115
+
116
+ diagram_code = match.group(1) # Extract content after '```diagram' and before closing '```'
117
+
118
+ # Force the diagram name and filename to "diagram"
119
+ diagram_code = re.sub(r'with Diagram\(".*?"', 'with Diagram("diagram"', diagram_code, count=1)
120
+ diagram_code = re.sub(r'filename="[^"]*"', 'filename="diagram"', diagram_code)
121
+
122
+
123
+ diagram_code = re.sub(r'DynamoDB', 'Dynamodb', diagram_code)
124
+ # Combine imports and diagram code
125
+ full_code = import_block + "\n" + diagram_code
126
+
127
+ # Write the full code to a script file
128
+ script_path = "diagram_app.py"
129
+ with open(script_path, "w") as f:
130
+ f.write(full_code)
131
+
132
+ # Execute the script to generate the diagram
133
+ try:
134
+ result = subprocess.run(
135
+ [sys.executable, script_path],
136
+ check=True,
137
+ stdout=subprocess.PIPE,
138
+ stderr=subprocess.PIPE
139
+ )
140
+ except subprocess.CalledProcessError as e:
141
+ error_details = e.stderr.decode('utf-8') if e.stderr else str(e)
142
+ print("Error generating the diagram. Details below:")
143
+ print(error_details)
144
+ return None
145
+
146
+ # Look for the generated diagram image
147
+ image_path = "diagram.png"
148
+ if os.path.exists(image_path):
149
+ return image_path
150
+ else:
151
+ print("Diagram image not found.")
152
+ return None
153
+ # ----- Main UI -----
154
+ st.title(diagram_type)
155
+ if diagram_type == "AWS Architecture Diagram":
156
+ st.write("Generate a clear and organized AWS architecture diagram simply by describing your architecture below.")
157
+ placeholder_text = "Enter your detailed AWS architecture description here..."
158
+ else:
159
+ st.write("Generate an easy-to-understand flowchart diagram by describing your process or system below.")
160
+ placeholder_text = "Enter your detailed flowchart description here..."
161
+
162
+ user_input = st.text_area("Diagram Description", height=200, placeholder=placeholder_text)
163
+
164
+ if st.button("Generate Diagram"):
165
+ if not user_input.strip():
166
+ st.error("Please enter a diagram description.")
167
+ else:
168
+ # Build the prompt and choose the proper import block based on selection
169
+ if diagram_type == "AWS Architecture Diagram":
170
+ full_prompt = (
171
+ "Your task is to generate code using a diagram DSL similar to the Diagrams library. Always make an easy diagram to understand the architecture.\n"
172
+ "Client class doesnt exist use Route53 from the 20 list only and related pickup Follow these guidelines:\n"
173
+ "- Start with a with Diagram(\"diagram\", show=False, direction=\"TB\") block.\n"
174
+ "- Use clusters with with Cluster(\"Cluster Name\") to group related nodes.\n"
175
+ "- Instantiate nodes using functions named after AWS services.\n"
176
+ "- Connect nodes using arrow operators (>> or <<) to indicate data flow.\n"
177
+ "- Nested clusters can be used to represent hierarchical architectures.\n"
178
+ "- Strictly always Use only the following 20 AWS services: and these 20 classes only given below as these are only supported and use same naming for them \n"
179
+ " 1. EC2\n"
180
+ " 2. Lambda\n"
181
+ " 3. Fargate\n"
182
+ " 4. ECS\n"
183
+ " 5. RDS\n"
184
+ " 6. Dynamodb\n"
185
+ " 7. Redshift\n"
186
+ " 8. Athena\n"
187
+ " 9. ELB\n"
188
+ " 10. APIGateway\n"
189
+ " 11. CloudFront\n"
190
+ " 12. Route53\n"
191
+ " 13. VPC\n"
192
+ " 14. S3\n"
193
+ " 15. EBS\n"
194
+ " 16. SQS\n"
195
+ " 17. SNS\n"
196
+ " 18. Cloudwatch\n"
197
+ " 19. Sagemaker\n"
198
+ " 20. ElasticBeanstalk\n"
199
+ "Do not include any extra services, explanation, or markdown formatting. Do not include any formatting tags such as <think>, </think>, triple backticks (```diagram or ```), or the word 'python' anywhere in your output.\n"
200
+ "Ensure that only one diagram is generated. \n"
201
+ "Examples of proper diagram code structure (do not include these examples in your output):\n"
202
+ "1. **Connect nodes using arrow operators like `>>` or `<<` to indicate data flow:**\n"
203
+ "```python\n"
204
+ "with Diagram(\"Grouped Workers\", show=False, direction=\"TB\"):\n"
205
+ " ELB(\"lb\") >> [EC2(\"worker1\"),\n"
206
+ " EC2(\"worker2\"),\n"
207
+ " EC2(\"worker3\"),\n"
208
+ " EC2(\"worker4\"),\n"
209
+ " EC2(\"worker5\")] >> RDS(\"events\")\n"
210
+ "```\n"
211
+ "2. **Nested Clusters:**\n"
212
+ "```python\n"
213
+ "with Diagram(\"Event Processing\", show=False):\n"
214
+ " source = EKS(\"k8s source\")\n\n"
215
+ " with Cluster(\"Event Flows\"):\n"
216
+ " with Cluster(\"Event Workers\"):\n"
217
+ " workers = [ECS(\"worker1\"), ECS(\"worker2\"), ECS(\"worker3\")]\n\n"
218
+ " queue = SQS(\"event queue\")\n\n"
219
+ " with Cluster(\"Processing\"):\n"
220
+ " handlers = [Lambda(\"proc1\"), Lambda(\"proc2\"), Lambda(\"proc3\")]\n\n"
221
+ " store = S3(\"events store\")\n"
222
+ " dw = Redshift(\"analytics\")\n\n"
223
+ " source >> workers >> queue >> handlers\n"
224
+ " handlers >> store\n"
225
+ " handlers >> dw\n"
226
+ "```\n"
227
+ "3. **Custom Edges and Styling:**\n"
228
+ "```python\n"
229
+ "with Diagram(name=\"Advanced Web Service with On-Premises (colored)\", show=False):\n"
230
+ " ingress = Nginx(\"ingress\")\n\n"
231
+ " metrics = Prometheus(\"metric\")\n"
232
+ " metrics << Edge(color=\"firebrick\", style=\"dashed\") << Grafana(\"monitoring\")\n\n"
233
+ " with Cluster(\"Service Cluster\"):\n"
234
+ " grpcsvc = [Server(\"grpc1\"), Server(\"grpc2\"), Server(\"grpc3\")]\n\n"
235
+ " with Cluster(\"Sessions HA\"):\n"
236
+ " primary = Redis(\"session\")\n"
237
+ " primary - Edge(color=\"brown\", style=\"dashed\") - Redis(\"replica\") << Edge(label=\"collect\") << metrics\n"
238
+ " grpcsvc >> Edge(color=\"brown\") >> primary\n\n"
239
+ " with Cluster(\"Database HA\"):\n"
240
+ " primary = PostgreSQL(\"users\")\n"
241
+ " primary - Edge(color=\"brown\", style=\"dotted\") - PostgreSQL(\"replica\") << Edge(label=\"collect\") << metrics\n"
242
+ " grpcsvc >> Edge(color=\"black\") >> primary\n\n"
243
+ " aggregator = Fluentd(\"logging\")\n"
244
+ " aggregator >> Edge(label=\"parse\") >> Kafka(\"stream\") >> Edge(color=\"black\", style=\"bold\") >> Spark(\"analytics\")\n\n"
245
+ " ingress >> Edge(color=\"darkgreen\") << grpcsvc >> Edge(color=\"darkorange\") >> aggregator\n"
246
+ "```\n"
247
+ "Architecture Description:\n"
248
+ " it is Dynamodb always the function name and not DynamoDB Keep the naming in detail and explanation with good names and strictly keep the names same as given as those are library names. ALWAYS GIVE CODE WITH BACKTICKS AND 'diagram' as heading and only one diagram\n" + user_input
249
+ )
250
+ import_block = aws_imports
251
+ else:
252
+ full_prompt = (
253
+ "Your task is to generate code using a diagram DSL similar to the Diagrams library. "
254
+ "Always create an easy-to-understand flowchart diagram that clearly represents the process or system.\n"
255
+ "Follow these guidelines:\n"
256
+ "- Start with a with Diagram(\"diagram\", show=False, direction=\"TB\") block.\n"
257
+ "- Use clusters (with Cluster(\"Cluster Name\")) to group related nodes if needed.\n"
258
+ "- Use only the following flowchart node functions for your diagram: and same naming\n"
259
+ " • Action\n"
260
+ " • Collate\n"
261
+ " • Database\n"
262
+ " • Decision\n"
263
+ " • Delay\n"
264
+ " • Display\n"
265
+ " • Document\n"
266
+ " • InputOutput\n"
267
+ " • Inspection\n"
268
+ " • InternalStorage\n"
269
+ " • LoopLimit\n"
270
+ " • ManualInput\n"
271
+ " • ManualLoop\n"
272
+ " • Merge\n"
273
+ " • MultipleDocuments\n"
274
+ " • OffPageConnectorLeft\n"
275
+ " • OffPageConnectorRight\n"
276
+ " • Or\n"
277
+ " • PredefinedProcess\n"
278
+ " • Preparation\n"
279
+ " • Sort\n"
280
+ " • StartEnd\n"
281
+ " • StoredData\n"
282
+ " • SummingJunction\n"
283
+ "Connect nodes using arrow operators (>> or <<) to indicate the flow.\n"
284
+ "Do not include any extra nodes, explanation, or markdown formatting. Do not include any formatting tags such as <think>, </think>, triple backticks (```diagram or ```), or the word 'python' anywhere in your output.\n"
285
+ "Ensure that only one diagram is generated.\n"
286
+ "Examples of proper diagram code structure (do not include these examples in your output):\n"
287
+ "1. **Connect nodes using arrow operators like `>>` or `<<` to indicate data flow:**\n"
288
+ "```python\n"
289
+ "with Diagram(\"Grouped Workers\", show=False, direction=\"TB\"):\n"
290
+ " Action(\"Start\") >> [Action(\"Task1\"), Action(\"Task2\"), Action(\"Task3\")] >> Action(\"End\")\n"
291
+ "```\n"
292
+ "2. **Nested Clusters:**\n"
293
+ "```python\n"
294
+ "with Diagram(\"Event Processing\", show=False):\n"
295
+ " source = Action(\"Data Ingest\")\n\n"
296
+ " with Cluster(\"Data Flow\"):\n"
297
+ " source >> Action(\"Processing\") >> Action(\"Storage\")\n\n"
298
+ " storage = Action(\"Store Data\")\n"
299
+ " analytics = Action(\"Analytics\")\n\n"
300
+ " source >> storage\n"
301
+ " storage >> analytics\n"
302
+ "```\n"
303
+ "3. **Custom Edges and Styling:**\n"
304
+ "```python\n"
305
+ "with Diagram(\"Custom Flowchart\", show=False):\n"
306
+ " start = Action(\"Start\")\n"
307
+ " task1 = Action(\"Task 1\")\n"
308
+ " task2 = Action(\"Task 2\")\n"
309
+ " task3 = Action(\"Task 3\")\n\n"
310
+ " start >> Edge(color=\"blue\") >> task1\n"
311
+ " task1 >> Edge(color=\"red\", style=\"dashed\") >> task2\n"
312
+ " task2 >> task3\n"
313
+ "```\n"
314
+ "Flowchart Description: Strictly only use the classes given above and nothing else. ALWAYS GIVE CODE WITH BACKTICKS AND 'diagram' as heading and only one diagram\n" + user_input
315
+ )
316
+ import_block = flowchart_imports
317
+
318
+ st.info("Generating diagram code from your description...")
319
+ try:
320
+ diagram_code = call_groq_api(full_prompt)
321
+ except Exception as ex:
322
+ st.error("An error occurred while calling the Groq API:")
323
+
324
+ diagram_code = None
325
+
326
+ # Always show the generated diagram code in an expander for debugging,
327
+ # even if errors occur later.
328
+
329
+ if diagram_code:
330
+ with st.spinner("Generating diagram image..."):
331
+ image_path = generate_diagram(diagram_code, import_block)
332
+ if image_path:
333
+ st.success("Diagram generated successfully!")
334
+ st.image(image_path, caption="Generated Diagram", use_container_width=True)
335
+ with open(image_path, "rb") as file:
336
+ st.download_button("Download Diagram", file, file_name="diagram.png", mime="image/png")
337
+ else:
338
+ st.error("Failed to generate the diagram image. Please try again.")
339
+ else:
340
+ st.error("Failed to generate diagram code. Please try again.")
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ streamlit
2
+ groq
3
+ pillow
4
+ diagrams
5
+ python-dotenv