abhidgp1978 commited on
Commit
486c775
·
verified ·
1 Parent(s): 2240425

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +190 -159
app.py CHANGED
@@ -46,134 +46,181 @@ def groq_api_chat(prompt, model="llama3-8b-8192", max_tokens=800):
46
  "Authorization": f"Bearer {GROQ_API_KEY}",
47
  "Content-Type": "application/json"
48
  }
49
- data = {
50
  "model": model,
51
- "messages": [
52
- {
53
- "role": "user",
54
- "content": prompt
55
- }
56
- ],
57
- "max_tokens": max_tokens
58
  }
59
- response = requests.post(GROQ_API_URL, headers=headers, json=data)
60
  response.raise_for_status()
61
- return response.json()['choices'][0]['message']['content']
62
-
63
 
64
  # -------------------------------
65
- # App-specific Functions
66
  # -------------------------------
67
- def check_ip_on_load(request: gr.Request):
68
- if not ENABLE_IP_LIMIT:
69
- return 0, gr.update(visible=False), gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True)
 
 
 
 
 
 
 
 
70
 
71
- client_ip = request.client.host
72
- if client_ip in ip_usage:
73
- ip_usage[client_ip] += 1
74
- else:
75
- ip_usage[client_ip] = 1
 
 
 
 
 
76
 
77
- save_usage(ip_usage)
 
 
 
 
 
 
 
78
 
79
- if ip_usage[client_ip] > MAX_USES:
 
 
 
 
 
 
 
80
  return (
81
- ip_usage[client_ip],
82
- gr.update(visible=True),
83
- gr.update(interactive=False),
84
- gr.update(interactive=False),
85
- gr.update(interactive=False)
 
 
 
 
 
86
  )
87
- return (
88
- ip_usage[client_ip],
89
- gr.update(visible=False),
90
- gr.update(interactive=True),
91
- gr.update(interactive=True),
92
- gr.update(interactive=True)
93
- )
94
-
95
- def get_component_updates(is_interactive=True):
96
- return (
97
- gr.update(interactive=is_interactive), gr.update(interactive=is_interactive), gr.update(interactive=is_interactive),
98
- gr.update(interactive=is_interactive), gr.update(interactive=is_interactive), gr.update(interactive=is_interactive),
99
- gr.update(interactive=is_interactive), gr.update(interactive=is_interactive), gr.update(interactive=is_interactive),
100
- gr.update(interactive=is_interactive), gr.update(interactive=is_interactive), gr.update(interactive=is_interactive),
101
- )
102
 
103
  # -------------------------------
104
- # Core Business Logic
105
  # -------------------------------
106
- def namecraft_agent(
107
- product_name,
108
- do_competitors,
109
- do_message,
110
- do_competitor_analysis,
111
- do_launch_time,
112
- do_seo,
113
- do_budget_roi,
114
- ):
115
- system_prompt = "You are an expert marketing agent called 'NameCraft'. Your primary function is to generate highly effective and creative business or product names based on user input. You should provide names and a brief explanation for each one. Also, act as a multi-modal marketing assistant to help with other tasks if asked. Be concise and professional."
116
 
117
- user_prompt = f"The user wants to generate creative names for a product named '{product_name}'. Provide 5 unique and relevant name suggestions, each with a brief 1-2 sentence explanation of the name's meaning or appeal."
 
 
 
 
 
 
 
 
 
 
 
118
 
119
- # Sub-agent prompts
 
120
  if do_competitors:
121
- user_prompt += "\n\nAdditionally, suggest 3 potential direct competitors based on the product name."
122
- if do_message:
123
- user_prompt += "\n\nAdditionally, write a compelling, 2-sentence elevator pitch for the product."
124
  if do_competitor_analysis:
125
- user_prompt += "\n\nAdditionally, perform a brief SWOT analysis (1-2 sentences for each section) for the product."
 
 
126
  if do_launch_time:
127
- user_prompt += "\n\nAdditionally, suggest an optimal launch date and time, and explain why it's a good choice."
128
  if do_seo:
129
- user_prompt += "\n\nAdditionally, suggest 5 relevant SEO keywords."
130
  if do_budget_roi:
