abhidgp1978 commited on
Commit
23c5eb8
Β·
verified Β·
1 Parent(s): 90cf83d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +281 -50
app.py CHANGED
@@ -6,8 +6,13 @@ import json
6
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
7
  GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
8
 
9
- MAX_USES = 3 # πŸ‘ˆ change this limit if needed
10
- USAGE_FILE = "ip_usage.json"
 
 
 
 
 
11
 
12
  if not GROQ_API_KEY:
13
  raise ValueError("GROQ_API_KEY not found. Please add it in the Space Secrets.")
@@ -54,98 +59,324 @@ def groq_api_chat(prompt, model="llama3-8b-8192", max_tokens=800):
54
  return data["choices"][0]["message"]["content"].strip()
55
 
56
  # -------------------------------
57
- # Limit Enforcement
58
  # -------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
59
  def enforce_limit(request: gr.Request):
60
  ip = request.client.host if request and request.client else "unknown"
61
- used = ip_usage.get(ip, 0)
 
 
 
 
 
 
 
62
 
63
- if used >= MAX_USES:
64
- return ip, False, f"⚠️ This IP has reached the maximum of {MAX_USES} clicks.", f"Remaining attempts: 0/{MAX_USES}"
 
65
 
66
- used += 1
67
- ip_usage[ip] = used
68
- save_usage(ip_usage)
 
69
 
70
- remaining = MAX_USES - used
71
- return ip, True, None, f"Remaining attempts: {remaining}/{MAX_USES}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
  # -------------------------------
74
- # Core Functions (only logic updated)
75
  # -------------------------------
76
- def run_agent(request: gr.Request, *args):
 
 
 
 
 
 
 
 
77
  ip, allowed, msg, counter = enforce_limit(request)
 
78
  if not allowed:
79
- return ("⚠️ Limit reached. No more responses.",
80
- counter)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  try:
83
- response = groq_api_chat("Run agent prompt", max_tokens=800)
84
  except Exception as e:
85
  response = f"Error calling API: {e}"
86
 
87
- return (response, counter)
88
 
89
-
90
- def generate_hashtags(request: gr.Request, *args):
 
 
91
  ip, allowed, msg, counter = enforce_limit(request)
 
92
  if not allowed:
93
- return ("⚠️ Limit reached. No more hashtags.",
94
- counter)
 
 
 
 
95
 
 
 
 
 
96
  try:
97
- tags = groq_api_chat("Generate hashtags prompt")
98
  except Exception as e:
99
  tags = f"Error generating hashtags: {e}"
100
 
101
- return (tags, counter)
102
-
103
 
104
- def social_channel_launch(request: gr.Request, *args):
 
 
 
105
  ip, allowed, msg, counter = enforce_limit(request)
 
106
  if not allowed:
107
- return ("⚠️ Limit reached. Launch blocked.",
108
- counter)
109
-
110
- return ("βœ… Campaign launched!", counter)
 
 
111
 
 
 
 
 
112
 
113
  # -------------------------------
114
- # UI (untouched from your file)
115
  # -------------------------------
116
  with gr.Blocks() as demo:
117
- counter_box = gr.Markdown("Remaining attempts: ∞")
 
118
 
119
- product_name = gr.Textbox(label="Product Name")
120
- do_message = gr.Checkbox(label="Campaign Messages")
121
 
122
- run_btn = gr.Button("πŸš€ Generate")
123
- output_box = gr.Markdown()
 
124
 
125
- hashtags = gr.Textbox(label="Generated Hashtags")
126
- generate_btn = gr.Button("Generate Hashtags")
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
  social_channels = gr.Dropdown(
129
- choices=["Twitter", "Facebook", "LinkedIn"], label="Social Channel"
 
 
 
 
130
  )
131
- confirm_launch = gr.Checkbox(label="Confirm Launch")
 
 
 
 
132
  launch_btn = gr.Button("πŸš€ Launch Campaign")
 
133
  launch_output = gr.Markdown()
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  run_btn.click(
136
- run_agent,
137
- [product_name, do_message],
138
- [output_box, counter_box]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  )
140
- generate_btn.click(
141
- generate_hashtags,
142
- [product_name],
143
- [hashtags, counter_box]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  )
 
145
  launch_btn.click(
146
- social_channel_launch,
147
- [social_channels, hashtags, confirm_launch],
148
- [launch_output, counter_box]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  )
150
 
151
- demo.launch()
 
6
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
7
  GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
8
 
9
+ # ===============================
10
+ # πŸ”§ Usage Limit Configuration
11
+ # ===============================
12
+ ENABLE_IP_LIMIT = True # πŸ‘ˆ Comment/Set False to disable IP limiting
13
+ MAX_USES = 3 # πŸ‘ˆ Maximum allowed actions per IP
14
+ USAGE_FILE = "ip_usage.json" # πŸ‘ˆ Persistent storage file
15
+ # ===============================
16
 
17
  if not GROQ_API_KEY:
18
  raise ValueError("GROQ_API_KEY not found. Please add it in the Space Secrets.")
 
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()