File size: 13,371 Bytes
1a1a604
 
 
02b5914
1a1a604
96139ba
 
52f1557
23c5eb8
 
 
ab8f116
 
 
23c5eb8
976c4aa
 
 
96139ba
02b5914
976c4aa
02b5914
 
976c4aa
 
 
 
 
 
02b5914
 
 
976c4aa
 
 
 
 
02b5914
976c4aa
02b5914
 
976c4aa
02b5914
976c4aa
1a1a604
 
 
 
486c775
1a1a604
486c775
 
742276d
 
1a1a604
486c775
1a1a604
486c775
 
f1d0143
23c5eb8
742276d
23c5eb8
742276d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486c775
742276d
 
 
 
 
 
486c775
742276d
 
 
 
 
 
 
 
 
 
23c5eb8
742276d
e13a65f
742276d
486c775
 
742276d
486c775
742276d
486c775
742276d
23c5eb8
2240425
742276d
 
 
 
 
 
 
 
 
 
 
2240425
742276d
 
 
 
 
 
e13a65f
742276d
 
 
 
 
2240425
486c775
 
742276d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486c775
 
 
742276d
 
 
976c4aa
742276d
976c4aa
742276d
 
 
486c775
742276d
 
 
 
 
 
 
 
 
 
e13a65f
742276d
 
 
 
 
 
 
2240425
486c775
2240425
742276d
486c775
742276d
 
 
 
 
 
 
486c775
742276d
 
 
 
e13a65f
742276d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ed3aa0
23c5eb8
742276d
 
2240425
742276d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90cf83d
742276d
 
 
 
 
 
 
23c5eb8
486c775
742276d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90cf83d
23c5eb8
 
742276d
 
 
 
 
 
 
23c5eb8
 
742276d
 
 
 
 
 
 
 
 
90cf83d
23c5eb8
90cf83d
742276d
 
 
 
 
 
 
23c5eb8
 
0ed3aa0
742276d
 
 
 
 
 
 
 
23c5eb8
742276d
 
23c5eb8
 
742276d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90cf83d
6dbd1cf
23c5eb8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import gradio as gr
import os
import requests
import json

GROQ_API_KEY = os.getenv("GROQ_API_KEY")
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"

# ===============================
# πŸ”§ Usage Limit Configuration
# ===============================
ENABLE_IP_LIMIT = True        # πŸ‘ˆ Comment/Set False to disable IP limiting
MAX_USES = 1                  # πŸ‘ˆ Maximum allowed actions per IP
USAGE_FILE = "ip_usage.json"  # πŸ‘ˆ Persistent storage file
# ===============================

if not GROQ_API_KEY:
    raise ValueError("GROQ_API_KEY not found. Please add it in the Space Secrets.")

# -------------------------------
# Persistent usage tracking
# -------------------------------
def load_usage():
    if os.path.exists(USAGE_FILE):
        try:
            with open(USAGE_FILE, "r") as f:
                return json.load(f)
        except Exception:
            return {}
    return {}

def save_usage(data):
    try:
        with open(USAGE_FILE, "w") as f:
            json.dump(data, f)
    except Exception:
        pass

ip_usage = load_usage()

# -------------------------------
# API Call
# -------------------------------
def groq_api_chat(prompt, model="llama3-8b-8192", max_tokens=800):
    headers = {
        "Authorization": f"Bearer {GROQ_API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": model,
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": max_tokens,
        "temperature": 0.6,
        "top_p": 0.9,
    }
    response = requests.post(GROQ_API_URL, headers=headers, json=payload)
    response.raise_for_status()
    data = response.json()
    return data["choices"][0]["message"]["content"].strip()

# -------------------------------
# Helpers
# -------------------------------
def get_component_updates(interactive_state: bool):
    """Returns a tuple of gr.update objects for all interactive components."""
    upd = gr.update(interactive=interactive_state)
    return (
        upd, upd, upd,  # run_btn, generate_hashtags_btn, launch_btn
        upd,           # product_name
        upd, upd, upd, upd, upd, upd,  # 6 checkboxes
        upd,           # social_channels
        upd,           # hashtags textbox
        upd            # launch_checkbox
    )

def enforce_limit(request: gr.Request):
    ip = request.client.host if request and request.client else "unknown"
    if ENABLE_IP_LIMIT:
        used = ip_usage.get(ip, 0)
        
        if used >= MAX_USES:
            return ip, False, (
                f"⚠️ This IP has reached the maximum limit of {MAX_USES} uses. "
                "All controls are disabled. Contact the admin."
            ), f"Remaining attempts: 0/{MAX_USES}"

        used += 1
        ip_usage[ip] = used
        save_usage(ip_usage)

        remaining = MAX_USES - used
        return ip, True, None, f"Remaining attempts: {remaining}/{MAX_USES}"
    
    return ip, True, None, "Unlimited attempts"

