shaheerawan3 commited on
Commit
6953566
Β·
verified Β·
1 Parent(s): dc3f91a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +227 -0
app.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
48
+ {user_idea}
49
+
50
+ Provide 3-5 enhanced versions of this idea with:
51
+ 1. Additional useful features
52
+ 2. Error handling suggestions
53
+ 3. Optimization tips
54
+ 4. Integration possibilities
55
+
56
+ Keep each suggestion concise but actionable. Format as a numbered list."""
57
+
58
+ response = client.text_generation(
59
+ prompt,
60
+ model=model_choice,
61
+ max_new_tokens=800,
62
+ temperature=temperature,
63
+ return_full_text=False
64
+ )
65
+
66
+ st.session_state['enhanced_ideas'] = response
67
+ st.session_state['original_idea'] = user_idea
68
+
69
+ except Exception as e:
70
+ st.error(f"Error: {str(e)}")
71
+ else:
72
+ st.warning("Please enter a workflow idea first!")
73
+
74
+ with col2:
75
+ st.header("✨ Enhanced Suggestions")
76
+ if 'enhanced_ideas' in st.session_state:
77
+ st.markdown(st.session_state['enhanced_ideas'])
78
+ else:
79
+ st.info("Click 'Enhance My Idea' to get AI-powered suggestions")
80
+
81
+ st.markdown("---")
82
+
83
+ # Generation section
84
+ st.header("πŸš€ Generate n8n Workflow")
85
+
86
+ final_idea = st.text_area(
87
+ "Final workflow description (edit if needed)",
88
+ value=st.session_state.get('original_idea', ''),
89
+ height=100,
90
+ key="final_idea"
91
+ )
92
+
93
+ col_gen1, col_gen2, col_gen3 = st.columns([1, 1, 1])
94
+
95
+ with col_gen1:
96
+ include_error_handling = st.checkbox("Include error handling", value=True)
97
+ with col_gen2:
98
+ include_schedule = st.checkbox("Add schedule trigger", value=False)
99
+ with col_gen3:
100
+ workflow_complexity = st.select_slider("Complexity", ["Simple", "Medium", "Advanced"], value="Medium")
101
+
102
+ if st.button("⚑ Generate n8n JSON", type="primary", use_container_width=True):
103
+ if final_idea:
104
+ with st.spinner("Generating your workflow..."):
105
+ try:
106
+ prompt = f"""You are an expert n8n workflow developer. Create a complete, working n8n workflow JSON based on this description:
107
+
108
+ {final_idea}
109
+
110
+ Requirements:
111
+ - Complexity level: {workflow_complexity}
112
+ - Error handling: {"Yes" if include_error_handling else "No"}
113
+ - Schedule trigger: {"Yes" if include_schedule else "No"}
114
+
115
+ Generate ONLY valid n8n workflow JSON. The JSON must include:
116
+ 1. "nodes" array with proper node types
117
+ 2. "connections" object linking nodes
118
+ 3. Realistic node configurations
119
+ 4. Valid n8n node types (HTTP Request, Set, IF, Schedule Trigger, etc.)
120
+
121
+ Return ONLY the JSON, no explanations. Make it production-ready."""
122
+
123
+ response = client.text_generation(
124
+ prompt,
125
+ model=model_choice,
126
+ max_new_tokens=2000,
127
+ temperature=0.3, # Lower temperature for more precise JSON
128
+ return_full_text=False
129
+ )
130
+
131
+ # Try to extract JSON from response
132
+ json_str = response.strip()
133
+
134
+ # Remove markdown code blocks if present
135
+ if json_str.startswith("```"):
136
+ json_str = json_str.split("```")[1]
137
+ if json_str.startswith("json"):
138
+ json_str = json_str[4:]
139
+ json_str = json_str.strip()
140
+
141
+ # Validate JSON
142
+ try:
143
+ workflow_json = json.loads(json_str)
144
+
145
+ # Add metadata if missing
146
+ if "name" not in workflow_json:
147
+ workflow_json["name"] = "AI Generated Workflow"
148
+ if "nodes" not in workflow_json:
149
+ workflow_json["nodes"] = []
150
+ if "connections" not in workflow_json:
151
+ workflow_json["connections"] = {}
152
+
153
+ st.session_state['generated_workflow'] = workflow_json
154
+ st.success("βœ… Workflow generated successfully!")
155
+
156
+ except json.JSONDecodeError as je:
157
+ st.error("Generated response wasn't valid JSON. Trying to fix...")
158
+ # Create a basic fallback workflow
159
+ workflow_json = {
160
+ "name": "AI Generated Workflow",
161
+ "nodes": [
162
+ {
163
+ "parameters": {},
164
+ "name": "Start",
165
+ "type": "n8n-nodes-base.start",
166
+ "typeVersion": 1,
167
+ "position": [250, 300]
168
+ },
169
+ {
170
+ "parameters": {
171
+ "url": "https://api.example.com",
172
+ "options": {}
173
+ },
174
+ "name": "HTTP Request",
175
+ "type": "n8n-nodes-base.httpRequest",
176
+ "typeVersion": 1,
177
+ "position": [450, 300]
178
+ }
179
+ ],
180
+ "connections": {
181
+ "Start": {
182
+ "main": [[{"node": "HTTP Request", "type": "main", "index": 0}]]
183
+ }
184
+ }
185
+ }
186
+ st.session_state['generated_workflow'] = workflow_json
187
+ st.info("Created a basic template. Please customize it in n8n.")
188
+
189
+ except Exception as e:
190
+ st.error(f"Generation error: {str(e)}")
191
+ else:
192
+ st.warning("Please enter a workflow description!")
193
+
194
+ # Display and download section
195
+ if 'generated_workflow' in st.session_state:
196
+ st.markdown("---")
197
+ st.header("πŸ“‹ Your n8n Workflow")
198
+
199
+ workflow = st.session_state['generated_workflow']
200
+
201
+ # Display stats
202
+ col_stat1, col_stat2, col_stat3 = st.columns(3)
203
+ with col_stat1:
204
+ st.metric("Nodes", len(workflow.get('nodes', [])))
205
+ with col_stat2:
206
+ st.metric("Connections", len(workflow.get('connections', {})))
207
+ with col_stat3:
208
+ st.metric("Ready to Import", "βœ“")
209
+
210
+ # JSON display
211
+ st.json(workflow)
212
+
213
+ # Download button
214
+ json_str = json.dumps(workflow, indent=2)
215
+ st.download_button(
216
+ label="πŸ“₯ Download Workflow JSON",
217
+ data=json_str,
218
+ file_name="n8n_workflow.json",
219
+ mime="application/json",
220
+ use_container_width=True
221
+ )
222
+
223
+ st.info("πŸ’‘ **How to import:** Open n8n β†’ Workflows β†’ Import from File β†’ Select the downloaded JSON")
224
+
225
+ # Footer
226
+ st.markdown("---")
227
+ st.markdown("Made by Muhammad Shaheer")