Spaces:
Sleeping
Sleeping
2 variation for normal banner
Browse files- app/services/banner_service.py +255 -254
app/services/banner_service.py
CHANGED
|
@@ -1,255 +1,256 @@
|
|
| 1 |
-
from io import BytesIO
|
| 2 |
-
from typing import Dict
|
| 3 |
-
|
| 4 |
-
from google import genai
|
| 5 |
-
from google.genai import types
|
| 6 |
-
from PIL import Image, ImageEnhance, ImageOps, ImageFilter
|
| 7 |
-
import logging
|
| 8 |
-
from app.config.settings import settings
|
| 9 |
-
from app.utils.reach_upload import upload_to_reach
|
| 10 |
-
from app.utils.name_generator import generate_brand_name
|
| 11 |
-
import math
|
| 12 |
-
|
| 13 |
-
logger = logging.getLogger(__name__)
|
| 14 |
-
logging.basicConfig(level=logging.INFO)
|
| 15 |
-
|
| 16 |
-
def get_banner_prompts(brand_details: str, primary_color: str) -> Dict[str, str]:
|
| 17 |
-
device_prompts = {
|
| 18 |
-
'desktop': f'''Generate a realistic image which includes real people and
|
| 19 |
-
The image must show essence of the brand:
|
| 20 |
-
|
| 21 |
-
{brand_details}
|
| 22 |
-
|
| 23 |
-
Exclude the use of color {primary_color} in the palette. Do not Include any text, typographic or Alphanumeric Elements.''',
|
| 24 |
-
'ipad': f'''Generate a realistic image which includes real people and
|
| 25 |
-
The image must show essence of the brand:
|
| 26 |
-
|
| 27 |
-
{brand_details}
|
| 28 |
-
|
| 29 |
-
Exclude the use of color {primary_color} in the palette. Do not Include any text, typographic or Alphanumeric Elements.''',
|
| 30 |
-
'mobile': f'''Generate a realistic image which includes real people and
|
| 31 |
-
The image must show essence of the brand:
|
| 32 |
-
|
| 33 |
-
{brand_details}
|
| 34 |
-
|
| 35 |
-
Exclude the use of color {primary_color} in the palette. Do not Include any text, typographic or Alphanumeric Elements.''',
|
| 36 |
-
}
|
| 37 |
-
return device_prompts
|
| 38 |
-
|
| 39 |
-
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 40 |
-
"""
|
| 41 |
-
Resize, sharpen, enhance and compress an image to fit a given resolution and file size.
|
| 42 |
-
Optimized for 1024x1024 source images with better quality preservation.
|
| 43 |
-
"""
|
| 44 |
-
img = Image.open(BytesIO(image_data)).convert('RGB')
|
| 45 |
-
original_width, original_height = img.size
|
| 46 |
-
|
| 47 |
-
# Calculate aspect ratios
|
| 48 |
-
original_ratio = original_width / original_height
|
| 49 |
-
target_ratio = target_width / target_height
|
| 50 |
-
|
| 51 |
-
# Step 1: Smart upscaling based on target size relative to source
|
| 52 |
-
# Only upscale if target is significantly larger than source
|
| 53 |
-
upscale_threshold = max(target_width, target_height) / max(original_width, original_height)
|
| 54 |
-
|
| 55 |
-
if upscale_threshold > 1.2: # Only upscale if target is 20% larger
|
| 56 |
-
scale_factor = min(3, math.ceil(upscale_threshold)) # Cap at 3x to avoid excessive processing
|
| 57 |
-
intermediate_width = original_width * scale_factor
|
| 58 |
-
intermediate_height = original_height * scale_factor
|
| 59 |
-
|
| 60 |
-
# Use bicubic for upscaling (better than Lanczos for enlargement)
|
| 61 |
-
working_img = img.resize((intermediate_width, intermediate_height), Image.BICUBIC)
|
| 62 |
-
|
| 63 |
-
# Apply subtle unsharp mask for upscaled images
|
| 64 |
-
working_img = working_img.filter(ImageFilter.UnsharpMask(radius=1.0, percent=120, threshold=3))
|
| 65 |
-
else:
|
| 66 |
-
working_img = img
|
| 67 |
-
|
| 68 |
-
# Step 2: Smart cropping/fitting based on aspect ratio difference
|
| 69 |
-
if abs(original_ratio - target_ratio) > 0.1: # Significant aspect ratio difference
|
| 70 |
-
# Crop to target ratio first, then resize (preserves more detail)
|
| 71 |
-
if original_ratio > target_ratio:
|
| 72 |
-
# Source is wider - crop width
|
| 73 |
-
new_width = int(working_img.height * target_ratio)
|
| 74 |
-
left = (working_img.width - new_width) // 2
|
| 75 |
-
working_img = working_img.crop((left, 0, left + new_width, working_img.height))
|
| 76 |
-
else:
|
| 77 |
-
# Source is taller - crop height
|
| 78 |
-
new_height = int(working_img.width / target_ratio)
|
| 79 |
-
top = (working_img.height - new_height) // 2
|
| 80 |
-
working_img = working_img.crop((0, top, working_img.width, top + new_height))
|
| 81 |
-
|
| 82 |
-
# Step 3: Final resize to target dimensions
|
| 83 |
-
# Use Lanczos for downscaling, bicubic for upscaling
|
| 84 |
-
current_size = max(working_img.size)
|
| 85 |
-
target_size = max(target_width, target_height)
|
| 86 |
-
|
| 87 |
-
if current_size > target_size:
|
| 88 |
-
# Downscaling - use Lanczos
|
| 89 |
-
final_img = working_img.resize((target_width, target_height), Image.LANCZOS)
|
| 90 |
-
else:
|
| 91 |
-
# Upscaling - use bicubic
|
| 92 |
-
final_img = working_img.resize((target_width, target_height), Image.BICUBIC)
|
| 93 |
-
|
| 94 |
-
# Step 4: Conditional enhancement based on target size
|
| 95 |
-
target_pixels = target_width * target_height
|
| 96 |
-
|
| 97 |
-
if target_pixels < 500000: # Small images need more sharpening
|
| 98 |
-
final_img = ImageEnhance.Sharpness(final_img).enhance(1.4)
|
| 99 |
-
final_img = ImageEnhance.Contrast(final_img).enhance(1.15)
|
| 100 |
-
final_img = ImageEnhance.Color(final_img).enhance(1.05)
|
| 101 |
-
elif target_pixels < 1500000: # Medium images
|
| 102 |
-
final_img = ImageEnhance.Sharpness(final_img).enhance(1.2)
|
| 103 |
-
final_img = ImageEnhance.Contrast(final_img).enhance(1.1)
|
| 104 |
-
final_img = ImageEnhance.Color(final_img).enhance(1.08)
|
| 105 |
-
else: # Large images need subtle enhancement
|
| 106 |
-
final_img = ImageEnhance.Sharpness(final_img).enhance(1.1)
|
| 107 |
-
final_img = ImageEnhance.Contrast(final_img).enhance(1.05)
|
| 108 |
-
final_img = ImageEnhance.Color(final_img).enhance(1.03)
|
| 109 |
-
|
| 110 |
-
# Step 5: Intelligent compression with quality optimization
|
| 111 |
-
buffer = BytesIO()
|
| 112 |
-
|
| 113 |
-
# Start with higher quality for better results
|
| 114 |
-
quality = 98
|
| 115 |
-
max_file_size = 500 * 1024 # 500KB
|
| 116 |
-
|
| 117 |
-
while quality >= 75: # Don't go below 75 quality
|
| 118 |
-
buffer.seek(0)
|
| 119 |
-
buffer.truncate()
|
| 120 |
-
|
| 121 |
-
# Adjust subsampling based on quality
|
| 122 |
-
if quality >= 95:
|
| 123 |
-
subsampling = 0 # No chroma subsampling for highest quality
|
| 124 |
-
elif quality >= 85:
|
| 125 |
-
subsampling = 1 # Moderate chroma subsampling
|
| 126 |
-
else:
|
| 127 |
-
subsampling = 2 # Standard chroma subsampling
|
| 128 |
-
|
| 129 |
-
final_img.save(
|
| 130 |
-
buffer,
|
| 131 |
-
format='JPEG',
|
| 132 |
-
quality=quality,
|
| 133 |
-
optimize=True,
|
| 134 |
-
progressive=True,
|
| 135 |
-
subsampling=subsampling
|
| 136 |
-
)
|
| 137 |
-
|
| 138 |
-
current_size = buffer.tell()
|
| 139 |
-
|
| 140 |
-
# If we're within size limit or quality is getting too low, stop
|
| 141 |
-
if current_size <= max_file_size or quality <= 80:
|
| 142 |
-
break
|
| 143 |
-
|
| 144 |
-
# Adjust quality reduction based on how far over we are
|
| 145 |
-
overage_ratio = current_size / max_file_size
|
| 146 |
-
if overage_ratio > 2:
|
| 147 |
-
quality -= 8 # Aggressive reduction if way over
|
| 148 |
-
elif overage_ratio > 1.5:
|
| 149 |
-
quality -= 5 # Moderate reduction
|
| 150 |
-
else:
|
| 151 |
-
quality -= 3 # Conservative reduction
|
| 152 |
-
|
| 153 |
-
return buffer.getvalue()
|
| 154 |
-
|
| 155 |
-
def process_images_for_devices(image_data: bytes) -> Dict[str, bytes]:
|
| 156 |
-
"""
|
| 157 |
-
Resize banner image for desktop, tablet (iPad), and mobile.
|
| 158 |
-
"""
|
| 159 |
-
return {
|
| 160 |
-
'desktop': process_image(image_data, 1440, 500),
|
| 161 |
-
'ipad': process_image(image_data, 768, 500),
|
| 162 |
-
'mobile': process_image(image_data, 375, 500)
|
| 163 |
-
}
|
| 164 |
-
|
| 165 |
-
def generate_banner(brand_details: str, primary_color: str) -> Dict:
|
| 166 |
-
"""
|
| 167 |
-
Generate multiple variations of banner images for each device using Gemini and upload to Reach platform.
|
| 168 |
-
Returns a dictionary with URLs for different device sizes and prompt variations.
|
| 169 |
-
"""
|
| 170 |
-
api_key = settings.GEMINI_API_KEY
|
| 171 |
-
client = genai.Client(api_key=api_key)
|
| 172 |
-
brand_name = generate_brand_name()
|
| 173 |
-
|
| 174 |
-
#
|
| 175 |
-
base_prompt = get_banner_prompts(brand_details, primary_color)
|
| 176 |
-
all_prompt_sets = [base_prompt] #
|
| 177 |
-
|
| 178 |
-
all_banner_results = []
|
| 179 |
-
|
| 180 |
-
logger.info(f"Starting banner generation with ID: {brand_name}")
|
| 181 |
-
|
| 182 |
-
# Device-specific dimensions
|
| 183 |
-
device_dimensions = {
|
| 184 |
-
'desktop': (1440, 500),
|
| 185 |
-
'ipad': (768, 500),
|
| 186 |
-
'mobile': (375, 500)
|
| 187 |
-
}
|
| 188 |
-
|
| 189 |
-
# File types used for uploading
|
| 190 |
-
device_file_types = {
|
| 191 |
-
"desktop": "DESKTOP_IMAGE",
|
| 192 |
-
"ipad": "IPAD_IMAGE",
|
| 193 |
-
"mobile": "WEB_IMAGE"
|
| 194 |
-
}
|
| 195 |
-
|
| 196 |
-
# Loop through all variations of prompt sets
|
| 197 |
-
for variation_index, device_prompts in enumerate(all_prompt_sets, start=1):
|
| 198 |
-
banner_results = {}
|
| 199 |
-
|
| 200 |
-
for device, prompt in device_prompts.items():
|
| 201 |
-
logger.info(f"Generating variation {variation_index}, device: {device}")
|
| 202 |
-
|
| 203 |
-
try:
|
| 204 |
-
response = client.models.generate_content(
|
| 205 |
-
model="gemini-2.0-flash-exp-image-generation",
|
| 206 |
-
contents=prompt,
|
| 207 |
-
config=types.GenerateContentConfig(response_modalities=['TEXT', 'IMAGE'])
|
| 208 |
-
)
|
| 209 |
-
|
| 210 |
-
for part in response.candidates[0].content.parts:
|
| 211 |
-
if part.inline_data is not None:
|
| 212 |
-
image_data = part.inline_data.data
|
| 213 |
-
mime_type = part.inline_data.mime_type
|
| 214 |
-
|
| 215 |
-
# Determine image format
|
| 216 |
-
if "jpeg" in mime_type or "jpg" in mime_type:
|
| 217 |
-
image_format = "jpeg"
|
| 218 |
-
elif "png" in mime_type:
|
| 219 |
-
image_format = "png"
|
| 220 |
-
elif "webp" in mime_type:
|
| 221 |
-
image_format = "webp"
|
| 222 |
-
else:
|
| 223 |
-
image_format = "jpeg"
|
| 224 |
-
|
| 225 |
-
logger.info(f"Processing image for {device} in variation {variation_index}")
|
| 226 |
-
|
| 227 |
-
# Resize and enhance
|
| 228 |
-
width, height = device_dimensions[device]
|
| 229 |
-
processed_image = process_image(image_data, width, height)
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
"
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
|
|
|
| 255 |
return {"variations": all_banner_results}
|
|
|
|
| 1 |
+
from io import BytesIO
|
| 2 |
+
from typing import Dict
|
| 3 |
+
|
| 4 |
+
from google import genai
|
| 5 |
+
from google.genai import types
|
| 6 |
+
from PIL import Image, ImageEnhance, ImageOps, ImageFilter
|
| 7 |
+
import logging
|
| 8 |
+
from app.config.settings import settings
|
| 9 |
+
from app.utils.reach_upload import upload_to_reach
|
| 10 |
+
from app.utils.name_generator import generate_brand_name
|
| 11 |
+
import math
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
logging.basicConfig(level=logging.INFO)
|
| 15 |
+
|
| 16 |
+
def get_banner_prompts(brand_details: str, primary_color: str) -> Dict[str, str]:
|
| 17 |
+
device_prompts = {
|
| 18 |
+
'desktop': f'''Generate a realistic image which includes real people and
|
| 19 |
+
The image must show essence of the brand:
|
| 20 |
+
|
| 21 |
+
{brand_details}
|
| 22 |
+
|
| 23 |
+
Exclude the use of color {primary_color} in the palette. Do not Include any text, typographic or Alphanumeric Elements.''',
|
| 24 |
+
'ipad': f'''Generate a realistic image which includes real people and
|
| 25 |
+
The image must show essence of the brand:
|
| 26 |
+
|
| 27 |
+
{brand_details}
|
| 28 |
+
|
| 29 |
+
Exclude the use of color {primary_color} in the palette. Do not Include any text, typographic or Alphanumeric Elements.''',
|
| 30 |
+
'mobile': f'''Generate a realistic image which includes real people and
|
| 31 |
+
The image must show essence of the brand:
|
| 32 |
+
|
| 33 |
+
{brand_details}
|
| 34 |
+
|
| 35 |
+
Exclude the use of color {primary_color} in the palette. Do not Include any text, typographic or Alphanumeric Elements.''',
|
| 36 |
+
}
|
| 37 |
+
return device_prompts
|
| 38 |
+
|
| 39 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 40 |
+
"""
|
| 41 |
+
Resize, sharpen, enhance and compress an image to fit a given resolution and file size.
|
| 42 |
+
Optimized for 1024x1024 source images with better quality preservation.
|
| 43 |
+
"""
|
| 44 |
+
img = Image.open(BytesIO(image_data)).convert('RGB')
|
| 45 |
+
original_width, original_height = img.size
|
| 46 |
+
|
| 47 |
+
# Calculate aspect ratios
|
| 48 |
+
original_ratio = original_width / original_height
|
| 49 |
+
target_ratio = target_width / target_height
|
| 50 |
+
|
| 51 |
+
# Step 1: Smart upscaling based on target size relative to source
|
| 52 |
+
# Only upscale if target is significantly larger than source
|
| 53 |
+
upscale_threshold = max(target_width, target_height) / max(original_width, original_height)
|
| 54 |
+
|
| 55 |
+
if upscale_threshold > 1.2: # Only upscale if target is 20% larger
|
| 56 |
+
scale_factor = min(3, math.ceil(upscale_threshold)) # Cap at 3x to avoid excessive processing
|
| 57 |
+
intermediate_width = original_width * scale_factor
|
| 58 |
+
intermediate_height = original_height * scale_factor
|
| 59 |
+
|
| 60 |
+
# Use bicubic for upscaling (better than Lanczos for enlargement)
|
| 61 |
+
working_img = img.resize((intermediate_width, intermediate_height), Image.BICUBIC)
|
| 62 |
+
|
| 63 |
+
# Apply subtle unsharp mask for upscaled images
|
| 64 |
+
working_img = working_img.filter(ImageFilter.UnsharpMask(radius=1.0, percent=120, threshold=3))
|
| 65 |
+
else:
|
| 66 |
+
working_img = img
|
| 67 |
+
|
| 68 |
+
# Step 2: Smart cropping/fitting based on aspect ratio difference
|
| 69 |
+
if abs(original_ratio - target_ratio) > 0.1: # Significant aspect ratio difference
|
| 70 |
+
# Crop to target ratio first, then resize (preserves more detail)
|
| 71 |
+
if original_ratio > target_ratio:
|
| 72 |
+
# Source is wider - crop width
|
| 73 |
+
new_width = int(working_img.height * target_ratio)
|
| 74 |
+
left = (working_img.width - new_width) // 2
|
| 75 |
+
working_img = working_img.crop((left, 0, left + new_width, working_img.height))
|
| 76 |
+
else:
|
| 77 |
+
# Source is taller - crop height
|
| 78 |
+
new_height = int(working_img.width / target_ratio)
|
| 79 |
+
top = (working_img.height - new_height) // 2
|
| 80 |
+
working_img = working_img.crop((0, top, working_img.width, top + new_height))
|
| 81 |
+
|
| 82 |
+
# Step 3: Final resize to target dimensions
|
| 83 |
+
# Use Lanczos for downscaling, bicubic for upscaling
|
| 84 |
+
current_size = max(working_img.size)
|
| 85 |
+
target_size = max(target_width, target_height)
|
| 86 |
+
|
| 87 |
+
if current_size > target_size:
|
| 88 |
+
# Downscaling - use Lanczos
|
| 89 |
+
final_img = working_img.resize((target_width, target_height), Image.LANCZOS)
|
| 90 |
+
else:
|
| 91 |
+
# Upscaling - use bicubic
|
| 92 |
+
final_img = working_img.resize((target_width, target_height), Image.BICUBIC)
|
| 93 |
+
|
| 94 |
+
# Step 4: Conditional enhancement based on target size
|
| 95 |
+
target_pixels = target_width * target_height
|
| 96 |
+
|
| 97 |
+
if target_pixels < 500000: # Small images need more sharpening
|
| 98 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.4)
|
| 99 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.15)
|
| 100 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.05)
|
| 101 |
+
elif target_pixels < 1500000: # Medium images
|
| 102 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.2)
|
| 103 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.1)
|
| 104 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.08)
|
| 105 |
+
else: # Large images need subtle enhancement
|
| 106 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.1)
|
| 107 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.05)
|
| 108 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.03)
|
| 109 |
+
|
| 110 |
+
# Step 5: Intelligent compression with quality optimization
|
| 111 |
+
buffer = BytesIO()
|
| 112 |
+
|
| 113 |
+
# Start with higher quality for better results
|
| 114 |
+
quality = 98
|
| 115 |
+
max_file_size = 500 * 1024 # 500KB
|
| 116 |
+
|
| 117 |
+
while quality >= 75: # Don't go below 75 quality
|
| 118 |
+
buffer.seek(0)
|
| 119 |
+
buffer.truncate()
|
| 120 |
+
|
| 121 |
+
# Adjust subsampling based on quality
|
| 122 |
+
if quality >= 95:
|
| 123 |
+
subsampling = 0 # No chroma subsampling for highest quality
|
| 124 |
+
elif quality >= 85:
|
| 125 |
+
subsampling = 1 # Moderate chroma subsampling
|
| 126 |
+
else:
|
| 127 |
+
subsampling = 2 # Standard chroma subsampling
|
| 128 |
+
|
| 129 |
+
final_img.save(
|
| 130 |
+
buffer,
|
| 131 |
+
format='JPEG',
|
| 132 |
+
quality=quality,
|
| 133 |
+
optimize=True,
|
| 134 |
+
progressive=True,
|
| 135 |
+
subsampling=subsampling
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
current_size = buffer.tell()
|
| 139 |
+
|
| 140 |
+
# If we're within size limit or quality is getting too low, stop
|
| 141 |
+
if current_size <= max_file_size or quality <= 80:
|
| 142 |
+
break
|
| 143 |
+
|
| 144 |
+
# Adjust quality reduction based on how far over we are
|
| 145 |
+
overage_ratio = current_size / max_file_size
|
| 146 |
+
if overage_ratio > 2:
|
| 147 |
+
quality -= 8 # Aggressive reduction if way over
|
| 148 |
+
elif overage_ratio > 1.5:
|
| 149 |
+
quality -= 5 # Moderate reduction
|
| 150 |
+
else:
|
| 151 |
+
quality -= 3 # Conservative reduction
|
| 152 |
+
|
| 153 |
+
return buffer.getvalue()
|
| 154 |
+
|
| 155 |
+
def process_images_for_devices(image_data: bytes) -> Dict[str, bytes]:
|
| 156 |
+
"""
|
| 157 |
+
Resize banner image for desktop, tablet (iPad), and mobile.
|
| 158 |
+
"""
|
| 159 |
+
return {
|
| 160 |
+
'desktop': process_image(image_data, 1440, 500),
|
| 161 |
+
'ipad': process_image(image_data, 768, 500),
|
| 162 |
+
'mobile': process_image(image_data, 375, 500)
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
def generate_banner(brand_details: str, primary_color: str) -> Dict:
|
| 166 |
+
"""
|
| 167 |
+
Generate multiple variations of banner images for each device using Gemini and upload to Reach platform.
|
| 168 |
+
Returns a dictionary with URLs for different device sizes and prompt variations.
|
| 169 |
+
"""
|
| 170 |
+
api_key = settings.GEMINI_API_KEY
|
| 171 |
+
client = genai.Client(api_key=api_key)
|
| 172 |
+
brand_name = generate_brand_name()
|
| 173 |
+
|
| 174 |
+
# Create two identical prompt sets for two variations
|
| 175 |
+
base_prompt = get_banner_prompts(brand_details, primary_color)
|
| 176 |
+
all_prompt_sets = [base_prompt, base_prompt] # Two variations, same prompts
|
| 177 |
+
|
| 178 |
+
all_banner_results = []
|
| 179 |
+
|
| 180 |
+
logger.info(f"Starting banner generation with ID: {brand_name}")
|
| 181 |
+
|
| 182 |
+
# Device-specific dimensions
|
| 183 |
+
device_dimensions = {
|
| 184 |
+
'desktop': (1440, 500),
|
| 185 |
+
'ipad': (768, 500),
|
| 186 |
+
'mobile': (375, 500)
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
# File types used for uploading
|
| 190 |
+
device_file_types = {
|
| 191 |
+
"desktop": "DESKTOP_IMAGE",
|
| 192 |
+
"ipad": "IPAD_IMAGE",
|
| 193 |
+
"mobile": "WEB_IMAGE"
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
# Loop through all variations of prompt sets
|
| 197 |
+
for variation_index, device_prompts in enumerate(all_prompt_sets, start=1):
|
| 198 |
+
banner_results = {}
|
| 199 |
+
|
| 200 |
+
for device, prompt in device_prompts.items():
|
| 201 |
+
logger.info(f"Generating variation {variation_index}, device: {device}")
|
| 202 |
+
|
| 203 |
+
try:
|
| 204 |
+
response = client.models.generate_content(
|
| 205 |
+
model="gemini-2.0-flash-exp-image-generation",
|
| 206 |
+
contents=prompt,
|
| 207 |
+
config=types.GenerateContentConfig(response_modalities=['TEXT', 'IMAGE'])
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
for part in response.candidates[0].content.parts:
|
| 211 |
+
if part.inline_data is not None:
|
| 212 |
+
image_data = part.inline_data.data
|
| 213 |
+
mime_type = part.inline_data.mime_type
|
| 214 |
+
|
| 215 |
+
# Determine image format
|
| 216 |
+
if "jpeg" in mime_type or "jpg" in mime_type:
|
| 217 |
+
image_format = "jpeg"
|
| 218 |
+
elif "png" in mime_type:
|
| 219 |
+
image_format = "png"
|
| 220 |
+
elif "webp" in mime_type:
|
| 221 |
+
image_format = "webp"
|
| 222 |
+
else:
|
| 223 |
+
image_format = "jpeg"
|
| 224 |
+
|
| 225 |
+
logger.info(f"Processing image for {device} in variation {variation_index}")
|
| 226 |
+
|
| 227 |
+
# Resize and enhance
|
| 228 |
+
width, height = device_dimensions[device]
|
| 229 |
+
processed_image = process_image(image_data, width, height)
|
| 230 |
+
# Upload to Reach with UUID-based name
|
| 231 |
+
result = upload_to_reach(
|
| 232 |
+
processed_image,
|
| 233 |
+
f"banner_{brand_name}_{device}_v{variation_index}",
|
| 234 |
+
image_format,
|
| 235 |
+
1,
|
| 236 |
+
device_file_types[device]
|
| 237 |
+
)
|
| 238 |
+
banner_results[device] = result['url']
|
| 239 |
+
|
| 240 |
+
logger.info(f"{device} banner uploaded successfully for variation {variation_index}")
|
| 241 |
+
|
| 242 |
+
except Exception as error:
|
| 243 |
+
logger.error(f"Error processing {device} banner in variation {variation_index}: {str(error)}")
|
| 244 |
+
raise
|
| 245 |
+
|
| 246 |
+
if not banner_results:
|
| 247 |
+
logger.error(f"No images were generated for variation {variation_index}")
|
| 248 |
+
raise Exception(f"No images were generated for variation {variation_index}")
|
| 249 |
+
|
| 250 |
+
all_banner_results.append({
|
| 251 |
+
"variation": variation_index,
|
| 252 |
+
"banners": banner_results
|
| 253 |
+
})
|
| 254 |
+
|
| 255 |
+
logger.info("All banner variations generated successfully.")
|
| 256 |
return {"variations": all_banner_results}
|