131
- user_prompt += "\n\nAdditionally, provide a high-level marketing budget breakdown (in percentages) for a 3-month launch campaign."
132
 
133
- try:
134
- full_response = groq_api_chat(user_prompt)
135
- return full_response
136
- except Exception as e:
137
- return f"An error occurred: {e}"
 
 
138
 
139
- def generate_hashtags(product_name):
140
- prompt = f"Generate 5 popular and creative hashtags for a product named '{product_name}'."
141
  try:
142
- return groq_api_chat(prompt)
143
  except Exception as e:
144
- return f"An error occurred: {e}"
145
 
146
- def social_channel_launch(channels, hashtags, launch_checkbox):
147
- if not launch_checkbox:
148
- return ""
149
-
150
- if not channels:
151
- return "Please select at least one social media channel to launch to."
152
 
153
- channel_list = ", ".join(channels)
154
-
155
- prompt = f"The user wants to launch their product on the following social media channels: {channel_list}. The hashtags they want to use are: {hashtags}. Write a short, engaging post for a product launch announcement. Include the hashtags. Do not include channel-specific formatting like @-mentions."
156
-
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  try:
158
- return groq_api_chat(prompt)
159
  except Exception as e:
160
- return f"An error occurred: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  # ----------------------------------------------
163
  # 🎨 Gradio UI
164
  # ----------------------------------------------
165
-
166
  with gr.Blocks(title="NameCraft AI") as demo:
167
  gr.Markdown("# <span style='color: #00bcd4;'>NameCraft</span> Agentic AI")
168
  gr.Markdown("Leverage the power of Agentic AI to generate creative names and a full marketing strategy for your product.")
169
-
170
- # Usage tracking components
171
- counter_box = gr.Textbox(label="Uses this session", value=0, interactive=False, visible=True)
172
- limit_banner = gr.Markdown("⚠️ **Usage limit reached.** Please visit again later.", visible=False)
173
-
174
  with gr.Row():
175
  product_name = gr.Textbox(label="Product Name/Concept", placeholder="e.g., A new fitness app that uses AI to create personalized workout plans.")
176
-
177
  with gr.Accordion("Select Your Agentic Tasks", open=False):
178
  with gr.Row():
179
  do_competitors = gr.Checkbox(label="Suggest Competitors")
@@ -183,13 +230,10 @@ with gr.Blocks(title="NameCraft AI") as demo:
183
  do_launch_time = gr.Checkbox(label="Recommend Launch Time")
184
  do_seo = gr.Checkbox(label="Suggest SEO Keywords")
185
  do_budget_roi = gr.Checkbox(label="Generate Budget Breakdown")
186
-
187
  run_btn = gr.Button("Generate Marketing Plan")
188
  output = gr.Markdown(label="Marketing Plan")
189
 
190
- # ----------------------------------------------------
191
- # Social Media Launch Section
192
- # ----------------------------------------------------
193
  with gr.Accordion("Social Media Launch Agent", open=False):
194
  gr.Markdown("Generate hashtags and draft social media posts.")
195
  with gr.Row():
@@ -198,26 +242,26 @@ with gr.Blocks(title="NameCraft AI") as demo:
198
  choices=["Twitter", "Facebook", "Instagram", "LinkedIn", "TikTok"]
199
  )
200
  launch_checkbox = gr.Checkbox(label="Draft a social media post")
 
201
  generate_hashtags_btn = gr.Button("Generate Hashtags")
202
  hashtags = gr.Textbox(label="Generated Hashtags")
203
 
204
  launch_btn = gr.Button("Launch to Social Media")
205
  launch_output = gr.Markdown(label="Social Media Post")
206
 
207
- # ---------------------------------------------
208
  # Event Listeners
209
- # ---------------------------------------------
210
  run_btn.click(
211
- fn=get_component_updates,
212
  inputs=[],
213
- outputs=[\
214
- run_btn, generate_hashtags_btn, launch_btn, product_name,\
215
- do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,\
216
- social_channels, hashtags, launch_checkbox\
217
  ]
218
  ).then(
219
- fn=namecraft_agent,
220
  inputs=[
 
221
  product_name,
222
  do_competitors,
223
  do_message,
@@ -226,81 +270,68 @@ with gr.Blocks(title="NameCraft AI") as demo:
226
  do_seo,
227
  do_budget_roi
228
  ],
229
- outputs=output,
230
- ).then(
231
- fn=get_component_updates,
232
- inputs=[],
233
- outputs=[\
234
- run_btn, generate_hashtags_btn, launch_btn, product_name,\
235
- do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,\
236
- social_channels, hashtags, launch_checkbox\
237
- ],
238
  )
