Spaces:
Sleeping
Sleeping
Download app.py from abhidgp1978/NameCraftAI: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/spaces/abhidgp1978/NameCraftAI/resolve/main/app.py
- Command line
-
hf download hf://spaces/abhidgp1978/NameCraftAI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/abhidgp1978/NameCraftAI/resolve/main/app.py
13.4 kB
| 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() |