omarash2016 commited on
Commit
45b4b82
·
verified ·
1 Parent(s): 782d2aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -143
app.py CHANGED
@@ -1,213 +1,219 @@
1
  import gradio as gr
2
- import httpx # Included in requirements
3
- from openai import OpenAI # We use the OpenAI client to talk to Nebius!
4
  import os
5
 
6
- # --- 1. CONFIGURE YOUR CLIENTS ---
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
- # This will show a nice error in the Gradio app if the secret isn't set
20
- raise gr.Error("NEBIUS_API_KEY is not set. Please add it to your Hugging Face Space secrets.")
21
 
22
- # Set up the single Nebius client (it's OpenAI-compatible)
23
  nebius_client = OpenAI(
24
  api_key=NEBIUS_API_KEY,
25
  base_url=NEBIUS_BASE_URL,
26
  )
27
 
28
- # --- 2. DEFINE YOUR AGENT'S TOOLS ---
29
 
30
- def call_text_gen_tool(prompt: str, system_message: str) -> str:
31
  """
32
- Tool 1: Calls the Nebius LLM for text generation.
33
- Takes a customizable system message.
34
  """
35
- print(f"Calling Text Tool: {prompt[:30]}...")
36
  try:
37
- chat_completion = nebius_client.chat.completions.create(
38
  messages=[
39
  {"role": "system", "content": system_message},
40
  {"role": "user", "content": prompt},
41
  ],
42
  model=TEXT_MODEL,
43
- max_tokens=256,
 
44
  )
45
- return chat_completion.choices[0].message.content
46
  except Exception as e:
47
- print(f"Error calling Nebius LLM: {e}")
48
- raise gr.Error(f"Nebius Text API Error: {e}")
49
 
50
- def call_image_gen_tool(prompt: str) -> str:
51
- """Tool 2: Calls the Nebius Image API for image generation."""
52
- print(f"Calling Image Tool: {prompt[:30]}...")
 
 
 
53
  try:
54
  response = nebius_client.images.generate(
55
  model=IMAGE_MODEL,
56
  prompt=prompt,
57
  n=1,
58
- size="1024x1024",
59
  )
60
- # The API returns a URL to the generated image
61
  return response.data[0].url
62
  except Exception as e:
63
- print(f"Error calling Nebius Image API: {e}")
64
- raise gr.Error(f"Nebius Image API Error: {e}")
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
- # --- 3. DEFINE THE AUTONOMOUS AGENT LOGIC ---
68
 
69
- def run_brand_agent_plan(company_name, business_type, style, progress=gr.Progress()):
 
 
 
70
 
71
- # 1. PLANNING
72
- progress(0, desc="Agent is creating a plan...")
73
 
74
- plan = [
75
- {"step": 1, "action": "generate_color_text", "prompt": f"Generate a 5-color palette for a {business_type} with a {style} vibe. List the colors as a simple, comma-separated string, e.g., 'Deep espresso brown, warm cream, rustic bronze, slate grey, soft olive green'."},
76
- {"step": 2, "action": "generate_logo_from_colors"},
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
- log_message = "Agent Plan Created:\n"
82
- log_message += f"- Step 1: Generate color palette (as text)\n"
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
- results = {}
 
88
 
89
- # 2. EXECUTION
 
90
 
91
- # Step 1: Generate Color Palette (as Text)
92
- progress(0.2, desc="Executing Step 1: Calling Nebius Text Tool (for Colors)...")
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
- # Step 2: Generate Logo (using colors from Step 1)
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
- # Step 3: Generate Color Palette Image (using colors from Step 1)
105
- progress(0.7, desc="Executing Step 3: Calling Nebius Image Tool (Color Palette)...")
106
- palette_prompt = f"A refined color palette presentation. Show 5 distinct, harmonious colors in a modern, clean layout. The colors are: {results['color_text']}. No text."
107
- results["palette_url"] = call_image_gen_tool(palette_prompt)
108
- log_message += f"Step 3 Complete. Color Palette URL acquired.\n"
 
 
 
 
 
 
 
 
109
 
110
- # Step 4: Generate Social Copy
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
- progress(1.0, desc="Agent Execution Complete!")
117
- log_message += "Plan executed successfully."
 
 
 
 
 
 
 
 
 
 
118
 
119
- # 3. RESULT
120
- return results["logo_url"], results["palette_url"], results["copy_text"], log_message
 
 
 
 
 
121
 
122
- # --- 4. CHATBOT FUNCTION ---
123
- def chat_with_brand_agent(message, history):
124
- system_prompt_chat = "You are a friendly and creative branding expert. A user is asking for ideas for their new brand. Give them suggestions, ask clarifying questions, and help them brainstorm."
 
 
125
 
126
- # Build the message list from history
127
- messages = [{"role": "system", "content": system_prompt_chat}]
128
- for user_msg, assistant_msg in history:
 
129
  messages.append({"role": "user", "content": user_msg})
130
- messages.append({"role": "assistant", "content": assistant_msg})
 
 
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
- bot_message = response.choices[0].message.content
140
-
141
- history.append((message, bot_message))
142
-
143
  return history, ""
144
-
145
  except Exception as e:
146
- print(f"Error in chat: {e}")
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
- # --- 5. CREATE THE GRADIO UI ---
153
-
154
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
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
- company_input = gr.Textbox(label="Company Name", value="Aura")
165
- business_type_input = gr.Textbox(label="Business Type / Industry", value="Skincare Brand")
166
- style_input = gr.Textbox(label="Style / Vibe", value="modern, minimalist, clean")
167
-
168
- submit_btn = gr.Button("🚀 Generate Brand Kit")
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
- # --- TAB 2: AGENT LOG ---
179
- with gr.TabItem("Agent Log"):
180
- log_output = gr.Textbox(label="Agent Plan & Execution Log", lines=10, interactive=False)
181
-
182
- # --- TAB 3: CHATBOT ---
183
- with gr.TabItem("Brand Chatbot"):
184
- chatbot = gr.Chatbot(label="Brand Brainstormer")
185
- chat_msg = gr.Textbox(label="Ask for ideas...", placeholder="e.g., 'What are some good names for my new skincare brand?'")
186
- chat_btn = gr.Button("Send")
187
-
188
- # --- Wire up the UI ---
189
-
190
- submit_btn.click(
191
- fn=run_brand_agent_plan,
192
- inputs=[company_input, business_type_input, style_input],
193
- outputs=[logo_output, color_palette_output, copy_output, log_output]
 
 
 
 
 
194
  )
195
 
196
- # *** UPDATED: Simplified the click/submit handlers ***
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()