239
 
240
  generate_hashtags_btn.click(
241
- fn=get_component_updates,
242
  inputs=[],
243
- outputs=[\
244
- run_btn, generate_hashtags_btn, launch_btn, product_name,\
245
- do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,\
246
- social_channels, hashtags, launch_checkbox\
247
  ]
248
  ).then(
249
  fn=generate_hashtags,
250
- inputs=product_name,
251
- outputs=hashtags,
252
- ).then(
253
- fn=get_component_updates,
254
- inputs=[],
255
- outputs=[\
256
- run_btn, generate_hashtags_btn, launch_btn, product_name,\
257
- do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,\
258
- social_channels, hashtags, launch_checkbox\
259
- ],
260
  )
261
 
262
  launch_btn.click(
263
  fn=lambda: get_component_updates(False),
264
  inputs=[],
265
- outputs=[\
266
- run_btn, generate_hashtags_btn, launch_btn, product_name,\
267
- do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,\
268
- social_channels, hashtags, launch_checkbox\
269
  ]
270
  ).then(
271
  fn=social_channel_launch,
272
- inputs=[social_channels, hashtags, launch_checkbox],
273
- outputs=[\
274
- launch_output,\
275
- counter_box,\
276
- limit_banner,\
277
- run_btn, generate_hashtags_btn, launch_btn, product_name,\
278
- do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,\
279
- social_channels, hashtags, launch_checkbox\
280
- ],
281
  )
282
- # ---------------------------------------------
283
-
284
  demo.load(
285
  fn=check_ip_on_load,
286
- inputs=None,
287
- outputs=[\
288
- counter_box,\
289
- limit_banner,\
290
- run_btn,\
291
- generate_hashtags_btn,\
292
- launch_btn,\
293
- product_name,\
294
- do_competitors,\
295
- do_message,\
296
- do_competitor_analysis,\
297
- do_launch_time,\
298
- do_seo,\
299
- do_budget_roi,\
300
- social_channels,\
301
- hashtags,\
302
- launch_checkbox\
303
- ],
304
  )
305
 
306
  demo.launch()
 
46
  "Authorization": f"Bearer {GROQ_API_KEY}",
47
  "Content-Type": "application/json"
48
  }
49
+ payload = {
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()
58
+ data = response.json()
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
+ if not product_name_val or not product_name_val.strip():
186
+ return ("Please enter a product or campaign name first.", counter, gr.update(visible=False), *get_component_updates(True))
187
+
188
+ prompt = f"Generate relevant social media hashtags for the product or campaign named '{product_name_val}'. List hashtags separated by commas."
189
  try:
190
+ tags = groq_api_chat(prompt)
191
  except Exception as e:
192
+ tags = f"Error generating hashtags: {e}"
193
+
194
+ return (tags, counter, gr.update(visible=False), *get_component_updates(True))
195
+
196
+ # -------------------------------
197
+ # Social Media Launch
198
+ # -------------------------------
199
+ def social_channel_launch(request: gr.Request, channel, hashtags, checkbox_value):
200
+ ip, allowed, msg, counter = enforce_limit(request)
201
+ if not allowed:
202
+ return (
203
+ "⚠️ Limit reached. Launch blocked.",
204
+ counter,
205
+ gr.update(value=f"<div style='color:white; background-color:red; padding:10px; font-weight:bold;'>{msg}</div>", visible=True),
206
+ *get_component_updates(False)
207
+ )
208
+ if checkbox_value:
209
+ return (f"✅ Launched campaign on {channel} with hashtags: {hashtags}", counter, gr.update(visible=False), *get_component_updates(True))
210
+ else:
211
+ return ("Please tick the checkbox to launch to social media.", counter, gr.update(visible=False), *get_component_updates(True))
212
+
213
 
214
  # ----------------------------------------------
215
  # 🎨 Gradio UI
216
  # ----------------------------------------------
 
217
  with gr.Blocks(title="NameCraft AI") as demo:
218
  gr.Markdown("# <span style='color: #00bcd4;'>NameCraft</span> Agentic AI")
219
  gr.Markdown("Leverage the power of Agentic AI to generate creative names and a full marketing strategy for your product.")
220
+
 
 
 
 
221
  with gr.Row():
222
  product_name = gr.Textbox(label="Product Name/Concept", placeholder="e.g., A new fitness app that uses AI to create personalized workout plans.")
223
+
224
  with gr.Accordion("Select Your Agentic Tasks", open=False):
225
  with gr.Row():
226
  do_competitors = gr.Checkbox(label="Suggest Competitors")
 
230
  do_launch_time = gr.Checkbox(label="Recommend Launch Time")
231
  do_seo = gr.Checkbox(label="Suggest SEO Keywords")
232
  do_budget_roi = gr.Checkbox(label="Generate Budget Breakdown")
233
+
234
  run_btn = gr.Button("Generate Marketing Plan")
235
  output = gr.Markdown(label="Marketing Plan")
236
 
 
 
 
237
  with gr.Accordion("Social Media Launch Agent", open=False):
238
  gr.Markdown("Generate hashtags and draft social media posts.")
239
  with gr.Row():
 
242
  choices=["Twitter", "Facebook", "Instagram", "LinkedIn", "TikTok"]
243
  )
