abhidgp1978 commited on
Commit
742276d
Β·
verified Β·
1 Parent(s): 0ed3aa0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +275 -129
app.py CHANGED
@@ -50,6 +50,8 @@ def groq_api_chat(prompt, model="llama3-8b-8192", max_tokens=800):
50
  "model": model,
51
  "messages": [{"role": "user", "content": prompt}],
52
  "max_tokens": max_tokens,
 
 
53
  }
54
  response = requests.post(GROQ_API_URL, headers=headers, json=payload)
55
  response.raise_for_status()
@@ -57,180 +59,324 @@ def groq_api_chat(prompt, model="llama3-8b-8192", max_tokens=800):
57
  return data["choices"][0]["message"]["content"].strip()
58
 
59
  # -------------------------------
60
- # App-specific Functions
61
  # -------------------------------
62
- def check_ip_on_load(request: gr.Request):
63
- if not ENABLE_IP_LIMIT:
64
- return (
65
- gr.update(value="Unlimited attempts"),
66
- gr.update(visible=False),
67
- gr.update(interactive=True)
68
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- client_ip = request.client.host
71
- used = ip_usage.get(client_ip, 0)
 
 
 
 
72
 
73
- if used >= MAX_USES:
74
- msg = f"⚠️ This IP has reached the maximum limit of {MAX_USES} uses. All controls are disabled."
 
 
 
 
 
 
 
 
75
  return (
76
- gr.update(value=f"Remaining attempts: 0/{MAX_USES}"),
77
- gr.update(value=msg, visible=True),
78
- gr.update(interactive=False)
79
  )
80
  else:
81
- remaining = MAX_USES - used
82
  return (
83
- gr.update(value=f"Remaining attempts: {remaining}/{MAX_USES}"),
84
  gr.update(visible=False),
85
- gr.update(interactive=True)
86
  )
87
 
88
- def update_components_state(is_interactive):
89
- return (
90
- gr.update(interactive=is_interactive), # run_btn
91
- gr.update(interactive=is_interactive), # generate_hashtags_btn
92
- gr.update(interactive=is_interactive), # launch_btn
93
- gr.update(interactive=is_interactive), # product_name
94
- gr.update(interactive=is_interactive), # do_competitors
95
- gr.update(interactive=is_interactive), # do_message
96
- gr.update(interactive=is_interactive), # do_competitor_analysis
97
- gr.update(interactive=is_interactive), # do_launch_time
98
- gr.update(interactive=is_interactive), # do_seo
99
- gr.update(interactive=is_interactive), # do_budget_roi
100
- gr.update(interactive=is_interactive), # social_channels
101
- gr.update(interactive=is_interactive), # hashtags
102
- gr.update(interactive=is_interactive) # launch_checkbox
103
- )
104
 
105
- def run_agent(product_name, do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi, request: gr.Request):
106
- client_ip = request.client.host
107
- ip_usage[client_ip] = ip_usage.get(client_ip, 0) + 1
108
- save_usage(ip_usage)
 
 
 
 
 
 
 
 
109
 
110
  prompt = f"Create a detailed marketing plan for '{product_name}'.\nOnly include these sections:\n"
111
  sections = []
112
- if do_competitors: sections.append("Competitor Names")
113
- if do_competitor_analysis: sections.append("Competitor Analysis Insights")
114
- if do_message: sections.append("Campaign Messages")
115
- if do_launch_time: sections.append("Best Launch Time")
116
- if do_seo: sections.append("SEO Keywords")
117
- if do_budget_roi: sections.append("Budget and ROI")
118
- if not sections: return "Please select at least one option to generate the marketing plan."
 
 
 
 
 
 
 
 
119
 
120
  for s in sections:
121
  prompt += f"- {s}\n"
122
-
 
 
123
  try:
124
- response = groq_api_chat(prompt)
125
- return response
126
  except Exception as e:
127
- return f"Error calling API: {e}"
 
 
128
 
129
- def generate_hashtags(product_name):
130
- if not product_name: return "Please enter a product or campaign name first."
131
- prompt = f"Generate relevant social media hashtags for '{product_name}'. List hashtags separated by commas."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  try:
133
  tags = groq_api_chat(prompt)
134
- return tags
135
  except Exception as e:
136
- return f"Error generating hashtags: {e}"
137
 
138
- def social_channel_launch(channels, hashtags, checkbox_value):
139
- if not checkbox_value: return "Please tick the checkbox to launch to social media."
140
- if not channels: return "Please select at least one social media channel to launch to."
141
- if not hashtags: return "Please generate hashtags first."
142
-
143
- channel_list = ", ".join(channels)
144
- prompt = f"Write a short, engaging social media post for a product launch announcement on {channel_list}. Include the hashtags: {hashtags}."
145
-
146
- try:
147
- post = groq_api_chat(prompt)
148
- return f"βœ… Launching on social media...\n\n---\n{post}"
149
- except Exception as e:
150
- return f"Error drafting social media post: {e}"
151
-
152
- # ----------------------------------------------
153
- # 🎨 Gradio UI
154
- # ----------------------------------------------
155
- with gr.Blocks(title="NameCraft AI") as demo:
156
- gr.Markdown("# <span style='color: #00bcd4;'>NameCraft</span> Agentic AI")
157
- gr.Markdown("Leverage the power of Agentic AI to generate creative names and a full marketing strategy for your product.")
158
 
159
- usage_counter = gr.Textbox(label="Remaining attempts", interactive=False)
160
- limit_banner = gr.Markdown(visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  with gr.Row():
163
- product_name = gr.Textbox(label="Product Name/Concept", placeholder="e.g., A new fitness app that uses AI to create personalized workout plans.")
164
-
165
- with gr.Accordion("Select Your Agentic Tasks", open=False):
166
- with gr.Row():
167
- do_competitors = gr.Checkbox(label="Suggest Competitors")
168
- do_message = gr.Checkbox(label="Create Elevator Pitch")
169
- do_competitor_analysis = gr.Checkbox(label="Conduct SWOT Analysis")
170
- with gr.Row():
171
- do_launch_time = gr.Checkbox(label="Recommend Launch Time")
172
- do_seo = gr.Checkbox(label="Suggest SEO Keywords")
173
- do_budget_roi = gr.Checkbox(label="Generate Budget Breakdown")
174
-
175
- run_btn = gr.Button("Generate Marketing Plan")
176
- output = gr.Markdown(label="Marketing Plan")
177
-
178
- with gr.Accordion("Social Media Launch Agent", open=False):
179
- gr.Markdown("Generate hashtags and draft social media posts.")
180
- with gr.Row():
181
- social_channels = gr.CheckboxGroup(
182
- label="Select social media channels",
183
- choices=["Twitter", "Facebook", "Instagram", "LinkedIn", "TikTok"]
184
- )
185
- launch_checkbox = gr.Checkbox(label="Draft a social media post")
186
-
187
- generate_hashtags_btn = gr.Button("Generate Hashtags")
188
- hashtags = gr.Textbox(label="Generated Hashtags")
189
-
190
- launch_btn = gr.Button("Launch to Social Media")
191
- launch_output = gr.Markdown(label="Social Media Post")
192
 
193
- # Event Listeners
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  run_btn.click(
195
- fn=lambda: update_components_state(False),
196
- outputs=update_components_state(False)
 
 
 
 
 
197
  ).then(
198
  fn=run_agent,
199
- inputs=[product_name, do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi, gr.State(value=None)],
200
- outputs=output
201
- ).then(
202
- fn=lambda: check_ip_on_load(gr.Request()),
203
- outputs=[usage_counter, limit_banner] + list(update_components_state(True))
 
 
 
 
 
 
 
 
 
 
 
 
204
  )
205
 
206
  generate_hashtags_btn.click(
207
- fn=lambda: update_components_state(False),
208
- outputs=update_components_state(False)
 
 
 
 
 
209
  ).then(
210
  fn=generate_hashtags,
211
- inputs=product_name,
212
- outputs=hashtags
213
- ).then(
214
- fn=lambda: check_ip_on_load(gr.Request()),
215
- outputs=[usage_counter, limit_banner] + list(update_components_state(True))
 
 
 
 
216
  )
217
 
218
  launch_btn.click(
219
- fn=lambda: update_components_state(False),
220
- outputs=update_components_state(False)
 
 
 
 
 
221
  ).then(
222
  fn=social_channel_launch,
223
  inputs=[social_channels, hashtags, launch_checkbox],
224
- outputs=launch_output
225
- ).then(
226
- fn=lambda: check_ip_on_load(gr.Request()),
227
- outputs=[usage_counter, limit_banner] + list(update_components_state(True))
 
 
 
 
228
  )
229
-
 
230
  demo.load(
231
  fn=check_ip_on_load,
232
- inputs=[gr.State(value=None)],
233
- outputs=[usage_counter, limit_banner] + list(update_components_state(True))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  )
235
 
236
  demo.launch()
 
50
  "model": model,
51
  "messages": [{"role": "user", "content": prompt}],
52
  "max_tokens": max_tokens,
53
+ "temperature": 0.6,
54
+ "top_p": 0.9,
55
  }
56
  response = requests.post(GROQ_API_URL, headers=headers, json=payload)
57
  response.raise_for_status()
 
59
  return data["choices"][0]["message"]["content"].strip()
60
 
61
  # -------------------------------
62
+ # Helpers
63
  # -------------------------------
64
+ def get_component_updates(interactive_state: bool):
65
+ """Returns a tuple of gr.update objects for all interactive components."""
66
+ upd = gr.update(interactive=interactive_state)
67
+ return (
68
+ upd, upd, upd, # run_btn, generate_hashtags_btn, launch_btn
69
+ upd, # product_name
70
+ upd, upd, upd, upd, upd, upd, # 6 checkboxes
71
+ upd, # social_channels
72
+ upd, # hashtags textbox
73
+ upd # launch_checkbox
74
+ )
75
+
76
+ def enforce_limit(request: gr.Request):
77
+ ip = request.client.host if request and request.client else "unknown"
78
+ if ENABLE_IP_LIMIT:
79
+ used = ip_usage.get(ip, 0)
80
+
81
+ if used >= MAX_USES:
82
+ return ip, False, (
83
+ f"⚠️ This IP has reached the maximum limit of {MAX_USES} uses. "
84
+ "All controls are disabled. Contact the admin."
85
+ ), f"Remaining attempts: 0/{MAX_USES}"
86
 
87
+ used += 1
88
+ ip_usage[ip] = used
89
+ save_usage(ip_usage)
90
+
91
+ remaining = MAX_USES - used
92
+ return ip, True, None, f"Remaining attempts: {remaining}/{MAX_USES}"
93
 
94
+ return ip, True, None, "Unlimited attempts"
95
+
96
+ # -------------------------------
97
+ # Check IP status on load
98
+ # -------------------------------
99
+ def check_ip_on_load(request: gr.Request):
100
+ ip = request.client.host if request and request.client else "unknown"
101
+ used = ip_usage.get(ip, 0)
102
+ if ENABLE_IP_LIMIT and used >= MAX_USES:
103
+ msg = f"⚠️ This IP has reached the maximum limit of {MAX_USES} uses. All controls are disabled. Contact the admin."
104
  return (
105
+ f"Remaining attempts: 0/{MAX_USES}",
106
+ gr.update(value=f"<div style='color:white; background-color:red; padding:10px; font-weight:bold;'>{msg}</div>", visible=True),
107
+ *get_component_updates(False)
108
  )
109
  else:
110
+ remaining = MAX_USES - used if ENABLE_IP_LIMIT else "∞"
111
  return (
112
+ f"Remaining attempts: {remaining}/{MAX_USES}" if ENABLE_IP_LIMIT else "Unlimited attempts",
113
  gr.update(visible=False),
114
+ *get_component_updates(True)
115
  )
116
 
117
+ # -------------------------------
118
+ # Main Agent (Generate)
119
+ # -------------------------------
120
+ def run_agent(request: gr.Request,
121
+ product_name,
122
+ do_competitors,
123
+ do_message,
124
+ do_competitor_analysis,
125
+ do_launch_time,
126
+ do_seo,
127
+ do_budget_roi):
 
 
 
 
 
128
 
129
+ ip, allowed, msg, counter = enforce_limit(request)
130
+
131
+ if not allowed:
132
+ return (
133
+ "⚠️ Limit reached. No more responses.",
134
+ counter,
135
+ gr.update(value=f"<div style='color:white; background-color:red; padding:10px; font-weight:bold;'>{msg}</div>", visible=True),
136
+ *get_component_updates(False)
137
+ )
138
+
139
+ if not product_name or not product_name.strip():
140
+ return ("Please enter a valid product or campaign name.", counter, gr.update(visible=False), *get_component_updates(True))
141
 
142
  prompt = f"Create a detailed marketing plan for '{product_name}'.\nOnly include these sections:\n"
143
  sections = []
144
+ if do_competitors:
145
+ sections.append("Competitor Names")
146
+ if do_competitor_analysis:
147
+ sections.append("Competitor Analysis Insights")
148
+ if do_message:
149
+ sections.append("Campaign Messages")
150
+ if do_launch_time:
151
+ sections.append("Best Launch Time")
152
+ if do_seo:
153
+ sections.append("SEO Keywords")
154
+ if do_budget_roi:
155
+ sections.append("Budget and ROI")
156
+
157
+ if not sections:
158
+ return ("Please select at least one option to generate the marketing plan.", counter, gr.update(visible=False), *get_component_updates(True))
159
 
160
  for s in sections:
161
  prompt += f"- {s}\n"
162
+
163
+ prompt += "\nRespond with each section clearly headed as shown above."
164
+
165
  try:
166
+ response = groq_api_chat(prompt, max_tokens=800)
 
167
  except Exception as e:
168
+ response = f"Error calling API: {e}"
169
+
170
+ return (response, counter, gr.update(visible=False), *get_component_updates(True))
171
 
172
+ # -------------------------------
173
+ # Hashtag Generator
174
+ # -------------------------------
175
+ def generate_hashtags(request: gr.Request, product_name_val):
176
+ ip, allowed, msg, counter = enforce_limit(request)
177
+
178
+ if not allowed:
179
+ return (
180
+ "⚠️ Limit reached. No more hashtags.",
181
+ counter,
182
+ gr.update(value=f"<div style='color:white; background-color:red; padding:10px; font-weight:bold;'>{msg}</div>", visible=True),
183
+ *get_component_updates(False)
184
+ )
185
+
186
+ if not product_name_val or not product_name_val.strip():
187
+ return ("Please enter a product or campaign name first.", counter, gr.update(visible=False), *get_component_updates(True))
188
+
189
+ prompt = f"Generate relevant social media hashtags for the product or campaign named '{product_name_val}'. List hashtags separated by commas."
190
  try:
191
  tags = groq_api_chat(prompt)
 
192
  except Exception as e:
193
+ tags = f"Error generating hashtags: {e}"
194
 
195
+ return (tags, counter, gr.update(visible=False), *get_component_updates(True))
196
+
197
+ # -------------------------------
198
+ # Social Media Launch
199
+ # -------------------------------
200
+ def social_channel_launch(request: gr.Request, channel, hashtags, checkbox_value):
201
+ ip, allowed, msg, counter = enforce_limit(request)
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
+ if not allowed:
204
+ return (
205
+ "⚠️ Limit reached. Launch blocked.",
206
+ counter,
207
+ gr.update(value=f"<div style='color:white; background-color:red; padding:10px; font-weight:bold;'>{msg}</div>", visible=True),
208
+ *get_component_updates(False)
209
+ )
210
+
211
+ if checkbox_value:
212
+ return (f"βœ… Launched campaign on {channel} with hashtags: {hashtags}", counter, gr.update(visible=False), *get_component_updates(True))
213
+ else:
214
+ return ("", counter, gr.update(visible=False), *get_component_updates(True))
215
+
216
+ # -------------------------------
217
+ # UI
218
+ # -------------------------------
219
+ with gr.Blocks() as demo:
220
+ # Persistent warning banner
221
+ limit_banner = gr.Markdown("", visible=False)
222
+
223
+ product_name = gr.Textbox(label="Product or Campaign Name", placeholder="Enter product or campaign name here...")
224
 
225
  with gr.Row():
226
+ goals_vision = gr.Checkbox(label="Goals & Vision (disabled for now)", value=False, interactive=False)
227
+ target_audience = gr.Checkbox(label="Target Audience (disabled for now)", value=False, interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
 
229
+ with gr.Row():
230
+ do_competitors = gr.Checkbox(label="Competitor Names", value=False)
231
+ do_message = gr.Checkbox(label="Campaign Messages & Social Media", value=False)
232
+ with gr.Row():
233
+ do_competitor_analysis = gr.Checkbox(label="Competitor Analysis Insights", value=False)
234
+ do_launch_time = gr.Checkbox(label="Best Campaign Launch Time", value=False)
235
+ with gr.Row():
236
+ do_seo = gr.Checkbox(label="SEO Keywords", value=False)
237
+ do_budget_roi = gr.Checkbox(label="Campaign Budget Estimation & ROI", value=False)
238
+
239
+ # Counter
240
+ counter_box = gr.Markdown("Remaining attempts: ∞")
241
+
242
+ run_btn = gr.Button("πŸš€ Generate", interactive=False)
243
+ output_box = gr.Markdown()
244
+
245
+ social_channels = gr.Dropdown(
246
+ label="Select Social Media Channel to Launch",
247
+ choices=["Twitter", "Facebook", "Instagram", "LinkedIn"],
248
+ value="Twitter",
249
+ interactive=True,
250
+ multiselect=False
251
+ )
252
+
253
+ hashtags = gr.Textbox(label="Generated Hashtags", interactive=False)
254
+ generate_hashtags_btn = gr.Button("Generate Hashtags")
255
+
256
+ launch_checkbox = gr.Checkbox(label="Confirm Launch Campaign", value=False)
257
+ launch_btn = gr.Button("πŸš€ Launch Campaign")
258
+
259
+ launch_output = gr.Markdown()
260
+
261
+ # Enable Generate dynamically
262
+ def enable_generate_button(product_name_val, *checkbox_values):
263
+ product_entered = bool(product_name_val and product_name_val.strip())
264
+ any_checked = any(checkbox_values)
265
+ return gr.update(interactive=product_entered and any_checked)
266
+
267
+ inputs_for_enable = [product_name,
268
+ do_competitors,
269
+ do_message,
270
+ do_competitor_analysis,
271
+ do_launch_time,
272
+ do_seo,
273
+ do_budget_roi]
274
+
275
+ for comp in inputs_for_enable:
276
+ comp.change(fn=enable_generate_button,
277
+ inputs=[product_name,
278
+ do_competitors,
279
+ do_message,
280
+ do_competitor_analysis,
281
+ do_launch_time,
282
+ do_seo,
283
+ do_budget_roi],
284
+ outputs=run_btn)
285
+
286
+ # NEW Chained Callbacks to prevent race condition
287
+ # ---------------------------------------------
288
  run_btn.click(
289
+ fn=lambda: get_component_updates(False),
290
+ inputs=[],
291
+ outputs=[
292
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
293
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
294
+ social_channels, hashtags, launch_checkbox
295
+ ]
296
  ).then(
297
  fn=run_agent,
298
+ inputs=[
299
+ product_name,
300
+ do_competitors,
301
+ do_message,
302
+ do_competitor_analysis,
303
+ do_launch_time,
304
+ do_seo,
305
+ do_budget_roi
306
+ ],
307
+ outputs=[
308
+ output_box,
309
+ counter_box,
310
+ limit_banner,
311
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
312
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
313
+ social_channels, hashtags, launch_checkbox
314
+ ],
315
  )
316
 
317
  generate_hashtags_btn.click(
318
+ fn=lambda: get_component_updates(False),
319
+ inputs=[],
320
+ outputs=[
321
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
322
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
323
+ social_channels, hashtags, launch_checkbox
324
+ ]
325
  ).then(
326
  fn=generate_hashtags,
327
+ inputs=[product_name],
328
+ outputs=[
329
+ hashtags,
330
+ counter_box,
331
+ limit_banner,
332
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
333
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
334
+ social_channels, hashtags, launch_checkbox
335
+ ],
336
  )
337
 
338
  launch_btn.click(
339
+ fn=lambda: get_component_updates(False),
340
+ inputs=[],
341
+ outputs=[
342
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
343
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
344
+ social_channels, hashtags, launch_checkbox
345
+ ]
346
  ).then(
347
  fn=social_channel_launch,
348
  inputs=[social_channels, hashtags, launch_checkbox],
349
+ outputs=[
350
+ launch_output,
351
+ counter_box,
352
+ limit_banner,
353
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
354
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
355
+ social_channels, hashtags, launch_checkbox
356
+ ],
357
  )
358
+ # ---------------------------------------------
359
+
360
  demo.load(
361
  fn=check_ip_on_load,
362
+ inputs=None,
363
+ outputs=[
364
+ counter_box,
365
+ limit_banner,
366
+ run_btn,
367
+ generate_hashtags_btn,
368
+ launch_btn,
369
+ product_name,
370
+ do_competitors,
371
+ do_message,
372
+ do_competitor_analysis,
373
+ do_launch_time,
374
+ do_seo,
375
+ do_budget_roi,
376
+ social_channels,
377
+ hashtags,
378
+ launch_checkbox,
379
+ ],
380
  )
381
 
382
  demo.launch()