Update app.py
Browse files
app.py
CHANGED
|
@@ -1,213 +1,219 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
-
from
|
| 4 |
import os
|
| 5 |
|
| 6 |
-
# --- 1.
|
| 7 |
|
| 8 |
-
# Get your secret key from Hugging Face Space Secrets
|
| 9 |
NEBIUS_API_KEY = os.environ.get("NEBIUS_API_KEY")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
# --- UPDATE THESE VALUES ---
|
| 12 |
-
# Make sure to include "https://" and the "/v1/" path
|
| 13 |
-
NEBIUS_BASE_URL = "https://api.tokenfactory.nebius.com/v1/" # Use the URL from your Nebius dashboard
|
| 14 |
-
TEXT_MODEL = "meta-llama/Llama-3.3-70B-Instruct" # Use a text model from your dashboard
|
| 15 |
-
IMAGE_MODEL = "black-forest-labs/flux-dev" # Use an image model from your dashboard
|
| 16 |
-
|
| 17 |
-
# Check if the API key is set
|
| 18 |
if not NEBIUS_API_KEY:
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
|
| 22 |
-
#
|
| 23 |
nebius_client = OpenAI(
|
| 24 |
api_key=NEBIUS_API_KEY,
|
| 25 |
base_url=NEBIUS_BASE_URL,
|
| 26 |
)
|
| 27 |
|
| 28 |
-
# --- 2. DEFINE
|
| 29 |
|
| 30 |
-
def
|
| 31 |
"""
|
| 32 |
-
Tool
|
| 33 |
-
Takes a customizable system message.
|
| 34 |
"""
|
| 35 |
-
print(f"
|
| 36 |
try:
|
| 37 |
-
|
| 38 |
messages=[
|
| 39 |
{"role": "system", "content": system_message},
|
| 40 |
{"role": "user", "content": prompt},
|
| 41 |
],
|
| 42 |
model=TEXT_MODEL,
|
| 43 |
-
max_tokens=
|
|
|
|
| 44 |
)
|
| 45 |
-
return
|
| 46 |
except Exception as e:
|
| 47 |
-
print(f"
|
| 48 |
-
raise gr.Error(f"
|
| 49 |
|
| 50 |
-
def
|
| 51 |
-
"""
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
| 53 |
try:
|
| 54 |
response = nebius_client.images.generate(
|
| 55 |
model=IMAGE_MODEL,
|
| 56 |
prompt=prompt,
|
| 57 |
n=1,
|
| 58 |
-
size="1024x1024",
|
| 59 |
)
|
| 60 |
-
#
|
| 61 |
return response.data[0].url
|
| 62 |
except Exception as e:
|
| 63 |
-
print(f"
|
| 64 |
-
raise gr.Error(f"
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
# --- 3.
|
| 68 |
|
| 69 |
-
def
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
# 1
|
| 72 |
-
progress(0, desc="
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
{"step": 3, "action": "generate_palette_from_colors"},
|
| 78 |
-
{"step": 4, "action": "generate_social_copy", "prompt": f"Write 3 short, catchy social media posts (for X/Twitter) announcing a new {business_type} called '{company_name}'. The vibe is {style}."}
|
| 79 |
-
]
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
log_message += f"- Step 2: Generate logo from colors\n"
|
| 84 |
-
log_message += f"- Step 3: Generate palette image from colors\n"
|
| 85 |
-
log_message += f"- Step 4: Generate social media copy\n"
|
| 86 |
|
| 87 |
-
|
|
|
|
| 88 |
|
| 89 |
-
# 2
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
system_prompt_colors = "You are a concise branding expert. Only output a single, comma-separated list of 5 colors. Do not add any other text, labels, or explanations."
|
| 94 |
-
color_palette_text = call_text_gen_tool(plan[0]["prompt"], system_prompt_colors)
|
| 95 |
-
results["color_text"] = color_palette_text.strip().strip('.') # Clean up the output
|
| 96 |
-
log_message += f"Step 1 Complete. Colors decided: {results['color_text']}\n"
|
| 97 |
|
| 98 |
-
|
| 99 |
-
progress(0.4, desc="Executing Step 2: Calling Nebius Image Tool (Logo)...")
|
| 100 |
-
logo_prompt = f"A {style} logo for a {business_type} named '{company_name}'. Use *only* the following colors: {results['color_text']}. The logo should be an abstract icon or geometric mark. NO TEXT."
|
| 101 |
-
results["logo_url"] = call_image_gen_tool(logo_prompt)
|
| 102 |
-
log_message += f"Step 2 Complete. Logo URL acquired.\n"
|
| 103 |
|
| 104 |
-
#
|
| 105 |
-
progress(0.
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
-
|
| 111 |
-
progress(0.9, desc="Executing Step 4: Calling Nebius Text Tool (Copy)...")
|
| 112 |
-
system_prompt_kit = "You are a helpful branding assistant. Be creative and concise."
|
| 113 |
-
results["copy_text"] = call_text_gen_tool(plan[3]["prompt"], system_prompt_kit)
|
| 114 |
-
log_message += "Step 4 Complete. Copy generated.\n"
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
| 129 |
messages.append({"role": "user", "content": user_msg})
|
| 130 |
-
messages.append({"role": "assistant", "content":
|
|
|
|
|
|
|
| 131 |
messages.append({"role": "user", "content": message})
|
| 132 |
-
|
| 133 |
try:
|
| 134 |
response = nebius_client.chat.completions.create(
|
| 135 |
messages=messages,
|
| 136 |
model=TEXT_MODEL,
|
| 137 |
max_tokens=300,
|
| 138 |
)
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
history.append((message, bot_message))
|
| 142 |
-
|
| 143 |
return history, ""
|
| 144 |
-
|
| 145 |
except Exception as e:
|
| 146 |
-
|
| 147 |
-
# Return an error message in the chat
|
| 148 |
-
history.append((message, f"Sorry, I ran into an error: {e}"))
|
| 149 |
return history, ""
|
| 150 |
|
|
|
|
| 151 |
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
gr.Markdown(
|
| 156 |
-
"""
|
| 157 |
-
# 🤖 AutoBrand Studio
|
| 158 |
-
Powered by **Hugging Face** and **Nebius Token Factory**.
|
| 159 |
-
This agent autonomously plans and calls Nebius APIs for text and image generation to build a brand kit.
|
| 160 |
-
"""
|
| 161 |
-
)
|
| 162 |
|
| 163 |
with gr.Row():
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
with gr.Tabs():
|
| 171 |
-
# --- TAB 1: BRAND KIT ---
|
| 172 |
-
with gr.TabItem("Brand Kit Results"):
|
| 173 |
-
with gr.Row():
|
| 174 |
-
logo_output = gr.Image(label="Generated Logo (from Nebius)", height=400)
|
| 175 |
-
color_palette_output = gr.Image(label="Generated Color Palette (from Nebius)", height=400)
|
| 176 |
-
copy_output = gr.Textbox(label="Generated Social Media Copy (from Nebius)", lines=8, interactive=True)
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
)
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
# Click handler for the new chatbot
|
| 199 |
-
chat_btn.click(
|
| 200 |
-
fn=chat_with_brand_agent,
|
| 201 |
-
inputs=[chat_msg, chatbot],
|
| 202 |
-
outputs=[chatbot, chat_msg] # Clears chat_msg
|
| 203 |
-
)
|
| 204 |
-
|
| 205 |
-
# Submit handler for the new chatbot (pressing Enter)
|
| 206 |
-
chat_msg.submit(
|
| 207 |
-
fn=chat_with_brand_agent,
|
| 208 |
-
inputs=[chat_msg, chatbot],
|
| 209 |
-
outputs=[chatbot, chat_msg] # Clears chat_msg
|
| 210 |
-
)
|
| 211 |
|
| 212 |
if __name__ == "__main__":
|
| 213 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from openai import OpenAI
|
| 3 |
+
from duckduckgo_search import DDGS
|
| 4 |
import os
|
| 5 |
|
| 6 |
+
# --- 1. CONFIGURATION ---
|
| 7 |
|
|
|
|
| 8 |
NEBIUS_API_KEY = os.environ.get("NEBIUS_API_KEY")
|
| 9 |
+
# Ensure the URL is correct for the OpenAI-compatible endpoint
|
| 10 |
+
NEBIUS_BASE_URL = "https://api.studio.nebius.ai/v1/"
|
| 11 |
+
TEXT_MODEL = "meta-llama/Llama-3.3-70B-Instruct"
|
| 12 |
+
IMAGE_MODEL = "black-forest-labs/flux-schnell"
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
if not NEBIUS_API_KEY:
|
| 15 |
+
# Check for the key but don't crash immediately to allow UI to load with error message
|
| 16 |
+
print("WARNING: API Key is not set.")
|
| 17 |
|
| 18 |
+
# Initialize the client
|
| 19 |
nebius_client = OpenAI(
|
| 20 |
api_key=NEBIUS_API_KEY,
|
| 21 |
base_url=NEBIUS_BASE_URL,
|
| 22 |
)
|
| 23 |
|
| 24 |
+
# --- 2. DEFINE LOCAL TOOLS ---
|
| 25 |
|
| 26 |
+
def tool_generate_text(prompt: str, system_message: str = "You are a helpful assistant.") -> str:
|
| 27 |
"""
|
| 28 |
+
Tool: Generates text using the LLM.
|
|
|
|
| 29 |
"""
|
| 30 |
+
print(f"📝 Text Tool calling API: {prompt[:40]}...")
|
| 31 |
try:
|
| 32 |
+
response = nebius_client.chat.completions.create(
|
| 33 |
messages=[
|
| 34 |
{"role": "system", "content": system_message},
|
| 35 |
{"role": "user", "content": prompt},
|
| 36 |
],
|
| 37 |
model=TEXT_MODEL,
|
| 38 |
+
max_tokens=512,
|
| 39 |
+
temperature=0.7,
|
| 40 |
)
|
| 41 |
+
return response.choices[0].message.content
|
| 42 |
except Exception as e:
|
| 43 |
+
print(f"❌ Text Tool Error: {e}")
|
| 44 |
+
raise gr.Error(f"Text Generation Failed: {e}")
|
| 45 |
|
| 46 |
+
def tool_generate_image(prompt: str) -> str:
|
| 47 |
+
"""
|
| 48 |
+
Tool: Generates an image using the Image API.
|
| 49 |
+
Returns a URL to the image.
|
| 50 |
+
"""
|
| 51 |
+
print(f"🎨 Image Tool calling API: {prompt[:40]}...")
|
| 52 |
try:
|
| 53 |
response = nebius_client.images.generate(
|
| 54 |
model=IMAGE_MODEL,
|
| 55 |
prompt=prompt,
|
| 56 |
n=1,
|
| 57 |
+
size="1024x1024", # Standard size for Flux
|
| 58 |
)
|
| 59 |
+
# Return the URL
|
| 60 |
return response.data[0].url
|
| 61 |
except Exception as e:
|
| 62 |
+
print(f"❌ Image Tool Error: {e}")
|
| 63 |
+
raise gr.Error(f"Image Generation Failed: {e}")
|
| 64 |
|
| 65 |
+
def tool_web_search(query: str) -> str:
|
| 66 |
+
"""
|
| 67 |
+
Tool: Searches the web using DuckDuckGo.
|
| 68 |
+
Returns a summarized string of results.
|
| 69 |
+
"""
|
| 70 |
+
print(f"🔍 Search Tool searching for: {query}...")
|
| 71 |
+
try:
|
| 72 |
+
results = DDGS().text(query, max_results=3)
|
| 73 |
+
if not results:
|
| 74 |
+
return "No relevant search results found."
|
| 75 |
+
|
| 76 |
+
formatted_results = ""
|
| 77 |
+
for result in results:
|
| 78 |
+
formatted_results += f"- {result['title']}: {result['body']}\n"
|
| 79 |
+
|
| 80 |
+
return formatted_results
|
| 81 |
+
except Exception as e:
|
| 82 |
+
print(f"❌ Search Tool Error: {e}")
|
| 83 |
+
return "Error performing web search."
|
| 84 |
|
| 85 |
+
# --- 3. AGENT LOGIC (THE BRAIN) ---
|
| 86 |
|
| 87 |
+
def run_autonomous_agent(company_name, business_type, style, progress=gr.Progress()):
|
| 88 |
+
"""
|
| 89 |
+
This is the 'Agent' that plans and executes the workflow.
|
| 90 |
+
"""
|
| 91 |
|
| 92 |
+
# --- PHASE 1: PLANNING & COLOR ---
|
| 93 |
+
progress(0.1, desc="Step 1: Planning & Color Palette...")
|
| 94 |
|
| 95 |
+
# Prompt to get a structured color palette from the text model
|
| 96 |
+
color_prompt = f"Create a distinct, 5-color palette for a {business_type} named '{company_name}' with a {style} style. Return ONLY a comma-separated list of color names/hex codes. No intro/outro."
|
| 97 |
+
colors_text = tool_generate_text(color_prompt, "You are a design expert. Output only the requested list.")
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
# Clean up the response
|
| 100 |
+
colors_text = colors_text.strip().strip('.')
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
log = f"✅ Plan Started for {company_name}\n"
|
| 103 |
+
log += f"🎨 Palette Decided: {colors_text}\n"
|
| 104 |
|
| 105 |
+
# --- PHASE 2: LOGO GENERATION ---
|
| 106 |
+
progress(0.3, desc="Step 2: Generating Logo...")
|
| 107 |
|
| 108 |
+
logo_prompt = f"A {style} logo for a {business_type} named '{company_name}'. Use these colors: {colors_text}. Minimalist, vector style, white background. NO TEXT."
|
| 109 |
+
logo_url = tool_generate_image(logo_prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
+
log += f"🖼️ Logo Generated.\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
# --- PHASE 3: BRAND ASSET GENERATION ---
|
| 114 |
+
progress(0.5, desc="Step 3: Generating Brand Asset...")
|
| 115 |
+
|
| 116 |
+
asset_prompt = f"A sophisticated color palette display for a brand. Show swatches of these colors: {colors_text}. Clean, modern layout, high quality, {style} aesthetic. No text."
|
| 117 |
+
asset_url = tool_generate_image(asset_prompt)
|
| 118 |
+
|
| 119 |
+
log += f"🖼️ Brand Asset Generated.\n"
|
| 120 |
+
|
| 121 |
+
# --- PHASE 4: MARKET RESEARCH ---
|
| 122 |
+
progress(0.7, desc="Step 4: Researching Market Trends...")
|
| 123 |
+
|
| 124 |
+
search_query = f"current social media marketing trends for {style} {business_type} 2024 2025"
|
| 125 |
+
search_data = tool_web_search(search_query)
|
| 126 |
|
| 127 |
+
log += f"🔍 Market Trends Found: {search_data[:100]}...\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
# --- PHASE 5: COPYWRITING ---
|
| 130 |
+
progress(0.9, desc="Step 5: Writing Content...")
|
| 131 |
+
|
| 132 |
+
copy_system_msg = "You are a professional social media manager."
|
| 133 |
+
copy_prompt = f"""
|
| 134 |
+
Write 3 engaging social media posts (Twitter/X style) for a new {business_type} called '{company_name}'.
|
| 135 |
+
|
| 136 |
+
Brand Vibe: {style}
|
| 137 |
+
|
| 138 |
+
Integrate these real-time market insights:
|
| 139 |
+
{search_data}
|
| 140 |
+
"""
|
| 141 |
|
| 142 |
+
social_copy = tool_generate_text(copy_prompt, copy_system_msg)
|
| 143 |
+
|
| 144 |
+
log += f"✍️ Copy Written.\n✅ Agent Execution Complete."
|
| 145 |
+
|
| 146 |
+
return logo_url, asset_url, social_copy, log
|
| 147 |
+
|
| 148 |
+
# --- 4. CHATBOT LOGIC ---
|
| 149 |
|
| 150 |
+
def chat_response(message, history):
|
| 151 |
+
"""
|
| 152 |
+
A simple chat interface that remembers context.
|
| 153 |
+
"""
|
| 154 |
+
system_message = "You are a creative brand consultant. Help the user brainstorm ideas."
|
| 155 |
|
| 156 |
+
messages = [{"role": "system", "content": system_message}]
|
| 157 |
+
|
| 158 |
+
# Add history
|
| 159 |
+
for user_msg, bot_msg in history:
|
| 160 |
messages.append({"role": "user", "content": user_msg})
|
| 161 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
| 162 |
+
|
| 163 |
+
# Add current message
|
| 164 |
messages.append({"role": "user", "content": message})
|
| 165 |
+
|
| 166 |
try:
|
| 167 |
response = nebius_client.chat.completions.create(
|
| 168 |
messages=messages,
|
| 169 |
model=TEXT_MODEL,
|
| 170 |
max_tokens=300,
|
| 171 |
)
|
| 172 |
+
bot_reply = response.choices[0].message.content
|
| 173 |
+
history.append((message, bot_reply))
|
|
|
|
|
|
|
| 174 |
return history, ""
|
|
|
|
| 175 |
except Exception as e:
|
| 176 |
+
history.append((message, f"Error: {e}"))
|
|
|
|
|
|
|
| 177 |
return history, ""
|
| 178 |
|
| 179 |
+
# --- 5. UI CONSTRUCTION ---
|
| 180 |
|
| 181 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="AutoBrand Studio") as demo:
|
| 182 |
+
gr.Markdown("# 🤖 AutoBrand Studio")
|
| 183 |
+
gr.Markdown("An Autonomous Agent powered by **AI Models** & **DuckDuckGo**. Generates a full brand kit with real-time market research.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
with gr.Row():
|
| 186 |
+
with gr.Column(scale=1):
|
| 187 |
+
company_input = gr.Textbox(label="Company Name", value="Lumina")
|
| 188 |
+
type_input = gr.Textbox(label="Business Type", value="Organic Candle Shop")
|
| 189 |
+
style_input = gr.Textbox(label="Style / Vibe", value="Minimalist, calming, sage green tones")
|
| 190 |
+
generate_btn = gr.Button("✨ Create Brand Kit", variant="primary")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
+
with gr.Column(scale=2):
|
| 193 |
+
with gr.Tabs():
|
| 194 |
+
with gr.Tab("🎨 Brand Assets"):
|
| 195 |
+
with gr.Row():
|
| 196 |
+
out_logo = gr.Image(label="Logo Concept")
|
| 197 |
+
out_asset = gr.Image(label="Color Palette / Mood")
|
| 198 |
+
out_copy = gr.Textbox(label="Social Media Strategy (Data-Driven)", lines=10)
|
| 199 |
+
|
| 200 |
+
with gr.Tab("⚙️ Agent Logs"):
|
| 201 |
+
out_log = gr.Textbox(label="Execution Log", lines=15)
|
| 202 |
+
|
| 203 |
+
with gr.Tab("💬 Consultant"):
|
| 204 |
+
chatbot = gr.Chatbot(label="Brand Consultant", height=400)
|
| 205 |
+
chat_input = gr.Textbox(label="Ask about your brand...")
|
| 206 |
+
chat_btn = gr.Button("Send")
|
| 207 |
+
|
| 208 |
+
# Event Handlers
|
| 209 |
+
generate_btn.click(
|
| 210 |
+
fn=run_autonomous_agent,
|
| 211 |
+
inputs=[company_input, type_input, style_input],
|
| 212 |
+
outputs=[out_logo, out_asset, out_copy, out_log]
|
| 213 |
)
|
| 214 |
|
| 215 |
+
chat_btn.click(fn=chat_response, inputs=[chat_input, chatbot], outputs=[chatbot, chat_input])
|
| 216 |
+
chat_input.submit(fn=chat_response, inputs=[chat_input, chatbot], outputs=[chatbot, chat_input])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
if __name__ == "__main__":
|
| 219 |
demo.launch()
|