# -------------------------------
# Check IP status on load
# -------------------------------
def check_ip_on_load(request: gr.Request):
    ip = request.client.host if request and request.client else "unknown"
    used = ip_usage.get(ip, 0)
    if ENABLE_IP_LIMIT and used >= MAX_USES:
        msg = f"⚠️ This IP has reached the maximum limit of {MAX_USES} uses. All controls are disabled. Contact the admin."
        return (
            f"Remaining attempts: 0/{MAX_USES}",
            gr.update(value=f"{msg}", visible=True),
            *get_component_updates(False)
        )
    else:
        remaining = MAX_USES - used if ENABLE_IP_LIMIT else "∞"
        return (
            f"Remaining attempts: {remaining}/{MAX_USES}" if ENABLE_IP_LIMIT else "Unlimited attempts",
            gr.update(visible=False),
            *get_component_updates(True)
        )

# -------------------------------
# Main Agent (Generate)
# -------------------------------
def run_agent(request: gr.Request,
              product_name,
              do_competitors,
              do_message,
              do_competitor_analysis,
              do_launch_time,
              do_seo,
              do_budget_roi):

    ip, allowed, msg, counter = enforce_limit(request)
    
    if not allowed:
        return (
            "⚠️ Limit reached. No more responses.",
            counter,
            gr.update(value=f"{msg}", visible=True),
            *get_component_updates(False)
        )
    
    if not product_name or not product_name.strip():
        return ("Please enter a valid product or campaign name.", counter, gr.update(visible=False), *get_component_updates(True))

    prompt = f"Create a detailed marketing plan for '{product_name}'.\nOnly include these sections:\n"
    sections = []
    if do_competitors:
        sections.append("Competitor Names")
    if do_competitor_analysis:
        sections.append("Competitor Analysis Insights")
    if do_message:
        sections.append("Campaign Messages")
    if do_launch_time:
        sections.append("Best Launch Time")
    if do_seo:
        sections.append("SEO Keywords")
    if do_budget_roi:
        sections.append("Budget and ROI")

    if not sections:
        return ("Please select at least one option to generate the marketing plan.", counter, gr.update(visible=False), *get_component_updates(True))

    for s in sections:
        prompt += f"- {s}\n"

    prompt += "\nRespond with each section clearly headed as shown above."

    try:
        response = groq_api_chat(prompt, max_tokens=800)
    except Exception as e:
        response = f"Error calling API: {e}"

    return (response, counter, gr.update(visible=False), *get_component_updates(True))

# -------------------------------
# Hashtag Generator
# -------------------------------
def generate_hashtags(request: gr.Request, product_name_val):
    ip, allowed, msg, counter = enforce_limit(request)

    if not allowed:
        return (
            "⚠️ Limit reached. No more hashtags.",
            counter,
            gr.update(value=f"{msg}", visible=True),
            *get_component_updates(False)
        )

    if not product_name_val or not product_name_val.strip():
        return ("Please enter a product or campaign name first.", counter, gr.update(visible=False), *get_component_updates(True))

    prompt = f"Generate relevant social media hashtags for the product or campaign named '{product_name_val}'. List hashtags separated by commas."
    try:
        tags = groq_api_chat(prompt)
    except Exception as e:
        tags = f"Error generating hashtags: {e}"

    return (tags, counter, gr.update(visible=False), *get_component_updates(True))

# -------------------------------
# Social Media Launch
# -------------------------------
def social_channel_launch(request: gr.Request, channel, hashtags, checkbox_value):
    ip, allowed, msg, counter = enforce_limit(request)
    
    if not allowed:
        return (
            "⚠️ Limit reached. Launch blocked.",
            counter,
            gr.update(value=f"{msg}", visible=True),
            *get_component_updates(False)
        )

    if checkbox_value:
        return (f"βœ… Launched campaign on {channel} with hashtags: {hashtags}", counter, gr.update(visible=False), *get_component_updates(True))
    else:
        return ("", counter, gr.update(visible=False), *get_component_updates(True))

