File size: 7,466 Bytes
da3d35e 8fc4f50 da3d35e 44fd7c4 da3d35e d9d9089 8fc4f50 d9d9089 da3d35e d9d9089 44fd7c4 da3d35e 44fd7c4 b0b7bfe d9d9089 44fd7c4 b0b7bfe d9d9089 570fcfb b0b7bfe d9d9089 b0b7bfe 8fc4f50 b0b7bfe 8fc4f50 b0b7bfe 8fc4f50 b0b7bfe 8fc4f50 d9d9089 8fc4f50 d9d9089 8fc4f50 b0b7bfe 8fc4f50 b0b7bfe 8fc4f50 d9d9089 8fc4f50 b0b7bfe 8fc4f50 b0b7bfe 8fc4f50 b0b7bfe 8fc4f50 b0b7bfe 8fc4f50 b0b7bfe 8fc4f50 b0b7bfe d9d9089 8fc4f50 d9d9089 da3d35e 8fc4f50 44fd7c4 8fc4f50 |
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 |
"""
Marketing Image Generator with AI Review
Clean, simple Gradio interface
"""
import gradio as gr
import json
import os
import logging
from PIL import Image, ImageDraw, ImageFont
import io
import hashlib
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Google AI setup
google_auth_configured = False
GOOGLE_SERVICE_ACCOUNT_JSON = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON", "")
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "")
# Try to configure Google AI
try:
import google.generativeai as genai
from google import genai as genai_sdk
if GOOGLE_SERVICE_ACCOUNT_JSON:
credentials_dict = json.loads(GOOGLE_SERVICE_ACCOUNT_JSON)
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_info(credentials_dict)
genai.configure(credentials=credentials)
google_auth_configured = True
logger.info("β
Google Cloud configured")
elif GOOGLE_API_KEY:
genai.configure(api_key=GOOGLE_API_KEY)
google_auth_configured = True
logger.info("β
Google API configured")
except Exception as e:
logger.error(f"Google setup failed: {e}")
def create_demo_image(prompt, style, width=512, height=512):
"""Create demo image"""
colors = {
"Professional": (59, 130, 246),
"Creative": (139, 92, 246),
"Minimalist": (107, 114, 128),
"Corporate": (30, 64, 175),
"Modern": (5, 150, 105)
}
color = colors.get(style, (59, 130, 246))
img = Image.new('RGB', (width, height), color)
draw = ImageDraw.Draw(img)
try:
font = ImageFont.load_default()
title = "Marketing Image"
bbox = draw.textbbox((0, 0), title, font=font)
text_width = bbox[2] - bbox[0]
x = (width - text_width) // 2
y = height // 2 - 20
draw.text((x, y), title, fill="white", font=font)
style_text = f"{style} Style"
bbox2 = draw.textbbox((0, 0), style_text, font=font)
text_width2 = bbox2[2] - bbox2[0]
x2 = (width - text_width2) // 2
draw.text((x2, y + 30), style_text, fill="white", font=font)
except:
pass
return img
def generate_with_google_ai(prompt, style):
"""Generate with Google Imagen"""
if not google_auth_configured:
return None
try:
enhanced_prompt = f"{prompt}, {style.lower()} style, professional marketing image, high quality, 4K"
if GOOGLE_SERVICE_ACCOUNT_JSON:
client = genai_sdk.Client()
else:
client = genai_sdk.Client(api_key=GOOGLE_API_KEY)
result = client.models.generate_images(
model="imagen-3.0-generate-002",
prompt=enhanced_prompt,
config={"number_of_images": 1, "output_mime_type": "image/png"}
)
if result and hasattr(result, 'generated_images') and result.generated_images:
img_data = result.generated_images[0]
if hasattr(img_data, 'image') and hasattr(img_data.image, 'image_bytes'):
return Image.open(io.BytesIO(img_data.image.image_bytes))
except Exception as e:
logger.warning(f"Google Imagen failed: {e}")
return None
def review_with_ai(image, prompt):
"""Review with Gemini"""
if not google_auth_configured:
return "Demo mode - Add Google credentials for AI review"
try:
model = genai.GenerativeModel('gemini-2.0-flash-exp')
review_prompt = f"Review this marketing image from: '{prompt}'. Rate 1-10 and give brief feedback. Keep under 100 words."
response = model.generate_content([review_prompt, image])
return response.text[:200]
except Exception as e:
logger.warning(f"AI review failed: {e}")
return "AI review unavailable"
def generate_marketing_image(prompt, style):
"""Main function - Agent1 generates, Agent2 reviews"""
if not prompt or not prompt.strip():
return None, "Please enter a prompt"
logger.info(f"π€ Agent1: Generating image for '{prompt}' in {style} style")
# Agent1: Try Google Imagen
if google_auth_configured:
real_image = generate_with_google_ai(prompt, style)
if real_image:
logger.info("β
Agent1: Real image generated with Google Imagen")
logger.info("π Agent2: Starting AI review...")
review = review_with_ai(real_image, prompt)
logger.info("β
Agent2: Review completed")
return real_image, f"β
Google Imagen + AI Review\n\n{review}"
# Agent1: Fallback to demo
logger.info("π€ Agent1: Creating demo image (fallback)")
demo_image = create_demo_image(prompt, style)
# Agent2: Basic review
logger.info("π Agent2: Basic review (fallback)")
word_count = len(prompt.split())
quality = "Good" if word_count > 10 else "Basic"
review = f"Demo Mode Review:\n\nPrompt Quality: {quality} ({word_count} words)\nStyle: {style}\nRecommendation: Add Google credentials for full AI generation and review."
return demo_image, review
# Interface configuration
title = "π¨ Marketing Image Generator with AI Review"
description = """
<p style='text-align: center'>
<b>Agent-Based Marketing Image Generation</b><br>
Agent1 creates images with Google Imagen3 β Agent2 reviews with Gemini Vision
</p>
"""
article = """
<p style='text-align: center'>
<b>How it Works:</b><br>
1. Agent1 (Generator) enhances your prompt and creates professional marketing images<br>
2. Agent2 (Reviewer) analyzes the image for quality and marketing effectiveness<br>
3. Get instant feedback and download high-quality results
</p>
"""
examples = [
["Professional team collaboration in modern office", "Professional"],
["Clean product showcase on white background", "Minimalist"],
["Customer service representative with headset", "Corporate"],
["Modern workspace with laptop and plants", "Modern"],
["Creative marketing team brainstorming session", "Creative"]
]
def main():
# Status message
if google_auth_configured:
status_msg = "β
Google AI Connected - Full Agent Pipeline Active"
else:
status_msg = "β οΈ Demo Mode - Add GOOGLE_SERVICE_ACCOUNT_JSON for full AI capabilities"
full_description = f"""
{description}
<p style='text-align: center; color: {"green" if google_auth_configured else "orange"}'>
<b>Status:</b> {status_msg}
</p>
"""
iface = gr.Interface(
fn=generate_marketing_image,
inputs=[
gr.Textbox(
label="Marketing Image Description",
placeholder="A professional team meeting in a modern office space...",
lines=3
),
gr.Dropdown(
choices=["Professional", "Creative", "Minimalist", "Corporate", "Modern"],
value="Professional",
label="Style"
)
],
outputs=[
gr.Image(label="Generated Marketing Image", height=400),
gr.Textbox(label="AI Agent Review", lines=5)
],
title=title,
description=full_description,
article=article,
examples=examples,
theme="soft",
allow_flagging="never"
)
iface.launch()
if __name__ == '__main__':
main() |