Spaces:
Sleeping
Sleeping
Update app/services/custom_banner_service.py
Browse files- app/services/custom_banner_service.py +165 -152
app/services/custom_banner_service.py
CHANGED
|
@@ -1,152 +1,165 @@
|
|
| 1 |
-
import logging
|
| 2 |
-
from io import BytesIO
|
| 3 |
-
from typing import Dict
|
| 4 |
-
|
| 5 |
-
from google import genai
|
| 6 |
-
from google.genai import types
|
| 7 |
-
from PIL import Image, ImageEnhance, ImageOps
|
| 8 |
-
|
| 9 |
-
from app.config.settings import settings
|
| 10 |
-
from app.utils.reach_upload import upload_to_reach
|
| 11 |
-
|
| 12 |
-
# Logger setup
|
| 13 |
-
logger = logging.getLogger(__name__)
|
| 14 |
-
logger.setLevel(logging.INFO)
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def get_custom_prompts(brand_name: str, domain: str, description: str) -> list[str]:
|
| 18 |
-
"""
|
| 19 |
-
Generate prompt templates to guide Gemini for banner image generation.
|
| 20 |
-
"""
|
| 21 |
-
return [
|
| 22 |
-
f"Generate a powerful banner for {brand_name} in the {domain} sector that incorporates the following description: {description}. "
|
| 23 |
-
"Create a sophisticated visualization. Use a modern color scheme that emphasizes reliability and strength. "
|
| 24 |
-
"The composition should be optimized for 530x352 dimensions while maintaining visual clarity. Do not use text. Use Visual elements",
|
| 25 |
-
|
| 26 |
-
f"Design an impactful banner for {brand_name} in the {domain} industry based on this description: {description}. "
|
| 27 |
-
"Create a bold, abstract representation. Incorporate subtle depth and dimension. "
|
| 28 |
-
"Ensure the design is effective at 530x352 resolution. No text should be included in the image."
|
| 29 |
-
]
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 33 |
-
"""
|
| 34 |
-
Resize, sharpen, enhance, and compress image for upload.
|
| 35 |
-
"""
|
| 36 |
-
img = Image.open(BytesIO(image_data)).convert("RGB")
|
| 37 |
-
|
| 38 |
-
# Step 1: upscale, sharpen, contrast
|
| 39 |
-
intermediate_size = (target_width * 4, target_height * 4)
|
| 40 |
-
upscaled = ImageOps.fit(img, intermediate_size, method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 41 |
-
upscaled = ImageEnhance.Sharpness(upscaled).enhance(1.3)
|
| 42 |
-
upscaled = ImageEnhance.Contrast(upscaled).enhance(1.1)
|
| 43 |
-
|
| 44 |
-
# Step 2: final resize and finishing
|
| 45 |
-
final = ImageOps.fit(upscaled, (target_width, target_height), method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 46 |
-
final = ImageEnhance.Sharpness(final).enhance(1.1)
|
| 47 |
-
final = ImageEnhance.Color(final).enhance(1.1)
|
| 48 |
-
|
| 49 |
-
# Step 3: Compress with JPEG, max 500KB
|
| 50 |
-
buffer = BytesIO()
|
| 51 |
-
quality = 95
|
| 52 |
-
|
| 53 |
-
while True:
|
| 54 |
-
buffer.seek(0)
|
| 55 |
-
buffer.truncate()
|
| 56 |
-
|
| 57 |
-
final.save(
|
| 58 |
-
buffer,
|
| 59 |
-
format="JPEG",
|
| 60 |
-
quality=quality,
|
| 61 |
-
optimize=True,
|
| 62 |
-
progressive=True,
|
| 63 |
-
subsampling=0 if quality >= 90 else 1
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
-
if buffer.tell() <= 500 * 1024 or quality <= 80:
|
| 67 |
-
break
|
| 68 |
-
quality -= 3
|
| 69 |
-
|
| 70 |
-
return buffer.getvalue()
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def process_images_for_devices(image_data: bytes) -> Dict[str, bytes]:
|
| 74 |
-
"""
|
| 75 |
-
Process a single image into different aspect ratios/sizes per device.
|
| 76 |
-
"""
|
| 77 |
-
return {
|
| 78 |
-
"desktop": process_image(image_data, 1440, 500),
|
| 79 |
-
"ipad": process_image(image_data, 768, 500),
|
| 80 |
-
"mobile": process_image(image_data, 375, 500),
|
| 81 |
-
}
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
def generate_custom_banner(brand_name: str, domain: str, description: str) -> Dict:
|
| 85 |
-
"""
|
| 86 |
-
Generates multiple visual variations of a banner using Gemini image generation.
|
| 87 |
-
Returns dictionary containing image URLs grouped by device and variation.
|
| 88 |
-
"""
|
| 89 |
-
client = genai.Client(api_key=settings.GEMINI_API_KEY)
|
| 90 |
-
prompts = get_custom_prompts(brand_name, domain, description)
|
| 91 |
-
all_banner_results = []
|
| 92 |
-
|
| 93 |
-
for prompt_index, prompt in enumerate(prompts, start=1):
|
| 94 |
-
logger.info(f"Generating banner variation {prompt_index} for brand '{brand_name}'")
|
| 95 |
-
|
| 96 |
-
try:
|
| 97 |
-
response = client.models.generate_content(
|
| 98 |
-
model="gemini-2.0-flash-exp-image-generation",
|
| 99 |
-
contents=prompt,
|
| 100 |
-
config=types.GenerateContentConfig(response_modalities=["TEXT", "IMAGE"])
|
| 101 |
-
)
|
| 102 |
-
|
| 103 |
-
for part in response.candidates[0].content.parts:
|
| 104 |
-
if part.inline_data is not None:
|
| 105 |
-
try:
|
| 106 |
-
image_data = part.inline_data.data
|
| 107 |
-
mime_type = part.inline_data.mime_type
|
| 108 |
-
|
| 109 |
-
# Determine format from MIME type
|
| 110 |
-
if "jpeg" in mime_type or "jpg" in mime_type:
|
| 111 |
-
image_format = "jpeg"
|
| 112 |
-
elif "png" in mime_type:
|
| 113 |
-
image_format = "png"
|
| 114 |
-
elif "webp" in mime_type:
|
| 115 |
-
image_format = "webp"
|
| 116 |
-
else:
|
| 117 |
-
image_format = "jpeg"
|
| 118 |
-
|
| 119 |
-
logger.info(f"Processing banner image variation {prompt_index}")
|
| 120 |
-
|
| 121 |
-
processed_images = process_images_for_devices(image_data)
|
| 122 |
-
banner_results = {}
|
| 123 |
-
|
| 124 |
-
for device, img_data in processed_images.items():
|
| 125 |
-
result = upload_to_reach(
|
| 126 |
-
img_data,
|
| 127 |
-
f"custom_banner_{brand_name}_{device}_v{prompt_index}",
|
| 128 |
-
image_format,
|
| 129 |
-
prompt_index
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from io import BytesIO
|
| 3 |
+
from typing import Dict
|
| 4 |
+
|
| 5 |
+
from google import genai
|
| 6 |
+
from google.genai import types
|
| 7 |
+
from PIL import Image, ImageEnhance, ImageOps
|
| 8 |
+
|
| 9 |
+
from app.config.settings import settings
|
| 10 |
+
from app.utils.reach_upload import upload_to_reach
|
| 11 |
+
|
| 12 |
+
# Logger setup
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
logger.setLevel(logging.INFO)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_custom_prompts(brand_name: str, domain: str, description: str) -> list[str]:
|
| 18 |
+
"""
|
| 19 |
+
Generate prompt templates to guide Gemini for banner image generation.
|
| 20 |
+
"""
|
| 21 |
+
return [
|
| 22 |
+
f"Generate a powerful banner for {brand_name} in the {domain} sector that incorporates the following description: {description}. "
|
| 23 |
+
"Create a sophisticated visualization. Use a modern color scheme that emphasizes reliability and strength. "
|
| 24 |
+
"The composition should be optimized for 530x352 dimensions while maintaining visual clarity. Do not use text. Use Visual elements",
|
| 25 |
+
|
| 26 |
+
f"Design an impactful banner for {brand_name} in the {domain} industry based on this description: {description}. "
|
| 27 |
+
"Create a bold, abstract representation. Incorporate subtle depth and dimension. "
|
| 28 |
+
"Ensure the design is effective at 530x352 resolution. No text should be included in the image."
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 33 |
+
"""
|
| 34 |
+
Resize, sharpen, enhance, and compress image for upload.
|
| 35 |
+
"""
|
| 36 |
+
img = Image.open(BytesIO(image_data)).convert("RGB")
|
| 37 |
+
|
| 38 |
+
# Step 1: upscale, sharpen, contrast
|
| 39 |
+
intermediate_size = (target_width * 4, target_height * 4)
|
| 40 |
+
upscaled = ImageOps.fit(img, intermediate_size, method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 41 |
+
upscaled = ImageEnhance.Sharpness(upscaled).enhance(1.3)
|
| 42 |
+
upscaled = ImageEnhance.Contrast(upscaled).enhance(1.1)
|
| 43 |
+
|
| 44 |
+
# Step 2: final resize and finishing
|
| 45 |
+
final = ImageOps.fit(upscaled, (target_width, target_height), method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 46 |
+
final = ImageEnhance.Sharpness(final).enhance(1.1)
|
| 47 |
+
final = ImageEnhance.Color(final).enhance(1.1)
|
| 48 |
+
|
| 49 |
+
# Step 3: Compress with JPEG, max 500KB
|
| 50 |
+
buffer = BytesIO()
|
| 51 |
+
quality = 95
|
| 52 |
+
|
| 53 |
+
while True:
|
| 54 |
+
buffer.seek(0)
|
| 55 |
+
buffer.truncate()
|
| 56 |
+
|
| 57 |
+
final.save(
|
| 58 |
+
buffer,
|
| 59 |
+
format="JPEG",
|
| 60 |
+
quality=quality,
|
| 61 |
+
optimize=True,
|
| 62 |
+
progressive=True,
|
| 63 |
+
subsampling=0 if quality >= 90 else 1
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
if buffer.tell() <= 500 * 1024 or quality <= 80:
|
| 67 |
+
break
|
| 68 |
+
quality -= 3
|
| 69 |
+
|
| 70 |
+
return buffer.getvalue()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def process_images_for_devices(image_data: bytes) -> Dict[str, bytes]:
|
| 74 |
+
"""
|
| 75 |
+
Process a single image into different aspect ratios/sizes per device.
|
| 76 |
+
"""
|
| 77 |
+
return {
|
| 78 |
+
"desktop": process_image(image_data, 1440, 500),
|
| 79 |
+
"ipad": process_image(image_data, 768, 500),
|
| 80 |
+
"mobile": process_image(image_data, 375, 500),
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def generate_custom_banner(brand_name: str, domain: str, description: str) -> Dict:
|
| 85 |
+
"""
|
| 86 |
+
Generates multiple visual variations of a banner using Gemini image generation.
|
| 87 |
+
Returns dictionary containing image URLs grouped by device and variation.
|
| 88 |
+
"""
|
| 89 |
+
client = genai.Client(api_key=settings.GEMINI_API_KEY)
|
| 90 |
+
prompts = get_custom_prompts(brand_name, domain, description)
|
| 91 |
+
all_banner_results = []
|
| 92 |
+
|
| 93 |
+
for prompt_index, prompt in enumerate(prompts, start=1):
|
| 94 |
+
logger.info(f"Generating banner variation {prompt_index} for brand '{brand_name}'")
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
response = client.models.generate_content(
|
| 98 |
+
model="gemini-2.0-flash-exp-image-generation",
|
| 99 |
+
contents=prompt,
|
| 100 |
+
config=types.GenerateContentConfig(response_modalities=["TEXT", "IMAGE"])
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
for part in response.candidates[0].content.parts:
|
| 104 |
+
if part.inline_data is not None:
|
| 105 |
+
try:
|
| 106 |
+
image_data = part.inline_data.data
|
| 107 |
+
mime_type = part.inline_data.mime_type
|
| 108 |
+
|
| 109 |
+
# Determine format from MIME type
|
| 110 |
+
if "jpeg" in mime_type or "jpg" in mime_type:
|
| 111 |
+
image_format = "jpeg"
|
| 112 |
+
elif "png" in mime_type:
|
| 113 |
+
image_format = "png"
|
| 114 |
+
elif "webp" in mime_type:
|
| 115 |
+
image_format = "webp"
|
| 116 |
+
else:
|
| 117 |
+
image_format = "jpeg"
|
| 118 |
+
|
| 119 |
+
logger.info(f"Processing banner image variation {prompt_index}")
|
| 120 |
+
|
| 121 |
+
processed_images = process_images_for_devices(image_data)
|
| 122 |
+
banner_results = {}
|
| 123 |
+
|
| 124 |
+
for device, img_data in processed_images.items():
|
| 125 |
+
result = upload_to_reach(
|
| 126 |
+
img_data,
|
| 127 |
+
f"custom_banner_{brand_name}_{device}_v{prompt_index}",
|
| 128 |
+
image_format,
|
| 129 |
+
prompt_index
|
| 130 |
+
)
|
| 131 |
+
# Extract name from URL
|
| 132 |
+
url = result['url']
|
| 133 |
+
name = url.split('mvno/')[-1] if 'mvno/' in url else result['name']
|
| 134 |
+
|
| 135 |
+
banner_results[device] = {
|
| 136 |
+
"id": f"logo_{device}_v{prompt_index}",
|
| 137 |
+
"url": url,
|
| 138 |
+
"format": image_format,
|
| 139 |
+
"name": name
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
all_banner_results.append({
|
| 143 |
+
"variation": prompt_index,
|
| 144 |
+
"banners": banner_results
|
| 145 |
+
})
|
| 146 |
+
|
| 147 |
+
logger.info(f"Uploaded banner variation {prompt_index} successfully")
|
| 148 |
+
|
| 149 |
+
except Exception as e:
|
| 150 |
+
logger.error(f"Error processing banner for variation {prompt_index}: {str(e)}")
|
| 151 |
+
raise
|
| 152 |
+
|
| 153 |
+
except Exception as gen_err:
|
| 154 |
+
logger.error(f"Error generating banner variation {prompt_index}: {str(gen_err)}")
|
| 155 |
+
raise
|
| 156 |
+
|
| 157 |
+
if not all_banner_results:
|
| 158 |
+
logger.error("No images were successfully generated and processed.")
|
| 159 |
+
raise Exception("No banners generated")
|
| 160 |
+
|
| 161 |
+
return {
|
| 162 |
+
"banner": {
|
| 163 |
+
"variations": all_banner_results
|
| 164 |
+
}
|
| 165 |
+
}
|