Noo88ear commited on
Commit
9e6ba7a
·
verified ·
1 Parent(s): 6a586cf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -290
app.py CHANGED
@@ -1,321 +1,73 @@
1
  import gradio as gr
2
- import os
3
- from PIL import Image, ImageDraw, ImageFont, ImageStat
4
- import io
5
- import json
6
  import random
7
 
8
- # Simple function to create a working demo image
9
  def create_image(prompt, style):
10
- """Create a simple colored image that actually works"""
 
 
 
11
 
12
- colors = {
13
- "Professional": "#3B82F6",
14
- "Creative": "#8B5CF6",
15
- "Minimalist": "#6B7280",
16
- "Corporate": "#1E40AF",
17
- "Modern": "#059669"
18
- }
19
-
20
- color_hex = colors.get(style, "#3B82F6")
21
- color_rgb = tuple(int(color_hex[i:i+2], 16) for i in (1, 4, 7))
22
-
23
- # Create image
24
- img = Image.new('RGB', (512, 512), color_rgb)
25
  draw = ImageDraw.Draw(img)
26
  font = ImageFont.load_default()
27
-
28
- # Use textlength for better positioning
29
- title = "Marketing Image"
30
- title_width = draw.textlength(title, font=font)
31
- draw.text(((512 - title_width) // 2, 200), title, fill="white", font=font)
32
-
33
- style_text = f"{style} Style"
34
- style_width = draw.textlength(style_text, font=font)
35
- draw.text(((512 - style_width) // 2, 230), style_text, fill="white", font=font)
36
-
37
- prompt_short = prompt[:40] + "..." if len(prompt) > 40 else prompt
38
- prompt_width = draw.textlength(prompt_short, font=font)
39
- draw.text(((512 - prompt_width) // 2, 260), prompt_short, fill=(200, 200, 200), font=font)
40
 
41
  return img
42
 
43
- def generate_variants(prompt, style):
44
- """Generate 3 variants of the same prompt"""
45
- variants = []
46
- for i in range(3):
47
- # Create slight variations by adding random elements
48
- variant_img = create_image(prompt, style)
49
- variants.append(variant_img)
50
- return variants
51
-
52
  def generate_and_review(prompt, style):
53
- """Main function that generates image and provides review"""
54
-
55
  if not prompt.strip():
56
- return None, "⚠️ **Please enter a description for your marketing image.**"
57
-
58
- # Generate image
59
- image = create_image(prompt, style)
60
 
61
- # Create review with Markdown formatting
62
  word_count = len(prompt.split())
 
63
 
64
- if word_count > 15:
65
- quality = "Excellent"
66
- quality_emoji = "🌟"
67
- elif word_count > 8:
68
- quality = "Good"
69
- quality_emoji = "✅"
70
- else:
71
- quality = "Basic"
72
- quality_emoji = "⚠️"
73
-
74
- review_md = f"""### 🤖 Agent Workflow Results
75
-
76
- **Agent1 (Generator):** Created *{style.lower()}* style marketing image
77
- **Agent2 (Reviewer):** Analyzed image content and quality
78
-
79
- ---
80
-
81
- ### 📊 Analysis Summary
82
 
83
- **{quality_emoji} Prompt Quality:** {quality} ({word_count} words)
84
- **🎨 Style Applied:** {style}
85
- **📈 Marketing Suitability:** Good for *{style.lower()}* marketing campaigns
86
- **🎯 Brand Alignment:** Professional marketing ready
87
 
88
- ---
 
 
89
 
90
- ### 💡 Recommendations
91
-
92
- - Image successfully generated in **{style.lower()}** style
93
- - Consider adding more specific visual descriptors for enhanced results
94
- - Ready for marketing use across digital platforms
95
-
96
- **✅ Status:** Workflow Complete | **🚀 Ready to Deploy**
97
- """
98
 
99
- return image, review_md
100
 
101
- def detect_brand_tone(uploaded_img):
102
- """Analyze uploaded image for brand tone"""
103
- if uploaded_img is None:
104
- return ""
105
 
106
- try:
107
- stat = ImageStat.Stat(uploaded_img.convert("RGB"))
108
- avg_brightness = sum(stat.mean) / 3
 
 
 
 
 
 
 
 
 
 
109
 
110
- if avg_brightness > 180:
111
- tone = "Creative"
112
- tone_emoji = "🎨"
113
- description = "Bright, vibrant imagery suggests creative, innovative branding"
114
- elif avg_brightness > 100:
115
- tone = "Professional"
116
- tone_emoji = "💼"
117
- description = "Balanced lighting indicates professional, corporate tone"
118
- else:
119
- tone = "Corporate"
120
- tone_emoji = "🏢"
121
- description = "Darker tones suggest serious, authoritative branding"
122
-
123
- return f"""### 🎯 Brand Tone Analysis
124
-
125
- **{tone_emoji} Detected Tone:** {tone}
126
- **📊 Average Brightness:** {int(avg_brightness)}/255
127
- **🧠 Analysis:** {description}
128
-
129
- **💡 Suggestion:** Use "{tone}" style for consistent brand messaging in your next generation!
130
- """
131
- except Exception as e:
132
- return f"⚠️ **Error analyzing image:** {str(e)}"
133
-
134
- def image_to_bytes(img):
135
- """Convert PIL image to bytes for download"""
136
- if img is None:
137
- return None
138
- buf = io.BytesIO()
139
- img.save(buf, format='PNG')
140
- buf.seek(0)
141
- return buf
142
-
143
- # Create improved Blocks interface
144
- with gr.Blocks(
145
- title="Marketing Image Generator - AI Agent System",
146
- theme=gr.themes.Soft(primary_hue="blue", secondary_hue="purple")
147
- ) as demo:
148
-
149
- # Header with better styling
150
- gr.Markdown("""
151
- # 🎨 AI Marketing Image Generator
152
- ## Agent1 generates → Agent2 reviews → ✅ Professional results
153
- *Multi-agent system for creating professional marketing visuals*
154
- """)
155
-
156
- with gr.Tab("🚀 Single Image Generation"):
157
- with gr.Row():
158
- # Input column with better spacing
159
- with gr.Column(scale=1):
160
- gr.Markdown("### 📝 Describe Your Marketing Visual")
161
-
162
- prompt = gr.Textbox(
163
- label="Marketing Image Description",
164
- placeholder="e.g. A professional team meeting in a modern office with natural lighting",
165
- lines=3,
166
- max_lines=5,
167
- elem_classes=["prompt-input"]
168
- )
169
-
170
- style = gr.Dropdown(
171
- choices=["Professional", "Creative", "Minimalist", "Corporate", "Modern"],
172
- value="Professional",
173
- label="Brand Style"
174
- )
175
-
176
- generate_btn = gr.Button(
177
- "🚀 Generate Marketing Image",
178
- variant="primary",
179
- size="lg"
180
- )
181
-
182
- # Output column with side-by-side layout
183
- with gr.Column(scale=2):
184
- with gr.Row():
185
- image_output = gr.Image(
186
- label="Generated Marketing Image",
187
- type="pil",
188
- show_label=True,
189
- height=400,
190
- show_download_button=True
191
- )
192
-
193
- review_output = gr.Markdown(
194
- label="AI Agent Review",
195
- value="*Generate an image to see detailed AI analysis*",
196
- elem_classes=["review-panel"]
197
- )
198
-
199
- # Examples with better formatting
200
- gr.Markdown("### 💡 Example Prompts")
201
- gr.Examples(
202
- examples=[
203
- ["Professional team collaboration with laptops in bright office", "Professional"],
204
- ["Clean minimalist product showcase on white background", "Minimalist"],
205
- ["Friendly customer service representative with headset", "Corporate"],
206
- ["Modern workspace with plants and natural lighting", "Modern"],
207
- ["Creative brainstorming session with colorful sticky notes", "Creative"]
208
- ],
209
- inputs=[prompt, style],
210
- label="Click any example to try it out!"
211
- )
212
-
213
- with gr.Tab("🎭 Multi-Variant Generator"):
214
- gr.Markdown("### Generate 3 variants and pick the best one")
215
-
216
- with gr.Row():
217
- with gr.Column(scale=1):
218
- multi_prompt = gr.Textbox(
219
- label="Marketing Image Description",
220
- placeholder="Describe your marketing visual...",
221
- lines=2,
222
- max_lines=4
223
- )
224
- multi_style = gr.Dropdown(
225
- choices=["Professional", "Creative", "Minimalist", "Corporate", "Modern"],
226
- value="Professional",
227
- label="Brand Style"
228
- )
229
- variants_btn = gr.Button("Generate 3 Variants", variant="primary")
230
-
231
- with gr.Column(scale=2):
232
- selected_image = gr.Image(label="✅ Selected Image", type="pil")
233
- download_file = gr.File(label="📥 Download Selected Image")
234
-
235
- # Variant display
236
- with gr.Row():
237
- variant1 = gr.Image(label="Variant 1", interactive=True, height=200)
238
- variant2 = gr.Image(label="Variant 2", interactive=True, height=200)
239
- variant3 = gr.Image(label="Variant 3", interactive=True, height=200)
240
-
241
- variant_review = gr.Markdown()
242
-
243
- # Handle variant generation and selection
244
- def handle_variant_selection(img, prompt):
245
- if img is None:
246
- return None, None, ""
247
-
248
- download_bytes = image_to_bytes(img)
249
- word_count = len(prompt.split())
250
- quality = "Excellent" if word_count > 15 else "Good" if word_count > 8 else "Basic"
251
-
252
- review = f"""### ✅ Variant Selected
253
-
254
- **Image Quality:** {quality}
255
- **Prompt Analysis:** {word_count} descriptive words
256
- **Status:** Ready for download and use
257
-
258
- 💡 **Tip:** This variant is optimized for professional marketing use.
259
- """
260
- return img, download_bytes, review
261
-
262
- variants_btn.click(
263
- fn=lambda p, s: generate_variants(p, s),
264
- inputs=[multi_prompt, multi_style],
265
- outputs=[variant1, variant2, variant3]
266
- )
267
-
268
- # Connect variant selection
269
- variant1.select(
270
- fn=lambda img: handle_variant_selection(img, multi_prompt.value if 'multi_prompt' in locals() else ""),
271
- inputs=[variant1],
272
- outputs=[selected_image, download_file, variant_review]
273
- )
274
- variant2.select(
275
- fn=lambda img: handle_variant_selection(img, multi_prompt.value if 'multi_prompt' in locals() else ""),
276
- inputs=[variant2],
277
- outputs=[selected_image, download_file, variant_review]
278
- )
279
- variant3.select(
280
- fn=lambda img: handle_variant_selection(img, multi_prompt.value if 'multi_prompt' in locals() else ""),
281
- inputs=[variant3],
282
- outputs=[selected_image, download_file, variant_review]
283
- )
284
 
285
- with gr.Tab("🔍 Brand Tone Analyzer"):
286
- gr.Markdown("### Upload an existing image to analyze its brand tone")
287
-
288
- with gr.Row():
289
- with gr.Column(scale=1):
290
- uploaded_img = gr.Image(
291
- type="pil",
292
- label="Upload Marketing Image for Analysis",
293
- height=300
294
- )
295
-
296
- with gr.Column(scale=1):
297
- tone_analysis = gr.Markdown(
298
- value="*Upload an image to see brand tone analysis*"
299
- )
300
-
301
- uploaded_img.change(
302
- fn=detect_brand_tone,
303
- inputs=uploaded_img,
304
- outputs=tone_analysis
305
- )
306
-
307
- # Connect main generation function
308
  generate_btn.click(
309
  fn=generate_and_review,
310
  inputs=[prompt, style],
311
  outputs=[image_output, review_output]
312
  )
313
-
314
- # Footer
315
- gr.Markdown("""
316
- ---
317
- **🤖 AI Marketing Agent System** | Agent1: Image Generation | Agent2: Quality Review | Built with Gradio
318
- """)
319
 
320
  if __name__ == "__main__":
321
  demo.launch()
 
1
  import gradio as gr
2
+ from PIL import Image, ImageDraw, ImageFont
 
 
 
3
  import random
4
 
 
5
  def create_image(prompt, style):
6
+ """Create a demo image"""
7
+ colors = {"Professional": "#3B82F6", "Creative": "#8B5CF6", "Minimalist": "#6B7280", "Corporate": "#1E40AF", "Modern": "#059669"}
8
+ color = colors.get(style, "#3B82F6")
9
+ rgb = tuple(int(color[i:i+2], 16) for i in (1, 4, 7))
10
 
11
+ img = Image.new("RGB", (512, 512), rgb)
 
 
 
 
 
 
 
 
 
 
 
 
12
  draw = ImageDraw.Draw(img)
13
  font = ImageFont.load_default()
14
+
15
+ draw.text((50, 200), "Marketing Image", fill="white", font=font)
16
+ draw.text((50, 230), f"{style} Style", fill="white", font=font)
17
+ draw.text((50, 260), prompt[:35] + "..." if len(prompt) > 35 else prompt, fill=(200, 200, 200), font=font)
 
 
 
 
 
 
 
 
 
18
 
19
  return img
20
 
 
 
 
 
 
 
 
 
 
21
  def generate_and_review(prompt, style):
22
+ """Generate image and review"""
 
23
  if not prompt.strip():
24
+ return None, "Please enter a prompt"
 
 
 
25
 
26
+ image = create_image(prompt, style)
27
  word_count = len(prompt.split())
28
+ quality = "Excellent" if word_count > 15 else "Good" if word_count > 8 else "Basic"
29
 
30
+ review = f"""**Agent Review Complete**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+ Agent1: Generated {style.lower()} marketing image
33
+ Agent2: Quality analysis complete
 
 
34
 
35
+ Prompt Quality: {quality} ({word_count} words)
36
+ Style: {style}
37
+ Status: Ready for use
38
 
39
+ Recommendation: {f"Great detail level!" if word_count > 15 else "Consider adding more descriptive details"}"""
 
 
 
 
 
 
 
40
 
41
+ return image, review
42
 
43
+ # Create simple interface
44
+ with gr.Blocks(title="AI Marketing Generator") as demo:
45
+ gr.Markdown("# 🎨 AI Marketing Image Generator")
46
+ gr.Markdown("Agent1 creates → Agent2 reviews → Professional results")
47
 
48
+ with gr.Row():
49
+ with gr.Column():
50
+ prompt = gr.Textbox(
51
+ label="Marketing Image Description",
52
+ placeholder="A professional team meeting in a modern office",
53
+ lines=3
54
+ )
55
+ style = gr.Dropdown(
56
+ choices=["Professional", "Creative", "Minimalist", "Corporate", "Modern"],
57
+ value="Professional",
58
+ label="Brand Style"
59
+ )
60
+ generate_btn = gr.Button("Generate Image", variant="primary")
61
 
62
+ with gr.Column():
63
+ image_output = gr.Image(label="Generated Image")
64
+ review_output = gr.Markdown(value="Click Generate to see review")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  generate_btn.click(
67
  fn=generate_and_review,
68
  inputs=[prompt, style],
69
  outputs=[image_output, review_output]
70
  )
 
 
 
 
 
 
71
 
72
  if __name__ == "__main__":
73
  demo.launch()