# -------------------------------
# UI
# -------------------------------
with gr.Blocks() as demo:
    # Persistent warning banner
    limit_banner = gr.Markdown("", visible=False)

    product_name = gr.Textbox(label="Product or Campaign Name", placeholder="Enter product or campaign name here...")

    with gr.Row():
        goals_vision = gr.Checkbox(label="Goals & Vision (disabled for now)", value=False, interactive=False)
        target_audience = gr.Checkbox(label="Target Audience (disabled for now)", value=False, interactive=False)

    with gr.Row():
        do_competitors = gr.Checkbox(label="Competitor Names", value=False)
        do_message = gr.Checkbox(label="Campaign Messages & Social Media", value=False)
    with gr.Row():
        do_competitor_analysis = gr.Checkbox(label="Competitor Analysis Insights", value=False)
        do_launch_time = gr.Checkbox(label="Best Campaign Launch Time", value=False)
    with gr.Row():
        do_seo = gr.Checkbox(label="SEO Keywords", value=False)
        do_budget_roi = gr.Checkbox(label="Campaign Budget Estimation & ROI", value=False)

    # Counter
    counter_box = gr.Markdown("Remaining attempts: ∞")

    run_btn = gr.Button("πŸš€ Generate", interactive=False)
    output_box = gr.Markdown()

    social_channels = gr.Dropdown(
        label="Select Social Media Channel to Launch",
        choices=["Twitter", "Facebook", "Instagram", "LinkedIn"],
        value="Twitter",
        interactive=True,
        multiselect=False
    )

    hashtags = gr.Textbox(label="Generated Hashtags", interactive=False)
    generate_hashtags_btn = gr.Button("Generate Hashtags")

    launch_checkbox = gr.Checkbox(label="Confirm Launch Campaign", value=False)
    launch_btn = gr.Button("πŸš€ Launch Campaign")

    launch_output = gr.Markdown()

    # Enable Generate dynamically
    def enable_generate_button(product_name_val, *checkbox_values):
        product_entered = bool(product_name_val and product_name_val.strip())
        any_checked = any(checkbox_values)
        return gr.update(interactive=product_entered and any_checked)

    inputs_for_enable = [product_name,
                         do_competitors,
                         do_message,
                         do_competitor_analysis,
                         do_launch_time,
                         do_seo,
                         do_budget_roi]

    for comp in inputs_for_enable:
        comp.change(fn=enable_generate_button,
                    inputs=[product_name,
                            do_competitors,
                            do_message,
                            do_competitor_analysis,
                            do_launch_time,
                            do_seo,
                            do_budget_roi],
                    outputs=run_btn)
    
    # NEW Chained Callbacks to prevent race condition
    # ---------------------------------------------
    run_btn.click(
        fn=lambda: get_component_updates(False),
        inputs=[],
        outputs=[
            run_btn, generate_hashtags_btn, launch_btn, product_name,
            do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
            social_channels, hashtags, launch_checkbox
        ]
    ).then(
        fn=run_agent,
        inputs=[
            product_name,
            do_competitors,
            do_message,
            do_competitor_analysis,
            do_launch_time,
            do_seo,
            do_budget_roi
        ],
        outputs=[
            output_box,
            counter_box,
            limit_banner,
            run_btn, generate_hashtags_btn, launch_btn, product_name,
            do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
            social_channels, hashtags, launch_checkbox
        ],
    )

    generate_hashtags_btn.click(
        fn=lambda: get_component_updates(False),
        inputs=[],
        outputs=[
            run_btn, generate_hashtags_btn, launch_btn, product_name,
            do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
            social_channels, hashtags, launch_checkbox
        ]
    ).then(
        fn=generate_hashtags,
        inputs=[product_name],
        outputs=[
            hashtags,
            counter_box,
            limit_banner,
            run_btn, generate_hashtags_btn, launch_btn, product_name,
            do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
            social_channels, hashtags, launch_checkbox
        ],
    )

    launch_btn.click(
        fn=lambda: get_component_updates(False),
        inputs=[],
        outputs=[
            run_btn, generate_hashtags_btn, launch_btn, product_name,
            do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
            social_channels, hashtags, launch_checkbox
        ]
    ).then(
        fn=social_channel_launch,
        inputs=[social_channels, hashtags, launch_checkbox],
        outputs=[
            launch_output,
            counter_box,
            limit_banner,
            run_btn, generate_hashtags_btn, launch_btn, product_name,
            do_competitors, do_message, do_competitor_analysis, do_launch_time, do_seo, do_budget_roi,
            social_channels, hashtags, launch_checkbox
        ],
    )
    # ---------------------------------------------

    demo.load(
        fn=check_ip_on_load,
        inputs=None,
        outputs=[
            counter_box,
            limit_banner,
            run_btn,
            generate_hashtags_btn,
            launch_btn,
            product_name,
            do_competitors,
            do_message,
            do_competitor_analysis,
            do_launch_time,
            do_seo,
            do_budget_roi,
            social_channels,
            hashtags,
            launch_checkbox,
        ],
    )

demo.launch()