244
  launch_checkbox = gr.Checkbox(label="Draft a social media post")
245
+
246
  generate_hashtags_btn = gr.Button("Generate Hashtags")
247
  hashtags = gr.Textbox(label="Generated Hashtags")
248
 
249
  launch_btn = gr.Button("Launch to Social Media")
250
  launch_output = gr.Markdown(label="Social Media Post")
251
 
 
252
  # Event Listeners
 
253
  run_btn.click(
254
+ fn=lambda: get_component_updates(False),
255
  inputs=[],
256
+ outputs=[
257
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
258
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
259
+ social_channels, hashtags, launch_checkbox
260
  ]
261
  ).then(
262
+ fn=run_agent,
263
  inputs=[
264
+ gr.State(),
265
  product_name,
266
  do_competitors,
267
  do_message,
 
270
  do_seo,
271
  do_budget_roi
272
  ],
273
+ outputs=[
274
+ output,
275
+ gr.State(),
276
+ gr.State(),
277
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
278
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
279
+ social_channels, hashtags, launch_checkbox
280
+ ]
 
281
  )
282
 
283
  generate_hashtags_btn.click(
284
+ fn=lambda: get_component_updates(False),
285
  inputs=[],
286
+ outputs=[
287
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
288
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
289
+ social_channels, hashtags, launch_checkbox
290
  ]
291
  ).then(
292
  fn=generate_hashtags,
293
+ inputs=[gr.State(), product_name],
294
+ outputs=[
295
+ hashtags,
296
+ gr.State(),
297
+ gr.State(),
298
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
299
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
300
+ social_channels, hashtags, launch_checkbox
301
+ ]
 
302
  )
303
 
304
  launch_btn.click(
305
  fn=lambda: get_component_updates(False),
306
  inputs=[],
307
+ outputs=[
308
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
309
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
310
+ social_channels, hashtags, launch_checkbox
311
  ]
312
  ).then(
313
  fn=social_channel_launch,
314
+ inputs=[gr.State(), social_channels, hashtags, launch_checkbox],
315
+ outputs=[
316
+ launch_output,
317
+ gr.State(),
318
+ gr.State(),
319
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
320
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
321
+ social_channels, hashtags, launch_checkbox
322
+ ]
323
  )
324
+
 
325
  demo.load(
326
  fn=check_ip_on_load,
327
+ inputs=[gr.State()],
328
+ outputs=[
329
+ gr.State(),
330
+ gr.State(),
331
+ run_btn, generate_hashtags_btn, launch_btn, product_name,
332
+ do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
333
+ social_channels, hashtags, launch_checkbox
334
+ ]
 
 
 
 
 
 
 
 
 
 
335
  )
336
 
337
  demo.launch()