abhidgp1978 commited on
Commit
f1d0143
·
verified ·
1 Parent(s): 02b5914

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -59
app.py CHANGED
@@ -9,9 +9,9 @@ GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
9
  # ===============================
10
  # 🔧 Usage Limit Configuration
11
  # ===============================
12
- ENABLE_IP_LIMIT = True # 👈 Set to False (or comment) to disable
13
- MAX_USES = 3 # 👈 Maximum times allowed per IP
14
- USAGE_FILE = "ip_usage.json" # 👈 Persistent storage
15
  # ===============================
16
 
17
  if not GROQ_API_KEY:
@@ -41,7 +41,7 @@ ip_usage = load_usage()
41
  # -------------------------------
42
  # API Call
43
  # -------------------------------
44
- def groq_api_chat(prompt, model="llama3-8b-8192", max_tokens=512):
45
  headers = {
46
  "Authorization": f"Bearer {GROQ_API_KEY}",
47
  "Content-Type": "application/json"
@@ -59,7 +59,37 @@ def groq_api_chat(prompt, model="llama3-8b-8192", max_tokens=512):
59
  return data["choices"][0]["message"]["content"].strip()
60
 
61
  # -------------------------------
62
- # Main Agent
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  # -------------------------------
64
  def run_agent(request: gr.Request,
65
  product_name,
@@ -70,42 +100,33 @@ def run_agent(request: gr.Request,
70
  do_seo,
71
  do_budget_roi):
72
 
73
- ip = request.client.host if request and request.client else "unknown"
74
-
75
- # ✅ Enforce usage limit
76
- if ENABLE_IP_LIMIT:
77
- if ip_usage.get(ip, 0) >= MAX_USES:
78
- return f"⚠️ This IP has reached the maximum limit of {MAX_USES} uses. Please contact the admin."
79
- ip_usage[ip] = ip_usage.get(ip, 0) + 1
80
- save_usage(ip_usage)
81
 
82
  if not product_name or not product_name.strip():
83
- return "Please enter a valid product or campaign name."
84
-
85
- prompt = f"Create a detailed marketing plan for the product or campaign named '{product_name}'.\n"
86
- prompt += "Only include the sections explicitly requested below. Do not add any extra sections or general information.\n\n"
87
 
 
88
  sections = []
89
-
90
  if do_competitors:
91
- sections.append("Competitor Names: List the major competitor names relevant to this product or campaign.")
92
  if do_competitor_analysis:
93
- sections.append("Competitor Analysis Insights: Provide a detailed analysis of competitors, including strengths and weaknesses.")
94
  if do_message:
95
- sections.append("Campaign Messages: Provide key marketing messages tailored for social media, and specify which message is best suited for which channel (e.g., Facebook, Twitter, LinkedIn, Instagram). Format each message like this:\n\"<message>\" (Best suited for <channel>)")
96
  if do_launch_time:
97
- sections.append("Best Launch Time: Recommend the optimal timing for campaign launch.")
98
  if do_seo:
99
- sections.append("SEO Keywords: Suggest relevant SEO keywords for the campaign.")
100
  if do_budget_roi:
101
- sections.append("Budget and ROI: Estimate campaign budget and expected return on investment.")
102
 
103
  if not sections:
104
- return "Please select at least one option to generate the marketing plan."
105
 
106
- prompt += "Respond with the following sections only, using exactly these section headers:\n"
107
  for s in sections:
108
- prompt += f"- {s.split(':')[0]}\n"
109
 
110
  prompt += "\nRespond with each section clearly headed as shown above."
111
 
@@ -114,16 +135,39 @@ def run_agent(request: gr.Request,
114
  except Exception as e:
115
  response = f"Error calling API: {e}"
116
 
117
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  # -------------------------------
120
  # Social Media Launch
121
  # -------------------------------
122
- def social_channel_launch(channel, hashtags, checkbox_value):
 
 
 
 
123
  if checkbox_value:
124
- return f"✅ Launched campaign on {channel} with hashtags: {hashtags}"
125
  else:
126
- return ""
127
 
128
  # -------------------------------
129
  # UI
@@ -145,8 +189,10 @@ with gr.Blocks() as demo:
145
  do_seo = gr.Checkbox(label="SEO Keywords", value=False)
146
  do_budget_roi = gr.Checkbox(label="Campaign Budget Estimation & ROI", value=False)
147
 
148
- run_btn = gr.Button("🚀 Generate", interactive=False)
 
149
 
 
150
  output_box = gr.Markdown()
151
 
152
  social_channels = gr.Dropdown(
@@ -189,32 +235,76 @@ with gr.Blocks() as demo:
189
  do_budget_roi],
190
  outputs=run_btn)
191
 
192
- run_btn.click(fn=run_agent,
193
- inputs=[product_name,
194
- do_competitors,
195
- do_message,
196
- do_competitor_analysis,
197
- do_launch_time,
198
- do_seo,
199
- do_budget_roi],
200
- outputs=output_box)
201
-
202
- def generate_hashtags(product_name_val):
203
- if not product_name_val or not product_name_val.strip():
204
- return "Please enter a product or campaign name first."
205
- prompt = f"Generate relevant social media hashtags for the product or campaign named '{product_name_val}'. List hashtags separated by commas."
206
- try:
207
- tags = groq_api_chat(prompt)
208
- return tags
209
- except Exception as e:
210
- return f"Error generating hashtags: {e}"
211
-
212
- generate_hashtags_btn.click(fn=generate_hashtags,
213
- inputs=product_name,
214
- outputs=hashtags)
215
-
216
- launch_btn.click(fn=social_channel_launch,
217
- inputs=[social_channels, hashtags, launch_checkbox],
218
- outputs=launch_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
 
220
  demo.launch()
 
9
  # ===============================
10
  # 🔧 Usage Limit Configuration
11
  # ===============================
12
+ ENABLE_IP_LIMIT = True # 👈 Set to False (or comment) to disable IP limiting
13
+ MAX_USES = 3 # 👈 Maximum allowed actions per IP
14
+ USAGE_FILE = "ip_usage.json" # 👈 Persistent storage file (same folder as this app)
15
  # ===============================
16
 
17
  if not GROQ_API_KEY:
 
41
  # -------------------------------
42
  # API Call
43
  # -------------------------------
44
+ def groq_api_chat(prompt, model="llama3-8b-8192", max_tokens=800):
45
  headers = {
46
  "Authorization": f"Bearer {GROQ_API_KEY}",
47
  "Content-Type": "application/json"
 
59
  return data["choices"][0]["message"]["content"].strip()
60
 
61
  # -------------------------------
62
+ # Helper: return updates to freeze/unfreeze all inputs
63
+ # -------------------------------
64
+ def updates_freeze(disable: bool):
65
+ upd = gr.update(interactive=False) if disable else gr.update()
66
+ return [upd, upd, upd, # run_btn, generate_hashtags_btn, launch_btn
67
+ upd, # product_name
68
+ upd, upd, upd, # checkboxes row 1
69
+ upd, upd, upd, # checkboxes row 2
70
+ upd, # social_channels
71
+ upd, # hashtags textbox
72
+ upd] # launch_checkbox
73
+
74
+ # -------------------------------
75
+ # Shared IP enforcement
76
+ # -------------------------------
77
+ def enforce_limit(request: gr.Request):
78
+ ip = request.client.host if request and request.client else "unknown"
79
+ if ENABLE_IP_LIMIT:
80
+ used = ip_usage.get(ip, 0)
81
+ remaining = max(0, MAX_USES - used)
82
+ if used >= MAX_USES:
83
+ return ip, False, (f"⚠️ This IP has reached the maximum limit of {MAX_USES} uses. "
84
+ "All controls are disabled. Contact the admin."), f"Remaining attempts: 0/{MAX_USES}"
85
+ ip_usage[ip] = used + 1
86
+ save_usage(ip_usage)
87
+ remaining = MAX_USES - ip_usage[ip]
88
+ return ip, True, None, f"Remaining attempts: {remaining}/{MAX_USES}"
89
+ return ip, True, None, "Unlimited attempts"
90
+
91
+ # -------------------------------
92
+ # Main Agent (Generate)
93
  # -------------------------------
94
  def run_agent(request: gr.Request,
95
  product_name,
 
100
  do_seo,
101
  do_budget_roi):
102
 
103
+ ip, allowed, msg, counter = enforce_limit(request)
104
+ if not allowed:
105
+ return (msg, counter, *updates_freeze(disable=True))
 
 
 
 
 
106
 
107
  if not product_name or not product_name.strip():
108
+ return ("Please enter a valid product or campaign name.", counter, *updates_freeze(disable=False))
 
 
 
109
 
110
+ prompt = f"Create a detailed marketing plan for '{product_name}'.\nOnly include these sections:\n"
111
  sections = []
 
112
  if do_competitors:
113
+ sections.append("Competitor Names")
114
  if do_competitor_analysis:
115
+ sections.append("Competitor Analysis Insights")
116
  if do_message:
117
+ sections.append("Campaign Messages")
118
  if do_launch_time:
119
+ sections.append("Best Launch Time")
120
  if do_seo:
121
+ sections.append("SEO Keywords")
122
  if do_budget_roi:
123
+ sections.append("Budget and ROI")
124
 
125
  if not sections:
126
+ return ("Please select at least one option to generate the marketing plan.", counter, *updates_freeze(disable=False))
127
 
 
128
  for s in sections:
129
+ prompt += f"- {s}\n"
130
 
131
  prompt += "\nRespond with each section clearly headed as shown above."
132
 
 
135
  except Exception as e:
136
  response = f"Error calling API: {e}"
137
 
138
+ return (response, counter, *updates_freeze(disable=False))
139
+
140
+ # -------------------------------
141
+ # Hashtag Generator
142
+ # -------------------------------
143
+ def generate_hashtags(request: gr.Request, product_name_val):
144
+ ip, allowed, msg, counter = enforce_limit(request)
145
+ if not allowed:
146
+ return (msg, counter, *updates_freeze(disable=True))
147
+
148
+ if not product_name_val or not product_name_val.strip():
149
+ return ("Please enter a product or campaign name first.", counter, *updates_freeze(disable=False))
150
+
151
+ prompt = f"Generate relevant social media hashtags for the product or campaign named '{product_name_val}'. List hashtags separated by commas."
152
+ try:
153
+ tags = groq_api_chat(prompt)
154
+ except Exception as e:
155
+ tags = f"Error generating hashtags: {e}"
156
+
157
+ return (tags, counter, *updates_freeze(disable=False))
158
 
159
  # -------------------------------
160
  # Social Media Launch
161
  # -------------------------------
162
+ def social_channel_launch(request: gr.Request, channel, hashtags, checkbox_value):
163
+ ip, allowed, msg, counter = enforce_limit(request)
164
+ if not allowed:
165
+ return (msg, counter, *updates_freeze(disable=True))
166
+
167
  if checkbox_value:
168
+ return (f"✅ Launched campaign on {channel} with hashtags: {hashtags}", counter, *updates_freeze(disable=False))
169
  else:
170
+ return ("", counter, *updates_freeze(disable=False))
171
 
172
  # -------------------------------
173
  # UI
 
189
  do_seo = gr.Checkbox(label="SEO Keywords", value=False)
190
  do_budget_roi = gr.Checkbox(label="Campaign Budget Estimation & ROI", value=False)
191
 
192
+ # Counter
193
+ counter_box = gr.Markdown("Remaining attempts: ∞")
194
 
195
+ run_btn = gr.Button("🚀 Generate", interactive=False)
196
  output_box = gr.Markdown()
197
 
198
  social_channels = gr.Dropdown(
 
235
  do_budget_roi],
236
  outputs=run_btn)
237
 
238
+ run_btn.click(
239
+ fn=run_agent,
240
+ inputs=[product_name,
241
+ do_competitors,
242
+ do_message,
243
+ do_competitor_analysis,
244
+ do_launch_time,
245
+ do_seo,
246
+ do_budget_roi],
247
+ outputs=[
248
+ output_box,
249
+ counter_box,
250
+ run_btn,
251
+ generate_hashtags_btn,
252
+ launch_btn,
253
+ product_name,
254
+ do_competitors,
255
+ do_message,
256
+ do_competitor_analysis,
257
+ do_launch_time,
258
+ do_seo,
259
+ do_budget_roi,
260
+ social_channels,
261
+ hashtags,
262
+ launch_checkbox,
263
+ ],
264
+ )
265
+
266
+ generate_hashtags_btn.click(
267
+ fn=generate_hashtags,
268
+ inputs=[product_name],
269
+ outputs=[
270
+ hashtags,
271
+ counter_box,
272
+ run_btn,
273
+ generate_hashtags_btn,
274
+ launch_btn,
275
+ product_name,
276
+ do_competitors,
277
+ do_message,
278
+ do_competitor_analysis,
279
+ do_launch_time,
280
+ do_seo,
281
+ do_budget_roi,
282
+ social_channels,
283
+ hashtags,
284
+ launch_checkbox,
285
+ ],
286
+ )
287
+
288
+ launch_btn.click(
289
+ fn=social_channel_launch,
290
+ inputs=[social_channels, hashtags, launch_checkbox],
291
+ outputs=[
292
+ launch_output,
293
+ counter_box,
294
+ run_btn,
295
+ generate_hashtags_btn,
296
+ launch_btn,
297
+ product_name,
298
+ do_competitors,
299
+ do_message,
300
+ do_competitor_analysis,
301
+ do_launch_time,
302
+ do_seo,
303
+ do_budget_roi,
304
+ social_channels,
305
+ hashtags,
306
+ launch_checkbox,
307
+ ],
308
+ )
309
 
310
  demo.launch()