shaheerawan3 commited on
Commit
4d14e9a
Β·
verified Β·
1 Parent(s): e66fb1e

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +218 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,220 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import json
3
+ from huggingface_hub import InferenceClient
4
+ import time
5
 
6
+ # Initialize the client (no API key needed for public models)
7
+ @st.cache_resource
8
+ def get_client():
9
+ return InferenceClient()
10
+
11
+ client = get_client()
12
+
13
+ st.set_page_config(page_title="n8n Workflow Generator", page_icon="πŸ€–", layout="wide")
14
+
15
+ st.title("πŸ€– n8n Workflow Generator")
16
+ st.markdown("Generate n8n workflows from your ideas using AI - completely free!")
17
+
18
+ # Sidebar for settings
19
+ with st.sidebar:
20
+ st.header("βš™οΈ Settings")
21
+ model_choice = st.selectbox(
22
+ "Select Model",
23
+ ["Qwen/Qwen2.5-Coder-32B-Instruct", "meta-llama/Llama-3.2-3B-Instruct", "mistralai/Mistral-7B-Instruct-v0.3"],
24
+ index=0
25
+ )
26
+ temperature = st.slider("Creativity", 0.1, 1.0, 0.7)
27
+ st.markdown("---")
28
+ st.markdown("### πŸ“š How to Use")
29
+ st.markdown("1. Describe your workflow idea\n2. Get enhanced suggestions\n3. Generate n8n JSON\n4. Import to n8n")
30
+
31
+ # Main content
32
+ col1, col2 = st.columns([1, 1])
33
+
34
+ with col1:
35
+ st.header("πŸ’‘ Your Workflow Idea")
36
+ user_idea = st.text_area(
37
+ "Describe your workflow",
38
+ placeholder="Example: Create a workflow that monitors GitHub issues, sends them to Slack, and logs them in Google Sheets",
39
+ height=150
40
+ )
41
+
42
+ if st.button("πŸ” Enhance My Idea", type="primary", use_container_width=True):
43
+ if user_idea:
44
+ with st.spinner("Brainstorming enhancements..."):
45
+ try:
46
+ prompt = f"""You are an n8n workflow expert. A user wants to create this workflow:
47
+ {user_idea}
48
+ Provide 3-5 enhanced versions of this idea with:
49
+ 1. Additional useful features
50
+ 2. Error handling suggestions
51
+ 3. Optimization tips
52
+ 4. Integration possibilities
53
+ Keep each suggestion concise but actionable. Format as a numbered list."""
54
+
55
+ response = client.text_generation(
56
+ prompt,
57
+ model=model_choice,
58
+ max_new_tokens=800,
59
+ temperature=temperature,
60
+ return_full_text=False
61
+ )
62
+
63
+ st.session_state['enhanced_ideas'] = response
64
+ st.session_state['original_idea'] = user_idea
65
+
66
+ except Exception as e:
67
+ st.error(f"Error: {str(e)}")
68
+ else:
69
+ st.warning("Please enter a workflow idea first!")
70
+
71
+ with col2:
72
+ st.header("✨ Enhanced Suggestions")
73
+ if 'enhanced_ideas' in st.session_state:
74
+ st.markdown(st.session_state['enhanced_ideas'])
75
+ else:
76
+ st.info("Click 'Enhance My Idea' to get AI-powered suggestions")
77
+
78
+ st.markdown("---")
79
+
80
+ # Generation section
81
+ st.header("πŸš€ Generate n8n Workflow")
82
+
83
+ final_idea = st.text_area(
84
+ "Final workflow description (edit if needed)",
85
+ value=st.session_state.get('original_idea', ''),
86
+ height=100,
87
+ key="final_idea"
88
+ )
89
+
90
+ col_gen1, col_gen2, col_gen3 = st.columns([1, 1, 1])
91
+
92
+ with col_gen1:
93
+ include_error_handling = st.checkbox("Include error handling", value=True)
94
+ with col_gen2:
95
+ include_schedule = st.checkbox("Add schedule trigger", value=False)
96
+ with col_gen3:
97
+ workflow_complexity = st.select_slider("Complexity", ["Simple", "Medium", "Advanced"], value="Medium")
98
+
99
+ if st.button("⚑ Generate n8n JSON", type="primary", use_container_width=True):
100
+ if final_idea:
101
+ with st.spinner("Generating your workflow..."):
102
+ try:
103
+ prompt = f"""You are an expert n8n workflow developer. Create a complete, working n8n workflow JSON based on this description:
104
+ {final_idea}
105
+ Requirements:
106
+ - Complexity level: {workflow_complexity}
107
+ - Error handling: {"Yes" if include_error_handling else "No"}
108
+ - Schedule trigger: {"Yes" if include_schedule else "No"}
109
+ Generate ONLY valid n8n workflow JSON. The JSON must include:
110
+ 1. "nodes" array with proper node types
111
+ 2. "connections" object linking nodes
112
+ 3. Realistic node configurations
113
+ 4. Valid n8n node types (HTTP Request, Set, IF, Schedule Trigger, etc.)
114
+ Return ONLY the JSON, no explanations. Make it production-ready."""
115
+
116
+ response = client.text_generation(
117
+ prompt,
118
+ model=model_choice,
119
+ max_new_tokens=2000,
120
+ temperature=0.3, # Lower temperature for more precise JSON
121
+ return_full_text=False
122
+ )
123
+
124
+ # Try to extract JSON from response
125
+ json_str = response.strip()
126
+
127
+ # Remove markdown code blocks if present
128
+ if json_str.startswith("```"):
129
+ json_str = json_str.split("```")[1]
130
+ if json_str.startswith("json"):
131
+ json_str = json_str[4:]
132
+ json_str = json_str.strip()
133
+
134
+ # Validate JSON
135
+ try:
136
+ workflow_json = json.loads(json_str)
137
+
138
+ # Add metadata if missing
139
+ if "name" not in workflow_json:
140
+ workflow_json["name"] = "AI Generated Workflow"
141
+ if "nodes" not in workflow_json:
142
+ workflow_json["nodes"] = []
143
+ if "connections" not in workflow_json:
144
+ workflow_json["connections"] = {}
145
+
146
+ st.session_state['generated_workflow'] = workflow_json
147
+ st.success("βœ… Workflow generated successfully!")
148
+
149
+ except json.JSONDecodeError as je:
150
+ st.error("Generated response wasn't valid JSON. Trying to fix...")
151
+ # Create a basic fallback workflow
152
+ workflow_json = {
153
+ "name": "AI Generated Workflow",
154
+ "nodes": [
155
+ {
156
+ "parameters": {},
157
+ "name": "Start",
158
+ "type": "n8n-nodes-base.start",
159
+ "typeVersion": 1,
160
+ "position": [250, 300]
161
+ },
162
+ {
163
+ "parameters": {
164
+ "url": "https://api.example.com",
165
+ "options": {}
166
+ },
167
+ "name": "HTTP Request",
168
+ "type": "n8n-nodes-base.httpRequest",
169
+ "typeVersion": 1,
170
+ "position": [450, 300]
171
+ }
172
+ ],
173
+ "connections": {
174
+ "Start": {
175
+ "main": [[{"node": "HTTP Request", "type": "main", "index": 0}]]
176
+ }
177
+ }
178
+ }
179
+ st.session_state['generated_workflow'] = workflow_json
180
+ st.info("Created a basic template. Please customize it in n8n.")
181
+
182
+ except Exception as e:
183
+ st.error(f"Generation error: {str(e)}")
184
+ else:
185
+ st.warning("Please enter a workflow description!")
186
+
187
+ # Display and download section
188
+ if 'generated_workflow' in st.session_state:
189
+ st.markdown("---")
190
+ st.header("πŸ“‹ Your n8n Workflow")
191
+
192
+ workflow = st.session_state['generated_workflow']
193
+
194
+ # Display stats
195
+ col_stat1, col_stat2, col_stat3 = st.columns(3)
196
+ with col_stat1:
197
+ st.metric("Nodes", len(workflow.get('nodes', [])))
198
+ with col_stat2:
199
+ st.metric("Connections", len(workflow.get('connections', {})))
200
+ with col_stat3:
201
+ st.metric("Ready to Import", "βœ“")
202
+
203
+ # JSON display
204
+ st.json(workflow)
205
+
206
+ # Download button
207
+ json_str = json.dumps(workflow, indent=2)
208
+ st.download_button(
209
+ label="πŸ“₯ Download Workflow JSON",
210
+ data=json_str,
211
+ file_name="n8n_workflow.json",
212
+ mime="application/json",
213
+ use_container_width=True
214
+ )
215
+
216
+ st.info("πŸ’‘ **How to import:** Open n8n β†’ Workflows β†’ Import from File β†’ Select the downloaded JSON")
217
+
218
+ # Footer
219
+ st.markdown("---")
220
+ st.markdown("Made by Muhammad Shaheer")